[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[GNUnet-SVN] r5295 - in GNUnet: . libltdl src/applications/advertising s
From: |
gnunet |
Subject: |
[GNUnet-SVN] r5295 - in GNUnet: . libltdl src/applications/advertising src/applications/bootstrap_http src/applications/chat src/applications/datastore src/applications/dht/module src/applications/dht/tools src/applications/dstore src/applications/fragmentation src/applications/fs src/applications/fs/collection src/applications/fs/ecrs src/applications/fs/fsui src/applications/fs/lib src/applications/fs/module src/applications/fs/namespace src/applications/fs/tools src/applications/fs/uritrack src/applications/gap src/applications/getoption src/applications/identity src/applications/kvstore_sqlite src/applications/pingpong src/applications/rpc src/applications/session src/applications/sqstore_mysql src/applications/sqstore_mysql_embedded src/applications/sqstore_sqlite src/applications/state src/applications/stats src/applications/tbench src/applications/template src/applications/testbed src/applications/testing src/applications/topology_default src/applications/topology_f2f src/applications/tracekit src/applications/traffic src/applications/transport src/applications/vpn src/include src/server src/setup src/setup/gtk src/setup/lib src/setup/ncurses src/setup/text src/transports src/transports/upnp src/util/boot src/util/config src/util/config_impl src/util/containers src/util/cron src/util/crypto src/util/disk src/util/error src/util/getopt src/util/loggers src/util/network src/util/network_client src/util/os src/util/string src/util/threads src/util/win |
Date: |
Tue, 10 Jul 2007 02:36:40 -0600 (MDT) |
Author: grothoff
Date: 2007-07-10 02:36:37 -0600 (Tue, 10 Jul 2007)
New Revision: 5295
Added:
GNUnet/pre-commit
Modified:
GNUnet/libltdl/ltdl.c
GNUnet/libltdl/ltdl.h
GNUnet/src/applications/advertising/advertising.c
GNUnet/src/applications/advertising/advertising_test.c
GNUnet/src/applications/advertising/bootstrap.c
GNUnet/src/applications/advertising/bootstrap.h
GNUnet/src/applications/bootstrap_http/http.c
GNUnet/src/applications/bootstrap_http/httptest.c
GNUnet/src/applications/chat/chat.c
GNUnet/src/applications/chat/chat.h
GNUnet/src/applications/chat/gnunet-chat.c
GNUnet/src/applications/datastore/datastore.c
GNUnet/src/applications/datastore/filter.c
GNUnet/src/applications/datastore/filter.h
GNUnet/src/applications/datastore/prefetch.c
GNUnet/src/applications/datastore/prefetch.h
GNUnet/src/applications/dht/module/cs.c
GNUnet/src/applications/dht/module/dstore.c
GNUnet/src/applications/dht/module/dstore.h
GNUnet/src/applications/dht/module/routing.c
GNUnet/src/applications/dht/module/routing.h
GNUnet/src/applications/dht/module/service.c
GNUnet/src/applications/dht/module/table.c
GNUnet/src/applications/dht/module/table.h
GNUnet/src/applications/dht/tools/dht-query.c
GNUnet/src/applications/dht/tools/dht_api.c
GNUnet/src/applications/dht/tools/dhttest.c
GNUnet/src/applications/dht/tools/dhttest2.c
GNUnet/src/applications/dstore/dstore.c
GNUnet/src/applications/dstore/dstore_test.c
GNUnet/src/applications/fragmentation/fragmentation.c
GNUnet/src/applications/fragmentation/fragmentationtest.c
GNUnet/src/applications/fs/collection/collection.c
GNUnet/src/applications/fs/collection/collectiontest.c
GNUnet/src/applications/fs/ecrs/bincoder.c
GNUnet/src/applications/fs/ecrs/bincodertest.c
GNUnet/src/applications/fs/ecrs/directory.c
GNUnet/src/applications/fs/ecrs/directorytest.c
GNUnet/src/applications/fs/ecrs/download.c
GNUnet/src/applications/fs/ecrs/ecrs.c
GNUnet/src/applications/fs/ecrs/ecrs.h
GNUnet/src/applications/fs/ecrs/ecrstest.c
GNUnet/src/applications/fs/ecrs/helper.c
GNUnet/src/applications/fs/ecrs/indexinfo.c
GNUnet/src/applications/fs/ecrs/keyspace.c
GNUnet/src/applications/fs/ecrs/meta.c
GNUnet/src/applications/fs/ecrs/metatest.c
GNUnet/src/applications/fs/ecrs/metatest2.c
GNUnet/src/applications/fs/ecrs/namespace.c
GNUnet/src/applications/fs/ecrs/namespacetest.c
GNUnet/src/applications/fs/ecrs/parser.c
GNUnet/src/applications/fs/ecrs/search.c
GNUnet/src/applications/fs/ecrs/searchtest.c
GNUnet/src/applications/fs/ecrs/tree.c
GNUnet/src/applications/fs/ecrs/tree.h
GNUnet/src/applications/fs/ecrs/unindex.c
GNUnet/src/applications/fs/ecrs/upload.c
GNUnet/src/applications/fs/ecrs/uri.c
GNUnet/src/applications/fs/ecrs/uri.h
GNUnet/src/applications/fs/ecrs/uritest.c
GNUnet/src/applications/fs/ecrs_core.c
GNUnet/src/applications/fs/ecrs_core_test.c
GNUnet/src/applications/fs/fsui/deserialize.c
GNUnet/src/applications/fs/fsui/download.c
GNUnet/src/applications/fs/fsui/downloadtest.c
GNUnet/src/applications/fs/fsui/fsui-loader.c
GNUnet/src/applications/fs/fsui/fsui.c
GNUnet/src/applications/fs/fsui/fsui.h
GNUnet/src/applications/fs/fsui/fsuitest.c
GNUnet/src/applications/fs/fsui/fsuitest2.c
GNUnet/src/applications/fs/fsui/search.c
GNUnet/src/applications/fs/fsui/searchtest.c
GNUnet/src/applications/fs/fsui/serialize.c
GNUnet/src/applications/fs/fsui/serializetest.c
GNUnet/src/applications/fs/fsui/serializetest2.c
GNUnet/src/applications/fs/fsui/serializetest3.c
GNUnet/src/applications/fs/fsui/serializetest4.c
GNUnet/src/applications/fs/fsui/unindex.c
GNUnet/src/applications/fs/fsui/upload.c
GNUnet/src/applications/fs/lib/fslib.c
GNUnet/src/applications/fs/lib/fslibtest.c
GNUnet/src/applications/fs/module/anonymity.c
GNUnet/src/applications/fs/module/anonymity.h
GNUnet/src/applications/fs/module/dht_push.c
GNUnet/src/applications/fs/module/dht_push.h
GNUnet/src/applications/fs/module/fs.c
GNUnet/src/applications/fs/module/migration.c
GNUnet/src/applications/fs/module/migration.h
GNUnet/src/applications/fs/module/ondemand.c
GNUnet/src/applications/fs/module/ondemand.h
GNUnet/src/applications/fs/module/querymanager.c
GNUnet/src/applications/fs/module/querymanager.h
GNUnet/src/applications/fs/namespace/namespace_info.c
GNUnet/src/applications/fs/namespace/namespace_infotest.c
GNUnet/src/applications/fs/tools/gnunet-directory.c
GNUnet/src/applications/fs/tools/gnunet-download.c
GNUnet/src/applications/fs/tools/gnunet-insert.c
GNUnet/src/applications/fs/tools/gnunet-pseudonym.c
GNUnet/src/applications/fs/tools/gnunet-search.c
GNUnet/src/applications/fs/tools/gnunet-unindex.c
GNUnet/src/applications/fs/uritrack/callbacks.c
GNUnet/src/applications/fs/uritrack/callbacks.h
GNUnet/src/applications/fs/uritrack/file_info.c
GNUnet/src/applications/fs/uritrack/tracktest.c
GNUnet/src/applications/fs/uritrack/uri_info.c
GNUnet/src/applications/gap/gap.c
GNUnet/src/applications/gap/gap.h
GNUnet/src/applications/gap/gaptest.c
GNUnet/src/applications/gap/gaptest2.c
GNUnet/src/applications/gap/gaptest3.c
GNUnet/src/applications/gap/pid_table.c
GNUnet/src/applications/gap/pid_table.h
GNUnet/src/applications/getoption/clientapi.c
GNUnet/src/applications/getoption/getoption.c
GNUnet/src/applications/getoption/getoption.h
GNUnet/src/applications/identity/clientapi.c
GNUnet/src/applications/identity/hostkey.c
GNUnet/src/applications/identity/hostkey.h
GNUnet/src/applications/identity/identity.c
GNUnet/src/applications/identity/identity.h
GNUnet/src/applications/identity/identitytest.c
GNUnet/src/applications/kvstore_sqlite/kv_sqlite.c
GNUnet/src/applications/kvstore_sqlite/kv_sqlitetest.c
GNUnet/src/applications/pingpong/pingpong.c
GNUnet/src/applications/rpc/parameters.c
GNUnet/src/applications/rpc/parameterstest.c
GNUnet/src/applications/rpc/rpc.c
GNUnet/src/applications/session/connect.c
GNUnet/src/applications/session/sessiontest.c
GNUnet/src/applications/session/sessiontest2.c
GNUnet/src/applications/session/sessiontest_http.c
GNUnet/src/applications/sqstore_mysql/mysql.c
GNUnet/src/applications/sqstore_mysql/mysqltest.c
GNUnet/src/applications/sqstore_mysql/mysqltest2.c
GNUnet/src/applications/sqstore_mysql/mysqltest3.c
GNUnet/src/applications/sqstore_mysql_embedded/mysql.c
GNUnet/src/applications/sqstore_mysql_embedded/mysqltest.c
GNUnet/src/applications/sqstore_mysql_embedded/mysqltest2.c
GNUnet/src/applications/sqstore_mysql_embedded/mysqltest3.c
GNUnet/src/applications/sqstore_sqlite/sqlite.c
GNUnet/src/applications/sqstore_sqlite/sqlitetest.c
GNUnet/src/applications/sqstore_sqlite/sqlitetest2.c
GNUnet/src/applications/sqstore_sqlite/sqlitetest3.c
GNUnet/src/applications/state/state.c
GNUnet/src/applications/state/statetest.c
GNUnet/src/applications/stats/clientapi.c
GNUnet/src/applications/stats/gnunet-stats.c
GNUnet/src/applications/stats/sqstats.c
GNUnet/src/applications/stats/statistics.c
GNUnet/src/applications/stats/statistics.h
GNUnet/src/applications/tbench/gnunet-tbench.c
GNUnet/src/applications/tbench/tbench.c
GNUnet/src/applications/tbench/tbench.h
GNUnet/src/applications/tbench/tbenchtest.c
GNUnet/src/applications/template/gnunet-template.c
GNUnet/src/applications/template/template.c
GNUnet/src/applications/testbed/commands.c
GNUnet/src/applications/testbed/commands.h
GNUnet/src/applications/testbed/gnunet-testbed.c
GNUnet/src/applications/testbed/socket.c
GNUnet/src/applications/testbed/socket.h
GNUnet/src/applications/testbed/testbed.c
GNUnet/src/applications/testbed/testbed.h
GNUnet/src/applications/testing/testing.c
GNUnet/src/applications/testing/testingtest.c
GNUnet/src/applications/topology_default/topology.c
GNUnet/src/applications/topology_f2f/topology.c
GNUnet/src/applications/tracekit/gnunet-tracekit.c
GNUnet/src/applications/tracekit/tracekit.c
GNUnet/src/applications/tracekit/tracekit.h
GNUnet/src/applications/traffic/clientapi.c
GNUnet/src/applications/traffic/traffic.c
GNUnet/src/applications/traffic/traffic.h
GNUnet/src/applications/transport/transport.c
GNUnet/src/applications/vpn/gnunet-vpn.c
GNUnet/src/applications/vpn/vpn.c
GNUnet/src/include/core.h
GNUnet/src/include/dht.h
GNUnet/src/include/ecrs_core.h
GNUnet/src/include/fs.h
GNUnet/src/include/gnunet_blockstore.h
GNUnet/src/include/gnunet_bootstrap_service.h
GNUnet/src/include/gnunet_collection_lib.h
GNUnet/src/include/gnunet_core.h
GNUnet/src/include/gnunet_datastore_service.h
GNUnet/src/include/gnunet_dht_lib.h
GNUnet/src/include/gnunet_dht_service.h
GNUnet/src/include/gnunet_dstore_service.h
GNUnet/src/include/gnunet_ecrs_lib.h
GNUnet/src/include/gnunet_fragmentation_service.h
GNUnet/src/include/gnunet_fs_lib.h
GNUnet/src/include/gnunet_fsui_lib.h
GNUnet/src/include/gnunet_gap_service.h
GNUnet/src/include/gnunet_getoption_lib.h
GNUnet/src/include/gnunet_identity_lib.h
GNUnet/src/include/gnunet_identity_service.h
GNUnet/src/include/gnunet_kvstore_service.h
GNUnet/src/include/gnunet_namespace_lib.h
GNUnet/src/include/gnunet_peerinfo_lib.h
GNUnet/src/include/gnunet_pingpong_service.h
GNUnet/src/include/gnunet_protocols.h
GNUnet/src/include/gnunet_rpc_service.h
GNUnet/src/include/gnunet_session_service.h
GNUnet/src/include/gnunet_setup_lib.h
GNUnet/src/include/gnunet_sqstore_service.h
GNUnet/src/include/gnunet_state_service.h
GNUnet/src/include/gnunet_stats_lib.h
GNUnet/src/include/gnunet_stats_service.h
GNUnet/src/include/gnunet_testing_lib.h
GNUnet/src/include/gnunet_topology_service.h
GNUnet/src/include/gnunet_traffic_lib.h
GNUnet/src/include/gnunet_traffic_service.h
GNUnet/src/include/gnunet_transport.h
GNUnet/src/include/gnunet_transport_service.h
GNUnet/src/include/gnunet_upnp_service.h
GNUnet/src/include/gnunet_uritrack_lib.h
GNUnet/src/include/gnunet_util.h
GNUnet/src/include/gnunet_util_boot.h
GNUnet/src/include/gnunet_util_common.h
GNUnet/src/include/gnunet_util_config.h
GNUnet/src/include/gnunet_util_config_impl.h
GNUnet/src/include/gnunet_util_containers.h
GNUnet/src/include/gnunet_util_core.h
GNUnet/src/include/gnunet_util_cron.h
GNUnet/src/include/gnunet_util_crypto.h
GNUnet/src/include/gnunet_util_disk.h
GNUnet/src/include/gnunet_util_error.h
GNUnet/src/include/gnunet_util_error_loggers.h
GNUnet/src/include/gnunet_util_getopt.h
GNUnet/src/include/gnunet_util_network.h
GNUnet/src/include/gnunet_util_network_client.h
GNUnet/src/include/gnunet_util_os.h
GNUnet/src/include/gnunet_util_string.h
GNUnet/src/include/gnunet_util_threads.h
GNUnet/src/include/platform.h
GNUnet/src/include/plibc.h
GNUnet/src/include/winproc.h
GNUnet/src/server/connection.c
GNUnet/src/server/connection.h
GNUnet/src/server/core.c
GNUnet/src/server/gnunet-peer-info.c
GNUnet/src/server/gnunet-transport-check.c
GNUnet/src/server/gnunet-update.c
GNUnet/src/server/gnunetd.c
GNUnet/src/server/handler.c
GNUnet/src/server/handler.h
GNUnet/src/server/startup.c
GNUnet/src/server/startup.h
GNUnet/src/server/tcpserver.c
GNUnet/src/server/tcpserver.h
GNUnet/src/server/version.c
GNUnet/src/server/version.h
GNUnet/src/setup/gnunet-setup.c
GNUnet/src/setup/gnunet-win-tool.c
GNUnet/src/setup/gtk/about.c
GNUnet/src/setup/gtk/gconf.c
GNUnet/src/setup/gtk/gconf.h
GNUnet/src/setup/gtk/glade_support.c
GNUnet/src/setup/gtk/glade_support.h
GNUnet/src/setup/gtk/wizard_gtk.c
GNUnet/src/setup/gtk/wizard_gtk.h
GNUnet/src/setup/lib/gns.c
GNUnet/src/setup/lib/tree.c
GNUnet/src/setup/lib/tree.h
GNUnet/src/setup/lib/wizard_util.c
GNUnet/src/setup/lib/wizard_util.h
GNUnet/src/setup/ncurses/mconf.c
GNUnet/src/setup/ncurses/mconf.h
GNUnet/src/setup/ncurses/wizard_curs.c
GNUnet/src/setup/ncurses/wizard_curs.h
GNUnet/src/setup/text/conf.c
GNUnet/src/setup/text/conf.h
GNUnet/src/transports/http.c
GNUnet/src/transports/ip.c
GNUnet/src/transports/ip.h
GNUnet/src/transports/ip6.c
GNUnet/src/transports/ip6.h
GNUnet/src/transports/nat.c
GNUnet/src/transports/smtp.c
GNUnet/src/transports/tcp.c
GNUnet/src/transports/tcp6.c
GNUnet/src/transports/tcp_helper.c
GNUnet/src/transports/udp.c
GNUnet/src/transports/udp6.c
GNUnet/src/transports/udp_helper.c
GNUnet/src/transports/upnp/error.c
GNUnet/src/transports/upnp/error.h
GNUnet/src/transports/upnp/init.c
GNUnet/src/transports/upnp/ip.c
GNUnet/src/transports/upnp/ip.h
GNUnet/src/transports/upnp/upnp.c
GNUnet/src/transports/upnp/upnp.h
GNUnet/src/transports/upnp/upnptest.c
GNUnet/src/transports/upnp/util.c
GNUnet/src/transports/upnp/util.h
GNUnet/src/transports/upnp/xmlnode.c
GNUnet/src/transports/upnp/xmlnode.h
GNUnet/src/util/boot/startup.c
GNUnet/src/util/config/config.c
GNUnet/src/util/config_impl/configtest.c
GNUnet/src/util/config_impl/impl.c
GNUnet/src/util/containers/bloomfilter.c
GNUnet/src/util/containers/bloomtest.c
GNUnet/src/util/containers/hashtable.c
GNUnet/src/util/containers/hashtabletest.c
GNUnet/src/util/containers/hashtest.c
GNUnet/src/util/containers/vector.c
GNUnet/src/util/containers/vectortest.c
GNUnet/src/util/cron/cron.c
GNUnet/src/util/cron/crontest.c
GNUnet/src/util/cron/timertest.c
GNUnet/src/util/crypto/crc32.c
GNUnet/src/util/crypto/crctest.c
GNUnet/src/util/crypto/hashing.c
GNUnet/src/util/crypto/hashingtest.c
GNUnet/src/util/crypto/hashperf.c
GNUnet/src/util/crypto/hostkey_gcrypt.c
GNUnet/src/util/crypto/hostkeytest.c
GNUnet/src/util/crypto/kblockkey.c
GNUnet/src/util/crypto/kblockkey_test.c
GNUnet/src/util/crypto/locking_gcrypt.c
GNUnet/src/util/crypto/locking_gcrypt.h
GNUnet/src/util/crypto/random.c
GNUnet/src/util/crypto/symcipher_gcrypt.c
GNUnet/src/util/crypto/symciphertest.c
GNUnet/src/util/crypto/weakkeytest.c
GNUnet/src/util/disk/storage.c
GNUnet/src/util/disk/storagetest.c
GNUnet/src/util/error/error.c
GNUnet/src/util/getopt/getopt.c
GNUnet/src/util/getopt/printhelp.c
GNUnet/src/util/getopt/printversion.c
GNUnet/src/util/getopt/setoption.c
GNUnet/src/util/loggers/file.c
GNUnet/src/util/loggers/memory.c
GNUnet/src/util/loggers/smtp.c
GNUnet/src/util/network/dns.c
GNUnet/src/util/network/endian.c
GNUnet/src/util/network/io.c
GNUnet/src/util/network/ip.c
GNUnet/src/util/network/ipcheck.c
GNUnet/src/util/network/network.h
GNUnet/src/util/network/select.c
GNUnet/src/util/network/selecttest.c
GNUnet/src/util/network_client/daemon.c
GNUnet/src/util/network_client/tcpio.c
GNUnet/src/util/network_client/tcpiotest.c
GNUnet/src/util/os/console.c
GNUnet/src/util/os/cpustatus.c
GNUnet/src/util/os/daemon.c
GNUnet/src/util/os/daemontest.c
GNUnet/src/util/os/dso.c
GNUnet/src/util/os/init.c
GNUnet/src/util/os/installpath.c
GNUnet/src/util/os/osconfig.c
GNUnet/src/util/os/priority.c
GNUnet/src/util/os/semaphore.c
GNUnet/src/util/os/semaphoretest.c
GNUnet/src/util/os/statuscalls.c
GNUnet/src/util/os/statuscallstest.c
GNUnet/src/util/os/time.c
GNUnet/src/util/os/user.c
GNUnet/src/util/string/string.c
GNUnet/src/util/string/xmalloc.c
GNUnet/src/util/string/xmalloctest.c
GNUnet/src/util/threads/mutex.c
GNUnet/src/util/threads/pthread.c
GNUnet/src/util/threads/semaphore.c
GNUnet/src/util/threads/semaphoretest.c
GNUnet/src/util/threads/shutdown.c
GNUnet/src/util/threads/shutdowntest.c
GNUnet/src/util/threads/shutdowntest2.c
GNUnet/src/util/threads/signal.c
GNUnet/src/util/threads/time.c
GNUnet/src/util/threads/timertest.c
GNUnet/src/util/win/winproc.c
Log:
GNU indent
Modified: GNUnet/libltdl/ltdl.c
===================================================================
--- GNUnet/libltdl/ltdl.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/libltdl/ltdl.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -131,10 +131,10 @@
#if WITH_DMALLOC
# include <dmalloc.h>
#endif
+
-
/* --- WINDOWS SUPPORT --- */
@@ -162,7 +162,7 @@
struct dirent
{
char d_name[2048];
- int d_namlen;
+ int d_namlen;
};
typedef struct _DIR
@@ -174,8 +174,8 @@
} DIR;
#endif /* LT_USE_WINDOWS_DIRENT_EMULATION */
+
-
/* --- MANIFEST CONSTANTS --- */
@@ -199,30 +199,32 @@
/* This accounts for the _LTX_ separator */
#undef LT_SYMBOL_OVERHEAD
#define LT_SYMBOL_OVERHEAD 5
+
-
/* --- MEMORY HANDLING --- */
/* These are the functions used internally. In addition to making
use of the associated function pointers above, they also perform
error handling. */
-static char *lt_estrdup LT_PARAMS((const char *str));
-static lt_ptr lt_emalloc LT_PARAMS((size_t size));
-static lt_ptr lt_erealloc LT_PARAMS((lt_ptr addr, size_t size));
+static char *lt_estrdup LT_PARAMS ((const char *str));
+static lt_ptr lt_emalloc LT_PARAMS ((size_t size));
+static lt_ptr lt_erealloc LT_PARAMS ((lt_ptr addr, size_t size));
/* static lt_ptr rpl_realloc LT_PARAMS((lt_ptr ptr, size_t size)); */
#define rpl_realloc realloc
/* These are the pointers that can be changed by the caller: */
-LT_GLOBAL_DATA lt_ptr (*lt_dlmalloc) LT_PARAMS((size_t size))
- = (lt_ptr (*) LT_PARAMS((size_t))) malloc;
-LT_GLOBAL_DATA lt_ptr (*lt_dlrealloc) LT_PARAMS((lt_ptr ptr, size_t size))
- = (lt_ptr (*) LT_PARAMS((lt_ptr, size_t))) rpl_realloc;
-LT_GLOBAL_DATA void (*lt_dlfree) LT_PARAMS((lt_ptr ptr))
- = (void (*) LT_PARAMS((lt_ptr))) free;
+LT_GLOBAL_DATA
+lt_ptr (*lt_dlmalloc)
+LT_PARAMS ((size_t size)) = (lt_ptr (*)LT_PARAMS ((size_t))) malloc;
+ LT_GLOBAL_DATA lt_ptr (*lt_dlrealloc)
+ LT_PARAMS ((lt_ptr ptr, size_t size)) =
+ (lt_ptr (*)LT_PARAMS ((lt_ptr, size_t))) rpl_realloc;
+ LT_GLOBAL_DATA void (*lt_dlfree) LT_PARAMS ((lt_ptr ptr)) =
+ (void (*)LT_PARAMS ((lt_ptr))) free;
/* The following macros reduce the amount of typing needed to cast
assigned memory. */
@@ -251,29 +253,28 @@
#define LT_DLMEM_REASSIGN(p, q) LT_STMT_START { \
if ((p) != (q)) { if (p) lt_dlfree (p); (p) = (q); (q) = 0; } \
} LT_STMT_END
+
-
/* --- REPLACEMENT FUNCTIONS --- */
#undef strdup
#define strdup rpl_strdup
-static char *strdup LT_PARAMS((const char *str));
+ static char *strdup LT_PARAMS ((const char *str));
-static char *
-strdup(str)
+ static char *strdup (str)
const char *str;
{
char *tmp = 0;
if (str)
{
- tmp = LT_DLMALLOC (char, 1+ strlen (str));
+ tmp = LT_DLMALLOC (char, 1 + strlen (str));
if (tmp)
- {
- strcpy(tmp, str);
- }
+ {
+ strcpy (tmp, str);
+ }
}
return tmp;
@@ -285,7 +286,7 @@
#undef strcmp
#define strcmp rpl_strcmp
-static int strcmp LT_PARAMS((const char *str1, const char *str2));
+static int strcmp LT_PARAMS ((const char *str1, const char *str2));
static int
strcmp (str1, str2)
@@ -299,13 +300,13 @@
if (str2 == 0)
return 1;
- for (;*str1 && *str2; ++str1, ++str2)
+ for (; *str1 && *str2; ++str1, ++str2)
{
if (*str1 != *str2)
- break;
+ break;
}
- return (int)(*str1 - *str2);
+ return (int) (*str1 - *str2);
}
#endif
@@ -317,19 +318,19 @@
# else
# define strchr rpl_strchr
-static const char *strchr LT_PARAMS((const char *str, int ch));
+static const char *strchr LT_PARAMS ((const char *str, int ch));
-static const char*
-strchr(str, ch)
+static const char *
+strchr (str, ch)
const char *str;
int ch;
{
const char *p;
- for (p = str; *p != (char)ch && *p != LT_EOS_CHAR; ++p)
- /*NOWORK*/;
+ for (p = str; *p != (char) ch && *p != LT_EOS_CHAR; ++p)
+ /*NOWORK*/;
- return (*p == (char)ch) ? p : 0;
+ return (*p == (char) ch) ? p : 0;
}
# endif
@@ -343,10 +344,10 @@
# else
# define strrchr rpl_strrchr
-static const char *strrchr LT_PARAMS((const char *str, int ch));
+static const char *strrchr LT_PARAMS ((const char *str, int ch));
-static const char*
-strrchr(str, ch)
+static const char *
+strrchr (str, ch)
const char *str;
int ch;
{
@@ -355,9 +356,9 @@
for (p = str; *p != LT_EOS_CHAR; ++p)
{
if (*p == (char) ch)
- {
- q = p;
- }
+ {
+ q = p;
+ }
}
return q;
@@ -377,7 +378,7 @@
# else
# define memcpy rpl_memcpy
-static lt_ptr memcpy LT_PARAMS((lt_ptr dest, const lt_ptr src, size_t size));
+static lt_ptr memcpy LT_PARAMS ((lt_ptr dest, const lt_ptr src, size_t size));
static lt_ptr
memcpy (dest, src, size)
@@ -385,9 +386,9 @@
const lt_ptr src;
size_t size;
{
- const char * s = src;
- char * d = dest;
- size_t i = 0;
+ const char *s = src;
+ char *d = dest;
+ size_t i = 0;
for (i = 0; i < size; ++i)
{
@@ -398,12 +399,13 @@
}
# endif /* !HAVE_BCOPY */
-#endif /* !HAVE_MEMCPY */
+#endif /* !HAVE_MEMCPY */
#if ! HAVE_MEMMOVE
# define memmove rpl_memmove
-static lt_ptr memmove LT_PARAMS((lt_ptr dest, const lt_ptr src, size_t size));
+static lt_ptr memmove
+LT_PARAMS ((lt_ptr dest, const lt_ptr src, size_t size));
static lt_ptr
memmove (dest, src, size)
@@ -411,21 +413,21 @@
const lt_ptr src;
size_t size;
{
- const char * s = src;
- char * d = dest;
- size_t i;
+ const char *s = src;
+ char *d = dest;
+ size_t i;
if (d < s)
for (i = 0; i < size; ++i)
{
- d[i] = s[i];
+ d[i] = s[i];
}
else if (d > s && size > 0)
- for (i = size -1; ; --i)
+ for (i = size - 1;; --i)
{
- d[i] = s[i];
- if (i == 0)
- break;
+ d[i] = s[i];
+ if (i == 0)
+ break;
}
return dest;
@@ -435,74 +437,76 @@
#ifdef LT_USE_WINDOWS_DIRENT_EMULATION
-static void closedir LT_PARAMS((DIR *entry));
+static void closedir LT_PARAMS ((DIR * entry));
static void
-closedir(entry)
- DIR *entry;
+closedir (entry)
+ DIR *entry;
{
- assert(entry != (DIR *) NULL);
- FindClose(entry->hSearch);
- lt_dlfree((lt_ptr)entry);
+ assert (entry != (DIR *) NULL);
+ FindClose (entry->hSearch);
+ lt_dlfree ((lt_ptr) entry);
}
-static DIR * opendir LT_PARAMS((const char *path));
+static DIR *opendir LT_PARAMS ((const char *path));
-static DIR*
+static DIR *
opendir (path)
- const char *path;
+ const char *path;
{
char file_specification[LT_FILENAME_MAX];
DIR *entry;
- assert(path != (char *) NULL);
+ assert (path != (char *) NULL);
/* allow space for: path + '\\' '\\' '*' '.' '*' + '\0' */
- (void) strncpy (file_specification, path, LT_FILENAME_MAX-6);
- file_specification[LT_FILENAME_MAX-6] = LT_EOS_CHAR;
- (void) strcat(file_specification,"\\");
- entry = LT_DLMALLOC (DIR,sizeof(DIR));
+ (void) strncpy (file_specification, path, LT_FILENAME_MAX - 6);
+ file_specification[LT_FILENAME_MAX - 6] = LT_EOS_CHAR;
+ (void) strcat (file_specification, "\\");
+ entry = LT_DLMALLOC (DIR, sizeof (DIR));
if (entry != (DIR *) 0)
{
entry->firsttime = TRUE;
- entry->hSearch = FindFirstFile(file_specification,&entry->Win32FindData);
+ entry->hSearch =
+ FindFirstFile (file_specification, &entry->Win32FindData);
}
if (entry->hSearch == INVALID_HANDLE_VALUE)
{
- (void) strcat(file_specification,"\\*.*");
- entry->hSearch = FindFirstFile(file_specification,&entry->Win32FindData);
+ (void) strcat (file_specification, "\\*.*");
+ entry->hSearch =
+ FindFirstFile (file_specification, &entry->Win32FindData);
if (entry->hSearch == INVALID_HANDLE_VALUE)
{
LT_DLFREE (entry);
return (DIR *) 0;
}
}
- return(entry);
+ return (entry);
}
-static struct dirent *readdir LT_PARAMS((DIR *entry));
+static struct dirent *readdir LT_PARAMS ((DIR * entry));
-static struct dirent *readdir(entry)
- DIR *entry;
+static struct dirent *
+readdir (entry)
+ DIR *entry;
{
- int
- status;
+ int status;
if (entry == (DIR *) 0)
- return((struct dirent *) 0);
+ return ((struct dirent *) 0);
if (!entry->firsttime)
{
- status = FindNextFile(entry->hSearch,&entry->Win32FindData);
+ status = FindNextFile (entry->hSearch, &entry->Win32FindData);
if (status == 0)
- return((struct dirent *) 0);
+ return ((struct dirent *) 0);
}
entry->firsttime = FALSE;
- (void) strncpy(entry->file_info.d_name,entry->Win32FindData.cFileName,
- LT_FILENAME_MAX-1);
+ (void) strncpy (entry->file_info.d_name, entry->Win32FindData.cFileName,
+ LT_FILENAME_MAX - 1);
entry->file_info.d_name[LT_FILENAME_MAX - 1] = LT_EOS_CHAR;
- entry->file_info.d_namlen = strlen(entry->file_info.d_name);
- return(&entry->file_info);
+ entry->file_info.d_namlen = strlen (entry->file_info.d_name);
+ return (&entry->file_info);
}
#endif /* LT_USE_WINDOWS_DIRENT_EMULATION */
@@ -533,9 +537,9 @@
{
/* For zero or less bytes, free the original memory */
if (ptr != 0)
- {
- lt_dlfree (ptr);
- }
+ {
+ lt_dlfree (ptr);
+ }
return (lt_ptr) 0;
}
@@ -550,13 +554,13 @@
lt_ptr mem = lt_dlmalloc (size);
if (mem)
- {
- memcpy (mem, ptr, size);
- lt_dlfree (ptr);
- }
+ {
+ memcpy (mem, ptr, size);
+ lt_dlfree (ptr);
+ }
/* Note that the contents of PTR are not damaged if there is
- insufficient memory to realloc. */
+ insufficient memory to realloc. */
return mem;
}
}
@@ -566,8 +570,8 @@
#if ! HAVE_ARGZ_APPEND
# define argz_append rpl_argz_append
-static error_t argz_append LT_PARAMS((char **pargz, size_t *pargz_len,
- const char *buf, size_t buf_len));
+static error_t argz_append LT_PARAMS ((char **pargz, size_t * pargz_len,
+ const char *buf, size_t buf_len));
static error_t
argz_append (pargz, pargz_len, buf, buf_len)
@@ -577,7 +581,7 @@
size_t buf_len;
{
size_t argz_len;
- char *argz;
+ char *argz;
assert (pargz);
assert (pargz_len);
@@ -608,8 +612,8 @@
#if ! HAVE_ARGZ_CREATE_SEP
# define argz_create_sep rpl_argz_create_sep
-static error_t argz_create_sep LT_PARAMS((const char *str, int delim,
- char **pargz, size_t *pargz_len));
+static error_t argz_create_sep LT_PARAMS ((const char *str, int delim,
+ char **pargz, size_t * pargz_len));
static error_t
argz_create_sep (str, delim, pargz, pargz_len)
@@ -627,7 +631,7 @@
/* Make a copy of STR, but replacing each occurrence of
DELIM with '\0'. */
- argz_len = 1+ LT_STRLEN (str);
+ argz_len = 1 + LT_STRLEN (str);
if (argz_len)
{
const char *p;
@@ -635,22 +639,22 @@
argz = LT_DLMALLOC (char, argz_len);
if (!argz)
- return ENOMEM;
+ return ENOMEM;
for (p = str, q = argz; *p != LT_EOS_CHAR; ++p)
- {
- if (*p == delim)
- {
- /* Ignore leading delimiters, and fold consecutive
- delimiters in STR into a single '\0' in ARGZ. */
- if ((q > argz) && (q[-1] != LT_EOS_CHAR))
- *q++ = LT_EOS_CHAR;
- else
- --argz_len;
- }
- else
- *q++ = *p;
- }
+ {
+ if (*p == delim)
+ {
+ /* Ignore leading delimiters, and fold consecutive
+ delimiters in STR into a single '\0' in ARGZ. */
+ if ((q > argz) && (q[-1] != LT_EOS_CHAR))
+ *q++ = LT_EOS_CHAR;
+ else
+ --argz_len;
+ }
+ else
+ *q++ = *p;
+ }
/* Copy terminating LT_EOS_CHAR. */
*q = *p;
}
@@ -671,8 +675,8 @@
#if ! HAVE_ARGZ_INSERT
# define argz_insert rpl_argz_insert
-static error_t argz_insert LT_PARAMS((char **pargz, size_t *pargz_len,
- char *before, const char *entry));
+static error_t argz_insert LT_PARAMS ((char **pargz, size_t * pargz_len,
+ char *before, const char *entry));
static error_t
argz_insert (pargz, pargz_len, before, entry)
@@ -688,7 +692,7 @@
/* No BEFORE address indicates ENTRY should be inserted after the
current last element. */
if (!before)
- return argz_append (pargz, pargz_len, entry, 1+ LT_STRLEN (entry));
+ return argz_append (pargz, pargz_len, entry, 1 + LT_STRLEN (entry));
/* This probably indicates a programmer error, but to preserve
semantics, scan back to the start of an entry if BEFORE points
@@ -697,10 +701,10 @@
--before;
{
- size_t entry_len = 1+ LT_STRLEN (entry);
- size_t argz_len = *pargz_len + entry_len;
- size_t offset = before - *pargz;
- char *argz = LT_DLREALLOC (char, *pargz, argz_len);
+ size_t entry_len = 1 + LT_STRLEN (entry);
+ size_t argz_len = *pargz_len + entry_len;
+ size_t offset = before - *pargz;
+ char *argz = LT_DLREALLOC (char, *pargz, argz_len);
if (!argz)
return ENOMEM;
@@ -713,7 +717,7 @@
space at the end -- making room to copy ENTRY into the
resulting gap. */
memmove (before + entry_len, before, *pargz_len - offset);
- memcpy (before, entry, entry_len);
+ memcpy (before, entry, entry_len);
/* Assign new values. */
*pargz = argz;
@@ -728,8 +732,8 @@
#if ! HAVE_ARGZ_NEXT
# define argz_next rpl_argz_next
-static char *argz_next LT_PARAMS((char *argz, size_t argz_len,
- const char *entry));
+static char *argz_next LT_PARAMS ((char *argz, size_t argz_len,
+ const char *entry));
static char *
argz_next (argz, argz_len, entry)
@@ -742,28 +746,28 @@
if (entry)
{
/* Either ARGZ/ARGZ_LEN is empty, or ENTRY points into an address
- within the ARGZ vector. */
+ within the ARGZ vector. */
assert ((!argz && !argz_len)
- || ((argz <= entry) && (entry < (argz + argz_len))));
+ || ((argz <= entry) && (entry < (argz + argz_len))));
/* Move to the char immediately after the terminating
- '\0' of ENTRY. */
- entry = 1+ strchr (entry, LT_EOS_CHAR);
+ '\0' of ENTRY. */
+ entry = 1 + strchr (entry, LT_EOS_CHAR);
/* Return either the new ENTRY, or else NULL if ARGZ is
- exhausted. */
+ exhausted. */
return (entry >= argz + argz_len) ? 0 : (char *) entry;
}
else
{
/* This should probably be flagged as a programmer error,
- since starting an argz_next loop with the iterator set
- to ARGZ is safer. To preserve semantics, handle the NULL
- case by returning the start of ARGZ (if any). */
+ since starting an argz_next loop with the iterator set
+ to ARGZ is safer. To preserve semantics, handle the NULL
+ case by returning the start of ARGZ (if any). */
if (argz_len > 0)
- return argz;
+ return argz;
else
- return 0;
+ return 0;
}
}
#endif /* !HAVE_ARGZ_NEXT */
@@ -773,8 +777,7 @@
#if ! HAVE_ARGZ_STRINGIFY
# define argz_stringify rpl_argz_stringify
-static void argz_stringify LT_PARAMS((char *argz, size_t argz_len,
- int sep));
+static void argz_stringify LT_PARAMS ((char *argz, size_t argz_len, int sep));
static void
argz_stringify (argz, argz_len, sep)
@@ -786,68 +789,69 @@
if (sep)
{
- --argz_len; /* don't stringify the terminating EOS */
+ --argz_len; /* don't stringify the terminating EOS */
while (--argz_len > 0)
- {
- if (argz[argz_len] == LT_EOS_CHAR)
- argz[argz_len] = sep;
- }
+ {
+ if (argz[argz_len] == LT_EOS_CHAR)
+ argz[argz_len] = sep;
+ }
}
}
#endif /* !HAVE_ARGZ_STRINGIFY */
+
-
/* --- TYPE DEFINITIONS -- */
/* This type is used for the array of caller data sets in each handler. */
-typedef struct {
- lt_dlcaller_id key;
- lt_ptr data;
+typedef struct
+{
+ lt_dlcaller_id key;
+ lt_ptr data;
} lt_caller_data;
+
-
/* --- OPAQUE STRUCTURES DECLARED IN LTDL.H --- */
/* Extract the diagnostic strings from the error table macro in the same
order as the enumerated indices in ltdl.h. */
-static const char *lt_dlerror_strings[] =
- {
+static const char *lt_dlerror_strings[] = {
#define LT_ERROR(name, diagnostic) (diagnostic),
- lt_dlerror_table
+ lt_dlerror_table
#undef LT_ERROR
+ 0
+};
- 0
- };
-
/* This structure is used for the list of registered loaders. */
-struct lt_dlloader {
- struct lt_dlloader *next;
- const char *loader_name; /* identifying name for each loader */
- const char *sym_prefix; /* prefix for symbols */
- lt_module_open *module_open;
- lt_module_close *module_close;
- lt_find_sym *find_sym;
- lt_dlloader_exit *dlloader_exit;
- lt_user_data dlloader_data;
+struct lt_dlloader
+{
+ struct lt_dlloader *next;
+ const char *loader_name; /* identifying name for each loader */
+ const char *sym_prefix; /* prefix for symbols */
+ lt_module_open *module_open;
+ lt_module_close *module_close;
+ lt_find_sym *find_sym;
+ lt_dlloader_exit *dlloader_exit;
+ lt_user_data dlloader_data;
};
-struct lt_dlhandle_struct {
- struct lt_dlhandle_struct *next;
- lt_dlloader *loader; /* dlopening interface */
- lt_dlinfo info;
- int depcount; /* number of dependencies */
- lt_dlhandle *deplibs; /* dependencies */
- lt_module module; /* system module handle */
- lt_ptr system; /* system specific data */
- lt_caller_data *caller_data; /* per caller associated data */
- int flags; /* various boolean stats */
+struct lt_dlhandle_struct
+{
+ struct lt_dlhandle_struct *next;
+ lt_dlloader *loader; /* dlopening interface */
+ lt_dlinfo info;
+ int depcount; /* number of dependencies */
+ lt_dlhandle *deplibs; /* dependencies */
+ lt_module module; /* system module handle */
+ lt_ptr system; /* system specific data */
+ lt_caller_data *caller_data; /* per caller associated data */
+ int flags; /* various boolean stats */
};
/* Various boolean flags can be stored in the flags field of an
@@ -863,18 +867,18 @@
#define LT_DLSTRERROR(name) lt_dlerror_strings[LT_CONC(LT_ERROR_,name)]
-static const char objdir[] = LTDL_OBJDIR;
-static const char archive_ext[] = LTDL_ARCHIVE_EXT;
+static const char objdir[] = LTDL_OBJDIR;
+static const char archive_ext[] = LTDL_ARCHIVE_EXT;
#ifdef LTDL_SHLIB_EXT
-static const char shlib_ext[] = LTDL_SHLIB_EXT;
+static const char shlib_ext[] = LTDL_SHLIB_EXT;
#endif
#ifdef LTDL_SYSSEARCHPATH
-static const char sys_search_path[] = LTDL_SYSSEARCHPATH;
+static const char sys_search_path[] = LTDL_SYSSEARCHPATH;
#endif
+
-
/* --- MUTEX LOCKING --- */
@@ -900,11 +904,11 @@
/* The mutex functions stored here are global, and are necessarily the
same for all threads that wish to share access to libltdl. */
-static lt_dlmutex_lock *lt_dlmutex_lock_func = 0;
-static lt_dlmutex_unlock *lt_dlmutex_unlock_func = 0;
-static lt_dlmutex_seterror *lt_dlmutex_seterror_func = 0;
-static lt_dlmutex_geterror *lt_dlmutex_geterror_func = 0;
-static const char *lt_dllast_error = 0;
+static lt_dlmutex_lock *lt_dlmutex_lock_func = 0;
+static lt_dlmutex_unlock *lt_dlmutex_unlock_func = 0;
+static lt_dlmutex_seterror *lt_dlmutex_seterror_func = 0;
+static lt_dlmutex_geterror *lt_dlmutex_geterror_func = 0;
+static const char *lt_dllast_error = 0;
/* Either set or reset the mutex functions. Either all the arguments must
@@ -919,7 +923,7 @@
lt_dlmutex_geterror *geterror;
{
lt_dlmutex_unlock *old_unlock = unlock;
- int errors = 0;
+ int errors = 0;
/* Lock using the old lock() callback, if any. */
LT_DLMUTEX_LOCK ();
@@ -927,8 +931,8 @@
if ((lock && unlock && seterror && geterror)
|| !(lock || unlock || seterror || geterror))
{
- lt_dlmutex_lock_func = lock;
- lt_dlmutex_unlock_func = unlock;
+ lt_dlmutex_lock_func = lock;
+ lt_dlmutex_unlock_func = unlock;
lt_dlmutex_geterror_func = geterror;
}
else
@@ -946,23 +950,23 @@
this function. */
return errors;
}
+
-
/* --- ERROR HANDLING --- */
-static const char **user_error_strings = 0;
-static int errorcount = LT_ERROR_MAX;
+static const char **user_error_strings = 0;
+static int errorcount = LT_ERROR_MAX;
int
lt_dladderror (diagnostic)
const char *diagnostic;
{
- int errindex = 0;
- int result = -1;
- const char **temp = (const char **) 0;
+ int errindex = 0;
+ int result = -1;
+ const char **temp = (const char **) 0;
assert (diagnostic);
@@ -972,9 +976,9 @@
temp = LT_EREALLOC (const char *, user_error_strings, 1 + errindex);
if (temp)
{
- user_error_strings = temp;
- user_error_strings[errindex] = diagnostic;
- result = errorcount++;
+ user_error_strings = temp;
+ user_error_strings[errindex] = diagnostic;
+ result = errorcount++;
}
LT_DLMUTEX_UNLOCK ();
@@ -986,7 +990,7 @@
lt_dlseterror (errindex)
int errindex;
{
- int errors = 0;
+ int errors = 0;
LT_DLMUTEX_LOCK ();
@@ -1042,10 +1046,10 @@
LT_DLMUTEX_SETERROR (LT_DLSTRERROR (NO_MEMORY));
return copy;
}
+
-
/* --- DLOPEN() INTERFACE LOADER --- */
@@ -1107,7 +1111,7 @@
lt_user_data loader_data;
const char *filename;
{
- lt_module module = dlopen (filename, LT_GLOBAL | LT_LAZY_OR_NOW);
+ lt_module module = dlopen (filename, LT_GLOBAL | LT_LAZY_OR_NOW);
if (!module)
{
@@ -1149,20 +1153,20 @@
return address;
}
-static struct lt_user_dlloader sys_dl =
- {
+static struct lt_user_dlloader sys_dl = {
# ifdef NEED_USCORE
- "_",
+ "_",
# else
- 0,
+ 0,
# endif
- sys_dl_open, sys_dl_close, sys_dl_sym, 0, 0 };
+ sys_dl_open, sys_dl_close, sys_dl_sym, 0, 0
+};
#endif /* HAVE_LIBDL */
+
-
/* --- SHL_LOAD() INTERFACE LOADER --- */
#if HAVE_SHL_LOAD
@@ -1240,9 +1244,9 @@
module = shl_load (filename, LT_BIND_FLAGS, 0L);
if (!module)
- {
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (CANNOT_OPEN));
- }
+ {
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (CANNOT_OPEN));
+ }
}
return module;
@@ -1274,15 +1278,16 @@
/* sys_shl_open should never return a NULL module handle */
if (module == (lt_module) 0)
- {
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (INVALID_HANDLE));
- }
- else if (!shl_findsym((shl_t*) &module, symbol, TYPE_UNDEFINED, &address))
{
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (INVALID_HANDLE));
+ }
+ else
+ if (!shl_findsym ((shl_t *) & module, symbol, TYPE_UNDEFINED, &address))
+ {
if (!address)
- {
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (SYMBOL_NOT_FOUND));
- }
+ {
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (SYMBOL_NOT_FOUND));
+ }
}
return address;
@@ -1293,10 +1298,10 @@
};
#endif /* HAVE_SHL_LOAD */
+
-
/* --- LOADLIBRARY() INTERFACE LOADER --- */
#ifdef __WINDOWS__
@@ -1313,12 +1318,12 @@
lt_user_data loader_data;
const char *filename;
{
- lt_dlhandle cur;
- lt_module module = 0;
- const char *errormsg = 0;
- char *searchname = 0;
- char *ext;
- char self_name_buf[MAX_PATH];
+ lt_dlhandle cur;
+ lt_module module = 0;
+ const char *errormsg = 0;
+ char *searchname = 0;
+ char *ext;
+ char self_name_buf[MAX_PATH];
if (!filename)
{
@@ -1340,10 +1345,10 @@
else
{
/* Append a `.' to stop Windows from adding an
- implicit `.dll' extension. */
- searchname = LT_EMALLOC (char, 2+ LT_STRLEN (filename));
+ implicit `.dll' extension. */
+ searchname = LT_EMALLOC (char, 2 + LT_STRLEN (filename));
if (searchname)
- sprintf (searchname, "%s.", filename);
+ sprintf (searchname, "%s.", filename);
}
if (!searchname)
return 0;
@@ -1352,8 +1357,8 @@
/* Silence dialog from LoadLibrary on some failures.
No way to get the error mode, but to set it,
so set it twice to preserve any previous flags. */
- UINT errormode = SetErrorMode(SEM_FAILCRITICALERRORS);
- SetErrorMode(errormode | SEM_FAILCRITICALERRORS);
+ UINT errormode = SetErrorMode (SEM_FAILCRITICALERRORS);
+ SetErrorMode (errormode | SEM_FAILCRITICALERRORS);
#if defined(__CYGWIN__)
{
@@ -1366,7 +1371,7 @@
#endif
/* Restore the error mode. */
- SetErrorMode(errormode);
+ SetErrorMode (errormode);
}
LT_DLFREE (searchname);
@@ -1384,18 +1389,18 @@
while (cur)
{
if (!cur->module)
- {
- cur = 0;
- break;
- }
+ {
+ cur = 0;
+ break;
+ }
if (cur->module == module)
- {
- break;
- }
+ {
+ break;
+ }
cur = cur->next;
- }
+ }
LT_DLMUTEX_UNLOCK ();
if (cur || !module)
@@ -1412,9 +1417,9 @@
lt_user_data loader_data;
lt_module module;
{
- int errors = 0;
+ int errors = 0;
- if (FreeLibrary(module) == 0)
+ if (FreeLibrary (module) == 0)
{
LT_DLMUTEX_SETERROR (LT_DLSTRERROR (CANNOT_CLOSE));
++errors;
@@ -1429,7 +1434,7 @@
lt_module module;
const char *symbol;
{
- lt_ptr address = GetProcAddress (module, symbol);
+ lt_ptr address = GetProcAddress (module, symbol);
if (!address)
{
@@ -1444,10 +1449,10 @@
};
#endif /* __WINDOWS__ */
+
-
/* --- LOAD_ADD_ON() INTERFACE LOADER --- */
@@ -1473,7 +1478,7 @@
image_info info;
int32 cookie = 0;
if (get_next_image_info (0, &cookie, &info) == B_OK)
- image = load_add_on (info.name);
+ image = load_add_on (info.name);
}
if (image <= 0)
@@ -1524,10 +1529,10 @@
};
#endif /* __BEOS__ */
+
-
/* --- DLD_LINK() INTERFACE LOADER --- */
@@ -1563,7 +1568,7 @@
{
int errors = 0;
- if (dld_unlink_by_file ((char*)(module), 1) != 0)
+ if (dld_unlink_by_file ((char *) (module), 1) != 0)
{
LT_DLMUTEX_SETERROR (LT_DLSTRERROR (CANNOT_CLOSE));
++errors;
@@ -1616,10 +1621,11 @@
# define ENUM_DYLD_BOOL
# undef FALSE
# undef TRUE
- enum DYLD_BOOL {
- FALSE,
- TRUE
- };
+enum DYLD_BOOL
+{
+ FALSE,
+ TRUE
+};
#endif
#ifndef LC_REQ_DYLD
# define LC_REQ_DYLD 0x80000000
@@ -1627,10 +1633,18 @@
#ifndef LC_LOAD_WEAK_DYLIB
# define LC_LOAD_WEAK_DYLIB (0x18 | LC_REQ_DYLD)
#endif
-static const struct mach_header * (*ltdl_NSAddImage)(const char *image_name,
unsigned long options) = 0;
-static NSSymbol (*ltdl_NSLookupSymbolInImage)(const struct mach_header
*image,const char *symbolName, unsigned long options) = 0;
-static enum DYLD_BOOL (*ltdl_NSIsSymbolNameDefinedInImage)(const struct
mach_header *image, const char *symbolName) = 0;
-static enum DYLD_BOOL (*ltdl_NSMakePrivateModulePublic)(NSModule module) = 0;
+static const struct mach_header *(*ltdl_NSAddImage) (const char *image_name,
+ unsigned long options) =
+ 0;
+static NSSymbol (*ltdl_NSLookupSymbolInImage) (const struct mach_header *
+ image, const char *symbolName,
+ unsigned long options) = 0;
+static enum DYLD_BOOL (*ltdl_NSIsSymbolNameDefinedInImage) (const struct
+ mach_header *
+ image,
+ const char
+ *symbolName) = 0;
+static enum DYLD_BOOL (*ltdl_NSMakePrivateModulePublic) (NSModule module) = 0;
#ifndef NSADDIMAGE_OPTION_NONE
#define NSADDIMAGE_OPTION_NONE 0x0
@@ -1662,144 +1676,170 @@
static const char *
-lt_int_dyld_error(othererror)
- char* othererror;
+lt_int_dyld_error (othererror)
+ char *othererror;
{
/* return the dyld error string, or the passed in error string if none */
- NSLinkEditErrors ler;
- int lerno;
- const char *errstr;
- const char *file;
- NSLinkEditError(&ler,&lerno,&file,&errstr);
- if (!errstr || !strlen(errstr)) errstr = othererror;
- return errstr;
+ NSLinkEditErrors ler;
+ int lerno;
+ const char *errstr;
+ const char *file;
+ NSLinkEditError (&ler, &lerno, &file, &errstr);
+ if (!errstr || !strlen (errstr))
+ errstr = othererror;
+ return errstr;
}
static const struct mach_header *
-lt_int_dyld_get_mach_header_from_nsmodule(module)
- NSModule module;
+lt_int_dyld_get_mach_header_from_nsmodule (module)
+ NSModule module;
{
/* There should probably be an apple dyld api for this */
- int i=_dyld_image_count();
- int j;
- const char *modname=NSNameOfModule(module);
- const struct mach_header *mh=NULL;
- if (!modname) return NULL;
- for (j = 0; j < i; j++)
- {
- if (!strcmp(_dyld_get_image_name(j),modname))
- {
- mh=_dyld_get_image_header(j);
- break;
- }
- }
- return mh;
+ int i = _dyld_image_count ();
+ int j;
+ const char *modname = NSNameOfModule (module);
+ const struct mach_header *mh = NULL;
+ if (!modname)
+ return NULL;
+ for (j = 0; j < i; j++)
+ {
+ if (!strcmp (_dyld_get_image_name (j), modname))
+ {
+ mh = _dyld_get_image_header (j);
+ break;
+ }
+ }
+ return mh;
}
-static const char* lt_int_dyld_lib_install_name(mh)
- const struct mach_header *mh;
+static const char *
+lt_int_dyld_lib_install_name (mh)
+ const struct mach_header *mh;
{
/* NSAddImage is also used to get the loaded image, but it only works if the
lib
is installed, for uninstalled libs we need to check the install_names
against
each other. Note that this is still broken if DYLD_IMAGE_SUFFIX is set and a
different lib was loaded as a result
*/
- int j;
- struct load_command *lc;
- unsigned long offset = sizeof(struct mach_header);
- const char* retStr=NULL;
- for (j = 0; j < mh->ncmds; j++)
- {
- lc = (struct load_command*)(((unsigned long)mh) + offset);
- if (LC_ID_DYLIB == lc->cmd)
- {
- retStr=(char*)(((struct
dylib_command*)lc)->dylib.name.offset +
-
(unsigned long)lc);
- }
- offset += lc->cmdsize;
- }
- return retStr;
+ int j;
+ struct load_command *lc;
+ unsigned long offset = sizeof (struct mach_header);
+ const char *retStr = NULL;
+ for (j = 0; j < mh->ncmds; j++)
+ {
+ lc = (struct load_command *) (((unsigned long) mh) + offset);
+ if (LC_ID_DYLIB == lc->cmd)
+ {
+ retStr =
+ (char *) (((struct dylib_command *) lc)->dylib.name.offset +
+ (unsigned long) lc);
+ }
+ offset += lc->cmdsize;
+ }
+ return retStr;
}
static const struct mach_header *
-lt_int_dyld_match_loaded_lib_by_install_name(const char *name)
+lt_int_dyld_match_loaded_lib_by_install_name (const char *name)
{
- int i=_dyld_image_count();
- int j;
- const struct mach_header *mh=NULL;
- const char *id=NULL;
- for (j = 0; j < i; j++)
- {
- id=lt_int_dyld_lib_install_name(_dyld_get_image_header(j));
- if ((id) && (!strcmp(id,name)))
- {
- mh=_dyld_get_image_header(j);
- break;
- }
- }
- return mh;
+ int i = _dyld_image_count ();
+ int j;
+ const struct mach_header *mh = NULL;
+ const char *id = NULL;
+ for (j = 0; j < i; j++)
+ {
+ id = lt_int_dyld_lib_install_name (_dyld_get_image_header (j));
+ if ((id) && (!strcmp (id, name)))
+ {
+ mh = _dyld_get_image_header (j);
+ break;
+ }
+ }
+ return mh;
}
static NSSymbol
-lt_int_dyld_NSlookupSymbolInLinkedLibs(symbol,mh)
- const char *symbol;
- const struct mach_header *mh;
+lt_int_dyld_NSlookupSymbolInLinkedLibs (symbol, mh)
+ const char *symbol;
+ const struct mach_header *mh;
{
- /* Safe to assume our mh is good */
- int j;
- struct load_command *lc;
- unsigned long offset = sizeof(struct mach_header);
- NSSymbol retSym = 0;
- const struct mach_header *mh1;
- if ((ltdl_NSLookupSymbolInImage) && NSIsSymbolNameDefined(symbol) )
- {
- for (j = 0; j < mh->ncmds; j++)
- {
- lc = (struct load_command*)(((unsigned long)mh) +
offset);
- if ((LC_LOAD_DYLIB == lc->cmd) || (LC_LOAD_WEAK_DYLIB
== lc->cmd))
- {
-
mh1=lt_int_dyld_match_loaded_lib_by_install_name((char*)(((struct
dylib_command*)lc)->dylib.name.offset +
-
(unsigned long)lc));
- if (!mh1)
- {
- /* Maybe NSAddImage can find it */
- mh1=ltdl_NSAddImage((char*)(((struct
dylib_command*)lc)->dylib.name.offset +
-
(unsigned long)lc),
-
NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED +
-
NSADDIMAGE_OPTION_WITH_SEARCHING +
-
NSADDIMAGE_OPTION_RETURN_ON_ERROR );
- }
- if (mh1)
- {
- retSym = ltdl_NSLookupSymbolInImage(mh1,
-
symbol,
-
NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW
-
| NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR
-
);
- if (retSym) break;
- }
- }
- offset += lc->cmdsize;
- }
- }
- return retSym;
+ /* Safe to assume our mh is good */
+ int j;
+ struct load_command *lc;
+ unsigned long offset = sizeof (struct mach_header);
+ NSSymbol retSym = 0;
+ const struct mach_header *mh1;
+ if ((ltdl_NSLookupSymbolInImage) && NSIsSymbolNameDefined (symbol))
+ {
+ for (j = 0; j < mh->ncmds; j++)
+ {
+ lc = (struct load_command *) (((unsigned long) mh) + offset);
+ if ((LC_LOAD_DYLIB == lc->cmd) || (LC_LOAD_WEAK_DYLIB == lc->cmd))
+ {
+ mh1 =
+ lt_int_dyld_match_loaded_lib_by_install_name ((char
+ *) (((struct
+
dylib_command
+ *) lc)->
+ dylib.name.
+ offset +
+ (unsigned
+ long)
+ lc));
+ if (!mh1)
+ {
+ /* Maybe NSAddImage can find it */
+ mh1 =
+ ltdl_NSAddImage ((char *) (((struct dylib_command *) lc)->
+ dylib.name.offset +
+ (unsigned long) lc),
+ NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED +
+ NSADDIMAGE_OPTION_WITH_SEARCHING +
+ NSADDIMAGE_OPTION_RETURN_ON_ERROR);
+ }
+ if (mh1)
+ {
+ retSym = ltdl_NSLookupSymbolInImage (mh1,
+ symbol,
+
NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW
+ |
+
NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
+ if (retSym)
+ break;
+ }
+ }
+ offset += lc->cmdsize;
+ }
+ }
+ return retSym;
}
static int
-sys_dyld_init()
+sys_dyld_init ()
{
- int retCode = 0;
- int err = 0;
- if (!_dyld_present()) {
- retCode=1;
- }
- else {
- err = _dyld_func_lookup("__dyld_NSAddImage",(unsigned
long*)<dl_NSAddImage);
- err = _dyld_func_lookup("__dyld_NSLookupSymbolInImage",(unsigned
long*)<dl_NSLookupSymbolInImage);
- err = _dyld_func_lookup("__dyld_NSIsSymbolNameDefinedInImage",(unsigned
long*)<dl_NSIsSymbolNameDefinedInImage);
- err = _dyld_func_lookup("__dyld_NSMakePrivateModulePublic",(unsigned
long*)<dl_NSMakePrivateModulePublic);
+ int retCode = 0;
+ int err = 0;
+ if (!_dyld_present ())
+ {
+ retCode = 1;
}
- return retCode;
+ else
+ {
+ err =
+ _dyld_func_lookup ("__dyld_NSAddImage",
+ (unsigned long *) <dl_NSAddImage);
+ err =
+ _dyld_func_lookup ("__dyld_NSLookupSymbolInImage",
+ (unsigned long *) <dl_NSLookupSymbolInImage);
+ err =
+ _dyld_func_lookup ("__dyld_NSIsSymbolNameDefinedInImage",
+ (unsigned long *)
+ <dl_NSIsSymbolNameDefinedInImage);
+ err =
+ _dyld_func_lookup ("__dyld_NSMakePrivateModulePublic",
+ (unsigned long *) <dl_NSMakePrivateModulePublic);
+ }
+ return retCode;
}
static lt_module
@@ -1807,35 +1847,38 @@
lt_user_data loader_data;
const char *filename;
{
- lt_module module = 0;
- NSObjectFileImage ofi = 0;
- NSObjectFileImageReturnCode ofirc;
+ lt_module module = 0;
+ NSObjectFileImage ofi = 0;
+ NSObjectFileImageReturnCode ofirc;
- if (!filename)
- return (lt_module)-1;
- ofirc = NSCreateObjectFileImageFromFile(filename, &ofi);
- switch (ofirc)
- {
- case NSObjectFileImageSuccess:
- module = NSLinkModule(ofi, filename,
-
NSLINKMODULE_OPTION_RETURN_ON_ERROR
- | NSLINKMODULE_OPTION_PRIVATE
- | NSLINKMODULE_OPTION_BINDNOW);
- NSDestroyObjectFileImage(ofi);
- if (module)
- ltdl_NSMakePrivateModulePublic(module);
- break;
- case NSObjectFileImageInappropriateFile:
- if (ltdl_NSIsSymbolNameDefinedInImage &&
ltdl_NSLookupSymbolInImage)
- {
- module = (lt_module)ltdl_NSAddImage(filename,
NSADDIMAGE_OPTION_RETURN_ON_ERROR);
- break;
- }
- default:
- LT_DLMUTEX_SETERROR
(lt_int_dyld_error(LT_DLSTRERROR(CANNOT_OPEN)));
- return 0;
- }
- if (!module) LT_DLMUTEX_SETERROR
(lt_int_dyld_error(LT_DLSTRERROR(CANNOT_OPEN)));
+ if (!filename)
+ return (lt_module) - 1;
+ ofirc = NSCreateObjectFileImageFromFile (filename, &ofi);
+ switch (ofirc)
+ {
+ case NSObjectFileImageSuccess:
+ module = NSLinkModule (ofi, filename,
+ NSLINKMODULE_OPTION_RETURN_ON_ERROR
+ | NSLINKMODULE_OPTION_PRIVATE
+ | NSLINKMODULE_OPTION_BINDNOW);
+ NSDestroyObjectFileImage (ofi);
+ if (module)
+ ltdl_NSMakePrivateModulePublic (module);
+ break;
+ case NSObjectFileImageInappropriateFile:
+ if (ltdl_NSIsSymbolNameDefinedInImage && ltdl_NSLookupSymbolInImage)
+ {
+ module =
+ (lt_module) ltdl_NSAddImage (filename,
+ NSADDIMAGE_OPTION_RETURN_ON_ERROR);
+ break;
+ }
+ default:
+ LT_DLMUTEX_SETERROR (lt_int_dyld_error (LT_DLSTRERROR (CANNOT_OPEN)));
+ return 0;
+ }
+ if (!module)
+ LT_DLMUTEX_SETERROR (lt_int_dyld_error (LT_DLSTRERROR (CANNOT_OPEN)));
return module;
}
@@ -1844,43 +1887,45 @@
lt_user_data loader_data;
lt_module module;
{
- int retCode = 0;
- int flags = 0;
- if (module == (lt_module)-1) return 0;
+ int retCode = 0;
+ int flags = 0;
+ if (module == (lt_module) - 1)
+ return 0;
#ifdef __BIG_ENDIAN__
- if (((struct mach_header *)module)->magic == MH_MAGIC)
+ if (((struct mach_header *) module)->magic == MH_MAGIC)
#else
- if (((struct mach_header *)module)->magic == MH_CIGAM)
+ if (((struct mach_header *) module)->magic == MH_CIGAM)
#endif
- {
- LT_DLMUTEX_SETERROR("Can not close a dylib");
- retCode = 1;
- }
- else
- {
+ {
+ LT_DLMUTEX_SETERROR ("Can not close a dylib");
+ retCode = 1;
+ }
+ else
+ {
#if 1
/* Currently, if a module contains c++ static destructors and it is unloaded,
we
get a segfault in atexit(), due to compiler and dynamic loader differences
of
opinion, this works around that.
*/
- if ((const struct section *)NULL !=
-
getsectbynamefromheader(lt_int_dyld_get_mach_header_from_nsmodule(module),
- "__DATA","__mod_term_func"))
- {
- flags += NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED;
- }
+ if ((const struct section *) NULL !=
+ getsectbynamefromheader (lt_int_dyld_get_mach_header_from_nsmodule
+ (module), "__DATA", "__mod_term_func"))
+ {
+ flags += NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED;
+ }
#endif
#ifdef __ppc__
- flags += NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES;
+ flags += NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES;
#endif
- if (!NSUnLinkModule(module,flags))
- {
- retCode=1;
- LT_DLMUTEX_SETERROR
(lt_int_dyld_error(LT_DLSTRERROR(CANNOT_CLOSE)));
- }
- }
+ if (!NSUnLinkModule (module, flags))
+ {
+ retCode = 1;
+ LT_DLMUTEX_SETERROR (lt_int_dyld_error
+ (LT_DLSTRERROR (CANNOT_CLOSE)));
+ }
+ }
- return retCode;
+ return retCode;
}
static lt_ptr
@@ -1889,52 +1934,57 @@
lt_module module;
const char *symbol;
{
- lt_ptr address = 0;
- NSSymbol *nssym = 0;
- void *unused;
- const struct mach_header *mh=NULL;
- char saveError[256] = "Symbol not found";
- if (module == (lt_module)-1)
- {
- _dyld_lookup_and_bind(symbol,(unsigned long*)&address,&unused);
- return address;
- }
+ lt_ptr address = 0;
+ NSSymbol *nssym = 0;
+ void *unused;
+ const struct mach_header *mh = NULL;
+ char saveError[256] = "Symbol not found";
+ if (module == (lt_module) - 1)
+ {
+ _dyld_lookup_and_bind (symbol, (unsigned long *) &address, &unused);
+ return address;
+ }
#ifdef __BIG_ENDIAN__
- if (((struct mach_header *)module)->magic == MH_MAGIC)
+ if (((struct mach_header *) module)->magic == MH_MAGIC)
#else
- if (((struct mach_header *)module)->magic == MH_CIGAM)
+ if (((struct mach_header *) module)->magic == MH_CIGAM)
#endif
- {
- if (ltdl_NSIsSymbolNameDefinedInImage && ltdl_NSLookupSymbolInImage)
- {
- mh=module;
- if (ltdl_NSIsSymbolNameDefinedInImage((struct
mach_header*)module,symbol))
- {
- nssym = ltdl_NSLookupSymbolInImage((struct
mach_header*)module,
-
symbol,
-
NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW
-
| NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR
-
);
- }
- }
+ {
+ if (ltdl_NSIsSymbolNameDefinedInImage && ltdl_NSLookupSymbolInImage)
+ {
+ mh = module;
+ if (ltdl_NSIsSymbolNameDefinedInImage
+ ((struct mach_header *) module, symbol))
+ {
+ nssym =
+ ltdl_NSLookupSymbolInImage ((struct mach_header *) module,
+ symbol,
+
NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW
+ |
+
NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
+ }
+ }
- }
- else {
- nssym = NSLookupSymbolInModule(module, symbol);
- }
- if (!nssym)
- {
- strncpy(saveError,
lt_int_dyld_error(LT_DLSTRERROR(SYMBOL_NOT_FOUND)), 255);
- saveError[255] = 0;
- if (!mh) mh=lt_int_dyld_get_mach_header_from_nsmodule(module);
- nssym = lt_int_dyld_NSlookupSymbolInLinkedLibs(symbol,mh);
- }
- if (!nssym)
- {
- LT_DLMUTEX_SETERROR (saveError);
- return NULL;
- }
- return NSAddressOfSymbol(nssym);
+ }
+ else
+ {
+ nssym = NSLookupSymbolInModule (module, symbol);
+ }
+ if (!nssym)
+ {
+ strncpy (saveError,
+ lt_int_dyld_error (LT_DLSTRERROR (SYMBOL_NOT_FOUND)), 255);
+ saveError[255] = 0;
+ if (!mh)
+ mh = lt_int_dyld_get_mach_header_from_nsmodule (module);
+ nssym = lt_int_dyld_NSlookupSymbolInLinkedLibs (symbol, mh);
+ }
+ if (!nssym)
+ {
+ LT_DLMUTEX_SETERROR (saveError);
+ return NULL;
+ }
+ return NSAddressOfSymbol (nssym);
}
static struct lt_user_dlloader sys_dyld =
@@ -1942,8 +1992,8 @@
#endif /* HAVE_DYLD */
+
-
/* --- DLPREOPEN() INTERFACE LOADER --- */
@@ -1951,12 +2001,12 @@
typedef struct lt_dlsymlists_t
{
- struct lt_dlsymlists_t *next;
- const lt_dlsymlist *syms;
+ struct lt_dlsymlists_t *next;
+ const lt_dlsymlist *syms;
} lt_dlsymlists_t;
-static const lt_dlsymlist *default_preloaded_symbols = 0;
-static lt_dlsymlists_t *preloaded_symbols = 0;
+static const lt_dlsymlist *default_preloaded_symbols = 0;
+static lt_dlsymlists_t *preloaded_symbols = 0;
static int
presym_init (loader_data)
@@ -1987,7 +2037,7 @@
lists = preloaded_symbols;
while (lists)
{
- lt_dlsymlists_t *tmp = lists;
+ lt_dlsymlists_t *tmp = lists;
lists = lists->next;
LT_DLFREE (tmp);
@@ -2013,7 +2063,7 @@
{
lt_dlsymlists_t *tmp;
lt_dlsymlists_t *lists;
- int errors = 0;
+ int errors = 0;
LT_DLMUTEX_LOCK ();
@@ -2021,16 +2071,16 @@
while (lists)
{
if (lists->syms == preloaded)
- {
- goto done;
- }
+ {
+ goto done;
+ }
lists = lists->next;
}
tmp = LT_EMALLOC (lt_dlsymlists_t, 1);
if (tmp)
{
- memset (tmp, 0, sizeof(lt_dlsymlists_t));
+ memset (tmp, 0, sizeof (lt_dlsymlists_t));
tmp->syms = preloaded;
tmp->next = preloaded_symbols;
preloaded_symbols = tmp;
@@ -2040,7 +2090,7 @@
++errors;
}
- done:
+done:
LT_DLMUTEX_UNLOCK ();
return errors;
}
@@ -2051,7 +2101,7 @@
const char *filename;
{
lt_dlsymlists_t *lists;
- lt_module module = (lt_module) 0;
+ lt_module module = (lt_module) 0;
LT_DLMUTEX_LOCK ();
lists = preloaded_symbols;
@@ -2076,21 +2126,21 @@
const lt_dlsymlist *syms = lists->syms;
while (syms->name)
- {
- if (!syms->address && strcmp(syms->name, filename) == 0)
- {
- module = (lt_module) syms;
- goto done;
- }
- ++syms;
- }
+ {
+ if (!syms->address && strcmp (syms->name, filename) == 0)
+ {
+ module = (lt_module) syms;
+ goto done;
+ }
+ ++syms;
+ }
lists = lists->next;
}
LT_DLMUTEX_SETERROR (LT_DLSTRERROR (FILE_NOT_FOUND));
- done:
+done:
LT_DLMUTEX_UNLOCK ();
return module;
}
@@ -2111,18 +2161,18 @@
lt_module module;
const char *symbol;
{
- lt_dlsymlist *syms = (lt_dlsymlist*) module;
+ lt_dlsymlist *syms = (lt_dlsymlist *) module;
++syms;
while (syms->address)
{
- if (strcmp(syms->name, symbol) == 0)
- {
- return syms->address;
- }
+ if (strcmp (syms->name, symbol) == 0)
+ {
+ return syms->address;
+ }
- ++syms;
- }
+ ++syms;
+ }
LT_DLMUTEX_SETERROR (LT_DLSTRERROR (SYMBOL_NOT_FOUND));
@@ -2132,88 +2182,80 @@
static struct lt_user_dlloader presym = {
0, presym_open, presym_close, presym_sym, presym_exit, 0
};
+
-
/* --- DYNAMIC MODULE LOADING --- */
/* The type of a function used at each iteration of foreach_dirinpath(). */
-typedef int foreach_callback_func LT_PARAMS((char *filename, lt_ptr data1,
- lt_ptr data2));
+typedef int foreach_callback_func LT_PARAMS ((char *filename, lt_ptr data1,
+ lt_ptr data2));
-static int foreach_dirinpath LT_PARAMS((const char *search_path,
- const char *base_name,
- foreach_callback_func *func,
- lt_ptr data1, lt_ptr data2));
+static int foreach_dirinpath LT_PARAMS ((const char *search_path,
+ const char *base_name,
+ foreach_callback_func * func,
+ lt_ptr data1, lt_ptr data2));
-static int find_file_callback LT_PARAMS((char *filename, lt_ptr data,
- lt_ptr ignored));
-static int find_handle_callback LT_PARAMS((char *filename, lt_ptr data,
- lt_ptr ignored));
-static int foreachfile_callback LT_PARAMS((char *filename, lt_ptr data1,
- lt_ptr data2));
+static int find_file_callback LT_PARAMS ((char *filename, lt_ptr data,
+ lt_ptr ignored));
+static int find_handle_callback LT_PARAMS ((char *filename, lt_ptr data,
+ lt_ptr ignored));
+static int foreachfile_callback LT_PARAMS ((char *filename, lt_ptr data1,
+ lt_ptr data2));
-static int canonicalize_path LT_PARAMS((const char *path,
- char **pcanonical));
-static int argzize_path LT_PARAMS((const char *path,
- char **pargz,
- size_t *pargz_len));
-static FILE *find_file LT_PARAMS((const char *search_path,
- const char *base_name,
- char **pdir));
-static lt_dlhandle *find_handle LT_PARAMS((const char *search_path,
- const char *base_name,
- lt_dlhandle *handle));
-static int find_module LT_PARAMS((lt_dlhandle *handle,
- const char *dir,
- const char *libdir,
- const char *dlname,
- const char *old_name,
- int installed));
-static int free_vars LT_PARAMS((char *dlname, char *oldname,
- char *libdir, char *deplibs));
-static int load_deplibs LT_PARAMS((lt_dlhandle handle,
- char *deplibs));
-static int trim LT_PARAMS((char **dest,
- const char *str));
-static int try_dlopen LT_PARAMS((lt_dlhandle *handle,
- const char *filename));
-static int tryall_dlopen LT_PARAMS((lt_dlhandle *handle,
- const char *filename));
-static int unload_deplibs LT_PARAMS((lt_dlhandle handle));
-static int lt_argz_insert LT_PARAMS((char **pargz,
- size_t *pargz_len,
- char *before,
- const char *entry));
-static int lt_argz_insertinorder LT_PARAMS((char **pargz,
- size_t *pargz_len,
- const char *entry));
-static int lt_argz_insertdir LT_PARAMS((char **pargz,
- size_t *pargz_len,
- const char *dirnam,
- struct dirent *dp));
-static int lt_dlpath_insertdir LT_PARAMS((char **ppath,
- char *before,
- const char *dir));
-static int list_files_by_dir LT_PARAMS((const char *dirnam,
- char **pargz,
- size_t *pargz_len));
-static int file_not_found LT_PARAMS((void));
+static int canonicalize_path LT_PARAMS ((const char *path,
+ char **pcanonical));
+static int argzize_path LT_PARAMS ((const char *path,
+ char **pargz, size_t * pargz_len));
+static FILE *find_file LT_PARAMS ((const char *search_path,
+ const char *base_name, char **pdir));
+static lt_dlhandle *find_handle LT_PARAMS ((const char *search_path,
+ const char *base_name,
+ lt_dlhandle * handle));
+static int find_module LT_PARAMS ((lt_dlhandle * handle,
+ const char *dir,
+ const char *libdir,
+ const char *dlname,
+ const char *old_name, int installed));
+static int free_vars LT_PARAMS ((char *dlname, char *oldname,
+ char *libdir, char *deplibs));
+static int load_deplibs LT_PARAMS ((lt_dlhandle handle, char *deplibs));
+static int trim LT_PARAMS ((char **dest, const char *str));
+static int try_dlopen LT_PARAMS ((lt_dlhandle * handle,
+ const char *filename));
+static int tryall_dlopen LT_PARAMS ((lt_dlhandle * handle,
+ const char *filename));
+static int unload_deplibs LT_PARAMS ((lt_dlhandle handle));
+static int lt_argz_insert LT_PARAMS ((char **pargz,
+ size_t * pargz_len,
+ char *before, const char *entry));
+static int lt_argz_insertinorder LT_PARAMS ((char **pargz,
+ size_t * pargz_len,
+ const char *entry));
+static int lt_argz_insertdir LT_PARAMS ((char **pargz,
+ size_t * pargz_len,
+ const char *dirnam,
+ struct dirent * dp));
+static int lt_dlpath_insertdir LT_PARAMS ((char **ppath,
+ char *before, const char *dir));
+static int list_files_by_dir LT_PARAMS ((const char *dirnam,
+ char **pargz, size_t * pargz_len));
+static int file_not_found LT_PARAMS ((void));
-static char *user_search_path= 0;
-static lt_dlloader *loaders = 0;
-static lt_dlhandle handles = 0;
-static int initialized = 0;
+static char *user_search_path = 0;
+static lt_dlloader *loaders = 0;
+static lt_dlhandle handles = 0;
+static int initialized = 0;
/* Initialize libltdl. */
int
lt_dlinit ()
{
- int errors = 0;
+ int errors = 0;
LT_DLMUTEX_LOCK ();
@@ -2221,7 +2263,7 @@
if (++initialized == 1)
{
handles = 0;
- user_search_path = 0; /* empty search path */
+ user_search_path = 0; /* empty search path */
#if HAVE_LIBDL
errors += lt_dlloader_add (lt_dlloader_next (0), &sys_dl, "dlopen");
@@ -2239,21 +2281,21 @@
errors += lt_dlloader_add (lt_dlloader_next (0), &sys_dld, "dld");
#endif
#if HAVE_DYLD
- errors += lt_dlloader_add (lt_dlloader_next (0), &sys_dyld, "dyld");
- errors += sys_dyld_init();
+ errors += lt_dlloader_add (lt_dlloader_next (0), &sys_dyld, "dyld");
+ errors += sys_dyld_init ();
#endif
errors += lt_dlloader_add (lt_dlloader_next (0), &presym, "dlpreload");
if (presym_init (presym.dlloader_data))
- {
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (INIT_LOADER));
- ++errors;
- }
+ {
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (INIT_LOADER));
+ ++errors;
+ }
else if (errors != 0)
- {
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (DLOPEN_NOT_SUPPORTED));
- ++errors;
- }
+ {
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (DLOPEN_NOT_SUPPORTED));
+ ++errors;
+ }
}
LT_DLMUTEX_UNLOCK ();
@@ -2273,13 +2315,13 @@
}
else
{
- presym_free_symlists();
+ presym_free_symlists ();
LT_DLMUTEX_LOCK ();
if (default_preloaded_symbols)
- {
- errors = lt_dlpreload (default_preloaded_symbols);
- }
+ {
+ errors = lt_dlpreload (default_preloaded_symbols);
+ }
LT_DLMUTEX_UNLOCK ();
}
@@ -2301,7 +2343,7 @@
{
/* shut down libltdl */
lt_dlloader *loader;
- int errors = 0;
+ int errors = 0;
LT_DLMUTEX_LOCK ();
loader = loaders;
@@ -2316,54 +2358,54 @@
/* shut down only at last call. */
if (--initialized == 0)
{
- int level;
+ int level;
while (handles && LT_DLIS_RESIDENT (handles))
- {
- handles = handles->next;
- }
+ {
+ handles = handles->next;
+ }
/* close all modules */
for (level = 1; handles; ++level)
- {
- lt_dlhandle cur = handles;
- int saw_nonresident = 0;
+ {
+ lt_dlhandle cur = handles;
+ int saw_nonresident = 0;
- while (cur)
- {
- lt_dlhandle tmp = cur;
- cur = cur->next;
- if (!LT_DLIS_RESIDENT (tmp))
- saw_nonresident = 1;
- if (!LT_DLIS_RESIDENT (tmp) && tmp->info.ref_count <= level)
- {
- if (lt_dlclose (tmp))
- {
- ++errors;
- }
- }
- }
- /* done if only resident modules are left */
- if (!saw_nonresident)
- break;
- }
+ while (cur)
+ {
+ lt_dlhandle tmp = cur;
+ cur = cur->next;
+ if (!LT_DLIS_RESIDENT (tmp))
+ saw_nonresident = 1;
+ if (!LT_DLIS_RESIDENT (tmp) && tmp->info.ref_count <= level)
+ {
+ if (lt_dlclose (tmp))
+ {
+ ++errors;
+ }
+ }
+ }
+ /* done if only resident modules are left */
+ if (!saw_nonresident)
+ break;
+ }
/* close all loaders */
while (loader)
- {
- lt_dlloader *next = loader->next;
- lt_user_data data = loader->dlloader_data;
- if (loader->dlloader_exit && loader->dlloader_exit (data))
- {
- ++errors;
- }
+ {
+ lt_dlloader *next = loader->next;
+ lt_user_data data = loader->dlloader_data;
+ if (loader->dlloader_exit && loader->dlloader_exit (data))
+ {
+ ++errors;
+ }
- LT_DLMEM_REASSIGN (loader, next);
- }
+ LT_DLMEM_REASSIGN (loader, next);
+ }
loaders = 0;
}
- done:
+done:
LT_DLMUTEX_UNLOCK ();
return errors;
}
@@ -2373,15 +2415,15 @@
lt_dlhandle *handle;
const char *filename;
{
- lt_dlhandle cur;
- lt_dlloader *loader;
- const char *saved_error;
- int errors = 0;
+ lt_dlhandle cur;
+ lt_dlloader *loader;
+ const char *saved_error;
+ int errors = 0;
LT_DLMUTEX_GETERROR (saved_error);
LT_DLMUTEX_LOCK ();
- cur = handles;
+ cur = handles;
loader = loaders;
/* check whether the module was already opened */
@@ -2389,15 +2431,15 @@
{
/* try to dlopen the program itself? */
if (!cur->info.filename && !filename)
- {
- break;
- }
+ {
+ break;
+ }
if (cur->info.filename && filename
- && strcmp (cur->info.filename, filename) == 0)
- {
- break;
- }
+ && strcmp (cur->info.filename, filename) == 0)
+ {
+ break;
+ }
cur = cur->next;
}
@@ -2413,23 +2455,23 @@
if (filename)
{
/* Comment out the check of file permissions using access.
- This call seems to always return -1 with error EACCES.
- */
+ This call seems to always return -1 with error EACCES.
+ */
/* We need to catch missing file errors early so that
- file_not_found() can detect what happened.
- if (access (filename, R_OK) != 0)
- {
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (FILE_NOT_FOUND));
- ++errors;
- goto done;
- } */
+ file_not_found() can detect what happened.
+ if (access (filename, R_OK) != 0)
+ {
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (FILE_NOT_FOUND));
+ ++errors;
+ goto done;
+ } */
cur->info.filename = lt_estrdup (filename);
if (!cur->info.filename)
- {
- ++errors;
- goto done;
- }
+ {
+ ++errors;
+ goto done;
+ }
}
else
{
@@ -2443,9 +2485,9 @@
cur->module = loader->module_open (data, filename);
if (cur->module != 0)
- {
- break;
- }
+ {
+ break;
+ }
loader = loader->next;
}
@@ -2456,10 +2498,10 @@
goto done;
}
- cur->loader = loader;
+ cur->loader = loader;
LT_DLMUTEX_SETERROR (saved_error);
- done:
+done:
LT_DLMUTEX_UNLOCK ();
return errors;
@@ -2472,10 +2514,10 @@
const char *dirname;
const char *dlname;
{
- int error = 0;
- char *filename = 0;
- size_t filename_len = 0;
- size_t dirname_len = LT_STRLEN (dirname);
+ int error = 0;
+ char *filename = 0;
+ size_t filename_len = 0;
+ size_t dirname_len = LT_STRLEN (dirname);
assert (handle);
assert (dirname);
@@ -2487,13 +2529,13 @@
#endif
if (dirname_len > 0)
- if (dirname[dirname_len -1] == '/')
+ if (dirname[dirname_len - 1] == '/')
--dirname_len;
filename_len = dirname_len + 1 + LT_STRLEN (dlname);
/* Allocate memory, and combine DIRNAME and MODULENAME into it.
The PREFIX (if any) is handled below. */
- filename = LT_EMALLOC (char, dirname_len + 1 + filename_len + 1);
+ filename = LT_EMALLOC (char, dirname_len + 1 + filename_len + 1);
if (!filename)
return 1;
@@ -2505,7 +2547,7 @@
if (prefix)
{
error += tryall_dlopen_module (handle,
- (const char *) 0, prefix, filename);
+ (const char *) 0, prefix, filename);
}
else if (tryall_dlopen (handle, filename) != 0)
{
@@ -2538,24 +2580,25 @@
{
/* try to open the installed module */
if (installed && libdir)
- {
- if (tryall_dlopen_module (handle,
- (const char *) 0, libdir, dlname) == 0)
- return 0;
- }
+ {
+ if (tryall_dlopen_module (handle,
+ (const char *) 0, libdir, dlname) == 0)
+ return 0;
+ }
/* try to open the not-installed module */
if (!installed)
- {
- if (tryall_dlopen_module (handle, dir, objdir, dlname) == 0)
- return 0;
- }
+ {
+ if (tryall_dlopen_module (handle, dir, objdir, dlname) == 0)
+ return 0;
+ }
/* maybe it was moved to another directory */
{
- if (dir && (tryall_dlopen_module (handle,
- (const char *) 0, dir, dlname) == 0))
- return 0;
+ if (dir && (tryall_dlopen_module (handle,
+ (const char *) 0, dir,
+ dlname) == 0))
+ return 0;
}
}
@@ -2573,7 +2616,7 @@
assert (path && *path);
assert (pcanonical);
- canonical = LT_EMALLOC (char, 1+ LT_STRLEN (path));
+ canonical = LT_EMALLOC (char, 1 + LT_STRLEN (path));
if (!canonical)
return 1;
@@ -2582,38 +2625,38 @@
size_t src;
for (src = 0; path[src] != LT_EOS_CHAR; ++src)
{
- /* Path separators are not copied to the beginning or end of
- the destination, or if another separator would follow
- immediately. */
- if (path[src] == LT_PATHSEP_CHAR)
- {
- if ((dest == 0)
- || (path[1+ src] == LT_PATHSEP_CHAR)
- || (path[1+ src] == LT_EOS_CHAR))
- continue;
- }
+ /* Path separators are not copied to the beginning or end of
+ the destination, or if another separator would follow
+ immediately. */
+ if (path[src] == LT_PATHSEP_CHAR)
+ {
+ if ((dest == 0)
+ || (path[1 + src] == LT_PATHSEP_CHAR)
+ || (path[1 + src] == LT_EOS_CHAR))
+ continue;
+ }
- /* Anything other than a directory separator is copied verbatim. */
- if ((path[src] != '/')
+ /* Anything other than a directory separator is copied verbatim. */
+ if ((path[src] != '/')
#ifdef LT_DIRSEP_CHAR
- && (path[src] != LT_DIRSEP_CHAR)
+ && (path[src] != LT_DIRSEP_CHAR)
#endif
- )
- {
- canonical[dest++] = path[src];
- }
- /* Directory separators are converted and copied only if they are
- not at the end of a path -- i.e. before a path separator or
- NULL terminator. */
- else if ((path[1+ src] != LT_PATHSEP_CHAR)
- && (path[1+ src] != LT_EOS_CHAR)
+ )
+ {
+ canonical[dest++] = path[src];
+ }
+ /* Directory separators are converted and copied only if they are
+ not at the end of a path -- i.e. before a path separator or
+ NULL terminator. */
+ else if ((path[1 + src] != LT_PATHSEP_CHAR)
+ && (path[1 + src] != LT_EOS_CHAR)
#ifdef LT_DIRSEP_CHAR
- && (path[1+ src] != LT_DIRSEP_CHAR)
+ && (path[1 + src] != LT_DIRSEP_CHAR)
#endif
- && (path[1+ src] != '/'))
- {
- canonical[dest++] = '/';
- }
+ && (path[1 + src] != '/'))
+ {
+ canonical[dest++] = '/';
+ }
}
/* Add an end-of-string marker at the end. */
@@ -2641,14 +2684,14 @@
if ((error = argz_create_sep (path, LT_PATHSEP_CHAR, pargz, pargz_len)))
{
switch (error)
- {
- case ENOMEM:
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (NO_MEMORY));
- break;
- default:
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (UNKNOWN));
- break;
- }
+ {
+ case ENOMEM:
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (NO_MEMORY));
+ break;
+ default:
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (UNKNOWN));
+ break;
+ }
return 1;
}
@@ -2668,13 +2711,13 @@
lt_ptr data1;
lt_ptr data2;
{
- int result = 0;
- int filenamesize = 0;
- size_t lenbase = LT_STRLEN (base_name);
- size_t argz_len = 0;
- char *argz = 0;
- char *filename = 0;
- char *canonical = 0;
+ int result = 0;
+ int filenamesize = 0;
+ size_t lenbase = LT_STRLEN (base_name);
+ size_t argz_len = 0;
+ char *argz = 0;
+ char *filename = 0;
+ char *canonical = 0;
LT_DLMUTEX_LOCK ();
@@ -2694,35 +2737,35 @@
char *dir_name = 0;
while ((dir_name = argz_next (argz, argz_len, dir_name)))
{
- size_t lendir = LT_STRLEN (dir_name);
+ size_t lendir = LT_STRLEN (dir_name);
- if (lendir +1 +lenbase >= filenamesize)
- {
- LT_DLFREE (filename);
- filenamesize = lendir +1 +lenbase +1; /* "/d" + '/' + "f" + '\0' */
- filename = LT_EMALLOC (char, filenamesize);
- if (!filename)
- goto cleanup;
- }
+ if (lendir + 1 + lenbase >= filenamesize)
+ {
+ LT_DLFREE (filename);
+ filenamesize = lendir + 1 + lenbase + 1; /* "/d" + '/' + "f" +
'\0' */
+ filename = LT_EMALLOC (char, filenamesize);
+ if (!filename)
+ goto cleanup;
+ }
- assert (filenamesize > lendir);
- strcpy (filename, dir_name);
+ assert (filenamesize > lendir);
+ strcpy (filename, dir_name);
- if (base_name && *base_name)
- {
- if (filename[lendir -1] != '/')
- filename[lendir++] = '/';
- strcpy (filename +lendir, base_name);
- }
+ if (base_name && *base_name)
+ {
+ if (filename[lendir - 1] != '/')
+ filename[lendir++] = '/';
+ strcpy (filename + lendir, base_name);
+ }
- if ((result = (*func) (filename, data1, data2)))
- {
- break;
- }
+ if ((result = (*func) (filename, data1, data2)))
+ {
+ break;
+ }
}
}
- cleanup:
+cleanup:
LT_DLFREE (argz);
LT_DLFREE (canonical);
LT_DLFREE (filename);
@@ -2741,9 +2784,9 @@
lt_ptr data1;
lt_ptr data2;
{
- char **pdir = (char **) data1;
- FILE **pfile = (FILE **) data2;
- int is_done = 0;
+ char **pdir = (char **) data1;
+ FILE **pfile = (FILE **) data2;
+ int is_done = 0;
assert (filename && *filename);
assert (pdir);
@@ -2754,10 +2797,10 @@
char *dirend = strrchr (filename, '/');
if (dirend > filename)
- *dirend = LT_EOS_CHAR;
+ *dirend = LT_EOS_CHAR;
LT_DLFREE (*pdir);
- *pdir = lt_estrdup (filename);
+ *pdir = lt_estrdup (filename);
is_done = (*pdir == 0) ? -1 : 1;
}
@@ -2783,8 +2826,8 @@
lt_ptr data;
lt_ptr ignored;
{
- lt_dlhandle *handle = (lt_dlhandle *) data;
- int notfound = access (filename, R_OK);
+ lt_dlhandle *handle = (lt_dlhandle *) data;
+ int notfound = access (filename, R_OK);
/* Bail out if file cannot be read... */
if (notfound)
@@ -2810,7 +2853,7 @@
return 0;
if (!foreach_dirinpath (search_path, base_name, find_handle_callback,
- handle, 0))
+ handle, 0))
return 0;
return handle;
@@ -2822,12 +2865,12 @@
char *deplibs;
{
#if LTDL_DLOPEN_DEPLIBS
- char *p, *save_search_path = 0;
- int depcount = 0;
- int i;
- char **names = 0;
+ char *p, *save_search_path = 0;
+ int depcount = 0;
+ int i;
+ char **names = 0;
#endif
- int errors = 0;
+ int errors = 0;
handle->depcount = 0;
@@ -2843,7 +2886,7 @@
{
save_search_path = lt_estrdup (user_search_path);
if (!save_search_path)
- goto cleanup;
+ goto cleanup;
}
/* extract search paths and count deplibs */
@@ -2851,34 +2894,34 @@
while (*p)
{
if (!isspace ((int) *p))
- {
- char *end = p+1;
- while (*end && !isspace((int) *end))
- {
- ++end;
- }
+ {
+ char *end = p + 1;
+ while (*end && !isspace ((int) *end))
+ {
+ ++end;
+ }
- if (strncmp(p, "-L", 2) == 0 || strncmp(p, "-R", 2) == 0)
- {
- char save = *end;
- *end = 0; /* set a temporary string terminator */
- if (lt_dladdsearchdir(p+2))
- {
- goto cleanup;
- }
- *end = save;
- }
- else
- {
- ++depcount;
- }
+ if (strncmp (p, "-L", 2) == 0 || strncmp (p, "-R", 2) == 0)
+ {
+ char save = *end;
+ *end = 0; /* set a temporary string terminator */
+ if (lt_dladdsearchdir (p + 2))
+ {
+ goto cleanup;
+ }
+ *end = save;
+ }
+ else
+ {
+ ++depcount;
+ }
- p = end;
- }
+ p = end;
+ }
else
- {
- ++p;
- }
+ {
+ ++p;
+ }
}
if (!depcount)
@@ -2887,7 +2930,7 @@
goto cleanup;
}
- names = LT_EMALLOC (char *, depcount * sizeof (char*));
+ names = LT_EMALLOC (char *, depcount * sizeof (char *));
if (!names)
goto cleanup;
@@ -2897,40 +2940,40 @@
while (*p)
{
if (isspace ((int) *p))
- {
- ++p;
- }
+ {
+ ++p;
+ }
else
- {
- char *end = p+1;
- while (*end && !isspace ((int) *end))
- {
- ++end;
- }
+ {
+ char *end = p + 1;
+ while (*end && !isspace ((int) *end))
+ {
+ ++end;
+ }
- if (strncmp(p, "-L", 2) != 0 && strncmp(p, "-R", 2) != 0)
- {
- char *name;
- char save = *end;
- *end = 0; /* set a temporary string terminator */
- if (strncmp(p, "-l", 2) == 0)
- {
- size_t name_len = 3+ /* "lib" */ LT_STRLEN (p + 2);
- name = LT_EMALLOC (char, 1+ name_len);
- if (name)
- sprintf (name, "lib%s", p+2);
- }
- else
- name = lt_estrdup(p);
+ if (strncmp (p, "-L", 2) != 0 && strncmp (p, "-R", 2) != 0)
+ {
+ char *name;
+ char save = *end;
+ *end = 0; /* set a temporary string terminator */
+ if (strncmp (p, "-l", 2) == 0)
+ {
+ size_t name_len = 3 + /* "lib" */ LT_STRLEN (p + 2);
+ name = LT_EMALLOC (char, 1 + name_len);
+ if (name)
+ sprintf (name, "lib%s", p + 2);
+ }
+ else
+ name = lt_estrdup (p);
- if (!name)
- goto cleanup_names;
+ if (!name)
+ goto cleanup_names;
- names[depcount++] = name;
- *end = save;
- }
- p = end;
- }
+ names[depcount++] = name;
+ *end = save;
+ }
+ p = end;
+ }
}
/* load the deplibs (in reverse order)
@@ -2940,38 +2983,39 @@
later on if the loaded module cannot resolve all of its symbols. */
if (depcount)
{
- int j = 0;
+ int j = 0;
- handle->deplibs = (lt_dlhandle*) LT_EMALLOC (lt_dlhandle *, depcount);
+ handle->deplibs = (lt_dlhandle *) LT_EMALLOC (lt_dlhandle *, depcount);
if (!handle->deplibs)
- goto cleanup;
+ goto cleanup;
for (i = 0; i < depcount; ++i)
- {
- handle->deplibs[j] = lt_dlopenext(names[depcount-1-i]);
- if (handle->deplibs[j])
- {
- ++j;
- }
- }
+ {
+ handle->deplibs[j] = lt_dlopenext (names[depcount - 1 - i]);
+ if (handle->deplibs[j])
+ {
+ ++j;
+ }
+ }
- handle->depcount = j; /* Number of successfully loaded deplibs */
- errors = 0;
+ handle->depcount = j; /* Number of successfully loaded deplibs */
+ errors = 0;
}
- cleanup_names:
+cleanup_names:
for (i = 0; i < depcount; ++i)
{
LT_DLFREE (names[i]);
}
- cleanup:
+cleanup:
LT_DLFREE (names);
/* restore the old search path */
- if (user_search_path) {
- LT_DLFREE (user_search_path);
- user_search_path = save_search_path;
- }
+ if (user_search_path)
+ {
+ LT_DLFREE (user_search_path);
+ user_search_path = save_search_path;
+ }
LT_DLMUTEX_UNLOCK ();
#endif
@@ -2989,12 +3033,12 @@
if (handle->depcount)
{
for (i = 0; i < handle->depcount; ++i)
- {
- if (!LT_DLIS_RESIDENT (handle->deplibs[i]))
- {
- errors += lt_dlclose (handle->deplibs[i]);
- }
- }
+ {
+ if (!LT_DLIS_RESIDENT (handle->deplibs[i]))
+ {
+ errors += lt_dlclose (handle->deplibs[i]);
+ }
+ }
}
return errors;
@@ -3007,8 +3051,8 @@
{
/* remove the leading and trailing "'" from str
and store the result in dest */
- const char *end = strrchr (str, '\'');
- size_t len = LT_STRLEN (str);
+ const char *end = strrchr (str, '\'');
+ size_t len = LT_STRLEN (str);
char *tmp;
LT_DLFREE (*dest);
@@ -3020,10 +3064,10 @@
{
tmp = LT_EMALLOC (char, end - str);
if (!tmp)
- return 1;
+ return 1;
- strncpy(tmp, &str[1], (end - str) - 1);
- tmp[len-3] = LT_EOS_CHAR;
+ strncpy (tmp, &str[1], (end - str) - 1);
+ tmp[len - 3] = LT_EOS_CHAR;
*dest = tmp;
}
else
@@ -3054,14 +3098,14 @@
lt_dlhandle *phandle;
const char *filename;
{
- const char * ext = 0;
- const char * saved_error = 0;
- char * canonical = 0;
- char * base_name = 0;
- char * dir = 0;
- char * name = 0;
- int errors = 0;
- lt_dlhandle newhandle;
+ const char *ext = 0;
+ const char *saved_error = 0;
+ char *canonical = 0;
+ char *base_name = 0;
+ char *dir = 0;
+ char *name = 0;
+ int errors = 0;
+ lt_dlhandle newhandle;
assert (phandle);
assert (*phandle == 0);
@@ -3073,19 +3117,19 @@
{
*phandle = (lt_dlhandle) LT_EMALLOC (struct lt_dlhandle_struct, 1);
if (*phandle == 0)
- return 1;
+ return 1;
- memset (*phandle, 0, sizeof(struct lt_dlhandle_struct));
- newhandle = *phandle;
+ memset (*phandle, 0, sizeof (struct lt_dlhandle_struct));
+ newhandle = *phandle;
/* lt_dlclose()ing yourself is very bad! Disallow it. */
LT_DLSET_FLAG (*phandle, LT_DLRESIDENT_FLAG);
if (tryall_dlopen (&newhandle, 0) != 0)
- {
- LT_DLFREE (*phandle);
- return 1;
- }
+ {
+ LT_DLFREE (*phandle);
+ return 1;
+ }
goto register_handle;
}
@@ -3105,14 +3149,14 @@
base_name = strrchr (canonical, '/');
if (base_name)
{
- size_t dirlen = (1+ base_name) - canonical;
+ size_t dirlen = (1 + base_name) - canonical;
- dir = LT_EMALLOC (char, 1+ dirlen);
+ dir = LT_EMALLOC (char, 1 + dirlen);
if (!dir)
- {
- ++errors;
- goto cleanup;
- }
+ {
+ ++errors;
+ goto cleanup;
+ }
strncpy (dir, canonical, dirlen);
dir[dirlen] = LT_EOS_CHAR;
@@ -3129,41 +3173,41 @@
if (ext && strcmp (ext, archive_ext) == 0)
{
/* this seems to be a libtool module */
- FILE * file = 0;
- char * dlname = 0;
- char * old_name = 0;
- char * libdir = 0;
- char * deplibs = 0;
- char * line = 0;
- size_t line_len;
+ FILE *file = 0;
+ char *dlname = 0;
+ char *old_name = 0;
+ char *libdir = 0;
+ char *deplibs = 0;
+ char *line = 0;
+ size_t line_len;
/* if we can't find the installed flag, it is probably an
- installed libtool archive, produced with an old version
- of libtool */
- int installed = 1;
+ installed libtool archive, produced with an old version
+ of libtool */
+ int installed = 1;
/* extract the module name from the file name */
name = LT_EMALLOC (char, ext - base_name + 1);
if (!name)
- {
- ++errors;
- goto cleanup;
- }
+ {
+ ++errors;
+ goto cleanup;
+ }
/* canonicalize the module name */
{
size_t i;
for (i = 0; i < ext - base_name; ++i)
- {
- if (isalnum ((int)(base_name[i])))
- {
- name[i] = base_name[i];
- }
- else
- {
- name[i] = '_';
- }
- }
+ {
+ if (isalnum ((int) (base_name[i])))
+ {
+ name[i] = base_name[i];
+ }
+ else
+ {
+ name[i] = '_';
+ }
+ }
name[ext - base_name] = LT_EOS_CHAR;
}
@@ -3172,146 +3216,145 @@
prescribed paths. Otherwise (or in any case if the module was not
yet found) try opening just the module name as passed. */
if (!dir)
- {
- const char *search_path;
+ {
+ const char *search_path;
- LT_DLMUTEX_LOCK ();
- search_path = user_search_path;
- if (search_path)
- file = find_file (user_search_path, base_name, &dir);
- LT_DLMUTEX_UNLOCK ();
+ LT_DLMUTEX_LOCK ();
+ search_path = user_search_path;
+ if (search_path)
+ file = find_file (user_search_path, base_name, &dir);
+ LT_DLMUTEX_UNLOCK ();
- if (!file)
- {
- search_path = getenv (LTDL_SEARCHPATH_VAR);
- if (search_path)
- file = find_file (search_path, base_name, &dir);
- }
+ if (!file)
+ {
+ search_path = getenv (LTDL_SEARCHPATH_VAR);
+ if (search_path)
+ file = find_file (search_path, base_name, &dir);
+ }
#ifdef LTDL_SHLIBPATH_VAR
- if (!file)
- {
- search_path = getenv (LTDL_SHLIBPATH_VAR);
- if (search_path)
- file = find_file (search_path, base_name, &dir);
- }
+ if (!file)
+ {
+ search_path = getenv (LTDL_SHLIBPATH_VAR);
+ if (search_path)
+ file = find_file (search_path, base_name, &dir);
+ }
#endif
#ifdef LTDL_SYSSEARCHPATH
- if (!file && sys_search_path)
- {
- file = find_file (sys_search_path, base_name, &dir);
- }
+ if (!file && sys_search_path)
+ {
+ file = find_file (sys_search_path, base_name, &dir);
+ }
#endif
- }
+ }
if (!file)
- {
- file = fopen (filename, LT_READTEXT_MODE);
- }
+ {
+ file = fopen (filename, LT_READTEXT_MODE);
+ }
/* If we didn't find the file by now, it really isn't there. Set
- the status flag, and bail out. */
+ the status flag, and bail out. */
if (!file)
- {
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (FILE_NOT_FOUND));
- ++errors;
- goto cleanup;
- }
+ {
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (FILE_NOT_FOUND));
+ ++errors;
+ goto cleanup;
+ }
line_len = LT_FILENAME_MAX;
line = LT_EMALLOC (char, line_len);
if (!line)
- {
- fclose (file);
- ++errors;
- goto cleanup;
- }
+ {
+ fclose (file);
+ ++errors;
+ goto cleanup;
+ }
/* read the .la file */
while (!feof (file))
- {
- if (!fgets (line, (int) line_len, file))
- {
- break;
- }
+ {
+ if (!fgets (line, (int) line_len, file))
+ {
+ break;
+ }
- /* Handle the case where we occasionally need to read a line
- that is longer than the initial buffer size. */
- while ((line[LT_STRLEN(line) -1] != '\n') && (!feof (file)))
- {
- line = LT_DLREALLOC (char, line, line_len *2);
- if (!fgets (&line[line_len -1], (int) line_len +1, file))
- {
- break;
- }
- line_len *= 2;
- }
+ /* Handle the case where we occasionally need to read a line
+ that is longer than the initial buffer size. */
+ while ((line[LT_STRLEN (line) - 1] != '\n') && (!feof (file)))
+ {
+ line = LT_DLREALLOC (char, line, line_len * 2);
+ if (!fgets (&line[line_len - 1], (int) line_len + 1, file))
+ {
+ break;
+ }
+ line_len *= 2;
+ }
- if (line[0] == '\n' || line[0] == '#')
- {
- continue;
- }
+ if (line[0] == '\n' || line[0] == '#')
+ {
+ continue;
+ }
#undef STR_DLNAME
#define STR_DLNAME "dlname="
- if (strncmp (line, STR_DLNAME, sizeof (STR_DLNAME) - 1) == 0)
- {
- errors += trim (&dlname, &line[sizeof (STR_DLNAME) - 1]);
- }
+ if (strncmp (line, STR_DLNAME, sizeof (STR_DLNAME) - 1) == 0)
+ {
+ errors += trim (&dlname, &line[sizeof (STR_DLNAME) - 1]);
+ }
#undef STR_OLD_LIBRARY
#define STR_OLD_LIBRARY "old_library="
- else if (strncmp (line, STR_OLD_LIBRARY,
- sizeof (STR_OLD_LIBRARY) - 1) == 0)
- {
- errors += trim (&old_name, &line[sizeof (STR_OLD_LIBRARY) - 1]);
- }
+ else if (strncmp (line, STR_OLD_LIBRARY,
+ sizeof (STR_OLD_LIBRARY) - 1) == 0)
+ {
+ errors += trim (&old_name, &line[sizeof (STR_OLD_LIBRARY) - 1]);
+ }
#undef STR_LIBDIR
#define STR_LIBDIR "libdir="
- else if (strncmp (line, STR_LIBDIR, sizeof (STR_LIBDIR) - 1) == 0)
- {
- errors += trim (&libdir, &line[sizeof(STR_LIBDIR) - 1]);
- }
+ else if (strncmp (line, STR_LIBDIR, sizeof (STR_LIBDIR) - 1) == 0)
+ {
+ errors += trim (&libdir, &line[sizeof (STR_LIBDIR) - 1]);
+ }
#undef STR_DL_DEPLIBS
#define STR_DL_DEPLIBS "dependency_libs="
- else if (strncmp (line, STR_DL_DEPLIBS,
- sizeof (STR_DL_DEPLIBS) - 1) == 0)
- {
- errors += trim (&deplibs, &line[sizeof (STR_DL_DEPLIBS) - 1]);
- }
- else if (strcmp (line, "installed=yes\n") == 0)
- {
- installed = 1;
- }
- else if (strcmp (line, "installed=no\n") == 0)
- {
- installed = 0;
- }
+ else if (strncmp (line, STR_DL_DEPLIBS,
+ sizeof (STR_DL_DEPLIBS) - 1) == 0)
+ {
+ errors += trim (&deplibs, &line[sizeof (STR_DL_DEPLIBS) - 1]);
+ }
+ else if (strcmp (line, "installed=yes\n") == 0)
+ {
+ installed = 1;
+ }
+ else if (strcmp (line, "installed=no\n") == 0)
+ {
+ installed = 0;
+ }
#undef STR_LIBRARY_NAMES
#define STR_LIBRARY_NAMES "library_names="
- else if (! dlname && strncmp (line, STR_LIBRARY_NAMES,
- sizeof (STR_LIBRARY_NAMES) - 1) == 0)
- {
- char *last_libname;
- errors += trim (&dlname, &line[sizeof (STR_LIBRARY_NAMES) - 1]);
- if (!errors
- && dlname
- && (last_libname = strrchr (dlname, ' ')) != 0)
- {
- last_libname = lt_estrdup (last_libname + 1);
- if (!last_libname)
- {
- ++errors;
- goto cleanup;
- }
- LT_DLMEM_REASSIGN (dlname, last_libname);
- }
- }
+ else if (!dlname && strncmp (line, STR_LIBRARY_NAMES,
+ sizeof (STR_LIBRARY_NAMES) - 1) == 0)
+ {
+ char *last_libname;
+ errors += trim (&dlname, &line[sizeof (STR_LIBRARY_NAMES) - 1]);
+ if (!errors
+ && dlname && (last_libname = strrchr (dlname, ' ')) != 0)
+ {
+ last_libname = lt_estrdup (last_libname + 1);
+ if (!last_libname)
+ {
+ ++errors;
+ goto cleanup;
+ }
+ LT_DLMEM_REASSIGN (dlname, last_libname);
+ }
+ }
- if (errors)
- break;
- }
+ if (errors)
+ break;
+ }
fclose (file);
LT_DLFREE (line);
@@ -3319,105 +3362,106 @@
/* allocate the handle */
*phandle = (lt_dlhandle) LT_EMALLOC (struct lt_dlhandle_struct, 1);
if (*phandle == 0)
- ++errors;
+ ++errors;
if (errors)
- {
- free_vars (dlname, old_name, libdir, deplibs);
- LT_DLFREE (*phandle);
- goto cleanup;
- }
+ {
+ free_vars (dlname, old_name, libdir, deplibs);
+ LT_DLFREE (*phandle);
+ goto cleanup;
+ }
assert (*phandle);
- memset (*phandle, 0, sizeof(struct lt_dlhandle_struct));
+ memset (*phandle, 0, sizeof (struct lt_dlhandle_struct));
if (load_deplibs (*phandle, deplibs) == 0)
- {
- newhandle = *phandle;
- /* find_module may replace newhandle */
- if (find_module (&newhandle, dir, libdir, dlname, old_name,
installed))
- {
- unload_deplibs (*phandle);
- ++errors;
- }
- }
+ {
+ newhandle = *phandle;
+ /* find_module may replace newhandle */
+ if (find_module
+ (&newhandle, dir, libdir, dlname, old_name, installed))
+ {
+ unload_deplibs (*phandle);
+ ++errors;
+ }
+ }
else
- {
- ++errors;
- }
+ {
+ ++errors;
+ }
free_vars (dlname, old_name, libdir, deplibs);
if (errors)
- {
- LT_DLFREE (*phandle);
- goto cleanup;
- }
+ {
+ LT_DLFREE (*phandle);
+ goto cleanup;
+ }
if (*phandle != newhandle)
- {
- unload_deplibs (*phandle);
- }
+ {
+ unload_deplibs (*phandle);
+ }
}
else
{
/* not a libtool module */
*phandle = (lt_dlhandle) LT_EMALLOC (struct lt_dlhandle_struct, 1);
if (*phandle == 0)
- {
- ++errors;
- goto cleanup;
- }
+ {
+ ++errors;
+ goto cleanup;
+ }
memset (*phandle, 0, sizeof (struct lt_dlhandle_struct));
newhandle = *phandle;
/* If the module has no directory name component, try to find it
- first in user_search_path and then other prescribed paths.
- Otherwise (or in any case if the module was not yet found) try
- opening just the module name as passed. */
+ first in user_search_path and then other prescribed paths.
+ Otherwise (or in any case if the module was not yet found) try
+ opening just the module name as passed. */
if ((dir || (!find_handle (user_search_path, base_name, &newhandle)
- && !find_handle (getenv (LTDL_SEARCHPATH_VAR), base_name,
- &newhandle)
+ && !find_handle (getenv (LTDL_SEARCHPATH_VAR), base_name,
+ &newhandle)
#ifdef LTDL_SHLIBPATH_VAR
- && !find_handle (getenv (LTDL_SHLIBPATH_VAR), base_name,
- &newhandle)
+ && !find_handle (getenv (LTDL_SHLIBPATH_VAR), base_name,
+ &newhandle)
#endif
#ifdef LTDL_SYSSEARCHPATH
- && !find_handle (sys_search_path, base_name, &newhandle)
+ && !find_handle (sys_search_path, base_name, &newhandle)
#endif
- )))
- {
+ )))
+ {
if (tryall_dlopen (&newhandle, filename) != 0)
{
newhandle = NULL;
}
- }
+ }
if (!newhandle)
- {
- LT_DLFREE (*phandle);
- ++errors;
- goto cleanup;
- }
+ {
+ LT_DLFREE (*phandle);
+ ++errors;
+ goto cleanup;
+ }
}
- register_handle:
+register_handle:
LT_DLMEM_REASSIGN (*phandle, newhandle);
if ((*phandle)->info.ref_count == 0)
{
- (*phandle)->info.ref_count = 1;
+ (*phandle)->info.ref_count = 1;
LT_DLMEM_REASSIGN ((*phandle)->info.name, name);
LT_DLMUTEX_LOCK ();
- (*phandle)->next = handles;
- handles = *phandle;
+ (*phandle)->next = handles;
+ handles = *phandle;
LT_DLMUTEX_UNLOCK ();
}
LT_DLMUTEX_SETERROR (saved_error);
- cleanup:
+cleanup:
LT_DLFREE (dir);
LT_DLFREE (name);
LT_DLFREE (canonical);
@@ -3461,11 +3505,11 @@
lt_dlopenext (filename)
const char *filename;
{
- lt_dlhandle handle = 0;
- char * tmp = 0;
- char * ext = 0;
- size_t len;
- int errors = 0;
+ lt_dlhandle handle = 0;
+ char *tmp = 0;
+ char *ext = 0;
+ size_t len;
+ int errors = 0;
if (!filename)
{
@@ -3481,7 +3525,7 @@
to try appending additional extensions. */
if (ext && ((strcmp (ext, archive_ext) == 0)
#ifdef LTDL_SHLIB_EXT
- || (strcmp (ext, shlib_ext) == 0)
+ || (strcmp (ext, shlib_ext) == 0)
#endif
))
{
@@ -3515,7 +3559,7 @@
LT_DLFREE (tmp);
tmp = LT_EMALLOC (char, len + LT_STRLEN (shlib_ext) + 1);
if (!tmp)
- return 0;
+ return 0;
strcpy (tmp, filename);
}
@@ -3524,7 +3568,7 @@
tmp[len] = LT_EOS_CHAR;
}
- strcat(tmp, shlib_ext);
+ strcat (tmp, shlib_ext);
errors = try_dlopen (&handle, tmp);
/* As before, if the file was found but loading failed, return now
@@ -3563,14 +3607,14 @@
if (error)
{
switch (error)
- {
- case ENOMEM:
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (NO_MEMORY));
- break;
- default:
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (UNKNOWN));
- break;
- }
+ {
+ case ENOMEM:
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (NO_MEMORY));
+ break;
+ default:
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (UNKNOWN));
+ break;
+ }
return 1;
}
@@ -3592,10 +3636,12 @@
if (*pargz)
while ((before = argz_next (*pargz, *pargz_len, before)))
{
- int cmp = strcmp (entry, before);
+ int cmp = strcmp (entry, before);
- if (cmp < 0) break;
- if (cmp == 0) return 0; /* No duplicates! */
+ if (cmp < 0)
+ break;
+ if (cmp == 0)
+ return 0; /* No duplicates! */
}
return lt_argz_insert (pargz, pargz_len, before, entry);
@@ -3608,26 +3654,26 @@
const char *dirnam;
struct dirent *dp;
{
- char *buf = 0;
- size_t buf_len = 0;
- char *end = 0;
+ char *buf = 0;
+ size_t buf_len = 0;
+ char *end = 0;
size_t end_offset = 0;
- size_t dir_len = 0;
- int errors = 0;
+ size_t dir_len = 0;
+ int errors = 0;
assert (pargz);
assert (pargz_len);
assert (dp);
dir_len = LT_STRLEN (dirnam);
- end = dp->d_name + LT_D_NAMLEN(dp);
+ end = dp->d_name + LT_D_NAMLEN (dp);
/* Ignore version numbers. */
{
char *p;
- for (p = end; p -1 > dp->d_name; --p)
+ for (p = end; p - 1 > dp->d_name; --p)
if (strchr (".0123456789", p[-1]) == 0)
- break;
+ break;
if (*p == '.')
end = p;
@@ -3636,25 +3682,25 @@
/* Ignore filename extension. */
{
char *p;
- for (p = end -1; p > dp->d_name; --p)
+ for (p = end - 1; p > dp->d_name; --p)
if (*p == '.')
- {
- end = p;
- break;
- }
+ {
+ end = p;
+ break;
+ }
}
/* Prepend the directory name. */
- end_offset = end - dp->d_name;
- buf_len = dir_len + 1+ end_offset;
- buf = LT_EMALLOC (char, 1+ buf_len);
+ end_offset = end - dp->d_name;
+ buf_len = dir_len + 1 + end_offset;
+ buf = LT_EMALLOC (char, 1 + buf_len);
if (!buf)
return ++errors;
assert (buf);
- strcpy (buf, dirnam);
- strcat (buf, "/");
+ strcpy (buf, dirnam);
+ strcat (buf, "/");
strncat (buf, dp->d_name, end_offset);
buf[buf_len] = LT_EOS_CHAR;
@@ -3673,26 +3719,26 @@
char **pargz;
size_t *pargz_len;
{
- DIR *dirp = 0;
- int errors = 0;
+ DIR *dirp = 0;
+ int errors = 0;
assert (dirnam && *dirnam);
assert (pargz);
assert (pargz_len);
- assert (dirnam[LT_STRLEN(dirnam) -1] != '/');
+ assert (dirnam[LT_STRLEN (dirnam) - 1] != '/');
dirp = opendir (dirnam);
if (dirp)
{
- struct dirent *dp = 0;
+ struct dirent *dp = 0;
while ((dp = readdir (dirp)))
- if (dp->d_name[0] != '.')
- if (lt_argz_insertdir (pargz, pargz_len, dirnam, dp))
- {
- ++errors;
- break;
- }
+ if (dp->d_name[0] != '.')
+ if (lt_argz_insertdir (pargz, pargz_len, dirnam, dp))
+ {
+ ++errors;
+ break;
+ }
closedir (dirp);
}
@@ -3711,12 +3757,12 @@
lt_ptr data1;
lt_ptr data2;
{
- int (*func) LT_PARAMS((const char *filename, lt_ptr data))
- = (int (*) LT_PARAMS((const char *filename, lt_ptr data))) data1;
+ int (*func) LT_PARAMS ((const char *filename, lt_ptr data))
+ = (int (*)LT_PARAMS ((const char *filename, lt_ptr data))) data1;
- int is_done = 0;
- char *argz = 0;
- size_t argz_len = 0;
+ int is_done = 0;
+ char *argz = 0;
+ size_t argz_len = 0;
if (list_files_by_dir (dirname, &argz, &argz_len) != 0)
goto cleanup;
@@ -3727,10 +3773,10 @@
char *filename = 0;
while ((filename = argz_next (argz, argz_len, filename)))
if ((is_done = (*func) (filename, data2)))
- break;
+ break;
}
- cleanup:
+cleanup:
LT_DLFREE (argz);
return is_done;
@@ -3754,34 +3800,34 @@
if (search_path)
{
/* If a specific path was passed, search only the directories
- listed in it. */
+ listed in it. */
is_done = foreach_dirinpath (search_path, 0,
- foreachfile_callback, func, data);
+ foreachfile_callback, func, data);
}
else
{
/* Otherwise search the default paths. */
is_done = foreach_dirinpath (user_search_path, 0,
- foreachfile_callback, func, data);
+ foreachfile_callback, func, data);
if (!is_done)
- {
- is_done = foreach_dirinpath (getenv("LTDL_LIBRARY_PATH"), 0,
- foreachfile_callback, func, data);
- }
+ {
+ is_done = foreach_dirinpath (getenv ("LTDL_LIBRARY_PATH"), 0,
+ foreachfile_callback, func, data);
+ }
#ifdef LTDL_SHLIBPATH_VAR
if (!is_done)
- {
- is_done = foreach_dirinpath (getenv(LTDL_SHLIBPATH_VAR), 0,
- foreachfile_callback, func, data);
- }
+ {
+ is_done = foreach_dirinpath (getenv (LTDL_SHLIBPATH_VAR), 0,
+ foreachfile_callback, func, data);
+ }
#endif
#ifdef LTDL_SYSSEARCHPATH
if (!is_done)
- {
- is_done = foreach_dirinpath (getenv(LTDL_SYSSEARCHPATH), 0,
- foreachfile_callback, func, data);
- }
+ {
+ is_done = foreach_dirinpath (getenv (LTDL_SYSSEARCHPATH), 0,
+ foreachfile_callback, func, data);
+ }
#endif
}
@@ -3823,16 +3869,16 @@
lt_user_data data = handle->loader->dlloader_data;
if (handle != handles)
- {
- last->next = handle->next;
- }
+ {
+ last->next = handle->next;
+ }
else
- {
- handles = handle->next;
- }
+ {
+ handles = handle->next;
+ }
errors += handle->loader->module_close (data, handle->module);
- errors += unload_deplibs(handle);
+ errors += unload_deplibs (handle);
/* It is up to the callers to free the data itself. */
LT_DLFREE (handle->caller_data);
@@ -3850,7 +3896,7 @@
++errors;
}
- done:
+done:
LT_DLMUTEX_UNLOCK ();
return errors;
@@ -3862,8 +3908,8 @@
const char *symbol;
{
size_t lensym;
- char lsym[LT_SYMBOL_LENGTH];
- char *sym;
+ char lsym[LT_SYMBOL_LENGTH];
+ char *sym;
lt_ptr address;
lt_user_data data;
@@ -3880,7 +3926,7 @@
}
lensym = LT_STRLEN (symbol) + LT_STRLEN (handle->loader->sym_prefix)
- + LT_STRLEN (handle->info.name);
+ + LT_STRLEN (handle->info.name);
if (lensym + LT_SYMBOL_OVERHEAD < LT_SYMBOL_LENGTH)
{
@@ -3890,10 +3936,10 @@
{
sym = LT_EMALLOC (char, lensym + LT_SYMBOL_OVERHEAD + 1);
if (!sym)
- {
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (BUFFER_OVERFLOW));
- return 0;
- }
+ {
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (BUFFER_OVERFLOW));
+ return 0;
+ }
}
data = handle->loader->dlloader_data;
@@ -3905,40 +3951,40 @@
/* this is a libtool module */
if (handle->loader->sym_prefix)
- {
- strcpy(sym, handle->loader->sym_prefix);
- strcat(sym, handle->info.name);
- }
+ {
+ strcpy (sym, handle->loader->sym_prefix);
+ strcat (sym, handle->info.name);
+ }
else
- {
- strcpy(sym, handle->info.name);
- }
+ {
+ strcpy (sym, handle->info.name);
+ }
- strcat(sym, "_LTX_");
- strcat(sym, symbol);
+ strcat (sym, "_LTX_");
+ strcat (sym, symbol);
/* try "modulename_LTX_symbol" */
address = handle->loader->find_sym (data, handle->module, sym);
if (address)
- {
- if (sym != lsym)
- {
- LT_DLFREE (sym);
- }
- return address;
- }
+ {
+ if (sym != lsym)
+ {
+ LT_DLFREE (sym);
+ }
+ return address;
+ }
LT_DLMUTEX_SETERROR (saved_error);
}
/* otherwise try "symbol" */
if (handle->loader->sym_prefix)
{
- strcpy(sym, handle->loader->sym_prefix);
- strcat(sym, symbol);
+ strcpy (sym, handle->loader->sym_prefix);
+ strcat (sym, symbol);
}
else
{
- strcpy(sym, symbol);
+ strcpy (sym, symbol);
}
address = handle->loader->find_sym (data, handle->module, sym);
@@ -3967,10 +4013,10 @@
char *before;
const char *dir;
{
- int errors = 0;
- char *canonical = 0;
- char *argz = 0;
- size_t argz_len = 0;
+ int errors = 0;
+ char *canonical = 0;
+ char *argz = 0;
+ size_t argz_len = 0;
assert (ppath);
assert (dir && *dir);
@@ -3986,12 +4032,12 @@
/* If *PPATH is empty, set it to DIR. */
if (*ppath == 0)
{
- assert (!before); /* BEFORE cannot be set without PPATH.
*/
- assert (dir); /* Without DIR, don't call this function! */
+ assert (!before); /* BEFORE cannot be set without PPATH. */
+ assert (dir); /* Without DIR, don't call this function! */
*ppath = lt_estrdup (dir);
if (*ppath == 0)
- ++errors;
+ ++errors;
return errors;
}
@@ -4024,9 +4070,9 @@
}
argz_stringify (argz, argz_len, LT_PATHSEP_CHAR);
- LT_DLMEM_REASSIGN (*ppath, argz);
+ LT_DLMEM_REASSIGN (*ppath, argz);
- cleanup:
+cleanup:
LT_DLFREE (canonical);
LT_DLFREE (argz);
@@ -4043,7 +4089,7 @@
{
LT_DLMUTEX_LOCK ();
if (lt_dlpath_insertdir (&user_search_path, 0, search_dir) != 0)
- ++errors;
+ ++errors;
LT_DLMUTEX_UNLOCK ();
}
@@ -4061,12 +4107,12 @@
{
LT_DLMUTEX_LOCK ();
if ((before < user_search_path)
- || (before >= user_search_path + LT_STRLEN (user_search_path)))
- {
- LT_DLMUTEX_UNLOCK ();
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (INVALID_POSITION));
- return 1;
- }
+ || (before >= user_search_path + LT_STRLEN (user_search_path)))
+ {
+ LT_DLMUTEX_UNLOCK ();
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (INVALID_POSITION));
+ return 1;
+ }
LT_DLMUTEX_UNLOCK ();
}
@@ -4074,10 +4120,10 @@
{
LT_DLMUTEX_LOCK ();
if (lt_dlpath_insertdir (&user_search_path,
- (char *) before, search_dir) != 0)
- {
- ++errors;
- }
+ (char *) before, search_dir) != 0)
+ {
+ ++errors;
+ }
LT_DLMUTEX_UNLOCK ();
}
@@ -4088,7 +4134,7 @@
lt_dlsetsearchpath (search_path)
const char *search_path;
{
- int errors = 0;
+ int errors = 0;
LT_DLMUTEX_LOCK ();
LT_DLFREE (user_search_path);
@@ -4139,7 +4185,7 @@
}
int
-lt_dlisresident (handle)
+lt_dlisresident (handle)
lt_dlhandle handle;
{
if (!handle)
@@ -4150,10 +4196,10 @@
return LT_DLIS_RESIDENT (handle);
}
+
-
/* --- MODULE INFORMATION --- */
const lt_dlinfo *
@@ -4178,7 +4224,7 @@
int
lt_dlforeach (func, data)
- int (*func) LT_PARAMS((lt_dlhandle handle, lt_ptr data));
+ int (*func) LT_PARAMS ((lt_dlhandle handle, lt_ptr data));
lt_ptr data;
{
int errors = 0;
@@ -4193,10 +4239,10 @@
cur = cur->next;
if ((*func) (tmp, data))
- {
- ++errors;
- break;
- }
+ {
+ ++errors;
+ break;
+ }
}
LT_DLMUTEX_UNLOCK ();
@@ -4238,10 +4284,10 @@
for (i = 0; i < n_elements; ++i)
{
if (handle->caller_data[i].key == key)
- {
- stale = handle->caller_data[i].data;
- break;
- }
+ {
+ stale = handle->caller_data[i].data;
+ break;
+ }
}
/* Ensure that there is enough room in this handle's caller_data
@@ -4249,31 +4295,31 @@
if (i == n_elements)
{
lt_caller_data *temp
- = LT_DLREALLOC (lt_caller_data, handle->caller_data, 2+ n_elements);
+ = LT_DLREALLOC (lt_caller_data, handle->caller_data, 2 + n_elements);
if (!temp)
- {
- stale = 0;
- goto done;
- }
+ {
+ stale = 0;
+ goto done;
+ }
handle->caller_data = temp;
/* We only need this if we needed to allocate a new caller_data. */
- handle->caller_data[i].key = key;
- handle->caller_data[1+ i].key = 0;
+ handle->caller_data[i].key = key;
+ handle->caller_data[1 + i].key = 0;
}
handle->caller_data[i].data = data;
- done:
+done:
LT_DLMUTEX_UNLOCK ();
return stale;
}
lt_ptr
-lt_dlcaller_get_data (key, handle)
+lt_dlcaller_get_data (key, handle)
lt_dlcaller_id key;
lt_dlhandle handle;
{
@@ -4288,11 +4334,11 @@
int i;
for (i = 0; handle->caller_data[i].key; ++i)
{
- if (handle->caller_data[i].key == key)
- {
- result = handle->caller_data[i].data;
- break;
- }
+ if (handle->caller_data[i].key == key)
+ {
+ result = handle->caller_data[i].data;
+ break;
+ }
}
}
@@ -4300,9 +4346,9 @@
return result;
}
+
-
/* --- USER MODULE LOADER API --- */
@@ -4315,10 +4361,9 @@
int errors = 0;
lt_dlloader *node = 0, *ptr = 0;
- if ((dlloader == 0) /* diagnose null parameters */
+ if ((dlloader == 0) /* diagnose null parameters */
|| (dlloader->module_open == 0)
- || (dlloader->module_close == 0)
- || (dlloader->find_sym == 0))
+ || (dlloader->module_close == 0) || (dlloader->find_sym == 0))
{
LT_DLMUTEX_SETERROR (LT_DLSTRERROR (INVALID_LOADER));
return 1;
@@ -4329,14 +4374,14 @@
if (!node)
return 1;
- node->next = 0;
- node->loader_name = loader_name;
- node->sym_prefix = dlloader->sym_prefix;
- node->dlloader_exit = dlloader->dlloader_exit;
- node->module_open = dlloader->module_open;
- node->module_close = dlloader->module_close;
- node->find_sym = dlloader->find_sym;
- node->dlloader_data = dlloader->dlloader_data;
+ node->next = 0;
+ node->loader_name = loader_name;
+ node->sym_prefix = dlloader->sym_prefix;
+ node->dlloader_exit = dlloader->dlloader_exit;
+ node->module_open = dlloader->module_open;
+ node->module_close = dlloader->module_close;
+ node->find_sym = dlloader->find_sym;
+ node->dlloader_data = dlloader->dlloader_data;
LT_DLMUTEX_LOCK ();
if (!loaders)
@@ -4347,11 +4392,11 @@
else if (!place)
{
/* If PLACE is not set, add NODE to the end of the
- LOADERS list. */
+ LOADERS list. */
for (ptr = loaders; ptr->next; ptr = ptr->next)
- {
- /*NOWORK*/;
- }
+ {
+ /*NOWORK*/;
+ }
ptr->next = node;
}
@@ -4365,21 +4410,21 @@
{
/* Find the node immediately preceding PLACE. */
for (ptr = loaders; ptr->next != place; ptr = ptr->next)
- {
- /*NOWORK*/;
- }
+ {
+ /*NOWORK*/;
+ }
if (ptr->next != place)
- {
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (INVALID_LOADER));
- ++errors;
- }
+ {
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (INVALID_LOADER));
+ ++errors;
+ }
else
- {
- /* Insert NODE between PTR and PLACE. */
- node->next = place;
- ptr->next = node;
- }
+ {
+ /* Insert NODE between PTR and PLACE. */
+ node->next = place;
+ ptr->next = node;
+ }
}
LT_DLMUTEX_UNLOCK ();
@@ -4404,14 +4449,14 @@
LT_DLMUTEX_LOCK ();
/* Fail if there are any open modules which use this loader. */
- for (handle = handles; handle; handle = handle->next)
+ for (handle = handles; handle; handle = handle->next)
{
if (handle->loader == place)
- {
- LT_DLMUTEX_SETERROR (LT_DLSTRERROR (REMOVE_LOADER));
- ++errors;
- goto done;
- }
+ {
+ LT_DLMUTEX_SETERROR (LT_DLSTRERROR (REMOVE_LOADER));
+ ++errors;
+ goto done;
+ }
}
if (place == loaders)
@@ -4424,12 +4469,12 @@
/* Find the loader before the one being removed. */
lt_dlloader *prev;
for (prev = loaders; prev->next; prev = prev->next)
- {
- if (!strcmp (prev->next->loader_name, loader_name))
- {
- break;
- }
- }
+ {
+ if (!strcmp (prev->next->loader_name, loader_name))
+ {
+ break;
+ }
+ }
place = prev->next;
prev->next = prev->next->next;
@@ -4442,7 +4487,7 @@
LT_DLFREE (place);
- done:
+done:
LT_DLMUTEX_UNLOCK ();
return errors;
@@ -4511,9 +4556,9 @@
for (place = loaders; place; place = place->next)
{
if (strcmp (place->loader_name, loader_name) == 0)
- {
- break;
- }
+ {
+ break;
+ }
}
LT_DLMUTEX_UNLOCK ();
Modified: GNUnet/libltdl/ltdl.h
===================================================================
--- GNUnet/libltdl/ltdl.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/libltdl/ltdl.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -28,9 +28,9 @@
#ifndef LTDL_H
#define LTDL_H 1
-#include <sys/types.h> /* for size_t declaration */
-
+#include <sys/types.h> /* for size_t declaration */
+
/* --- MACROS FOR PORTABILITY --- */
@@ -44,13 +44,11 @@
# define LT_BEGIN_C_DECLS extern "C" {
# define LT_END_C_DECLS }
#else
-# define LT_BEGIN_C_DECLS /* empty */
-# define LT_END_C_DECLS /* empty */
+# define LT_BEGIN_C_DECLS /* empty */
+# define LT_END_C_DECLS /* empty */
#endif
LT_BEGIN_C_DECLS
-
-
/* LT_PARAMS is a macro used to wrap function prototypes, so that compilers
that don't understand ANSI C prototypes still work, and ANSI C
compilers can issue warnings about type mismatches. */
@@ -61,7 +59,6 @@
# define LT_PARAMS(protos) ()
# define lt_ptr char*
#endif
-
/* LT_STMT_START/END are used to create macros which expand to a
a single compound statement in a portable way. */
#if defined (__GNUC__) && !defined (__STRICT_ANSI__) && !defined (__cplusplus)
@@ -76,7 +73,6 @@
# define LT_STMT_END while (0)
# endif
#endif
-
/* LT_CONC creates a new concatenated symbol for the compiler
in a portable way. */
#if defined(__STDC__) || defined(__cplusplus) || defined(_MSC_VER)
@@ -84,15 +80,9 @@
#else
# define LT_CONC(s,t) s/**/t
#endif
-
/* LT_STRLEN can be used safely on NULL pointers. */
#define LT_STRLEN(s) (((s) && (s)[0]) ? strlen (s) : 0)
-
-
-
-/* --- WINDOWS SUPPORT --- */
-
-
+/* --- WINDOWS SUPPORT --- */
/* Canonicalise Windows and Cygwin recognition macros. */
#ifdef __CYGWIN32__
# ifndef __CYGWIN__
@@ -110,8 +100,6 @@
# endif
# endif
#endif
-
-
#ifdef __WINDOWS__
# ifndef __CYGWIN__
/* LT_DIRSEP_CHAR is accepted *in addition* to '/' as a directory
@@ -123,81 +111,72 @@
#ifndef LT_PATHSEP_CHAR
# define LT_PATHSEP_CHAR ':'
#endif
-
/* DLL building support on win32 hosts; mostly to workaround their
ridiculous implementation of data symbol exporting. */
#ifndef LT_SCOPE
# ifdef __WINDOWS__
-# ifdef DLL_EXPORT /* defined by libtool (if required) */
+# ifdef DLL_EXPORT /* defined by libtool (if required) */
# define LT_SCOPE __declspec(dllexport)
# endif
-# ifdef LIBLTDL_DLL_IMPORT /* define if linking with this dll */
+# ifdef LIBLTDL_DLL_IMPORT /* define if linking with this dll */
# define LT_SCOPE extern __declspec(dllimport)
# endif
# endif
-# ifndef LT_SCOPE /* static linking or !__WINDOWS__ */
+# ifndef LT_SCOPE /* static linking or !__WINDOWS__ */
# define LT_SCOPE extern
# endif
#endif
-
-
-#if defined(_MSC_VER) /* Visual Studio */
+#if defined(_MSC_VER) /* Visual Studio */
# define R_OK 4
#endif
+/* --- DYNAMIC MODULE LOADING API --- */
+typedef struct lt_dlhandle_struct *lt_dlhandle; /* A loaded module. */
-
-
-/* --- DYNAMIC MODULE LOADING API --- */
-
-
-typedef struct lt_dlhandle_struct *lt_dlhandle; /* A loaded module. */
-
/* Initialisation and finalisation functions for libltdl. */
-LT_SCOPE int lt_dlinit LT_PARAMS((void));
-LT_SCOPE int lt_dlexit LT_PARAMS((void));
+LT_SCOPE int lt_dlinit LT_PARAMS ((void));
+LT_SCOPE int lt_dlexit LT_PARAMS ((void));
/* Module search path manipulation. */
-LT_SCOPE int lt_dladdsearchdir LT_PARAMS((const char
*search_dir));
-LT_SCOPE int lt_dlinsertsearchdir LT_PARAMS((const char *before,
- const char *search_dir));
-LT_SCOPE int lt_dlsetsearchpath LT_PARAMS((const char
*search_path));
-LT_SCOPE const char *lt_dlgetsearchpath LT_PARAMS((void));
-LT_SCOPE int lt_dlforeachfile LT_PARAMS((
- const char *search_path,
- int (*func) (const char *filename, lt_ptr data),
- lt_ptr data));
+LT_SCOPE int lt_dladdsearchdir LT_PARAMS ((const char *search_dir));
+LT_SCOPE int lt_dlinsertsearchdir LT_PARAMS ((const char *before,
+ const char *search_dir));
+LT_SCOPE int lt_dlsetsearchpath LT_PARAMS ((const char *search_path));
+LT_SCOPE const char *lt_dlgetsearchpath LT_PARAMS ((void));
+LT_SCOPE int lt_dlforeachfile LT_PARAMS ((const char *search_path,
+ int (*func) (const char *filename,
+ lt_ptr data),
+ lt_ptr data));
/* Portable libltdl versions of the system dlopen() API. */
-LT_SCOPE lt_dlhandle lt_dlopen LT_PARAMS((const char
*filename));
-LT_SCOPE lt_dlhandle lt_dlopenext LT_PARAMS((const char
*filename));
-LT_SCOPE lt_ptr lt_dlsym LT_PARAMS((lt_dlhandle handle,
- const char *name));
-LT_SCOPE const char *lt_dlerror LT_PARAMS((void));
-LT_SCOPE int lt_dlclose LT_PARAMS((lt_dlhandle handle));
+LT_SCOPE lt_dlhandle lt_dlopen LT_PARAMS ((const char *filename));
+LT_SCOPE lt_dlhandle lt_dlopenext LT_PARAMS ((const char *filename));
+LT_SCOPE lt_ptr lt_dlsym LT_PARAMS ((lt_dlhandle handle, const char *name));
+LT_SCOPE const char *lt_dlerror LT_PARAMS ((void));
+LT_SCOPE int lt_dlclose LT_PARAMS ((lt_dlhandle handle));
/* Module residency management. */
-LT_SCOPE int lt_dlmakeresident LT_PARAMS((lt_dlhandle handle));
-LT_SCOPE int lt_dlisresident LT_PARAMS((lt_dlhandle handle));
+LT_SCOPE int lt_dlmakeresident LT_PARAMS ((lt_dlhandle handle));
+LT_SCOPE int lt_dlisresident LT_PARAMS ((lt_dlhandle handle));
+
-
/* --- MUTEX LOCKING --- */
-typedef void lt_dlmutex_lock LT_PARAMS((void));
-typedef void lt_dlmutex_unlock LT_PARAMS((void));
-typedef void lt_dlmutex_seterror LT_PARAMS((const char *errmsg));
-typedef const char *lt_dlmutex_geterror LT_PARAMS((void));
+typedef void lt_dlmutex_lock LT_PARAMS ((void));
+typedef void lt_dlmutex_unlock LT_PARAMS ((void));
+typedef void lt_dlmutex_seterror LT_PARAMS ((const char *errmsg));
+typedef const char *lt_dlmutex_geterror LT_PARAMS ((void));
-LT_SCOPE int lt_dlmutex_register LT_PARAMS((lt_dlmutex_lock
*lock,
- lt_dlmutex_unlock *unlock,
- lt_dlmutex_seterror *seterror,
- lt_dlmutex_geterror *geterror));
+LT_SCOPE int lt_dlmutex_register LT_PARAMS ((lt_dlmutex_lock * lock,
+ lt_dlmutex_unlock * unlock,
+ lt_dlmutex_seterror * seterror,
+ lt_dlmutex_geterror * geterror));
+
-
/* --- MEMORY HANDLING --- */
@@ -206,103 +185,109 @@
libltdl relies on a featureful realloc, but if you are sure yours
has the right semantics then you can assign it directly. Generally,
it is safe to assign just a malloc() and a free() function. */
-LT_SCOPE lt_ptr (*lt_dlmalloc) LT_PARAMS((size_t size));
-LT_SCOPE lt_ptr (*lt_dlrealloc) LT_PARAMS((lt_ptr ptr, size_t size));
-LT_SCOPE void (*lt_dlfree) LT_PARAMS((lt_ptr ptr));
+LT_SCOPE
+lt_ptr (*lt_dlmalloc)
+LT_PARAMS ((size_t size));
+ LT_SCOPE lt_ptr (*lt_dlrealloc) LT_PARAMS ((lt_ptr ptr, size_t size));
+ LT_SCOPE void (*lt_dlfree) LT_PARAMS ((lt_ptr ptr));
+
-
/* --- PRELOADED MODULE SUPPORT --- */
/* A preopened symbol. Arrays of this type comprise the exported
symbols for a dlpreopened module. */
-typedef struct {
- const char *name;
- lt_ptr address;
-} lt_dlsymlist;
+ typedef struct
+ {
+ const char *name;
+ lt_ptr address;
+ } lt_dlsymlist;
-LT_SCOPE int lt_dlpreload LT_PARAMS((const lt_dlsymlist
*preloaded));
-LT_SCOPE int lt_dlpreload_default
- LT_PARAMS((const lt_dlsymlist *preloaded));
+ LT_SCOPE int lt_dlpreload LT_PARAMS ((const lt_dlsymlist * preloaded));
+ LT_SCOPE int lt_dlpreload_default
+ LT_PARAMS ((const lt_dlsymlist * preloaded));
#define LTDL_SET_PRELOADED_SYMBOLS() LT_STMT_START{ \
extern const lt_dlsymlist lt_preloaded_symbols[]; \
lt_dlpreload_default(lt_preloaded_symbols); \
}LT_STMT_END
+
-
/* --- MODULE INFORMATION --- */
/* Read only information pertaining to a loaded module. */
-typedef struct {
- char *filename; /* file name */
- char *name; /* module name */
- int ref_count; /* number of times lt_dlopened minus
- number of times lt_dlclosed. */
-} lt_dlinfo;
+ typedef struct
+ {
+ char *filename; /* file name */
+ char *name; /* module name */
+ int ref_count; /* number of times lt_dlopened minus
+ number of times lt_dlclosed. */
+ } lt_dlinfo;
-LT_SCOPE const lt_dlinfo *lt_dlgetinfo LT_PARAMS((lt_dlhandle
handle));
-LT_SCOPE lt_dlhandle lt_dlhandle_next LT_PARAMS((lt_dlhandle
place));
-LT_SCOPE int lt_dlforeach LT_PARAMS((
- int (*func) (lt_dlhandle handle, lt_ptr data),
- lt_ptr data));
+ LT_SCOPE const lt_dlinfo *lt_dlgetinfo LT_PARAMS ((lt_dlhandle handle));
+ LT_SCOPE lt_dlhandle lt_dlhandle_next LT_PARAMS ((lt_dlhandle place));
+ LT_SCOPE int lt_dlforeach
+ LT_PARAMS ((int (*func) (lt_dlhandle handle, lt_ptr data),
+ lt_ptr data));
/* Associating user data with loaded modules. */
-typedef unsigned lt_dlcaller_id;
+ typedef unsigned lt_dlcaller_id;
-LT_SCOPE lt_dlcaller_id lt_dlcaller_register LT_PARAMS((void));
-LT_SCOPE lt_ptr lt_dlcaller_set_data LT_PARAMS((lt_dlcaller_id
key,
- lt_dlhandle handle,
- lt_ptr data));
-LT_SCOPE lt_ptr lt_dlcaller_get_data LT_PARAMS((lt_dlcaller_id
key,
- lt_dlhandle handle));
+ LT_SCOPE lt_dlcaller_id lt_dlcaller_register LT_PARAMS ((void));
+ LT_SCOPE lt_ptr lt_dlcaller_set_data LT_PARAMS ((lt_dlcaller_id key,
+ lt_dlhandle handle,
+ lt_ptr data));
+ LT_SCOPE lt_ptr lt_dlcaller_get_data LT_PARAMS ((lt_dlcaller_id key,
+ lt_dlhandle handle));
+
-
/* --- USER MODULE LOADER API --- */
-typedef struct lt_dlloader lt_dlloader;
-typedef lt_ptr lt_user_data;
-typedef lt_ptr lt_module;
+ typedef struct lt_dlloader lt_dlloader;
+ typedef lt_ptr lt_user_data;
+ typedef lt_ptr lt_module;
/* Function pointer types for creating user defined module loaders. */
-typedef lt_module lt_module_open LT_PARAMS((lt_user_data loader_data,
- const char *filename));
-typedef int lt_module_close LT_PARAMS((lt_user_data loader_data,
- lt_module handle));
-typedef lt_ptr lt_find_sym LT_PARAMS((lt_user_data loader_data,
- lt_module handle,
- const char *symbol));
-typedef int lt_dlloader_exit LT_PARAMS((lt_user_data loader_data));
+ typedef lt_module lt_module_open LT_PARAMS ((lt_user_data loader_data,
+ const char *filename));
+ typedef int lt_module_close LT_PARAMS ((lt_user_data loader_data,
+ lt_module handle));
+ typedef lt_ptr lt_find_sym LT_PARAMS ((lt_user_data loader_data,
+ lt_module handle,
+ const char *symbol));
+ typedef int lt_dlloader_exit LT_PARAMS ((lt_user_data loader_data));
-struct lt_user_dlloader {
- const char *sym_prefix;
- lt_module_open *module_open;
- lt_module_close *module_close;
- lt_find_sym *find_sym;
- lt_dlloader_exit *dlloader_exit;
- lt_user_data dlloader_data;
-};
+ struct lt_user_dlloader
+ {
+ const char *sym_prefix;
+ lt_module_open *module_open;
+ lt_module_close *module_close;
+ lt_find_sym *find_sym;
+ lt_dlloader_exit *dlloader_exit;
+ lt_user_data dlloader_data;
+ };
-LT_SCOPE lt_dlloader *lt_dlloader_next LT_PARAMS((lt_dlloader
*place));
-LT_SCOPE lt_dlloader *lt_dlloader_find LT_PARAMS((
- const char *loader_name));
-LT_SCOPE const char *lt_dlloader_name LT_PARAMS((lt_dlloader
*place));
-LT_SCOPE lt_user_data *lt_dlloader_data LT_PARAMS((lt_dlloader
*place));
-LT_SCOPE int lt_dlloader_add LT_PARAMS((lt_dlloader
*place,
- const struct lt_user_dlloader *dlloader,
- const char *loader_name));
-LT_SCOPE int lt_dlloader_remove LT_PARAMS((
- const char *loader_name));
+ LT_SCOPE lt_dlloader *lt_dlloader_next LT_PARAMS ((lt_dlloader * place));
+ LT_SCOPE lt_dlloader *lt_dlloader_find
+ LT_PARAMS ((const char *loader_name));
+ LT_SCOPE const char *lt_dlloader_name LT_PARAMS ((lt_dlloader * place));
+ LT_SCOPE lt_user_data *lt_dlloader_data
+ LT_PARAMS ((lt_dlloader * place));
+ LT_SCOPE int lt_dlloader_add
+ LT_PARAMS ((lt_dlloader * place,
+ const struct lt_user_dlloader * dlloader,
+ const char *loader_name));
+ LT_SCOPE int lt_dlloader_remove LT_PARAMS ((const char *loader_name));
+
-
/* --- ERROR MESSAGE HANDLING --- */
@@ -332,21 +317,21 @@
LT_ERROR(INVALID_POSITION, "invalid search path insert position")
/* Enumerate the symbolic error names. */
-enum {
+ enum
+ {
#define LT_ERROR(name, diagnostic) LT_CONC(LT_ERROR_, name),
- lt_dlerror_table
+ lt_dlerror_table
#undef LT_ERROR
+ LT_ERROR_MAX
+ };
- LT_ERROR_MAX
-};
-
/* These functions are only useful from inside custom module loaders. */
-LT_SCOPE int lt_dladderror LT_PARAMS((const char *diagnostic));
-LT_SCOPE int lt_dlseterror LT_PARAMS((int errorcode));
+ LT_SCOPE int lt_dladderror LT_PARAMS ((const char *diagnostic));
+ LT_SCOPE int lt_dlseterror LT_PARAMS ((int errorcode));
+
-
/* --- SOURCE COMPATIBILITY WITH OLD LIBLTDL --- */
@@ -362,5 +347,4 @@
#endif
LT_END_C_DECLS
-
#endif /* !LTDL_H */
Added: GNUnet/pre-commit
===================================================================
--- GNUnet/pre-commit (rev 0)
+++ GNUnet/pre-commit 2007-07-10 08:36:37 UTC (rev 5295)
@@ -0,0 +1,2 @@
+#!/bin/sh
+indent -nut `find * -name "*.c"` `find * -name "*.h"`
Modified: GNUnet/src/applications/advertising/advertising.c
===================================================================
--- GNUnet/src/applications/advertising/advertising.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/advertising/advertising.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -62,19 +62,19 @@
#define DEBUG_ADVERTISING NO
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static Transport_ServiceAPI * transport;
+static Transport_ServiceAPI *transport;
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
-static Pingpong_ServiceAPI * pingpong;
+static Pingpong_ServiceAPI *pingpong;
-static Topology_ServiceAPI * topology;
+static Topology_ServiceAPI *topology;
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
static int stat_hello_in;
@@ -109,16 +109,18 @@
static cron_t lasthelloMsg = 0;
-static double getConnectPriority() {
+static double
+getConnectPriority ()
+{
double preference;
/* we should'nt give lots of bandwidth for hellos if we're close to
the connection goal */
- preference = topology->getSaturation();
+ preference = topology->getSaturation ();
if (preference <= 0.0001)
preference = 0xFFFF;
else
- preference = 1/preference;
+ preference = 1 / preference;
/* always give some decent, but compared to (migrated) content
competitive amount of bandwidth to peers sending (valid)
hellos */
@@ -127,13 +129,15 @@
return preference;
}
-static void callAddHost(void * cls) {
- P2P_hello_MESSAGE * hello = cls;
+static void
+callAddHost (void *cls)
+{
+ P2P_hello_MESSAGE *hello = cls;
if (stats != NULL)
- stats->change(stat_hello_verified, 1);
- identity->addHost(hello);
- FREE(hello);
+ stats->change (stat_hello_verified, 1);
+ identity->addHost (hello);
+ FREE (hello);
}
/**
@@ -144,14 +148,14 @@
* @return SYSERR on error, OK on success
*/
static int
-receivedhello(const PeerIdentity * sender,
- const MESSAGE_HEADER * message) {
- TSession * tsession;
- P2P_hello_MESSAGE * copy;
+receivedhello (const PeerIdentity * sender, const MESSAGE_HEADER * message)
+{
+ TSession *tsession;
+ P2P_hello_MESSAGE *copy;
PeerIdentity foreignId;
- const P2P_hello_MESSAGE * msg;
- MESSAGE_HEADER * ping;
- char * buffer;
+ const P2P_hello_MESSAGE *msg;
+ MESSAGE_HEADER *ping;
+ char *buffer;
int helloEnd;
int mtu;
int res;
@@ -159,278 +163,283 @@
EncName enc;
/* first verify that it is actually a valid hello */
- msg = (const P2P_hello_MESSAGE* ) message;
- if ( (ntohs(msg->header.size) < sizeof(P2P_hello_MESSAGE)) ||
- (ntohs(msg->header.size) != P2P_hello_MESSAGE_size(msg)) ) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- identity->getPeerIdentity(&msg->publicKey,
- &foreignId);
- if (! equalsHashCode512(&msg->senderIdentity.hashPubKey,
- &foreignId.hashPubKey)) {
- GE_BREAK(ectx, 0);
- return SYSERR; /* public key and host hash do not match */
- }
- if (SYSERR == verifySig(&msg->senderIdentity,
- P2P_hello_MESSAGE_size(msg)
- - sizeof(Signature)
- - sizeof(PublicKey)
- - sizeof(MESSAGE_HEADER),
- &msg->signature,
- &msg->publicKey)) {
- IF_GELOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- hash2enc(&msg->senderIdentity.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("HELLO message from `%s' has an invalid signature. Dropping.\n"),
- (char*)&enc);
- GE_BREAK(ectx, 0);
- return SYSERR; /* message invalid */
- }
- if ((TIME_T)ntohl(msg->expirationTime) > TIME(NULL) + MAX_HELLO_EXPIRES) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("HELLO message has expiration too far in the future. Dropping.\n"));
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- if (SYSERR == transport->verifyhello(msg)) {
+ msg = (const P2P_hello_MESSAGE *) message;
+ if ((ntohs (msg->header.size) < sizeof (P2P_hello_MESSAGE)) ||
+ (ntohs (msg->header.size) != P2P_hello_MESSAGE_size (msg)))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ identity->getPeerIdentity (&msg->publicKey, &foreignId);
+ if (!equalsHashCode512 (&msg->senderIdentity.hashPubKey,
+ &foreignId.hashPubKey))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR; /* public key and host hash do not match */
+ }
+ if (SYSERR == verifySig (&msg->senderIdentity,
+ P2P_hello_MESSAGE_size (msg)
+ - sizeof (Signature)
+ - sizeof (PublicKey)
+ - sizeof (MESSAGE_HEADER),
+ &msg->signature, &msg->publicKey))
+ {
+ IF_GELOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ hash2enc (&msg->senderIdentity.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("HELLO message from `%s' has an invalid signature.
Dropping.\n"),
+ (char *) &enc);
+ GE_BREAK (ectx, 0);
+ return SYSERR; /* message invalid */
+ }
+ if ((TIME_T) ntohl (msg->expirationTime) > TIME (NULL) + MAX_HELLO_EXPIRES)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("HELLO message has expiration too far in the future.
Dropping.\n"));
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ if (SYSERR == transport->verifyhello (msg))
+ {
#if DEBUG_ADVERTISING
- IF_GELOG(ectx,
- GE_INFO | GE_BULK | GE_USER,
- hash2enc(&msg->senderIdentity.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- "Transport verification of HELLO message from `%s' failed (%u).\n",
- &enc,
- ntohs(msg->protocol));
+ IF_GELOG (ectx,
+ GE_INFO | GE_BULK | GE_USER,
+ hash2enc (&msg->senderIdentity.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_BULK | GE_USER,
+ "Transport verification of HELLO message from `%s' failed
(%u).\n",
+ &enc, ntohs (msg->protocol));
#endif
- return OK; /* not good, but do process rest of message */
- }
+ return OK; /* not good, but do process rest of message */
+ }
if (stats != NULL)
- stats->change(stat_hello_in, 1);
+ stats->change (stat_hello_in, 1);
#if DEBUG_ADVERTISING
- IF_GELOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- hash2enc(&msg->senderIdentity.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- "HELLO advertisement from `%s' for protocol %d received.\n",
- &enc,
- ntohs(msg->protocol));
+ IF_GELOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ hash2enc (&msg->senderIdentity.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ "HELLO advertisement from `%s' for protocol %d received.\n",
+ &enc, ntohs (msg->protocol));
#endif
- if (ntohs(msg->protocol) == NAT_PROTOCOL_NUMBER) {
- /* We *can* not verify NAT. Ever. So all we
- can do is just accept it. The best thing
- that we may do is check that it was not
- forwarded by another peer (forwarding NAT
- advertisements is invalid), but even that
- check can not be done securely (since we
- have to accept hellos in plaintext). Thus
- we take NAT advertisements at face value
- (which is OK since we never attempt to
- connect to a NAT). */
- identity->addHost(msg);
- if (stats != NULL)
- stats->change(stat_hello_nat_in, 1);
- return OK;
- }
-
- /* Then check if we have seen this hello before, if it is identical
- except for the TTL, we trust it and do not play PING-PONG */
- copy = identity->identity2Hello(&foreignId,
- ntohs(msg->protocol),
- NO);
- if (NULL != copy) {
- if ( (ntohs(copy->senderAddressSize) ==
- ntohs(msg->senderAddressSize)) &&
- (0 == memcmp(&msg->MTU,
- ©->MTU,
- sizeof(unsigned short)*2+
- sizeof(unsigned int) +
- ntohs(copy->senderAddressSize)) ) ) {
- /* ok, we've seen this one exactly like this before (at most the
- TTL has changed); thus we can 'trust' it without playing
- ping-pong */
- identity->addHost(msg);
+ if (ntohs (msg->protocol) == NAT_PROTOCOL_NUMBER)
+ {
+ /* We *can* not verify NAT. Ever. So all we
+ can do is just accept it. The best thing
+ that we may do is check that it was not
+ forwarded by another peer (forwarding NAT
+ advertisements is invalid), but even that
+ check can not be done securely (since we
+ have to accept hellos in plaintext). Thus
+ we take NAT advertisements at face value
+ (which is OK since we never attempt to
+ connect to a NAT). */
+ identity->addHost (msg);
if (stats != NULL)
- stats->change(stat_hello_update, 1);
- FREE(copy);
+ stats->change (stat_hello_nat_in, 1);
return OK;
}
+
+ /* Then check if we have seen this hello before, if it is identical
+ except for the TTL, we trust it and do not play PING-PONG */
+ copy = identity->identity2Hello (&foreignId, ntohs (msg->protocol), NO);
+ if (NULL != copy)
+ {
+ if ((ntohs (copy->senderAddressSize) ==
+ ntohs (msg->senderAddressSize)) &&
+ (0 == memcmp (&msg->MTU,
+ ©->MTU,
+ sizeof (unsigned short) * 2 +
+ sizeof (unsigned int) +
+ ntohs (copy->senderAddressSize))))
+ {
+ /* ok, we've seen this one exactly like this before (at most the
+ TTL has changed); thus we can 'trust' it without playing
+ ping-pong */
+ identity->addHost (msg);
+ if (stats != NULL)
+ stats->change (stat_hello_update, 1);
+ FREE (copy);
+ return OK;
+ }
#if DEBUG_ADVERTISING
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "HELLO advertisement differs from prior knowledge,"
- " requireing ping-pong confirmation.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "HELLO advertisement differs from prior knowledge,"
+ " requireing ping-pong confirmation.\n");
#endif
- FREE(copy);
- }
+ FREE (copy);
+ }
- if (YES == GC_get_configuration_value_yesno(coreAPI->cfg,
- "GNUNETD",
- "PRIVATE-NETWORK",
- NO)) {
- /* the option 'PRIVATE-NETWORK' can be used
- to limit the connections of this peer to
- peers of which the hostkey has been copied
- by hand to data/hosts; if this option is
- given, GNUnet will not accept advertisements
- of peers that the local node does not already
- know about. Note that in order for this
- option to work, HOSTLISTURL should either
- not be set at all or be set to a trusted
- peer that only advertises the private network.
- Also, the option does NOT work at the moment
- if the NAT transport is loaded; for that,
- a couple of lines above would need some minor
- editing :-). */
+ if (YES == GC_get_configuration_value_yesno (coreAPI->cfg,
+ "GNUNETD",
+ "PRIVATE-NETWORK", NO))
+ {
+ /* the option 'PRIVATE-NETWORK' can be used
+ to limit the connections of this peer to
+ peers of which the hostkey has been copied
+ by hand to data/hosts; if this option is
+ given, GNUnet will not accept advertisements
+ of peers that the local node does not already
+ know about. Note that in order for this
+ option to work, HOSTLISTURL should either
+ not be set at all or be set to a trusted
+ peer that only advertises the private network.
+ Also, the option does NOT work at the moment
+ if the NAT transport is loaded; for that,
+ a couple of lines above would need some minor
+ editing :-). */
#if DEBUG_ADVERTISING
- GE_LOG(ectx,
- GE_INFO | GE_BULK | GE_USER,
- "Private network, discarding unknown advertisements\n");
+ GE_LOG (ectx,
+ GE_INFO | GE_BULK | GE_USER,
+ "Private network, discarding unknown advertisements\n");
#endif
- return SYSERR;
- }
+ return SYSERR;
+ }
/* Ok, must play PING-PONG. Add the hello to the temporary
(in-memory only) buffer to make it available for a short
time in order to play PING-PONG */
- identity->addHostTemporarily(msg);
+ identity->addHostTemporarily (msg);
- now = get_time();
- if ( (sender != NULL) &&
- ( (now - lasthelloMsg) / cronSECONDS) *
- (os_network_monitor_get_limit(coreAPI->load_monitor,
- Download))
- < P2P_hello_MESSAGE_size(msg) * 10 ) {
- /* do not use more than about 10% of the
- available bandwidth to VERIFY hellos (by sending
- our own with a PING). This does not affect
- the hello advertising. Sure, we should not
- advertise much more than what other peers
- can verify, but the problem is that buggy/
- malicious peers can spam us with hellos, and
- we don't want to follow that up with massive
- hello-ing by ourselves. */
+ now = get_time ();
+ if ((sender != NULL) &&
+ ((now - lasthelloMsg) / cronSECONDS) *
+ (os_network_monitor_get_limit (coreAPI->load_monitor,
+ Download))
+ < P2P_hello_MESSAGE_size (msg) * 10)
+ {
+ /* do not use more than about 10% of the
+ available bandwidth to VERIFY hellos (by sending
+ our own with a PING). This does not affect
+ the hello advertising. Sure, we should not
+ advertise much more than what other peers
+ can verify, but the problem is that buggy/
+ malicious peers can spam us with hellos, and
+ we don't want to follow that up with massive
+ hello-ing by ourselves. */
#if DEBUG_ADVERTISING
- GE_LOG(ectx,
- GE_INFO | GE_BULK | GE_USER,
- "Not enough resources to verify HELLO message at this time (%u * %u < %u
* 10)\n",
- (unsigned int) ((now - lasthelloMsg) / cronSECONDS),
- (unsigned int) os_network_monitor_get_limit(coreAPI->load_monitor,
- Download),
- (unsigned int) P2P_hello_MESSAGE_size(msg));
+ GE_LOG (ectx,
+ GE_INFO | GE_BULK | GE_USER,
+ "Not enough resources to verify HELLO message at this time (%u *
%u < %u * 10)\n",
+ (unsigned int) ((now - lasthelloMsg) / cronSECONDS),
+ (unsigned int) os_network_monitor_get_limit (coreAPI->
+ load_monitor,
+ Download),
+ (unsigned int) P2P_hello_MESSAGE_size (msg));
#endif
- if (stats != NULL)
- stats->change(stat_hello_discard, 1);
- return SYSERR;
- }
+ if (stats != NULL)
+ stats->change (stat_hello_discard, 1);
+ return SYSERR;
+ }
lasthelloMsg = now;
/* Establish session as advertised in the hello */
- tsession = transport->connect(msg);
- if (tsession == NULL) {
- if (stats != NULL)
- stats->change(stat_hello_no_transport, 1);
- return SYSERR; /* could not connect */
- }
+ tsession = transport->connect (msg);
+ if (tsession == NULL)
+ {
+ if (stats != NULL)
+ stats->change (stat_hello_no_transport, 1);
+ return SYSERR; /* could not connect */
+ }
/* build message to send, ping must contain return-information,
such as a selection of our hellos... */
- mtu = transport->getMTU(tsession->ttype);
- if (mtu == 0) {
- mtu = 2048; /* bound size */
- } else {
- GE_ASSERT(ectx, mtu > P2P_MESSAGE_OVERHEAD);
- mtu -= P2P_MESSAGE_OVERHEAD;
- }
- copy = MALLOC(P2P_hello_MESSAGE_size(msg));
- memcpy(copy,
- msg,
- P2P_hello_MESSAGE_size(msg));
- ping = pingpong->pingUser(&msg->senderIdentity,
- &callAddHost,
- copy,
- YES,
- rand());
- if (ping == NULL) {
- res = SYSERR;
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- _("Could not send HELLO+PING, ping buffer full.\n"));
- transport->disconnect(tsession);
- if (stats != NULL)
- stats->change(stat_hello_ping_busy, 1);
- return SYSERR;
- }
- buffer = MALLOC(mtu);
- if (mtu > ntohs(ping->size)) {
- helloEnd = transport->getAdvertisedhellos(mtu - ntohs(ping->size),
- buffer);
- GE_ASSERT(ectx,
- mtu - ntohs(ping->size) >= helloEnd);
- } else {
- helloEnd = -2;
- }
- if (helloEnd <= 0) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Failed to create an advertisement for this peer. Will not send
PING.\n"));
- FREE(buffer);
- if (stats != NULL)
- stats->change(stat_hello_noselfad, 1);
- transport->disconnect(tsession);
- return SYSERR;
- }
+ mtu = transport->getMTU (tsession->ttype);
+ if (mtu == 0)
+ {
+ mtu = 2048; /* bound size */
+ }
+ else
+ {
+ GE_ASSERT (ectx, mtu > P2P_MESSAGE_OVERHEAD);
+ mtu -= P2P_MESSAGE_OVERHEAD;
+ }
+ copy = MALLOC (P2P_hello_MESSAGE_size (msg));
+ memcpy (copy, msg, P2P_hello_MESSAGE_size (msg));
+ ping = pingpong->pingUser (&msg->senderIdentity,
+ &callAddHost, copy, YES, rand ());
+ if (ping == NULL)
+ {
+ res = SYSERR;
+ GE_LOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ _("Could not send HELLO+PING, ping buffer full.\n"));
+ transport->disconnect (tsession);
+ if (stats != NULL)
+ stats->change (stat_hello_ping_busy, 1);
+ return SYSERR;
+ }
+ buffer = MALLOC (mtu);
+ if (mtu > ntohs (ping->size))
+ {
+ helloEnd = transport->getAdvertisedhellos (mtu - ntohs (ping->size),
+ buffer);
+ GE_ASSERT (ectx, mtu - ntohs (ping->size) >= helloEnd);
+ }
+ else
+ {
+ helloEnd = -2;
+ }
+ if (helloEnd <= 0)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("Failed to create an advertisement for this peer. Will not send
PING.\n"));
+ FREE (buffer);
+ if (stats != NULL)
+ stats->change (stat_hello_noselfad, 1);
+ transport->disconnect (tsession);
+ return SYSERR;
+ }
res = OK;
- memcpy(&buffer[helloEnd],
- ping,
- ntohs(ping->size));
- helloEnd += ntohs(ping->size);
- FREE(ping);
+ memcpy (&buffer[helloEnd], ping, ntohs (ping->size));
+ helloEnd += ntohs (ping->size);
+ FREE (ping);
/* ok, finally we can send! */
- if ( (res == OK) &&
- (SYSERR == coreAPI->sendPlaintext(tsession,
- buffer,
- helloEnd)) ) {
+ if ((res == OK) &&
+ (SYSERR == coreAPI->sendPlaintext (tsession, buffer, helloEnd)))
+ {
- if (stats != NULL)
- stats->change(stat_hello_send_error, 1);
+ if (stats != NULL)
+ stats->change (stat_hello_send_error, 1);
+ res = SYSERR;
+ }
+ if (res == OK)
+ {
+ if (stats != NULL)
+ stats->change (stat_plaintextPingSent, 1);
+ }
+ FREE (buffer);
+ if (SYSERR == transport->disconnect (tsession))
res = SYSERR;
- }
- if (res == OK) {
- if (stats != NULL)
- stats->change(stat_plaintextPingSent, 1);
- }
- FREE(buffer);
- if (SYSERR == transport->disconnect(tsession))
- res = SYSERR;
return res;
}
-typedef struct {
+typedef struct
+{
/* the hello message */
- P2P_hello_MESSAGE * m;
+ P2P_hello_MESSAGE *m;
/* send the hello in 1 out of n cases */
int n;
} SendData;
static int
-broadcastHelper(const PeerIdentity * hi,
- const unsigned short proto,
- int confirmed,
- void * cls) {
- SendData * sd = cls;
- P2P_hello_MESSAGE * hello;
- TSession * tsession;
+broadcastHelper (const PeerIdentity * hi,
+ const unsigned short proto, int confirmed, void *cls)
+{
+ SendData *sd = cls;
+ P2P_hello_MESSAGE *hello;
+ TSession *tsession;
int prio;
#if DEBUG_ADVERTISING
EncName other;
@@ -438,87 +447,73 @@
if (confirmed == NO)
return OK;
- if (proto == NAT_PROTOCOL_NUMBER) {
- sd->n--;
- return OK; /* don't advertise NAT addresses via broadcast */
- }
- if ( (sd->n != 0) &&
- (weak_randomi(sd->n) != 0) )
+ if (proto == NAT_PROTOCOL_NUMBER)
+ {
+ sd->n--;
+ return OK; /* don't advertise NAT addresses via broadcast
*/
+ }
+ if ((sd->n != 0) && (weak_randomi (sd->n) != 0))
return OK;
#if DEBUG_ADVERTISING
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&hi->hashPubKey,
- &other));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Entering `%s' with target `%s'.\n",
- __FUNCTION__,
- &other);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&hi->hashPubKey, &other));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Entering `%s' with target `%s'.\n", __FUNCTION__, &other);
#endif
- if (0 == memcmp(hi,
- coreAPI->myIdentity,
- sizeof(PeerIdentity)))
- return OK; /* never advertise to myself... */
- prio = (int) getConnectPriority();
+ if (0 == memcmp (hi, coreAPI->myIdentity, sizeof (PeerIdentity)))
+ return OK; /* never advertise to myself... */
+ prio = (int) getConnectPriority ();
if (prio >= EXTREME_PRIORITY)
prio = EXTREME_PRIORITY / 4;
- if (OK == coreAPI->queryPeerStatus(hi, NULL, NULL)) {
- coreAPI->unicast(hi,
- &sd->m->header,
- prio,
- HELLO_BROADCAST_FREQUENCY);
- if (stats != NULL)
- stats->change(stat_hello_out,
- 1);
- return OK;
- }
+ if (OK == coreAPI->queryPeerStatus (hi, NULL, NULL))
+ {
+ coreAPI->unicast (hi, &sd->m->header, prio, HELLO_BROADCAST_FREQUENCY);
+ if (stats != NULL)
+ stats->change (stat_hello_out, 1);
+ return OK;
+ }
/* with even lower probability (with n peers
trying to contact with a probability of 1/n^2,
we get a probability of 1/n for this, which
is what we want: fewer attempts to contact fresh
peers as the network grows): */
- if ( (sd->n != 0) &&
- (weak_randomi(sd->n) != 0) )
+ if ((sd->n != 0) && (weak_randomi (sd->n) != 0))
return OK;
/* establish short-lived connection, send, tear down */
- hello = identity->identity2Hello(hi,
- proto,
- NO);
- if (NULL == hello) {
+ hello = identity->identity2Hello (hi, proto, NO);
+ if (NULL == hello)
+ {
#if DEBUG_ADVERTISING
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Exit from `%s' (error: `%s' failed).\n",
- __FUNCTION__,
- "identity2Hello");
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Exit from `%s' (error: `%s' failed).\n",
+ __FUNCTION__, "identity2Hello");
#endif
- return OK;
- }
- tsession = transport->connect(hello);
- FREE(hello);
- if (tsession == NULL) {
+ return OK;
+ }
+ tsession = transport->connect (hello);
+ FREE (hello);
+ if (tsession == NULL)
+ {
#if DEBUG_ADVERTISING
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Exit from `%s' (%s error).\n",
- __FUNCTION__,
- "transportConnect");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Exit from `%s' (%s error).\n",
+ __FUNCTION__, "transportConnect");
#endif
- return OK; /* could not connect */
- }
+ return OK; /* could not connect */
+ }
if (stats != NULL)
- stats->change(stat_hello_out,
- 1);
- coreAPI->sendPlaintext(tsession,
- (char*)&sd->m->header,
- P2P_hello_MESSAGE_size(sd->m));
- transport->disconnect(tsession);
+ stats->change (stat_hello_out, 1);
+ coreAPI->sendPlaintext (tsession,
+ (char *) &sd->m->header,
+ P2P_hello_MESSAGE_size (sd->m));
+ transport->disconnect (tsession);
#if DEBUG_ADVERTISING
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Exit from %s.\n",
- __FUNCTION__);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "Exit from %s.\n", __FUNCTION__);
#endif
return OK;
}
@@ -528,154 +523,140 @@
* that we exist (called for each transport)...
*/
static void
-broadcasthelloTransport(TransportAPI * tapi,
- void * cls) {
- const int * prob = cls;
+broadcasthelloTransport (TransportAPI * tapi, void *cls)
+{
+ const int *prob = cls;
SendData sd;
cron_t now;
- if (os_network_monitor_get_load(coreAPI->load_monitor,
- Upload) > 100)
- return; /* network load too high... */
- if ( ((*prob) != 0) &&
- (0 != weak_randomi(*prob)) )
- return; /* ignore */
- now = get_time();
- sd.n = identity->forEachHost(now,
- NULL,
- NULL); /* just count */
- sd.m = transport->createhello(tapi->protocolNumber);
+ if (os_network_monitor_get_load (coreAPI->load_monitor, Upload) > 100)
+ return; /* network load too high... */
+ if (((*prob) != 0) && (0 != weak_randomi (*prob)))
+ return; /* ignore */
+ now = get_time ();
+ sd.n = identity->forEachHost (now, NULL, NULL); /* just count */
+ sd.m = transport->createhello (tapi->protocolNumber);
if (sd.m == NULL)
return;
#if DEBUG_ADVERTISING
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- _("Advertising my transport %d to selected peers.\n"),
- tapi->protocolNumber);
+ GE_LOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ _("Advertising my transport %d to selected peers.\n"),
+ tapi->protocolNumber);
#endif
- identity->addHost(sd.m);
- if (sd.n < 1) {
- if (identity->forEachHost(0, NULL, NULL) == 0)
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Announcing ourselves pointless: "
- "no other peers are known to us so far.\n"));
- FREE(sd.m);
- return; /* no point in trying... */
- }
- identity->forEachHost(now,
- &broadcastHelper,
- &sd);
- FREE(sd.m);
+ identity->addHost (sd.m);
+ if (sd.n < 1)
+ {
+ if (identity->forEachHost (0, NULL, NULL) == 0)
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Announcing ourselves pointless: "
+ "no other peers are known to us so far.\n"));
+ FREE (sd.m);
+ return; /* no point in trying... */
+ }
+ identity->forEachHost (now, &broadcastHelper, &sd);
+ FREE (sd.m);
}
/**
* Tell a couple of random hosts on the currentKnownHost list
* that we exist...
*/
-static void broadcasthello(void * unused) {
+static void
+broadcasthello (void *unused)
+{
unsigned int i;
- if (os_network_monitor_get_load(coreAPI->load_monitor,
- Upload) > 100)
- return; /* network load too high... */
- if (os_cpu_get_load(coreAPI->ectx,
- coreAPI->cfg) > 100)
- return; /* CPU load too high... */
- i = transport->forEach(NULL,
- NULL);
+ if (os_network_monitor_get_load (coreAPI->load_monitor, Upload) > 100)
+ return; /* network load too high... */
+ if (os_cpu_get_load (coreAPI->ectx, coreAPI->cfg) > 100)
+ return; /* CPU load too high... */
+ i = transport->forEach (NULL, NULL);
if (i > 0)
- transport->forEach(&broadcasthelloTransport,
- &i);
+ transport->forEach (&broadcasthelloTransport, &i);
}
-typedef struct {
- P2P_hello_MESSAGE * msg;
+typedef struct
+{
+ P2P_hello_MESSAGE *msg;
int prob;
} FCC;
-static void forwardCallback(const PeerIdentity * peer,
- void * cls) {
- FCC * fcc = cls;
- if (os_network_monitor_get_load(coreAPI->load_monitor,
- Upload) > 100)
- return; /* network load too high... */
- if ( (fcc->prob != 0) &&
- (weak_randomi(fcc->prob) != 0) )
- return; /* only forward with a certain chance */
- if (equalsHashCode512(&peer->hashPubKey,
- &fcc->msg->senderIdentity.hashPubKey))
- return; /* do not bounce the hello of a peer back
- to the same peer! */
+static void
+forwardCallback (const PeerIdentity * peer, void *cls)
+{
+ FCC *fcc = cls;
+ if (os_network_monitor_get_load (coreAPI->load_monitor, Upload) > 100)
+ return; /* network load too high... */
+ if ((fcc->prob != 0) && (weak_randomi (fcc->prob) != 0))
+ return; /* only forward with a certain chance */
+ if (equalsHashCode512 (&peer->hashPubKey,
+ &fcc->msg->senderIdentity.hashPubKey))
+ return; /* do not bounce the hello of a peer back
+ to the same peer! */
if (stats != NULL)
- stats->change(stat_hello_fwd, 1);
- coreAPI->unicast(peer,
- &fcc->msg->header,
- 0, /* priority */
- HELLO_BROADCAST_FREQUENCY);
+ stats->change (stat_hello_fwd, 1);
+ coreAPI->unicast (peer, &fcc->msg->header, 0, /* priority */
+ HELLO_BROADCAST_FREQUENCY);
}
/**
* Forward hellos from all known hosts to all connected hosts.
*/
static int
-forwardhelloHelper(const PeerIdentity * peer,
- unsigned short protocol,
- int confirmed,
- void * data) {
- int * probability = data;
- P2P_hello_MESSAGE * hello;
+forwardhelloHelper (const PeerIdentity * peer,
+ unsigned short protocol, int confirmed, void *data)
+{
+ int *probability = data;
+ P2P_hello_MESSAGE *hello;
TIME_T now;
int count;
FCC fcc;
- if (os_network_monitor_get_load(coreAPI->load_monitor,
- Upload) > 100)
- return SYSERR; /* network load too high... */
+ if (os_network_monitor_get_load (coreAPI->load_monitor, Upload) > 100)
+ return SYSERR; /* network load too high... */
if (confirmed == NO)
return OK;
if (protocol == NAT_PROTOCOL_NUMBER)
- return OK; /* don't forward NAT addresses */
- hello = identity->identity2Hello(peer,
- protocol,
- NO);
+ return OK; /* don't forward NAT addresses */
+ hello = identity->identity2Hello (peer, protocol, NO);
if (NULL == hello)
- return OK; /* this should not happen */
+ return OK; /* this should not happen */
/* do not forward expired hellos */
- TIME(&now);
- if ((TIME_T)ntohl(hello->expirationTime) < now) {
+ TIME (&now);
+ if ((TIME_T) ntohl (hello->expirationTime) < now)
+ {
#if DEBUG_ADVERTISING
- EncName enc;
- /* remove hellos that expired */
- IF_GELOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- hash2enc(&peer->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- "Removing HELLO from peer `%s' (expired %ds ago).\n",
- &enc,
- now - ntohl(hello->expirationTime));
+ EncName enc;
+ /* remove hellos that expired */
+ IF_GELOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ hash2enc (&peer->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ "Removing HELLO from peer `%s' (expired %ds ago).\n",
+ &enc, now - ntohl (hello->expirationTime));
#endif
- identity->delHostFromKnown(peer, protocol);
- FREE(hello);
- (*probability)--;
- return OK;
- }
- if (weak_randomi((*probability)+1) != 0) {
- FREE(hello);
- return OK; /* only forward with a certain chance,
- (on average: 1 peer per run!) */
- }
- count = coreAPI->forAllConnectedNodes(NULL,
- NULL);
- if (count > 0) {
- fcc.msg = hello;
- fcc.prob = count;
- coreAPI->forAllConnectedNodes(&forwardCallback,
- &fcc);
- }
- FREE(hello);
+ identity->delHostFromKnown (peer, protocol);
+ FREE (hello);
+ (*probability)--;
+ return OK;
+ }
+ if (weak_randomi ((*probability) + 1) != 0)
+ {
+ FREE (hello);
+ return OK; /* only forward with a certain chance,
+ (on average: 1 peer per run!) */
+ }
+ count = coreAPI->forAllConnectedNodes (NULL, NULL);
+ if (count > 0)
+ {
+ fcc.msg = hello;
+ fcc.prob = count;
+ coreAPI->forAllConnectedNodes (&forwardCallback, &fcc);
+ }
+ FREE (hello);
return OK;
}
@@ -685,50 +666,44 @@
* source and target).
*/
static void
-forwardhello(void * unused) {
+forwardhello (void *unused)
+{
int count;
- if (os_cpu_get_load(coreAPI->ectx,
- coreAPI->cfg) > 100)
- return; /* CPU load too high... */
- if (os_network_monitor_get_load(coreAPI->load_monitor,
- Upload) > 100)
- return; /* network load too high... */
- count = identity->forEachHost(0,
- NULL,
- NULL);
+ if (os_cpu_get_load (coreAPI->ectx, coreAPI->cfg) > 100)
+ return; /* CPU load too high... */
+ if (os_network_monitor_get_load (coreAPI->load_monitor, Upload) > 100)
+ return; /* network load too high... */
+ count = identity->forEachHost (0, NULL, NULL);
if (count > 0)
- identity->forEachHost(0, /* ignore blacklisting */
- &forwardhelloHelper,
- &count);
+ identity->forEachHost (0, /* ignore blacklisting */
+ &forwardhelloHelper, &count);
}
/**
* Type for a hello send via an encrypted channel.
*/
static int
-ehelloHandler(const PeerIdentity * sender,
- const MESSAGE_HEADER * message) {
- if (OK == receivedhello(sender,
- message)) {
- /* if the hello was ok, update traffic preference
- for the peer (depending on how much we like
- to learn about other peers) */
- coreAPI->preferTrafficFrom(sender,
- getConnectPriority());
- }
- return OK; /* even if we had errors processing the hello, keep going */
+ehelloHandler (const PeerIdentity * sender, const MESSAGE_HEADER * message)
+{
+ if (OK == receivedhello (sender, message))
+ {
+ /* if the hello was ok, update traffic preference
+ for the peer (depending on how much we like
+ to learn about other peers) */
+ coreAPI->preferTrafficFrom (sender, getConnectPriority ());
+ }
+ return OK; /* even if we had errors processing the hello,
keep going */
}
/**
* Type for a hello send in plaintext.
*/
static int
-phelloHandler(const PeerIdentity * sender,
- const MESSAGE_HEADER * message,
- TSession * session) {
- receivedhello(sender,
- message);
+phelloHandler (const PeerIdentity * sender,
+ const MESSAGE_HEADER * message, TSession * session)
+{
+ receivedhello (sender, message);
return OK;
}
@@ -738,59 +713,56 @@
* job!
*/
static int
-configurationUpdateCallback(void * ctx,
- struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option) {
- if (0 != strcmp(section, "NETWORK"))
+configurationUpdateCallback (void *ctx,
+ struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section, const char *option)
+{
+ if (0 != strcmp (section, "NETWORK"))
return 0;
- if (ACJ_ANNOUNCE == (activeCronJobs & ACJ_ANNOUNCE)) {
- if (YES == GC_get_configuration_value_yesno(cfg,
- "NETWORK",
- "DISABLE-ADVERTISEMENTS",
- NO))
- cron_del_job(coreAPI->cron,
- &broadcasthello,
- HELLO_BROADCAST_FREQUENCY,
- NULL);
- activeCronJobs -= ACJ_ANNOUNCE;
- } else {
- if (YES != GC_get_configuration_value_yesno(cfg,
- "NETWORK",
- "DISABLE-ADVERTISEMENTS",
- NO))
- cron_add_job(coreAPI->cron,
- &broadcasthello,
- 15 * cronSECONDS,
- HELLO_BROADCAST_FREQUENCY,
- NULL);
- activeCronJobs += ACJ_ANNOUNCE;
- }
- if (ACJ_FORWARD == (activeCronJobs & ACJ_FORWARD)) {
- if (YES != GC_get_configuration_value_yesno(cfg,
- "NETWORK",
- "HELLOEXCHANGE",
- YES)) {
- cron_del_job(coreAPI->cron,
- &forwardhello,
- HELLO_FORWARD_FREQUENCY,
- NULL); /* seven minutes: exchange */
+ if (ACJ_ANNOUNCE == (activeCronJobs & ACJ_ANNOUNCE))
+ {
+ if (YES == GC_get_configuration_value_yesno (cfg,
+ "NETWORK",
+ "DISABLE-ADVERTISEMENTS",
+ NO))
+ cron_del_job (coreAPI->cron,
+ &broadcasthello, HELLO_BROADCAST_FREQUENCY, NULL);
+ activeCronJobs -= ACJ_ANNOUNCE;
}
- activeCronJobs -= ACJ_FORWARD;
- } else {
- if (YES == GC_get_configuration_value_yesno(cfg,
- "NETWORK",
- "HELLOEXCHANGE",
- YES)) {
- cron_add_job(coreAPI->cron,
- &forwardhello,
- 15 * cronSECONDS,
- HELLO_FORWARD_FREQUENCY,
- NULL);
+ else
+ {
+ if (YES != GC_get_configuration_value_yesno (cfg,
+ "NETWORK",
+ "DISABLE-ADVERTISEMENTS",
+ NO))
+ cron_add_job (coreAPI->cron,
+ &broadcasthello,
+ 15 * cronSECONDS, HELLO_BROADCAST_FREQUENCY, NULL);
+ activeCronJobs += ACJ_ANNOUNCE;
}
- activeCronJobs += ACJ_FORWARD;
- }
+ if (ACJ_FORWARD == (activeCronJobs & ACJ_FORWARD))
+ {
+ if (YES != GC_get_configuration_value_yesno (cfg,
+ "NETWORK",
+ "HELLOEXCHANGE", YES))
+ {
+ cron_del_job (coreAPI->cron, &forwardhello, HELLO_FORWARD_FREQUENCY,
NULL); /* seven minutes: exchange */
+ }
+ activeCronJobs -= ACJ_FORWARD;
+ }
+ else
+ {
+ if (YES == GC_get_configuration_value_yesno (cfg,
+ "NETWORK",
+ "HELLOEXCHANGE", YES))
+ {
+ cron_add_job (coreAPI->cron,
+ &forwardhello,
+ 15 * cronSECONDS, HELLO_FORWARD_FREQUENCY, NULL);
+ }
+ activeCronJobs += ACJ_FORWARD;
+ }
return 0;
}
@@ -798,121 +770,145 @@
* Start advertising.
*/
int
-initialize_module_advertising(CoreAPIForApplication * capi) {
+initialize_module_advertising (CoreAPIForApplication * capi)
+{
coreAPI = capi;
ectx = capi->ectx;
- identity = capi->requestService("identity");
- if (identity == NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- transport = capi->requestService("transport");
- if (transport == NULL) {
- GE_BREAK(ectx, 0);
- capi->releaseService(identity);
- identity = NULL;
- return SYSERR;
- }
- pingpong = capi->requestService("pingpong");
- if (pingpong == NULL) {
- GE_BREAK(ectx, 0);
- capi->releaseService(identity);
- identity = NULL;
- capi->releaseService(transport);
- transport = NULL;
- return SYSERR;
- }
- topology = capi->requestService("topology");
- if (topology == NULL) {
- GE_BREAK(ectx, 0);
- capi->releaseService(identity);
- identity = NULL;
- capi->releaseService(transport);
- transport = NULL;
- capi->releaseService(pingpong);
- pingpong = NULL;
- return SYSERR;
- }
- stats = capi->requestService("stats");
- if (stats != NULL) {
- stat_hello_in = stats->create(gettext_noop("# Peer advertisements
received"));
- stat_hello_nat_in = stats->create(gettext_noop("# Peer advertisements of
type NAT received"));
- stat_hello_verified = stats->create(gettext_noop("# Peer advertisements
confirmed via PONG"));
- stat_hello_update = stats->create(gettext_noop("# Peer advertisements
updating earlier HELLOs"));
- stat_hello_discard = stats->create(gettext_noop("# Peer advertisements
discarded due to load"));
- stat_hello_no_transport = stats->create(gettext_noop("# Peer
advertisements for unsupported transport"));
- stat_hello_ping_busy = stats->create(gettext_noop("# Peer advertisements
not confirmed due to ping busy"));
- stat_hello_noselfad = stats->create(gettext_noop("# Peer advertisements
not confirmed due to lack of self ad"));
- stat_hello_send_error = stats->create(gettext_noop("# Peer advertisements
not confirmed due to send error"));
- stat_hello_out = stats->create(gettext_noop("# Self advertisments
transmitted"));
- stat_hello_fwd = stats->create(gettext_noop("# Foreign advertisements
forwarded"));
- stat_plaintextPingSent
- = stats->create(gettext_noop("# plaintext PING messages sent"));
- }
+ identity = capi->requestService ("identity");
+ if (identity == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ transport = capi->requestService ("transport");
+ if (transport == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ capi->releaseService (identity);
+ identity = NULL;
+ return SYSERR;
+ }
+ pingpong = capi->requestService ("pingpong");
+ if (pingpong == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ capi->releaseService (identity);
+ identity = NULL;
+ capi->releaseService (transport);
+ transport = NULL;
+ return SYSERR;
+ }
+ topology = capi->requestService ("topology");
+ if (topology == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ capi->releaseService (identity);
+ identity = NULL;
+ capi->releaseService (transport);
+ transport = NULL;
+ capi->releaseService (pingpong);
+ pingpong = NULL;
+ return SYSERR;
+ }
+ stats = capi->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_hello_in =
+ stats->create (gettext_noop ("# Peer advertisements received"));
+ stat_hello_nat_in =
+ stats->
+ create (gettext_noop ("# Peer advertisements of type NAT received"));
+ stat_hello_verified =
+ stats->
+ create (gettext_noop ("# Peer advertisements confirmed via PONG"));
+ stat_hello_update =
+ stats->
+ create (gettext_noop
+ ("# Peer advertisements updating earlier HELLOs"));
+ stat_hello_discard =
+ stats->
+ create (gettext_noop ("# Peer advertisements discarded due to load"));
+ stat_hello_no_transport =
+ stats->
+ create (gettext_noop
+ ("# Peer advertisements for unsupported transport"));
+ stat_hello_ping_busy =
+ stats->
+ create (gettext_noop
+ ("# Peer advertisements not confirmed due to ping busy"));
+ stat_hello_noselfad =
+ stats->
+ create (gettext_noop
+ ("# Peer advertisements not confirmed due to lack of self
ad"));
+ stat_hello_send_error =
+ stats->
+ create (gettext_noop
+ ("# Peer advertisements not confirmed due to send error"));
+ stat_hello_out =
+ stats->create (gettext_noop ("# Self advertisments transmitted"));
+ stat_hello_fwd =
+ stats->create (gettext_noop ("# Foreign advertisements forwarded"));
+ stat_plaintextPingSent =
+ stats->create (gettext_noop ("# plaintext PING messages sent"));
+ }
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _("`%s' registering handler %d (plaintext and ciphertext)\n"),
- "advertising",
- p2p_PROTO_hello);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ _("`%s' registering handler %d (plaintext and ciphertext)\n"),
+ "advertising", p2p_PROTO_hello);
- capi->registerHandler(p2p_PROTO_hello,
- &ehelloHandler);
- capi->registerPlaintextHandler(p2p_PROTO_hello,
- &phelloHandler);
- if (0 != GC_attach_change_listener(capi->cfg,
- &configurationUpdateCallback,
- NULL))
- GE_BREAK(capi->ectx, 0);
- startBootstrap(capi);
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "advertising",
- _("ensures that this peer is known
by other"
- " peers and discovers other
peers")));
+ capi->registerHandler (p2p_PROTO_hello, &ehelloHandler);
+ capi->registerPlaintextHandler (p2p_PROTO_hello, &phelloHandler);
+ if (0 != GC_attach_change_listener (capi->cfg,
+ &configurationUpdateCallback, NULL))
+ GE_BREAK (capi->ectx, 0);
+ startBootstrap (capi);
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "advertising",
+ _
+ ("ensures that this peer
is known by other"
+ " peers and discovers
other peers")));
return OK;
}
/**
* Stop advertising.
*/
-void done_module_advertising() {
- stopBootstrap();
- GC_detach_change_listener(coreAPI->cfg,
- &configurationUpdateCallback,
- NULL);
- if (ACJ_ANNOUNCE == (activeCronJobs & ACJ_ANNOUNCE)) {
- cron_del_job(coreAPI->cron,
- &broadcasthello,
- HELLO_BROADCAST_FREQUENCY,
- NULL);
- activeCronJobs -= ACJ_ANNOUNCE;
- }
- if (ACJ_FORWARD == (activeCronJobs & ACJ_FORWARD)) {
- cron_del_job(coreAPI->cron,
- &forwardhello,
- HELLO_FORWARD_FREQUENCY,
- NULL); /* seven minutes: exchange */
- activeCronJobs -= ACJ_FORWARD;
- }
- coreAPI->unregisterHandler(p2p_PROTO_hello,
- &ehelloHandler);
- coreAPI->unregisterPlaintextHandler(p2p_PROTO_hello,
- &phelloHandler);
- coreAPI->releaseService(transport);
+void
+done_module_advertising ()
+{
+ stopBootstrap ();
+ GC_detach_change_listener (coreAPI->cfg,
+ &configurationUpdateCallback, NULL);
+ if (ACJ_ANNOUNCE == (activeCronJobs & ACJ_ANNOUNCE))
+ {
+ cron_del_job (coreAPI->cron,
+ &broadcasthello, HELLO_BROADCAST_FREQUENCY, NULL);
+ activeCronJobs -= ACJ_ANNOUNCE;
+ }
+ if (ACJ_FORWARD == (activeCronJobs & ACJ_FORWARD))
+ {
+ cron_del_job (coreAPI->cron, &forwardhello, HELLO_FORWARD_FREQUENCY,
NULL); /* seven minutes: exchange */
+ activeCronJobs -= ACJ_FORWARD;
+ }
+ coreAPI->unregisterHandler (p2p_PROTO_hello, &ehelloHandler);
+ coreAPI->unregisterPlaintextHandler (p2p_PROTO_hello, &phelloHandler);
+ coreAPI->releaseService (transport);
transport = NULL;
- coreAPI->releaseService(identity);
+ coreAPI->releaseService (identity);
identity = NULL;
- coreAPI->releaseService(pingpong);
+ coreAPI->releaseService (pingpong);
pingpong = NULL;
- coreAPI->releaseService(topology);
+ coreAPI->releaseService (topology);
topology = NULL;
- if (stats != NULL) {
- coreAPI->releaseService(stats);
- stats = NULL;
- }
+ if (stats != NULL)
+ {
+ coreAPI->releaseService (stats);
+ stats = NULL;
+ }
coreAPI = NULL;
}
Modified: GNUnet/src/applications/advertising/advertising_test.c
===================================================================
--- GNUnet/src/applications/advertising/advertising_test.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/advertising/advertising_test.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -42,15 +42,15 @@
#define NUM_ROUNDS 10
-static int countConnections(const char * name,
- unsigned long long value,
- void * cls) {
- int * num = cls;
- if (0 == strcmp(_("# of connected peers"),
- name)) {
- *num = value;
- return SYSERR;
- }
+static int
+countConnections (const char *name, unsigned long long value, void *cls)
+{
+ int *num = cls;
+ if (0 == strcmp (_("# of connected peers"), name))
+ {
+ *num = value;
+ return SYSERR;
+ }
return OK;
}
@@ -58,13 +58,14 @@
* Testcase to test advertising
* @return 0: ok, -1: error
*/
-int main(int argc,
- const char ** argv) {
- struct DaemonContext * peers;
+int
+main (int argc, const char **argv)
+{
+ struct DaemonContext *peers;
int ret = 0;
- struct GE_Context * ectx;
- struct GC_Configuration * cfg;
- struct ClientServerConnection * sock;
+ struct GE_Context *ectx;
+ struct GC_Configuration *cfg;
+ struct ClientServerConnection *sock;
int i;
int k;
int have;
@@ -73,74 +74,67 @@
int min;
ectx = NULL;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- peers = gnunet_testing_start_daemons(NULL == strstr(argv[0], "_udp") ? "tcp"
: "udp",
- "advertising stats",
- "/tmp/gnunet-advertising-test",
- 2087,
- 10,
- NUM_PEERS);
- if (peers == NULL) {
- GC_free(cfg);
- return -1;
- }
- /* do circular connect */
- for (i=0;i<NUM_PEERS;i++) {
- if (OK != gnunet_testing_connect_daemons(2087 + 10*i,
- 2087 + 10* ( (i+1) % NUM_PEERS))) {
- gnunet_testing_stop_daemons(peers);
- fprintf(stderr,
- "Failed to connect peers %d and %d!\n",
- i,
- (i+1) % NUM_PEERS);
- GC_free(cfg);
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
return -1;
}
- }
- PTHREAD_SLEEP(15 * cronSECONDS);
+ peers =
+ gnunet_testing_start_daemons (NULL ==
+ strstr (argv[0], "_udp") ? "tcp" : "udp",
+ "advertising stats",
+ "/tmp/gnunet-advertising-test", 2087, 10,
+ NUM_PEERS);
+ if (peers == NULL)
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ /* do circular connect */
+ for (i = 0; i < NUM_PEERS; i++)
+ {
+ if (OK != gnunet_testing_connect_daemons (2087 + 10 * i,
+ 2087 +
+ 10 * ((i + 1) % NUM_PEERS)))
+ {
+ gnunet_testing_stop_daemons (peers);
+ fprintf (stderr,
+ "Failed to connect peers %d and %d!\n",
+ i, (i + 1) % NUM_PEERS);
+ GC_free (cfg);
+ return -1;
+ }
+ }
+ PTHREAD_SLEEP (15 * cronSECONDS);
/* check loops */
- for (k=0;k<NUM_ROUNDS;k++) {
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- found = 0;
- min = NUM_PEERS;
- for (i=0;i<NUM_PEERS;i++) {
- SNPRINTF(buf,
- 128,
- "localhost:%u",
- 2087 + i * 10);
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- buf);
- sock = client_connection_create(NULL,
- cfg);
- STATS_getStatistics(NULL,
- sock,
- &countConnections,
- &have);
- connection_destroy(sock);
- found += have;
- if (have < min)
- min = have;
+ for (k = 0; k < NUM_ROUNDS; k++)
+ {
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ found = 0;
+ min = NUM_PEERS;
+ for (i = 0; i < NUM_PEERS; i++)
+ {
+ SNPRINTF (buf, 128, "localhost:%u", 2087 + i * 10);
+ GC_set_configuration_value_string (cfg,
+ ectx, "NETWORK", "HOST", buf);
+ sock = client_connection_create (NULL, cfg);
+ STATS_getStatistics (NULL, sock, &countConnections, &have);
+ connection_destroy (sock);
+ found += have;
+ if (have < min)
+ min = have;
+ }
+ fprintf (stderr,
+ "Have %d connections total in round %d, minimum number was
%d\n",
+ found, k, min);
+ if (k < NUM_ROUNDS - 1)
+ PTHREAD_SLEEP (45 * cronSECONDS); /* one hello-forward round is
45s! */
}
- fprintf(stderr,
- "Have %d connections total in round %d, minimum number was %d\n",
- found,
- k,
- min);
- if (k < NUM_ROUNDS - 1)
- PTHREAD_SLEEP(45 * cronSECONDS); /* one hello-forward round is 45s! */
- }
- gnunet_testing_stop_daemons(peers);
- GC_free(cfg);
+ gnunet_testing_stop_daemons (peers);
+ GC_free (cfg);
return ret;
}
Modified: GNUnet/src/applications/advertising/bootstrap.c
===================================================================
--- GNUnet/src/applications/advertising/bootstrap.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/advertising/bootstrap.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -35,16 +35,17 @@
#define hello_HELPER_TABLE_START_SIZE 64
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static Bootstrap_ServiceAPI * bootstrap;
+static Bootstrap_ServiceAPI *bootstrap;
-static State_ServiceAPI * state;
+static State_ServiceAPI *state;
-static struct PTHREAD * pt;
+static struct PTHREAD *pt;
-typedef struct {
- P2P_hello_MESSAGE ** hellos;
+typedef struct
+{
+ P2P_hello_MESSAGE **hellos;
unsigned int hellosCount;
unsigned int hellosLen;
int do_shutdown;
@@ -52,163 +53,159 @@
static HelloListClosure hlc;
-static int testTerminate(void * cls) {
- HelloListClosure * c = cls;
- return ! c->do_shutdown;
+static int
+testTerminate (void *cls)
+{
+ HelloListClosure *c = cls;
+ return !c->do_shutdown;
}
-static void processhellos(HelloListClosure * hcq) {
+static void
+processhellos (HelloListClosure * hcq)
+{
int rndidx;
int i;
- P2P_hello_MESSAGE * msg;
+ P2P_hello_MESSAGE *msg;
- if (NULL == hcq) {
- GE_BREAK(coreAPI->ectx, 0);
- return;
- }
- while ( (! hcq->do_shutdown) &&
- (hcq->hellosCount > 0) ) {
- /* select hellos in random order */
- rndidx = weak_randomi(hcq->hellosCount);
+ if (NULL == hcq)
+ {
+ GE_BREAK (coreAPI->ectx, 0);
+ return;
+ }
+ while ((!hcq->do_shutdown) && (hcq->hellosCount > 0))
+ {
+ /* select hellos in random order */
+ rndidx = weak_randomi (hcq->hellosCount);
#if DEBUG_BOOTSTRAP
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "%s chose hello %d of %d\n",
- __FUNCTION__,
- rndidx, hcq->hellosCount);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "%s chose hello %d of %d\n",
+ __FUNCTION__, rndidx, hcq->hellosCount);
#endif
- msg = (P2P_hello_MESSAGE*) hcq->hellos[rndidx];
- hcq->hellos[rndidx]
- = hcq->hellos[hcq->hellosCount-1];
- GROW(hcq->hellos,
- hcq->hellosCount,
- hcq->hellosCount-1);
+ msg = (P2P_hello_MESSAGE *) hcq->hellos[rndidx];
+ hcq->hellos[rndidx] = hcq->hellos[hcq->hellosCount - 1];
+ GROW (hcq->hellos, hcq->hellosCount, hcq->hellosCount - 1);
- coreAPI->injectMessage(NULL,
- (const char*)msg,
- ntohs(msg->header.size),
- NO,
- NULL);
- FREE(msg);
- if ( (hcq->hellosCount > 0) &&
- (! hlc.do_shutdown) ) {
- /* wait a bit */
- unsigned int load;
- int nload;
- load = os_cpu_get_load(coreAPI->ectx,
- coreAPI->cfg);
- if (load == (unsigned int)-1)
- load = 50;
- nload = os_network_monitor_get_load(coreAPI->load_monitor,
- Upload);
- if (nload > load)
- load = nload;
- nload = os_network_monitor_get_load(coreAPI->load_monitor,
- Download);
- if (nload > load)
- load = nload;
- if (load > 100)
- load = 100;
+ coreAPI->injectMessage (NULL,
+ (const char *) msg,
+ ntohs (msg->header.size), NO, NULL);
+ FREE (msg);
+ if ((hcq->hellosCount > 0) && (!hlc.do_shutdown))
+ {
+ /* wait a bit */
+ unsigned int load;
+ int nload;
+ load = os_cpu_get_load (coreAPI->ectx, coreAPI->cfg);
+ if (load == (unsigned int) -1)
+ load = 50;
+ nload = os_network_monitor_get_load (coreAPI->load_monitor, Upload);
+ if (nload > load)
+ load = nload;
+ nload = os_network_monitor_get_load (coreAPI->load_monitor,
+ Download);
+ if (nload > load)
+ load = nload;
+ if (load > 100)
+ load = 100;
- PTHREAD_SLEEP(50 + weak_randomi((load+1)*(load+1)));
+ PTHREAD_SLEEP (50 + weak_randomi ((load + 1) * (load + 1)));
+ }
}
- }
- for (i=0;i<hcq->hellosCount;i++)
- FREE(hcq->hellos[i]);
- GROW(hcq->hellos,
- hcq->hellosCount,
- 0);
+ for (i = 0; i < hcq->hellosCount; i++)
+ FREE (hcq->hellos[i]);
+ GROW (hcq->hellos, hcq->hellosCount, 0);
}
-static void downloadHostlistCallback(const P2P_hello_MESSAGE * hello,
- void * c) {
- HelloListClosure * cls = c;
- if (cls->hellosCount >= cls->hellosLen) {
- GROW(cls->hellos,
- cls->hellosLen,
- cls->hellosLen + hello_HELPER_TABLE_START_SIZE);
- }
- cls->hellos[cls->hellosCount++] = MALLOC(ntohs(hello->header.size));
- memcpy(cls->hellos[cls->hellosCount-1],
- hello,
- ntohs(hello->header.size));
+static void
+downloadHostlistCallback (const P2P_hello_MESSAGE * hello, void *c)
+{
+ HelloListClosure *cls = c;
+ if (cls->hellosCount >= cls->hellosLen)
+ {
+ GROW (cls->hellos,
+ cls->hellosLen, cls->hellosLen + hello_HELPER_TABLE_START_SIZE);
+ }
+ cls->hellos[cls->hellosCount++] = MALLOC (ntohs (hello->header.size));
+ memcpy (cls->hellos[cls->hellosCount - 1],
+ hello, ntohs (hello->header.size));
}
#define BOOTSTRAP_INFO "bootstrap-info"
-static int needBootstrap() {
+static int
+needBootstrap ()
+{
static cron_t lastTest;
static cron_t delta;
cron_t now;
- char * data;
+ char *data;
- now = get_time();
- if (coreAPI->forAllConnectedNodes(NULL, NULL) >= 3) {
- /* still change delta and lastTest; even
- if the peer _briefly_ drops below 3
- connections, we don't want it to immediately
- go for the hostlist... */
- delta = 5 * cronMINUTES;
- lastTest = now;
- return NO;
- }
- if (lastTest == 0) {
- /* first run in this process */
- if (-1 != state->read(coreAPI->ectx,
- BOOTSTRAP_INFO,
- (void**)&data)) {
- /* but not first on this machine */
+ now = get_time ();
+ if (coreAPI->forAllConnectedNodes (NULL, NULL) >= 3)
+ {
+ /* still change delta and lastTest; even
+ if the peer _briefly_ drops below 3
+ connections, we don't want it to immediately
+ go for the hostlist... */
+ delta = 5 * cronMINUTES;
lastTest = now;
- delta = 2 * cronMINUTES; /* wait 2 minutes */
- FREE(data);
- } else {
- /* first on this machine, too! */
- state->write(coreAPI->ectx,
- BOOTSTRAP_INFO,
- 1,
- "X");
- delta = 60 * cronSECONDS;
+ return NO;
}
- }
- if (now - lastTest > delta) {
- lastTest = now;
- delta *= 2; /* exponential back-off */
- /* Maybe it should ALSO be based on how many peers
- we know (identity).
- Sure, in the end it goes to the topology, so
- probably that API should be extended here... */
- return YES;
- }
+ if (lastTest == 0)
+ {
+ /* first run in this process */
+ if (-1 != state->read (coreAPI->ectx, BOOTSTRAP_INFO, (void **) &data))
+ {
+ /* but not first on this machine */
+ lastTest = now;
+ delta = 2 * cronMINUTES; /* wait 2 minutes */
+ FREE (data);
+ }
+ else
+ {
+ /* first on this machine, too! */
+ state->write (coreAPI->ectx, BOOTSTRAP_INFO, 1, "X");
+ delta = 60 * cronSECONDS;
+ }
+ }
+ if (now - lastTest > delta)
+ {
+ lastTest = now;
+ delta *= 2; /* exponential back-off */
+ /* Maybe it should ALSO be based on how many peers
+ we know (identity).
+ Sure, in the end it goes to the topology, so
+ probably that API should be extended here... */
+ return YES;
+ }
/* wait a bit longer */
return NO;
}
-static void * processThread(void * unused) {
+static void *
+processThread (void *unused)
+{
hlc.hellos = NULL;
- while (NO == hlc.do_shutdown) {
- while (NO == hlc.do_shutdown) {
- PTHREAD_SLEEP(2 * cronSECONDS);
- if (needBootstrap())
- break;
- }
- if (YES == hlc.do_shutdown)
- break;
+ while (NO == hlc.do_shutdown)
+ {
+ while (NO == hlc.do_shutdown)
+ {
+ PTHREAD_SLEEP (2 * cronSECONDS);
+ if (needBootstrap ())
+ break;
+ }
+ if (YES == hlc.do_shutdown)
+ break;
#if DEBUG_BOOTSTRAP
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Starting bootstrap.\n");
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, "Starting bootstrap.\n");
#endif
- hlc.hellosLen = 0;
- hlc.hellosCount = 0;
- bootstrap->bootstrap(&downloadHostlistCallback,
- &hlc,
- &testTerminate,
- &hlc);
- GROW(hlc.hellos,
- hlc.hellosLen,
- hlc.hellosCount);
- processhellos(&hlc);
- }
+ hlc.hellosLen = 0;
+ hlc.hellosCount = 0;
+ bootstrap->bootstrap (&downloadHostlistCallback,
+ &hlc, &testTerminate, &hlc);
+ GROW (hlc.hellos, hlc.hellosLen, hlc.hellosCount);
+ processhellos (&hlc);
+ }
return NULL;
}
@@ -216,35 +213,34 @@
* Start using the bootstrap service to obtain
* advertisements if needed.
*/
-void startBootstrap(CoreAPIForApplication * capi) {
+void
+startBootstrap (CoreAPIForApplication * capi)
+{
coreAPI = capi;
- state = capi->requestService("state");
- GE_ASSERT(capi->ectx,
- state != NULL);
- bootstrap = capi->requestService("bootstrap");
- GE_ASSERT(capi->ectx,
- bootstrap != NULL);
+ state = capi->requestService ("state");
+ GE_ASSERT (capi->ectx, state != NULL);
+ bootstrap = capi->requestService ("bootstrap");
+ GE_ASSERT (capi->ectx, bootstrap != NULL);
hlc.do_shutdown = NO;
- pt = PTHREAD_CREATE(&processThread,
- NULL,
- 64 * 1024);
- GE_ASSERT(capi->ectx,
- pt != NULL);
+ pt = PTHREAD_CREATE (&processThread, NULL, 64 * 1024);
+ GE_ASSERT (capi->ectx, pt != NULL);
}
/**
* Stop advertising.
*/
-void stopBootstrap() {
- void * unused;
+void
+stopBootstrap ()
+{
+ void *unused;
hlc.do_shutdown = YES;
- PTHREAD_STOP_SLEEP(pt);
- PTHREAD_JOIN(pt, &unused);
+ PTHREAD_STOP_SLEEP (pt);
+ PTHREAD_JOIN (pt, &unused);
pt = NULL;
- coreAPI->releaseService(bootstrap);
+ coreAPI->releaseService (bootstrap);
bootstrap = NULL;
- coreAPI->releaseService(state);
+ coreAPI->releaseService (state);
state = NULL;
coreAPI = NULL;
}
Modified: GNUnet/src/applications/advertising/bootstrap.h
===================================================================
--- GNUnet/src/applications/advertising/bootstrap.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/advertising/bootstrap.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -34,12 +34,12 @@
* Start using the bootstrap service to obtain
* advertisements if needed.
*/
-void startBootstrap(CoreAPIForApplication * capi);
+void startBootstrap (CoreAPIForApplication * capi);
/**
* Stop the bootstap service.
*/
-void stopBootstrap(void);
+void stopBootstrap (void);
#endif
Modified: GNUnet/src/applications/bootstrap_http/http.c
===================================================================
--- GNUnet/src/applications/bootstrap_http/http.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/bootstrap_http/http.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -36,29 +36,30 @@
/**
* Stats service (maybe NULL!)
*/
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
static int stat_hellodownloaded;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-typedef struct {
+typedef struct
+{
bootstrap_hello_callback callback;
- void * arg;
+ void *arg;
bootstrap_terminate_callback termTest;
- void * targ;
+ void *targ;
- char * buf;
+ char *buf;
unsigned int bsize;
- const char * url;
+ const char *url;
unsigned long long total;
@@ -70,71 +71,62 @@
* Process downloaded bits by calling callback on each hello.
*/
static size_t
-downloadHostlistHelper(void * ptr,
- size_t size,
- size_t nmemb,
- void * ctx) {
- BootstrapContext * bctx = ctx;
+downloadHostlistHelper (void *ptr, size_t size, size_t nmemb, void *ctx)
+{
+ BootstrapContext *bctx = ctx;
size_t osize;
unsigned int total;
- const P2P_hello_MESSAGE * hello;
+ const P2P_hello_MESSAGE *hello;
unsigned int hs;
bctx->total += size * nmemb;
if (size * nmemb == 0)
- return 0; /* ok, no data */
+ return 0; /* ok, no data */
osize = bctx->bsize;
total = size * nmemb + osize;
- GROW(bctx->buf,
- bctx->bsize,
- total);
- memcpy(&bctx->buf[osize],
- ptr,
- size * nmemb);
- while ( (bctx->bsize >= sizeof(P2P_hello_MESSAGE)) &&
- (bctx->termTest(bctx->targ)) ) {
- hello = (const P2P_hello_MESSAGE*) &bctx->buf[0];
- hs = ntohs(hello->header.size);
- if (bctx->bsize < hs)
- break; /* incomplete */
- if ( (ntohs(hello->header.type) != p2p_PROTO_hello) ||
- (ntohs(hello->header.size) != P2P_hello_MESSAGE_size(hello) ) ||
- (P2P_hello_MESSAGE_size(hello) >= MAX_BUFFER_SIZE) ) {
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_IMMEDIATE,
- _("Bootstrap data obtained from `%s' is invalid.\n"),
- bctx->url);
- return 0; /* Error: invalid format! */
+ GROW (bctx->buf, bctx->bsize, total);
+ memcpy (&bctx->buf[osize], ptr, size * nmemb);
+ while ((bctx->bsize >= sizeof (P2P_hello_MESSAGE)) &&
+ (bctx->termTest (bctx->targ)))
+ {
+ hello = (const P2P_hello_MESSAGE *) &bctx->buf[0];
+ hs = ntohs (hello->header.size);
+ if (bctx->bsize < hs)
+ break; /* incomplete */
+ if ((ntohs (hello->header.type) != p2p_PROTO_hello) ||
+ (ntohs (hello->header.size) != P2P_hello_MESSAGE_size (hello)) ||
+ (P2P_hello_MESSAGE_size (hello) >= MAX_BUFFER_SIZE))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_IMMEDIATE,
+ _("Bootstrap data obtained from `%s' is invalid.\n"),
+ bctx->url);
+ return 0; /* Error: invalid format! */
+ }
+ if (stats != NULL)
+ stats->change (stat_hellodownloaded, 1);
+ bctx->callback (hello, bctx->arg);
+ memmove (&bctx->buf[0], &bctx->buf[hs], bctx->bsize - hs);
+ GROW (bctx->buf, bctx->bsize, bctx->bsize - hs);
}
- if (stats != NULL)
- stats->change(stat_hellodownloaded,
- 1);
- bctx->callback(hello,
- bctx->arg);
- memmove(&bctx->buf[0],
- &bctx->buf[hs],
- bctx->bsize - hs);
- GROW(bctx->buf,
- bctx->bsize,
- bctx->bsize - hs);
- }
return size * nmemb;
}
#define CURL_EASY_SETOPT(c, a, b) do { ret = curl_easy_setopt(c, a, b); if
(ret != CURLE_OK) GE_LOG(ectx, GE_WARNING | GE_USER | GE_BULK, _("%s failed at
%s:%d: `%s'\n"), "curl_easy_setopt", __FILE__, __LINE__,
curl_easy_strerror(ret)); } while (0);
-static void downloadHostlist(bootstrap_hello_callback callback,
- void * arg,
- bootstrap_terminate_callback termTest,
- void * targ) {
+static void
+downloadHostlist (bootstrap_hello_callback callback,
+ void *arg,
+ bootstrap_terminate_callback termTest, void *targ)
+{
BootstrapContext bctx;
- char * url;
- char * proxy;
- CURL * curl;
+ char *url;
+ char *proxy;
+ CURL *curl;
CURLcode ret;
#if USE_MULTI
- CURLM * multi;
+ CURLM *multi;
CURLMcode mret;
fd_set rs;
fd_set ws;
@@ -142,291 +134,265 @@
int max;
struct timeval tv;
int running;
- struct CURLMsg * msg;
+ struct CURLMsg *msg;
#endif
unsigned int urls;
size_t pos;
- if (0 != curl_global_init(CURL_GLOBAL_WIN32)) {
- GE_BREAK(ectx, 0);
- return;
- }
+ if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+ {
+ GE_BREAK (ectx, 0);
+ return;
+ }
bctx.callback = callback;
bctx.arg = arg;
bctx.termTest = termTest;
bctx.targ = targ;
bctx.buf = NULL;
bctx.bsize = 0;
- curl = curl_easy_init();
+ curl = curl_easy_init ();
#if USE_MULTI
multi = NULL;
#endif
- if (curl == NULL) {
- GE_BREAK(ectx, 0);
- return;
- }
+ if (curl == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return;
+ }
url = NULL;
- if (0 != GC_get_configuration_value_string(coreAPI->cfg,
- "GNUNETD",
- "HOSTLISTURL",
- "",
- &url)) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("No hostlist URL specified in configuration, will not bootstrap.\n"));
- FREE(url);
- curl_easy_cleanup(curl);
- return;
- }
+ if (0 != GC_get_configuration_value_string (coreAPI->cfg,
+ "GNUNETD",
+ "HOSTLISTURL", "", &url))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("No hostlist URL specified in configuration, will not
bootstrap.\n"));
+ FREE (url);
+ curl_easy_cleanup (curl);
+ return;
+ }
urls = 0;
- if (strlen(url) > 0) {
- urls++;
- pos = strlen(url) - 1;
- while (pos > 0) {
+ if (strlen (url) > 0)
+ {
+ urls++;
+ pos = strlen (url) - 1;
+ while (pos > 0)
+ {
+ if (url[pos] == ' ')
+ urls++;
+ pos--;
+ }
+ }
+ if (urls == 0)
+ {
+ FREE (url);
+ curl_easy_cleanup (curl);
+ return;
+ }
+ urls = weak_randomi (urls) + 1;
+ pos = strlen (url) - 1;
+ while (pos > 0)
+ {
if (url[pos] == ' ')
- urls++;
+ {
+ urls--;
+ url[pos] = '\0';
+ }
+ if (urls == 0)
+ {
+ pos++;
+ break;
+ }
pos--;
}
- }
- if (urls == 0) {
- FREE(url);
- curl_easy_cleanup(curl);
- return;
- }
- urls = weak_randomi(urls) + 1;
- pos = strlen(url) - 1;
- while (pos > 0) {
- if (url[pos] == ' ') {
- urls--;
- url[pos] = '\0';
- }
- if (urls == 0) {
- pos++;
- break;
- }
- pos--;
- }
- GE_LOG(ectx,
- GE_INFO | GE_BULK | GE_USER,
- _("Bootstrapping using `%s'.\n"),
- url);
+ GE_LOG (ectx,
+ GE_INFO | GE_BULK | GE_USER, _("Bootstrapping using `%s'.\n"), url);
bctx.url = url;
bctx.total = 0;
proxy = NULL;
- GC_get_configuration_value_string(coreAPI->cfg,
- "GNUNETD",
- "HTTP-PROXY",
- "",
- &proxy);
- CURL_EASY_SETOPT(curl,
- CURLOPT_WRITEFUNCTION,
- &downloadHostlistHelper);
- CURL_EASY_SETOPT(curl,
- CURLOPT_WRITEDATA,
- &bctx);
+ GC_get_configuration_value_string (coreAPI->cfg,
+ "GNUNETD", "HTTP-PROXY", "", &proxy);
+ CURL_EASY_SETOPT (curl, CURLOPT_WRITEFUNCTION, &downloadHostlistHelper);
+ CURL_EASY_SETOPT (curl, CURLOPT_WRITEDATA, &bctx);
if (ret != CURLE_OK)
goto cleanup;
- CURL_EASY_SETOPT(curl,
- CURLOPT_FAILONERROR,
- 1);
- CURL_EASY_SETOPT(curl,
- CURLOPT_URL,
- &url[pos]);
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- _("Trying to download hostlist from `%s'\n"),
- &url[pos]);
- if (strlen(proxy) > 0)
- CURL_EASY_SETOPT(curl,
- CURLOPT_PROXY,
- proxy);
- CURL_EASY_SETOPT(curl,
- CURLOPT_BUFFERSIZE,
- 1024); /* a bit more than one HELLO */
- if (0 == strncmp(&url[pos], "http", 4))
- CURL_EASY_SETOPT(curl,
- CURLOPT_USERAGENT,
- "GNUnet");
- CURL_EASY_SETOPT(curl,
- CURLOPT_CONNECTTIMEOUT,
- 150L);
+ CURL_EASY_SETOPT (curl, CURLOPT_FAILONERROR, 1);
+ CURL_EASY_SETOPT (curl, CURLOPT_URL, &url[pos]);
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ _("Trying to download hostlist from `%s'\n"), &url[pos]);
+ if (strlen (proxy) > 0)
+ CURL_EASY_SETOPT (curl, CURLOPT_PROXY, proxy);
+ CURL_EASY_SETOPT (curl, CURLOPT_BUFFERSIZE, 1024); /* a bit more than one
HELLO */
+ if (0 == strncmp (&url[pos], "http", 4))
+ CURL_EASY_SETOPT (curl, CURLOPT_USERAGENT, "GNUnet");
+ CURL_EASY_SETOPT (curl, CURLOPT_CONNECTTIMEOUT, 150L);
/* NOTE: use of CONNECTTIMEOUT without also
setting NOSIGNAL results in really weird
crashes on my system! */
- CURL_EASY_SETOPT(curl,
- CURLOPT_NOSIGNAL,
- 1);
+ CURL_EASY_SETOPT (curl, CURLOPT_NOSIGNAL, 1);
#if USE_MULTI
- multi = curl_multi_init();
- if (multi == NULL) {
- GE_BREAK(ectx, 0);
- goto cleanup;
- }
- mret = curl_multi_add_handle(multi, curl);
- if (mret != CURLM_OK) {
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- _("%s failed at %s:%d: `%s'\n"),
- "curl_multi_add_handle",
- __FILE__,
- __LINE__,
- curl_multi_strerror(mret));
- goto cleanup;
- }
- while ( (YES == termTest(targ)) &&
- (GNUNET_SHUTDOWN_TEST() == NO) ) {
- max = 0;
- FD_ZERO(&rs);
- FD_ZERO(&ws);
- FD_ZERO(&es);
- mret = curl_multi_fdset(multi,
- &rs,
- &ws,
- &es,
- &max);
- if (mret != CURLM_OK) {
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- _("%s failed at %s:%d: `%s'\n"),
- "curl_multi_fdset",
- __FILE__,
- __LINE__,
- curl_multi_strerror(mret));
+ multi = curl_multi_init ();
+ if (multi == NULL)
+ {
+ GE_BREAK (ectx, 0);
goto cleanup;
}
- /* use timeout of 1s in case that SELECT is not interrupted by
- signal (just to increase portability a bit) -- better a 1s
- delay in the reaction than hanging... */
- tv.tv_sec = 0;
- tv.tv_usec = 1000;
- SELECT(max + 1,
- &rs,
- &ws,
- &es,
- &tv);
- if (YES != termTest(targ))
- break;
- do {
- running = 0;
- mret = curl_multi_perform(multi, &running);
- if (running == 0) {
- do {
- msg = curl_multi_info_read(multi,
- &running);
- GE_BREAK(ectx, msg != NULL);
- if (msg == NULL)
- break;
- switch (msg->msg) {
- case CURLMSG_DONE:
- if (msg->data.result != CURLE_OK)
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- _("%s failed at %s:%d: `%s'\n"),
- "curl_multi_perform",
- __FILE__,
- __LINE__,
- curl_easy_strerror(msg->data.result));
- break;
- default:
- break;
- }
- } while (running > 0);
- break;
- }
- } while ( (mret == CURLM_CALL_MULTI_PERFORM) &&
- (YES == termTest(targ)) );
- if ( (mret != CURLM_OK) &&
- (mret != CURLM_CALL_MULTI_PERFORM) ) {
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- _("%s failed at %s:%d: `%s'\n"),
- "curl_multi_perform",
- __FILE__,
- __LINE__,
- curl_multi_strerror(mret));
+ mret = curl_multi_add_handle (multi, curl);
+ if (mret != CURLM_OK)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ _("%s failed at %s:%d: `%s'\n"),
+ "curl_multi_add_handle",
+ __FILE__, __LINE__, curl_multi_strerror (mret));
goto cleanup;
}
- if (running == 0)
- break;
- }
- mret = curl_multi_remove_handle(multi, curl);
- if (mret != CURLM_OK) {
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_DEVELOPER | GE_BULK,
- _("%s failed at %s:%d: `%s'\n"),
- "curl_multi_remove_handle",
- __FILE__,
- __LINE__,
- curl_multi_strerror(mret));
- goto cleanup;
- }
+ while ((YES == termTest (targ)) && (GNUNET_SHUTDOWN_TEST () == NO))
+ {
+ max = 0;
+ FD_ZERO (&rs);
+ FD_ZERO (&ws);
+ FD_ZERO (&es);
+ mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
+ if (mret != CURLM_OK)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ _("%s failed at %s:%d: `%s'\n"),
+ "curl_multi_fdset",
+ __FILE__, __LINE__, curl_multi_strerror (mret));
+ goto cleanup;
+ }
+ /* use timeout of 1s in case that SELECT is not interrupted by
+ signal (just to increase portability a bit) -- better a 1s
+ delay in the reaction than hanging... */
+ tv.tv_sec = 0;
+ tv.tv_usec = 1000;
+ SELECT (max + 1, &rs, &ws, &es, &tv);
+ if (YES != termTest (targ))
+ break;
+ do
+ {
+ running = 0;
+ mret = curl_multi_perform (multi, &running);
+ if (running == 0)
+ {
+ do
+ {
+ msg = curl_multi_info_read (multi, &running);
+ GE_BREAK (ectx, msg != NULL);
+ if (msg == NULL)
+ break;
+ switch (msg->msg)
+ {
+ case CURLMSG_DONE:
+ if (msg->data.result != CURLE_OK)
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ _("%s failed at %s:%d: `%s'\n"),
+ "curl_multi_perform",
+ __FILE__,
+ __LINE__,
+ curl_easy_strerror (msg->data.result));
+ break;
+ default:
+ break;
+ }
+ }
+ while (running > 0);
+ break;
+ }
+ }
+ while ((mret == CURLM_CALL_MULTI_PERFORM) && (YES == termTest (targ)));
+ if ((mret != CURLM_OK) && (mret != CURLM_CALL_MULTI_PERFORM))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ _("%s failed at %s:%d: `%s'\n"),
+ "curl_multi_perform",
+ __FILE__, __LINE__, curl_multi_strerror (mret));
+ goto cleanup;
+ }
+ if (running == 0)
+ break;
+ }
+ mret = curl_multi_remove_handle (multi, curl);
+ if (mret != CURLM_OK)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_DEVELOPER | GE_BULK,
+ _("%s failed at %s:%d: `%s'\n"),
+ "curl_multi_remove_handle",
+ __FILE__, __LINE__, curl_multi_strerror (mret));
+ goto cleanup;
+ }
#else
- ret = curl_easy_perform(curl);
+ ret = curl_easy_perform (curl);
if (ret != CURLE_OK)
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_DEVELOPER | GE_BULK,
- _("%s failed at %s:%d: `%s'\n"),
- "curl_easy_perform",
- __FILE__,
- __LINE__,
- curl_easy_strerror(ret));
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_DEVELOPER | GE_BULK,
+ _("%s failed at %s:%d: `%s'\n"),
+ "curl_easy_perform",
+ __FILE__, __LINE__, curl_easy_strerror (ret));
#endif
- curl_easy_cleanup(curl);
+ curl_easy_cleanup (curl);
#if USE_MULTI
- mret = curl_multi_cleanup(multi);
+ mret = curl_multi_cleanup (multi);
if (mret != CURLM_OK)
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_DEVELOPER | GE_BULK,
- _("%s failed at %s:%d: `%s'\n"),
- "curl_multi_cleanup",
- __FILE__,
- __LINE__,
- curl_multi_strerror(mret));
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_DEVELOPER | GE_BULK,
+ _("%s failed at %s:%d: `%s'\n"),
+ "curl_multi_cleanup",
+ __FILE__, __LINE__, curl_multi_strerror (mret));
#endif
- GE_LOG(ectx,
- GE_INFO | GE_BULK | GE_USER,
- _("Downloaded %llu bytes from `%s'.\n"),
- bctx.total,
- url);
- FREE(url);
- FREE(proxy);
- curl_global_cleanup();
+ GE_LOG (ectx,
+ GE_INFO | GE_BULK | GE_USER,
+ _("Downloaded %llu bytes from `%s'.\n"), bctx.total, url);
+ FREE (url);
+ FREE (proxy);
+ curl_global_cleanup ();
return;
cleanup:
- GE_BREAK(ectx, ret != CURLE_OK);
+ GE_BREAK (ectx, ret != CURLE_OK);
#if USE_MULTI
if (multi != NULL)
- curl_multi_remove_handle(multi, curl);
+ curl_multi_remove_handle (multi, curl);
#endif
- curl_easy_cleanup(curl);
+ curl_easy_cleanup (curl);
#if USE_MULTI
if (multi != NULL)
- curl_multi_cleanup(multi);
+ curl_multi_cleanup (multi);
#endif
- FREE(url);
- FREE(proxy);
- curl_global_cleanup();
+ FREE (url);
+ FREE (proxy);
+ curl_global_cleanup ();
}
Bootstrap_ServiceAPI *
-provide_module_bootstrap(CoreAPIForApplication * capi) {
+provide_module_bootstrap (CoreAPIForApplication * capi)
+{
static Bootstrap_ServiceAPI api;
coreAPI = capi;
ectx = capi->ectx;
- stats = coreAPI->requestService("stats");
- if (stats != NULL) {
- stat_hellodownloaded
- = stats->create(gettext_noop("# HELLOs downloaded via http"));
- }
+ stats = coreAPI->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_hellodownloaded
+ = stats->create (gettext_noop ("# HELLOs downloaded via http"));
+ }
api.bootstrap = &downloadHostlist;
return &api;
}
-void release_module_bootstrap() {
+void
+release_module_bootstrap ()
+{
if (stats != NULL)
- coreAPI->releaseService(stats);
+ coreAPI->releaseService (stats);
coreAPI = NULL;
}
Modified: GNUnet/src/applications/bootstrap_http/httptest.c
===================================================================
--- GNUnet/src/applications/bootstrap_http/httptest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/bootstrap_http/httptest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -32,80 +32,80 @@
#include "gnunet_bootstrap_service.h"
#include "gnunet_stats_service.h"
-void release_module_bootstrap();
+void release_module_bootstrap ();
-Bootstrap_ServiceAPI *
-provide_module_bootstrap(CoreAPIForApplication * capi);
+Bootstrap_ServiceAPI *provide_module_bootstrap (CoreAPIForApplication * capi);
-static void * rs(const char * name) { return NULL; }
+static void *
+rs (const char *name)
+{
+ return NULL;
+}
-static int rsx(void * s) { return OK; }
+static int
+rsx (void *s)
+{
+ return OK;
+}
static unsigned int count;
-static void hello(const P2P_hello_MESSAGE * m,
- void * arg) {
+static void
+hello (const P2P_hello_MESSAGE * m, void *arg)
+{
count++;
}
-static int terminate(void * arg) {
- if (GNUNET_SHUTDOWN_TEST() == YES)
+static int
+terminate (void *arg)
+{
+ if (GNUNET_SHUTDOWN_TEST () == YES)
return NO;
- return YES; /* todo: add timeout? */
+ return YES; /* todo: add timeout? */
}
-static void * pt(void * b) {
- Bootstrap_ServiceAPI * boot = b;
+static void *
+pt (void *b)
+{
+ Bootstrap_ServiceAPI *boot = b;
- boot->bootstrap(&hello,
- NULL,
- &terminate,
- NULL);
+ boot->bootstrap (&hello, NULL, &terminate, NULL);
return NULL;
}
-int main(int argc,
- char ** argv) {
+int
+main (int argc, char **argv)
+{
static CoreAPIForApplication capi;
- struct GC_Configuration * cfg;
- struct PluginHandle * plugin;
- Bootstrap_ServiceAPI * boot;
- struct PTHREAD * p;
- void * unused;
+ struct GC_Configuration *cfg;
+ struct PluginHandle *plugin;
+ Bootstrap_ServiceAPI *boot;
+ struct PTHREAD *p;
+ void *unused;
ServiceInitMethod init;
ServiceDoneMethod done;
count = 0;
- cfg = GC_create_C_impl();
- GC_set_configuration_value_string(cfg,
- NULL,
- "GNUNETD",
- "HOSTLISTURL",
- "http://gnunet.org/hostlist");
- memset(&capi,
- 0,
- sizeof(CoreAPIForApplication));
+ cfg = GC_create_C_impl ();
+ GC_set_configuration_value_string (cfg,
+ NULL,
+ "GNUNETD",
+ "HOSTLISTURL",
+ "http://gnunet.org/hostlist");
+ memset (&capi, 0, sizeof (CoreAPIForApplication));
capi.cfg = cfg;
capi.requestService = &rs;
capi.releaseService = &rsx;
- plugin = os_plugin_load(NULL,
- "libgnunetmodule_",
- "bootstrap");
- init = os_plugin_resolve_function(plugin,
- "provide_module_",
- YES);
- boot = init(&capi);
- p = PTHREAD_CREATE(&pt,
- boot,
- 1024 * 64);
- PTHREAD_JOIN(p, &unused);
- done = os_plugin_resolve_function(plugin,
- "release_module_",
- YES);
- done();
- os_plugin_unload(plugin);
- GC_free(cfg);
+ plugin = os_plugin_load (NULL, "libgnunetmodule_", "bootstrap");
+ init = os_plugin_resolve_function (plugin, "provide_module_", YES);
+ boot = init (&capi);
+ p = PTHREAD_CREATE (&pt, boot, 1024 * 64);
+ PTHREAD_JOIN (p, &unused);
+ done = os_plugin_resolve_function (plugin, "release_module_", YES);
+ done ();
+ os_plugin_unload (plugin);
+ GC_free (cfg);
if (count == 0)
return 1;
return 0;
Modified: GNUnet/src/applications/chat/chat.c
===================================================================
--- GNUnet/src/applications/chat/chat.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/chat/chat.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -30,7 +30,7 @@
#include "gnunet_protocols.h"
#include "chat.h"
-static CoreAPIForApplication * coreAPI = NULL;
+static CoreAPIForApplication *coreAPI = NULL;
#define MAX_LAST_MESSAGES 12
#define MAX_CLIENTS 4
@@ -41,144 +41,147 @@
static int ringIndex;
static Mutex chatMutex;
-static void markSeen(HashCode512 * hc) {
+static void
+markSeen (HashCode512 * hc)
+{
if (++ringIndex >= MAX_LAST_MESSAGES)
ringIndex = 0;
- memcpy(&lastMsgs[ringIndex],
- hc,
- sizeof(HashCode512));
+ memcpy (&lastMsgs[ringIndex], hc, sizeof (HashCode512));
}
-typedef struct {
- const MESSAGE_HEADER * message;
+typedef struct
+{
+ const MESSAGE_HEADER *message;
unsigned int prio;
unsigned int delay;
} BCC;
-static void bccHelper(const PeerIdentity * peer,
- BCC * bcc) {
- coreAPI->unicast(peer,
- bcc->message,
- bcc->prio,
- bcc->delay);
+static void
+bccHelper (const PeerIdentity * peer, BCC * bcc)
+{
+ coreAPI->unicast (peer, bcc->message, bcc->prio, bcc->delay);
}
-static void broadcastToConnected(const MESSAGE_HEADER * message,
- unsigned int prio,
- unsigned int delay) {
+static void
+broadcastToConnected (const MESSAGE_HEADER * message,
+ unsigned int prio, unsigned int delay)
+{
BCC bcc;
bcc.message = message;
bcc.prio = prio;
bcc.delay = delay;
- coreAPI->forAllConnectedNodes((PerNodeCallback)bccHelper,
- &bcc);
+ coreAPI->forAllConnectedNodes ((PerNodeCallback) bccHelper, &bcc);
}
-static int handleChatMSG(const PeerIdentity * sender,
- const MESSAGE_HEADER * message) {
+static int
+handleChatMSG (const PeerIdentity * sender, const MESSAGE_HEADER * message)
+{
int i;
int j;
- CS_chat_MESSAGE * cmsg;
- P2P_chat_MESSAGE * pmsg;
+ CS_chat_MESSAGE *cmsg;
+ P2P_chat_MESSAGE *pmsg;
HashCode512 hc;
- if (ntohs(message->size) != sizeof(P2P_chat_MESSAGE)) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Message received from peer is invalid.\n"));
- return SYSERR;
- }
- pmsg = (P2P_chat_MESSAGE*)message;
- cmsg = (CS_chat_MESSAGE*) message;
+ if (ntohs (message->size) != sizeof (P2P_chat_MESSAGE))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Message received from peer is invalid.\n"));
+ return SYSERR;
+ }
+ pmsg = (P2P_chat_MESSAGE *) message;
+ cmsg = (CS_chat_MESSAGE *) message;
/* check if we have seen this message already */
- hash(pmsg,
- sizeof(P2P_chat_MESSAGE),
- &hc);
+ hash (pmsg, sizeof (P2P_chat_MESSAGE), &hc);
j = -1;
- MUTEX_LOCK(&chatMutex);
- for (i=0;i<MAX_LAST_MESSAGES;i++)
- if (equalsHashCode512(&hc, &lastMsgs[i]))
+ MUTEX_LOCK (&chatMutex);
+ for (i = 0; i < MAX_LAST_MESSAGES; i++)
+ if (equalsHashCode512 (&hc, &lastMsgs[i]))
j = i;
- if (j == -1) {
- /* we have not seen it before, send to all TCP clients
- and broadcast to all peers */
- markSeen(&hc);
- broadcastToConnected(message, 5, 1);
- cmsg->header.type = htons(CS_PROTO_chat_MSG);
- for (j=0;j<clientCount;j++)
- coreAPI->sendToClient(clients[j],
- &cmsg->header);
- pmsg->nick[CHAT_NICK_LENGTH-1] = '\0';
- pmsg->message[CHAT_MSG_LENGTH-1] = '\0';
- /*
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- " CHAT: received new message from %s: %s\n",
- &pmsg->nick[0],
- &pmsg->message[0]);
- */
- }
- MUTEX_UNLOCK(&chatMutex);
+ if (j == -1)
+ {
+ /* we have not seen it before, send to all TCP clients
+ and broadcast to all peers */
+ markSeen (&hc);
+ broadcastToConnected (message, 5, 1);
+ cmsg->header.type = htons (CS_PROTO_chat_MSG);
+ for (j = 0; j < clientCount; j++)
+ coreAPI->sendToClient (clients[j], &cmsg->header);
+ pmsg->nick[CHAT_NICK_LENGTH - 1] = '\0';
+ pmsg->message[CHAT_MSG_LENGTH - 1] = '\0';
+ /*
+ GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ " CHAT: received new message from %s: %s\n",
+ &pmsg->nick[0],
+ &pmsg->message[0]);
+ */
+ }
+ MUTEX_UNLOCK (&chatMutex);
return OK;
}
-static int csHandleChatRequest(ClientHandle client,
- const CS_MESSAGE_HEADER * message) {
+static int
+csHandleChatRequest (ClientHandle client, const CS_MESSAGE_HEADER * message)
+{
int i;
int j;
- CS_chat_MESSAGE * cmsg;
- P2P_chat_MESSAGE * pmsg;
+ CS_chat_MESSAGE *cmsg;
+ P2P_chat_MESSAGE *pmsg;
HashCode512 hc;
- if (ntohs(message->size) != sizeof(CS_chat_MESSAGE)) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Message received from client is invalid\n"));
- return SYSERR; /* invalid message */
- }
- pmsg = (P2P_chat_MESSAGE*)message;
- cmsg = (CS_chat_MESSAGE*) message;
- hash(pmsg,
- sizeof(P2P_chat_MESSAGE),
- &hc);
- MUTEX_LOCK(&chatMutex);
- markSeen(&hc);
+ if (ntohs (message->size) != sizeof (CS_chat_MESSAGE))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Message received from client is invalid\n"));
+ return SYSERR; /* invalid message */
+ }
+ pmsg = (P2P_chat_MESSAGE *) message;
+ cmsg = (CS_chat_MESSAGE *) message;
+ hash (pmsg, sizeof (P2P_chat_MESSAGE), &hc);
+ MUTEX_LOCK (&chatMutex);
+ markSeen (&hc);
/* forward to all other TCP chat clients */
- j = -1; /* marker to check if this is a new client */
- for (i=0;i<clientCount;i++)
+ j = -1; /* marker to check if this is a new client */
+ for (i = 0; i < clientCount; i++)
if (clients[i] == client)
j = i;
else
- coreAPI->sendToClient(clients[i],
- message);
- if (j == -1) {
- if (clientCount == MAX_CLIENTS)
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Maximum number of chat clients reached.\n"));
- else {
- clients[clientCount++] = client;
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- _("Now %d of %d chat clients at this node.\n"),
- clientCount, MAX_CLIENTS);
+ coreAPI->sendToClient (clients[i], message);
+ if (j == -1)
+ {
+ if (clientCount == MAX_CLIENTS)
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Maximum number of chat clients reached.\n"));
+ else
+ {
+ clients[clientCount++] = client;
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ _("Now %d of %d chat clients at this node.\n"),
+ clientCount, MAX_CLIENTS);
+ }
}
- }
/* forward to all other nodes in the network */
- pmsg->header.type = htons(P2P_PROTO_chat_MSG);
- broadcastToConnected(&pmsg->header, 5, 1);
- MUTEX_UNLOCK(&chatMutex);
+ pmsg->header.type = htons (P2P_PROTO_chat_MSG);
+ broadcastToConnected (&pmsg->header, 5, 1);
+ MUTEX_UNLOCK (&chatMutex);
return OK;
}
-static void chatClientExitHandler(ClientHandle client) {
+static void
+chatClientExitHandler (ClientHandle client)
+{
int i;
- MUTEX_LOCK(&chatMutex);
- for (i=0;i<clientCount;i++)
- if (clients[i] == client) {
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Chat client exits.\n");
- clients[i] = clients[--clientCount];
- break;
- }
- MUTEX_UNLOCK(&chatMutex);
+ MUTEX_LOCK (&chatMutex);
+ for (i = 0; i < clientCount; i++)
+ if (clients[i] == client)
+ {
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Chat client exits.\n");
+ clients[i] = clients[--clientCount];
+ break;
+ }
+ MUTEX_UNLOCK (&chatMutex);
}
/**
@@ -186,44 +189,44 @@
* the library name (libgnunet_XXX => initialize_XXX).
* @return SYSERR on errors
*/
-int initialize_module_chat(CoreAPIForApplication * capi) {
+int
+initialize_module_chat (CoreAPIForApplication * capi)
+{
int ok = OK;
- GE_ASSERT(ectx, sizeof(P2P_chat_MESSAGE) == sizeof(CS_chat_MESSAGE));
- MUTEX_CREATE(&chatMutex);
+ GE_ASSERT (ectx, sizeof (P2P_chat_MESSAGE) == sizeof (CS_chat_MESSAGE));
+ MUTEX_CREATE (&chatMutex);
clientCount = 0;
coreAPI = capi;
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- _("`%s' registering handlers %d and %d\n"),
- "chat",
- P2P_PROTO_chat_MSG,
- CS_PROTO_chat_MSG);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ _("`%s' registering handlers %d and %d\n"),
+ "chat", P2P_PROTO_chat_MSG, CS_PROTO_chat_MSG);
- if (SYSERR == capi->registerHandler(P2P_PROTO_chat_MSG,
- &handleChatMSG))
+ if (SYSERR == capi->registerHandler (P2P_PROTO_chat_MSG, &handleChatMSG))
ok = SYSERR;
- if (SYSERR == capi->registerClientExitHandler(&chatClientExitHandler))
+ if (SYSERR == capi->registerClientExitHandler (&chatClientExitHandler))
ok = SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_chat_MSG,
- &csHandleChatRequest))
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_chat_MSG,
+ &csHandleChatRequest))
ok = SYSERR;
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "chat",
- _("enables P2P-chat (incomplete)")));
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "chat",
+ _
+ ("enables P2P-chat
(incomplete)")));
return ok;
}
-void done_module_chat() {
- coreAPI->unregisterHandler(P2P_PROTO_chat_MSG,
- &handleChatMSG);
- coreAPI->unregisterClientExitHandler(&chatClientExitHandler);
- coreAPI->unregisterClientHandler(CS_PROTO_chat_MSG,
- &csHandleChatRequest);
- MUTEX_DESTROY(&chatMutex);
+void
+done_module_chat ()
+{
+ coreAPI->unregisterHandler (P2P_PROTO_chat_MSG, &handleChatMSG);
+ coreAPI->unregisterClientExitHandler (&chatClientExitHandler);
+ coreAPI->unregisterClientHandler (CS_PROTO_chat_MSG, &csHandleChatRequest);
+ MUTEX_DESTROY (&chatMutex);
coreAPI = NULL;
}
Modified: GNUnet/src/applications/chat/chat.h
===================================================================
--- GNUnet/src/applications/chat/chat.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/chat/chat.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -30,13 +30,15 @@
#define CHAT_NICK_LENGTH 32
#define CHAT_MSG_LENGTH 1024
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
char nick[CHAT_NICK_LENGTH];
char message[CHAT_MSG_LENGTH];
} P2P_chat_MESSAGE;
-typedef struct {
+typedef struct
+{
CS_MESSAGE_HEADER header;
char nick[CHAT_NICK_LENGTH];
char message[CHAT_MSG_LENGTH];
Modified: GNUnet/src/applications/chat/gnunet-chat.c
===================================================================
--- GNUnet/src/applications/chat/gnunet-chat.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/chat/gnunet-chat.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,7 +30,7 @@
#define CHAT_VERSION "0.0.3"
-static Semaphore * doneSem;
+static Semaphore *doneSem;
/**
* Parse the options, set the timeout.
@@ -38,96 +38,87 @@
* @param argv the option list (including keywords)
* @return OK on error, SYSERR if we should exit
*/
-static int parseOptions(int argc,
- char ** argv) {
+static int
+parseOptions (int argc, char **argv)
+{
int option_index;
int c;
- FREENONNULL(setConfigurationString("GNUNETD",
- "LOGFILE",
- NULL));
- while (1) {
- static struct GNoption long_options[] = {
- LONG_DEFAULT_OPTIONS,
- { "nickname", 1, 0, 'n' },
- { 0,0,0,0 }
- };
- option_index=0;
- c = GNgetopt_long(argc,
- argv,
- "vhdc:L:H:n:",
- long_options,
- &option_index);
- if (c == -1)
- break; /* No more flags to process */
- if (YES == parseDefaultOptions(c, GNoptarg))
- continue;
- switch(c) {
- case 'n':
- FREENONNULL(setConfigurationString("GNUNET-CHAT",
- "NICK",
- GNoptarg));
- break;
- case 'v':
- printf("GNUnet v%s, gnunet-chat v%s\n",
- VERSION,
- CHAT_VERSION);
- return SYSERR;
- case 'h': {
- static Help help[] = {
- HELP_CONFIG,
- HELP_HELP,
- HELP_LOGLEVEL,
- { 'n', "nickname", NULL,
- gettext_noop("specify nickname") },
- HELP_VERSION,
- HELP_END,
+ FREENONNULL (setConfigurationString ("GNUNETD", "LOGFILE", NULL));
+ while (1)
+ {
+ static struct GNoption long_options[] = {
+ LONG_DEFAULT_OPTIONS,
+ {"nickname", 1, 0, 'n'},
+ {0, 0, 0, 0}
};
- formatHelp("gnunet-chat [OPTIONS]",
- _("Start GNUnet chat client."),
- help);
- return SYSERR;
- }
- default:
- GE_LOG(ectx, GE_ERROR | GE_IMMEDIATE | GE_USER,
- _("Use --help to get a list of options.\n"));
- return -1;
- } /* end of parsing commandline */
- } /* while (1) */
+ option_index = 0;
+ c = GNgetopt_long (argc,
+ argv, "vhdc:L:H:n:", long_options, &option_index);
+ if (c == -1)
+ break; /* No more flags to process */
+ if (YES == parseDefaultOptions (c, GNoptarg))
+ continue;
+ switch (c)
+ {
+ case 'n':
+ FREENONNULL (setConfigurationString ("GNUNET-CHAT",
+ "NICK", GNoptarg));
+ break;
+ case 'v':
+ printf ("GNUnet v%s, gnunet-chat v%s\n", VERSION, CHAT_VERSION);
+ return SYSERR;
+ case 'h':
+ {
+ static Help help[] = {
+ HELP_CONFIG,
+ HELP_HELP,
+ HELP_LOGLEVEL,
+ {'n', "nickname", NULL,
+ gettext_noop ("specify nickname")},
+ HELP_VERSION,
+ HELP_END,
+ };
+ formatHelp ("gnunet-chat [OPTIONS]",
+ _("Start GNUnet chat client."), help);
+ return SYSERR;
+ }
+ default:
+ GE_LOG (ectx, GE_ERROR | GE_IMMEDIATE | GE_USER,
+ _("Use --help to get a list of options.\n"));
+ return -1;
+ } /* end of parsing commandline */
+ } /* while (1) */
return OK;
}
-static void * receiveThread(void * arg) {
- struct ClientServerConnection * sock = arg;
- CS_chat_MESSAGE * buffer;
+static void *
+receiveThread (void *arg)
+{
+ struct ClientServerConnection *sock = arg;
+ CS_chat_MESSAGE *buffer;
- buffer = MALLOC(MAX_BUFFER_SIZE);
- while (OK == connection_read(sock,
- (CS_MESSAGE_HEADER **)&buffer)) {
- char timebuf[64];
- time_t timetmp;
- struct tm * tmptr;
+ buffer = MALLOC (MAX_BUFFER_SIZE);
+ while (OK == connection_read (sock, (CS_MESSAGE_HEADER **) & buffer))
+ {
+ char timebuf[64];
+ time_t timetmp;
+ struct tm *tmptr;
- time(&timetmp);
- tmptr = localtime(&timetmp);
- strftime(timebuf,
- 64,
- "%b %e %H:%M ",
- tmptr);
-
- if ( (ntohs(buffer->header.size) != sizeof(CS_chat_MESSAGE)) ||
- (ntohs(buffer->header.type) != CS_PROTO_chat_MSG) )
- continue;
- buffer->nick[CHAT_NICK_LENGTH-1] = '\0';
- buffer->message[CHAT_MSG_LENGTH-1] = '\0';
- printf("[%s][%s]: %s",
- timebuf,
- &buffer->nick[0],
- &buffer->message[0]);
- }
- FREE(buffer);
- SEMAPHORE_UP(doneSem);
- printf("CHAT receive loop ends!\n");
+ time (&timetmp);
+ tmptr = localtime (&timetmp);
+ strftime (timebuf, 64, "%b %e %H:%M ", tmptr);
+
+ if ((ntohs (buffer->header.size) != sizeof (CS_chat_MESSAGE)) ||
+ (ntohs (buffer->header.type) != CS_PROTO_chat_MSG))
+ continue;
+ buffer->nick[CHAT_NICK_LENGTH - 1] = '\0';
+ buffer->message[CHAT_MSG_LENGTH - 1] = '\0';
+ printf ("[%s][%s]: %s", timebuf, &buffer->nick[0], &buffer->message[0]);
+ }
+ FREE (buffer);
+ SEMAPHORE_UP (doneSem);
+ printf ("CHAT receive loop ends!\n");
return NULL;
}
@@ -137,66 +128,56 @@
* @param argv command line arguments
* @return return value from gnunetsearch: 0: ok, -1: error
*/
-int main(int argc, char ** argv) {
- struct ClientServerConnection * sock;
+int
+main (int argc, char **argv)
+{
+ struct ClientServerConnection *sock;
PTHREAD_T messageReceiveThread;
- void * unused;
+ void *unused;
CS_chat_MESSAGE msg;
- char * nick;
+ char *nick;
- if (SYSERR == initUtil(argc, argv, &parseOptions))
- return 0; /* parse error, --help, etc. */
- sock = getClientSocket();
+ if (SYSERR == initUtil (argc, argv, &parseOptions))
+ return 0; /* parse error, --help, etc. */
+ sock = getClientSocket ();
if (sock == NULL)
- errexit(_("Could not connect to gnunetd.\n"));
+ errexit (_("Could not connect to gnunetd.\n"));
- nick = getConfigurationString("GNUNET-CHAT", "NICK");
+ nick = getConfigurationString ("GNUNET-CHAT", "NICK");
if (nick == NULL)
- errexit(_("You must specify a nickname (use option `%s').\n"),
- "-n");
+ errexit (_("You must specify a nickname (use option `%s').\n"), "-n");
- doneSem = SEMAPHORE_CREATE(0);
- if (0 != PTHREAD_CREATE(&messageReceiveThread,
- &receiveThread,
- sock,
- 128 * 1024))
- DIE_STRERROR("pthread_create");
+ doneSem = SEMAPHORE_CREATE (0);
+ if (0 != PTHREAD_CREATE (&messageReceiveThread,
+ &receiveThread, sock, 128 * 1024))
+ DIE_STRERROR ("pthread_create");
- memset(&msg,
- 0,
- sizeof(CS_chat_MESSAGE));
- memcpy(&msg.message[0],
- "Hi!\n",
- strlen("Hi!\n"));
- msg.header.size
- = htons(sizeof(CS_chat_MESSAGE));
- msg.header.type
- = htons(CS_PROTO_chat_MSG);
- memcpy(&msg.nick[0],
- nick,
- strlen(nick));
+ memset (&msg, 0, sizeof (CS_chat_MESSAGE));
+ memcpy (&msg.message[0], "Hi!\n", strlen ("Hi!\n"));
+ msg.header.size = htons (sizeof (CS_chat_MESSAGE));
+ msg.header.type = htons (CS_PROTO_chat_MSG);
+ memcpy (&msg.nick[0], nick, strlen (nick));
/* send first "Hi!" message to gnunetd to indicate "join" */
- if (SYSERR == connection_write(sock,
- &msg.header))
- errexit(_("Could not send join message to gnunetd\n"));
+ if (SYSERR == connection_write (sock, &msg.header))
+ errexit (_("Could not send join message to gnunetd\n"));
/* read messages from command line and send */
- while (1) {
- memset(&msg.message, 0, 1024);
- if (NULL == fgets(&msg.message[0], 1024, stdin))
- break;
- if (SYSERR == connection_write(sock,
- &msg.header))
- errexit(_("Could not send message to gnunetd\n"));
- }
- closeSocketTemporarily(sock);
- SEMAPHORE_DOWN(doneSem);
- SEMAPHORE_DESTROY(doneSem);
- PTHREAD_JOIN(&messageReceiveThread, &unused);
- connection_destroy(sock);
+ while (1)
+ {
+ memset (&msg.message, 0, 1024);
+ if (NULL == fgets (&msg.message[0], 1024, stdin))
+ break;
+ if (SYSERR == connection_write (sock, &msg.header))
+ errexit (_("Could not send message to gnunetd\n"));
+ }
+ closeSocketTemporarily (sock);
+ SEMAPHORE_DOWN (doneSem);
+ SEMAPHORE_DESTROY (doneSem);
+ PTHREAD_JOIN (&messageReceiveThread, &unused);
+ connection_destroy (sock);
- doneUtil();
+ doneUtil ();
return 0;
}
Modified: GNUnet/src/applications/datastore/datastore.c
===================================================================
--- GNUnet/src/applications/datastore/datastore.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/datastore/datastore.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -42,12 +42,12 @@
/**
* SQ-store handle
*/
-static SQstore_ServiceAPI * sq;
+static SQstore_ServiceAPI *sq;
/**
* Core API handle.
*/
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
/**
* Minimum priority in the DB.
@@ -64,9 +64,9 @@
*/
static unsigned long long quota;
-static struct CronManager * cron;
+static struct CronManager *cron;
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static int stat_filtered;
@@ -78,87 +78,79 @@
*/
#define MIN_FREE (quota / 100)
-static unsigned long long getSize() {
- return sq->getSize();
+static unsigned long long
+getSize ()
+{
+ return sq->getSize ();
}
-static int get(const HashCode512 * query,
- unsigned int type,
- Datum_Iterator iter,
- void * closure) {
+static int
+get (const HashCode512 * query,
+ unsigned int type, Datum_Iterator iter, void *closure)
+{
int ret;
- if (! testAvailable(query)) {
+ if (!testAvailable (query))
+ {
#if DEBUG_DATASTORE
- EncName enc;
+ EncName enc;
- IF_GELOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(query,
- &enc));
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Datastore availability pre-test failed for `%s'.\n",
- &enc);
+ IF_GELOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (query, &enc));
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Datastore availability pre-test failed for `%s'.\n", &enc);
#endif
- if (stats != NULL)
- stats->change(stat_filtered, 1);
- return 0;
- }
- ret = sq->get(query,
- type,
- iter,
- closure);
- if ( (ret == 0) &&
- (stats != NULL) )
- stats->change(stat_filter_failed, 1);
+ if (stats != NULL)
+ stats->change (stat_filtered, 1);
+ return 0;
+ }
+ ret = sq->get (query, type, iter, closure);
+ if ((ret == 0) && (stats != NULL))
+ stats->change (stat_filter_failed, 1);
return ret;
}
/**
* Explicitly remove some content from the database.
*/
-static int del(const HashCode512 * query,
- const Datastore_Value * value) {
+static int
+del (const HashCode512 * query, const Datastore_Value * value)
+{
int ok;
EncName enc;
- if (! testAvailable(query)) {
- IF_GELOG(coreAPI->ectx,
- GE_WARNING | GE_BULK | GE_USER,
- hash2enc(query,
- &enc));
- GE_LOG(coreAPI->ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Availability test failed for `%s' at %s:%d.\n"),
- &enc,
- __FILE__, __LINE__);
- return 0;
- }
- ok = sq->del(query, value);
- if (ok >= 0) {
- makeUnavailable(query); /* update filter! */
- available += ntohl(value->size);
+ if (!testAvailable (query))
+ {
+ IF_GELOG (coreAPI->ectx,
+ GE_WARNING | GE_BULK | GE_USER, hash2enc (query, &enc));
+ GE_LOG (coreAPI->ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Availability test failed for `%s' at %s:%d.\n"),
+ &enc, __FILE__, __LINE__);
+ return 0;
+ }
+ ok = sq->del (query, value);
+ if (ok >= 0)
+ {
+ makeUnavailable (query); /* update filter! */
+ available += ntohl (value->size);
#if DEBUG_DATASTORE
- IF_GELOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(query,
- &enc));
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Deleted `%s' from database.\n",
- &enc);
+ IF_GELOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (query, &enc));
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Deleted `%s' from database.\n", &enc);
#endif
- } else {
- IF_GELOG(coreAPI->ectx,
- GE_WARNING | GE_BULK | GE_USER,
- hash2enc(query,
- &enc));
- GE_LOG(coreAPI->ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Database failed to delete `%s'.\n"),
- &enc);
- }
+ }
+ else
+ {
+ IF_GELOG (coreAPI->ectx,
+ GE_WARNING | GE_BULK | GE_USER, hash2enc (query, &enc));
+ GE_LOG (coreAPI->ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Database failed to delete `%s'.\n"), &enc);
+ }
return ok;
}
@@ -171,62 +163,64 @@
* to justify removing something else, SYSERR on
* other serious error (i.e. IO permission denied)
*/
-static int put(const HashCode512 * key,
- const Datastore_Value * value) {
+static int
+put (const HashCode512 * key, const Datastore_Value * value)
+{
int ok;
/* check if we have enough space / priority */
- if (ntohll(value->expirationTime) < get_time()) {
- GE_LOG(coreAPI->ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- "Received content for put already expired!\n");
- return NO;
- }
- if ( (available < ntohl(value->size) ) &&
- (minPriority > ntohl(value->prio)) ) {
- GE_LOG(coreAPI->ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- "Datastore full (%llu/%llu) and content priority too low to kick out
other content. Refusing put.\n",
- sq->getSize(),
- quota);
- return NO; /* new content has such a low priority that
- we should not even bother! */
- }
- if (ntohl(value->prio) < minPriority)
- minPriority = ntohl(value->prio);
+ if (ntohll (value->expirationTime) < get_time ())
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ "Received content for put already expired!\n");
+ return NO;
+ }
+ if ((available < ntohl (value->size)) &&
+ (minPriority > ntohl (value->prio)))
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ "Datastore full (%llu/%llu) and content priority too low to kick
out other content. Refusing put.\n",
+ sq->getSize (), quota);
+ return NO; /* new content has such a low priority that
+ we should not even bother! */
+ }
+ if (ntohl (value->prio) < minPriority)
+ minPriority = ntohl (value->prio);
/* add the content */
- ok = sq->put(key,
- value);
- if (ok == YES) {
- makeAvailable(key);
- available -= ntohl(value->size);
- }
+ ok = sq->put (key, value);
+ if (ok == YES)
+ {
+ makeAvailable (key);
+ available -= ntohl (value->size);
+ }
return ok;
}
-typedef struct {
+typedef struct
+{
int exists;
- const Datastore_Value * value;
- Datastore_Value * existing;
+ const Datastore_Value *value;
+ Datastore_Value *existing;
} CE;
-static int checkExists(const HashCode512 * key,
- const Datastore_Value * value,
- void * cls) {
- CE * ce = cls;
+static int
+checkExists (const HashCode512 * key,
+ const Datastore_Value * value, void *cls)
+{
+ CE *ce = cls;
- if ( (value->size != ce->value->size) ||
- (0 != memcmp(&value[1],
- &ce->value[1],
- ntohl(value->size) - sizeof(Datastore_Value))) )
- return OK; /* found another value, but different content! */
- ce->existing = MALLOC(ntohl(value->size));
- memcpy(ce->existing,
- value,
- ntohl(value->size));
+ if ((value->size != ce->value->size) ||
+ (0 != memcmp (&value[1],
+ &ce->value[1],
+ ntohl (value->size) - sizeof (Datastore_Value))))
+ return OK; /* found another value, but different content!
*/
+ ce->existing = MALLOC (ntohl (value->size));
+ memcpy (ce->existing, value, ntohl (value->size));
ce->exists = YES;
- return SYSERR; /* abort iteration! */
+ return SYSERR; /* abort iteration! */
}
/**
@@ -239,8 +233,9 @@
* to justify removing something else, SYSERR on
* other serious error (i.e. IO permission denied)
*/
-static int putUpdate(const HashCode512 * key,
- const Datastore_Value * value) {
+static int
+putUpdate (const HashCode512 * key, const Datastore_Value * value)
+{
CE cls;
int ok;
@@ -248,54 +243,47 @@
cls.exists = NO;
cls.existing = NULL;
cls.value = value;
- sq->get(key,
- ntohl(value->type),
- &checkExists,
- &cls);
- if (ntohl(value->type) == D_BLOCK)
- sq->get(key,
- ONDEMAND_BLOCK,
- &checkExists,
- &cls);
+ sq->get (key, ntohl (value->type), &checkExists, &cls);
+ if (ntohl (value->type) == D_BLOCK)
+ sq->get (key, ONDEMAND_BLOCK, &checkExists, &cls);
- if (cls.exists) {
- if ( (ntohl(value->prio) == 0) &&
- (ntohll(value->expirationTime) <= ntohll(cls.existing->expirationTime)) ) {
- FREE(cls.existing);
+ if (cls.exists)
+ {
+ if ((ntohl (value->prio) == 0) &&
+ (ntohll (value->expirationTime) <=
+ ntohll (cls.existing->expirationTime)))
+ {
+ FREE (cls.existing);
+ return OK;
+ }
+ /* update prio */
+ sq->update (key,
+ cls.existing,
+ ntohl (value->prio), ntohll (value->expirationTime));
+ FREE (cls.existing);
return OK;
}
- /* update prio */
- sq->update(key,
- cls.existing,
- ntohl(value->prio),
- ntohll(value->expirationTime));
- FREE(cls.existing);
- return OK;
- }
#if DEBUG_DATASTORE
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Migration: available %llu (need %u), min priority %u have %u\n",
- available,
- ntohl(value->size),
- minPriority,
- ntohl(value->prio));
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Migration: available %llu (need %u), min priority %u have %u\n",
+ available, ntohl (value->size), minPriority, ntohl (value->prio));
#endif
/* check if we have enough space / priority */
- if ( (available < ntohl(value->size) ) &&
- (minPriority > ntohl(value->prio)) )
- return NO; /* new content has such a low priority that
- we should not even bother! */
- if (ntohl(value->prio) < minPriority)
- minPriority = ntohl(value->prio);
+ if ((available < ntohl (value->size)) &&
+ (minPriority > ntohl (value->prio)))
+ return NO; /* new content has such a low priority that
+ we should not even bother! */
+ if (ntohl (value->prio) < minPriority)
+ minPriority = ntohl (value->prio);
/* add the content */
- ok = sq->put(key,
- value);
- if (ok == YES) {
- makeAvailable(key);
- available -= ntohl(value->size);
- }
+ ok = sq->put (key, value);
+ if (ok == YES)
+ {
+ makeAvailable (key);
+ available -= ntohl (value->size);
+ }
return ok;
}
@@ -304,34 +292,34 @@
* SYSERR if we have deleted all of the expired content
* OK if we deleted expired content and are above quota
*/
-static int freeSpaceExpired(const HashCode512 * key,
- const Datastore_Value * value,
- void * closure) {
- int * icls = closure;
+static int
+freeSpaceExpired (const HashCode512 * key,
+ const Datastore_Value * value, void *closure)
+{
+ int *icls = closure;
int ret;
- if (get_time() < ntohll(value->expirationTime))
- return SYSERR; /* not expired */
- ret = sq->del(key, value);
+ if (get_time () < ntohll (value->expirationTime))
+ return SYSERR; /* not expired */
+ ret = sq->del (key, value);
if (ret != SYSERR)
- available += ntohl(value->size);
- if ( (available > 0) &&
- (available >= MIN_FREE) )
+ available += ntohl (value->size);
+ if ((available > 0) && (available >= MIN_FREE))
return *icls;
return OK;
}
-static int freeSpaceLow(const HashCode512 * key,
- const Datastore_Value * value,
- void * closure) {
+static int
+freeSpaceLow (const HashCode512 * key,
+ const Datastore_Value * value, void *closure)
+{
int ret;
- minPriority = ntohl(value->prio);
- ret = sq->del(key, value);
+ minPriority = ntohl (value->prio);
+ ret = sq->del (key, value);
if (ret != SYSERR)
- available += ntohl(value->size);
- if ( (available > 0) &&
- (available >= MIN_FREE) )
+ available += ntohl (value->size);
+ if ((available > 0) && (available >= MIN_FREE))
return SYSERR;
return OK;
}
@@ -342,107 +330,110 @@
*
* Also updates available and minPriority.
*/
-static void cronMaintenance(void * unused) {
+static void
+cronMaintenance (void *unused)
+{
int syserr = SYSERR;
- available = quota - sq->getSize();
- if ( (available < 0) ||
- (available < MIN_FREE) ) {
- sq->iterateExpirationTime(ANY_BLOCK,
- &freeSpaceExpired,
- &syserr);
- if ( (available < 0) ||
- (available < MIN_FREE) ) {
- sq->iterateLowPriority(ANY_BLOCK,
- &freeSpaceLow,
- NULL);
+ available = quota - sq->getSize ();
+ if ((available < 0) || (available < MIN_FREE))
+ {
+ sq->iterateExpirationTime (ANY_BLOCK, &freeSpaceExpired, &syserr);
+ if ((available < 0) || (available < MIN_FREE))
+ {
+ sq->iterateLowPriority (ANY_BLOCK, &freeSpaceLow, NULL);
+ }
}
- } else {
- minPriority = 0;
- }
+ else
+ {
+ minPriority = 0;
+ }
}
/**
* Initialize the manager-module.
*/
Datastore_ServiceAPI *
-provide_module_datastore(CoreAPIForApplication * capi) {
+provide_module_datastore (CoreAPIForApplication * capi)
+{
static Datastore_ServiceAPI api;
unsigned long long lquota;
unsigned long long sqot;
- State_ServiceAPI * state;
+ State_ServiceAPI *state;
- if (-1 == GC_get_configuration_value_number(capi->cfg,
- "FS",
- "QUOTA",
- 0,
- ((unsigned long long)-1)/1024/1024,
- 1024,
- &lquota)) {
- GE_BREAK(capi->ectx, 0);
- return NULL; /* OOPS */
- }
- quota
- = lquota * 1024 * 1024; /* MB to bytes */
- stats = capi->requestService("stats");
- if (stats != NULL) {
- stat_filtered = stats->create(gettext_noop("# requests filtered by bloom
filter"));
- stat_filter_failed = stats->create(gettext_noop("# bloom filter false
positives"));
+ if (-1 == GC_get_configuration_value_number (capi->cfg,
+ "FS",
+ "QUOTA",
+ 0,
+ ((unsigned long long) -1) /
+ 1024 / 1024, 1024, &lquota))
+ {
+ GE_BREAK (capi->ectx, 0);
+ return NULL; /* OOPS */
+ }
+ quota = lquota * 1024 * 1024; /* MB to bytes */
+ stats = capi->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_filtered =
+ stats->create (gettext_noop ("# requests filtered by bloom filter"));
+ stat_filter_failed =
+ stats->create (gettext_noop ("# bloom filter false positives"));
- stats->set(stats->create(gettext_noop("# bytes allowed in datastore")),
- quota);
- }
- state = capi->requestService("state");
- if (state != NULL) {
- sqot = htonll(lquota);
- state->write(capi->ectx,
- "FS-LAST-QUOTA",
- sizeof(unsigned long long),
- &sqot);
- capi->releaseService(state);
- } else {
- GE_LOG(capi->ectx,
- GE_USER | GE_ADMIN | GE_ERROR | GE_BULK,
- _("Failed to load state service. Trying to do without.\n"));
- }
- sq = capi->requestService("sqstore");
- if (sq == NULL) {
- if (stats != NULL) {
- capi->releaseService(stats);
- stats = NULL;
+ stats->set (stats->
+ create (gettext_noop ("# bytes allowed in datastore")),
+ quota);
}
- GE_BREAK(capi->ectx, 0);
- return NULL;
- }
+ state = capi->requestService ("state");
+ if (state != NULL)
+ {
+ sqot = htonll (lquota);
+ state->write (capi->ectx,
+ "FS-LAST-QUOTA", sizeof (unsigned long long), &sqot);
+ capi->releaseService (state);
+ }
+ else
+ {
+ GE_LOG (capi->ectx,
+ GE_USER | GE_ADMIN | GE_ERROR | GE_BULK,
+ _("Failed to load state service. Trying to do without.\n"));
+ }
+ sq = capi->requestService ("sqstore");
+ if (sq == NULL)
+ {
+ if (stats != NULL)
+ {
+ capi->releaseService (stats);
+ stats = NULL;
+ }
+ GE_BREAK (capi->ectx, 0);
+ return NULL;
+ }
coreAPI = capi;
- initPrefetch(capi->ectx,
- capi->cfg,
- sq);
- if (OK != initFilters(capi->ectx,
- capi->cfg)) {
- GE_BREAK(capi->ectx, 0);
- donePrefetch();
- capi->releaseService(sq);
- if (stats != NULL) {
- capi->releaseService(stats);
- stats = NULL;
+ initPrefetch (capi->ectx, capi->cfg, sq);
+ if (OK != initFilters (capi->ectx, capi->cfg))
+ {
+ GE_BREAK (capi->ectx, 0);
+ donePrefetch ();
+ capi->releaseService (sq);
+ if (stats != NULL)
+ {
+ capi->releaseService (stats);
+ stats = NULL;
+ }
+ return NULL;
}
- return NULL;
- }
- available = quota - sq->getSize();
- cron = cron_create(capi->ectx);
- cron_add_job(cron,
- &cronMaintenance,
- 10 * cronSECONDS,
- 10 * cronSECONDS,
- NULL);
- cron_start(cron);
+ available = quota - sq->getSize ();
+ cron = cron_create (capi->ectx);
+ cron_add_job (cron,
+ &cronMaintenance, 10 * cronSECONDS, 10 * cronSECONDS, NULL);
+ cron_start (cron);
api.getSize = &getSize;
api.put = &put;
api.fast_get = &testAvailable;
api.putUpdate = &putUpdate;
api.get = &get;
- api.getRandom = &getRandom; /* in prefetch.c */
+ api.getRandom = &getRandom; /* in prefetch.c */
api.del = &del;
return &api;
@@ -451,21 +442,21 @@
/**
* Shutdown the manager module.
*/
-void release_module_datastore() {
- cron_stop(cron);
- cron_del_job(cron,
- &cronMaintenance,
- 10 * cronSECONDS,
- NULL);
- cron_destroy(cron);
+void
+release_module_datastore ()
+{
+ cron_stop (cron);
+ cron_del_job (cron, &cronMaintenance, 10 * cronSECONDS, NULL);
+ cron_destroy (cron);
cron = NULL;
- donePrefetch();
- doneFilters();
- coreAPI->releaseService(sq);
- if (stats != NULL) {
- coreAPI->releaseService(stats);
- stats = NULL;
- }
+ donePrefetch ();
+ doneFilters ();
+ coreAPI->releaseService (sq);
+ if (stats != NULL)
+ {
+ coreAPI->releaseService (stats);
+ stats = NULL;
+ }
sq = NULL;
coreAPI = NULL;
}
@@ -474,10 +465,11 @@
* Callback that adds all element of the SQStore to the
* bloomfilter.
*/
-static int filterAddAll(const HashCode512 * key,
- const Datastore_Value * value,
- void * closure) {
- makeAvailable(key);
+static int
+filterAddAll (const HashCode512 * key,
+ const Datastore_Value * value, void *closure)
+{
+ makeAvailable (key);
return OK;
}
@@ -486,57 +478,59 @@
* At some point we'll want to add code to convert data between
* different sqstore's here, too.
*/
-void update_module_datastore(UpdateAPI * uapi) {
+void
+update_module_datastore (UpdateAPI * uapi)
+{
unsigned long long quota;
unsigned long long lastQuota;
- unsigned long long * lq;
- State_ServiceAPI * state;
+ unsigned long long *lq;
+ State_ServiceAPI *state;
- if (-1 == GC_get_configuration_value_number(uapi->cfg,
- "FS",
- "QUOTA",
- 0,
- ((unsigned long long)-1)/1024/1024,
- 1024,
- "a))
- return; /* OOPS */
- state = uapi->requestService("state");
+ if (-1 == GC_get_configuration_value_number (uapi->cfg,
+ "FS",
+ "QUOTA",
+ 0,
+ ((unsigned long long) -1) /
+ 1024 / 1024, 1024, "a))
+ return; /* OOPS */
+ state = uapi->requestService ("state");
lq = NULL;
- if ( (state != NULL) &&
- (sizeof(unsigned long long) != state->read(uapi->ectx,
- "FS-LAST-QUOTA",
- (void**)&lq)) &&
- (ntohll(*lq) == quota) ) {
- uapi->releaseService(state);
- FREE(lq);
- return; /* no change */
- }
- FREENONNULL(lq);
+ if ((state != NULL) &&
+ (sizeof (unsigned long long) != state->read (uapi->ectx,
+ "FS-LAST-QUOTA",
+ (void **) &lq)) &&
+ (ntohll (*lq) == quota))
+ {
+ uapi->releaseService (state);
+ FREE (lq);
+ return; /* no change */
+ }
+ FREENONNULL (lq);
/* ok, need to convert! */
- deleteFilter(uapi->ectx,
- uapi->cfg);
- initFilters(uapi->ectx,
- uapi->cfg);
- sq = uapi->requestService("sqstore");
- if (sq != NULL) {
- sq->iterateAllNow(&filterAddAll,
- NULL);
- uapi->releaseService(sq);
- } else {
- GE_LOG(uapi->ectx,
- GE_USER | GE_ADMIN | GE_ERROR | GE_BULK,
- _("Failed to load sqstore service. Check your configuration!\n"));
- }
+ deleteFilter (uapi->ectx, uapi->cfg);
+ initFilters (uapi->ectx, uapi->cfg);
+ sq = uapi->requestService ("sqstore");
+ if (sq != NULL)
+ {
+ sq->iterateAllNow (&filterAddAll, NULL);
+ uapi->releaseService (sq);
+ }
+ else
+ {
+ GE_LOG (uapi->ectx,
+ GE_USER | GE_ADMIN | GE_ERROR | GE_BULK,
+ _
+ ("Failed to load sqstore service. Check your
configuration!\n"));
+ }
sq = NULL;
- doneFilters();
- if (state != NULL) {
- lastQuota = htonll(quota);
- state->write(uapi->ectx,
- "FS-LAST-QUOTA",
- sizeof(unsigned long long),
- &lastQuota);
- uapi->releaseService(state);
- }
+ doneFilters ();
+ if (state != NULL)
+ {
+ lastQuota = htonll (quota);
+ state->write (uapi->ectx,
+ "FS-LAST-QUOTA", sizeof (unsigned long long), &lastQuota);
+ uapi->releaseService (state);
+ }
}
Modified: GNUnet/src/applications/datastore/filter.c
===================================================================
--- GNUnet/src/applications/datastore/filter.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/datastore/filter.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -33,90 +33,93 @@
/**
* Filter.
*/
-static struct Bloomfilter * filter;
+static struct Bloomfilter *filter;
-static char * getFilterName(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- char * fn;
- char * bf;
+static char *
+getFilterName (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ char *fn;
+ char *bf;
fn = NULL;
- if (-1 == GC_get_configuration_value_filename(cfg,
- "FS",
- "DIR",
- VAR_DAEMON_DIRECTORY "/fs",
- &fn))
+ if (-1 == GC_get_configuration_value_filename (cfg,
+ "FS",
+ "DIR",
+ VAR_DAEMON_DIRECTORY "/fs",
+ &fn))
return NULL;
- if (OK != disk_directory_create(ectx,
- fn)) {
- FREE(fn);
- return NULL;
- }
- bf = MALLOC(strlen(fn)+
- strlen("/bloomfilter")+1);
- strcpy(bf, fn);
- strcat(bf, "/bloomfilter");
- FREE(fn);
+ if (OK != disk_directory_create (ectx, fn))
+ {
+ FREE (fn);
+ return NULL;
+ }
+ bf = MALLOC (strlen (fn) + strlen ("/bloomfilter") + 1);
+ strcpy (bf, fn);
+ strcat (bf, "/bloomfilter");
+ FREE (fn);
return bf;
}
-int initFilters(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- char * bf;
- unsigned long long quota; /* in kb */
+int
+initFilters (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ char *bf;
+ unsigned long long quota; /* in kb */
unsigned int bf_size;
- if (-1 == GC_get_configuration_value_number(cfg,
- "FS",
- "QUOTA",
- 0,
- ((unsigned long long)-1)/1024/1024,
- 1024,
- "a))
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "FS",
+ "QUOTA",
+ 0,
+ ((unsigned long long) -1) /
+ 1024 / 1024, 1024, "a))
return SYSERR;
quota *= 1024;
- bf_size = quota / 32; /* 8 bit per entry, 1 bit per 32 kb in DB */
- bf = getFilterName(ectx, cfg);
+ bf_size = quota / 32; /* 8 bit per entry, 1 bit per 32 kb in DB */
+ bf = getFilterName (ectx, cfg);
if (bf == NULL)
return SYSERR;
- filter
- = loadBloomfilter(ectx,
- bf,
- bf_size,
- 5); /* approx. 3% false positives at max use */
- FREE(bf);
+ filter = loadBloomfilter (ectx, bf, bf_size, 5); /* approx. 3% false
positives at max use */
+ FREE (bf);
if (filter == NULL)
return SYSERR;
return OK;
}
-void doneFilters() {
+void
+doneFilters ()
+{
if (filter != NULL)
- freeBloomfilter(filter);
+ freeBloomfilter (filter);
}
-void deleteFilter(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- char * fn;
+void
+deleteFilter (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ char *fn;
- GE_ASSERT(ectx, filter == NULL);
- fn = getFilterName(ectx, cfg);
- UNLINK(fn);
- FREE(fn);
+ GE_ASSERT (ectx, filter == NULL);
+ fn = getFilterName (ectx, cfg);
+ UNLINK (fn);
+ FREE (fn);
}
-void makeAvailable(const HashCode512 * key) {
- addToBloomfilter(filter, key);
+void
+makeAvailable (const HashCode512 * key)
+{
+ addToBloomfilter (filter, key);
}
-void makeUnavailable(const HashCode512 * key) {
- delFromBloomfilter(filter, key);
+void
+makeUnavailable (const HashCode512 * key)
+{
+ delFromBloomfilter (filter, key);
}
-int testAvailable(const HashCode512 * key) {
- return testBloomfilter(filter,
- key);
+int
+testAvailable (const HashCode512 * key)
+{
+ return testBloomfilter (filter, key);
}
/* end of filter.c */
-
Modified: GNUnet/src/applications/datastore/filter.h
===================================================================
--- GNUnet/src/applications/datastore/filter.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/datastore/filter.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -28,18 +28,16 @@
#include "gnunet_util.h"
-int initFilters(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+int initFilters (struct GE_Context *ectx, struct GC_Configuration *cfg);
-void doneFilters(void);
+void doneFilters (void);
-void deleteFilter(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+void deleteFilter (struct GE_Context *ectx, struct GC_Configuration *cfg);
-void makeAvailable(const HashCode512 * key);
+void makeAvailable (const HashCode512 * key);
-void makeUnavailable(const HashCode512 * key);
+void makeUnavailable (const HashCode512 * key);
-int testAvailable(const HashCode512 * key);
+int testAvailable (const HashCode512 * key);
#endif
Modified: GNUnet/src/applications/datastore/prefetch.c
===================================================================
--- GNUnet/src/applications/datastore/prefetch.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/datastore/prefetch.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -33,18 +33,18 @@
static HashCode512 rkey;
-static Datastore_Value * rvalue;
+static Datastore_Value *rvalue;
/**
* SQ-store handle
*/
-static SQstore_ServiceAPI * sq;
+static SQstore_ServiceAPI *sq;
/**
* Semaphore on which the RCB acquire thread waits
* if the RCB buffer is full.
*/
-static struct SEMAPHORE * acquireMoreSignal;
+static struct SEMAPHORE *acquireMoreSignal;
/**
* Set to YES to shutdown the module.
@@ -54,31 +54,30 @@
/**
* Lock for the RCB buffer.
*/
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-static struct PTHREAD * gather_thread;
+static struct PTHREAD *gather_thread;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
-
+static struct GC_Configuration *cfg;
-static int acquire(const HashCode512 * key,
- const Datastore_Value * value,
- void * closure) {
+
+static int
+acquire (const HashCode512 * key,
+ const Datastore_Value * value, void *closure)
+{
if (doneSignal)
return SYSERR;
- SEMAPHORE_DOWN(acquireMoreSignal, YES);
+ SEMAPHORE_DOWN (acquireMoreSignal, YES);
if (doneSignal)
return SYSERR;
- MUTEX_LOCK(lock);
- GE_ASSERT(NULL, rvalue == NULL);
+ MUTEX_LOCK (lock);
+ GE_ASSERT (NULL, rvalue == NULL);
rkey = *key;
- rvalue = MALLOC(ntohl(value->size));
- memcpy(rvalue,
- value,
- ntohl(value->size));
- MUTEX_UNLOCK(lock);
+ rvalue = MALLOC (ntohl (value->size));
+ memcpy (rvalue, value, ntohl (value->size));
+ MUTEX_UNLOCK (lock);
if (doneSignal)
return SYSERR;
return OK;
@@ -87,22 +86,23 @@
/**
* Acquire new block(s) to the migration buffer.
*/
-static void * rcbAcquire(void * unused) {
+static void *
+rcbAcquire (void *unused)
+{
int load;
- while (doneSignal == NO) {
- sq->iterateMigrationOrder(&acquire,
- NULL);
- /* sleep here - otherwise we may start looping immediately
- if there is no content in the DB! */
- load = os_cpu_get_load(ectx,
- cfg);
- if (load < 10)
- load = 10; /* never sleep less than 500 ms */
- if (load > 100)
- load = 100; /* never sleep longer than 5 seconds */
- if (doneSignal == NO)
- PTHREAD_SLEEP(50 * cronMILLIS * load);
- }
+ while (doneSignal == NO)
+ {
+ sq->iterateMigrationOrder (&acquire, NULL);
+ /* sleep here - otherwise we may start looping immediately
+ if there is no content in the DB! */
+ load = os_cpu_get_load (ectx, cfg);
+ if (load < 10)
+ load = 10; /* never sleep less than 500 ms */
+ if (load > 100)
+ load = 100; /* never sleep longer than 5 seconds */
+ if (doneSignal == NO)
+ PTHREAD_SLEEP (50 * cronMILLIS * load);
+ }
return NULL;
}
@@ -112,55 +112,57 @@
*
* @return SYSERR if the RCB is empty
*/
-int getRandom(const HashCode512 * receiver,
- unsigned int sizeLimit,
- HashCode512 * key,
- Datastore_Value ** value,
- unsigned int type) {
- MUTEX_LOCK(lock);
- if (rvalue == NULL) {
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
+int
+getRandom (const HashCode512 * receiver,
+ unsigned int sizeLimit,
+ HashCode512 * key, Datastore_Value ** value, unsigned int type)
+{
+ MUTEX_LOCK (lock);
+ if (rvalue == NULL)
+ {
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
*value = rvalue;
*key = rkey;
rvalue = NULL;
- MUTEX_UNLOCK(lock);
- SEMAPHORE_UP(acquireMoreSignal);
+ MUTEX_UNLOCK (lock);
+ SEMAPHORE_UP (acquireMoreSignal);
return OK;
}
-
-void initPrefetch(struct GE_Context * e,
- struct GC_Configuration * c,
- SQstore_ServiceAPI * s) {
+
+void
+initPrefetch (struct GE_Context *e,
+ struct GC_Configuration *c, SQstore_ServiceAPI * s)
+{
ectx = e;
cfg = c;
sq = s;
- acquireMoreSignal = SEMAPHORE_CREATE(1);
+ acquireMoreSignal = SEMAPHORE_CREATE (1);
doneSignal = NO;
- lock = MUTEX_CREATE(NO);
- gather_thread = PTHREAD_CREATE(&rcbAcquire,
- NULL,
- 64*1024);
+ lock = MUTEX_CREATE (NO);
+ gather_thread = PTHREAD_CREATE (&rcbAcquire, NULL, 64 * 1024);
if (gather_thread == NULL)
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_IMMEDIATE,
- "pthread_create");
+ GE_LOG_STRERROR (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_IMMEDIATE,
+ "pthread_create");
}
-void donePrefetch() {
- void * unused;
+void
+donePrefetch ()
+{
+ void *unused;
doneSignal = YES;
if (gather_thread != NULL)
- PTHREAD_STOP_SLEEP(gather_thread);
- SEMAPHORE_UP(acquireMoreSignal);
+ PTHREAD_STOP_SLEEP (gather_thread);
+ SEMAPHORE_UP (acquireMoreSignal);
if (gather_thread != NULL)
- PTHREAD_JOIN(gather_thread, &unused);
- SEMAPHORE_DESTROY(acquireMoreSignal);
- FREENONNULL(rvalue);
+ PTHREAD_JOIN (gather_thread, &unused);
+ SEMAPHORE_DESTROY (acquireMoreSignal);
+ FREENONNULL (rvalue);
rvalue = NULL;
- MUTEX_DESTROY(lock);
+ MUTEX_DESTROY (lock);
lock = NULL;
sq = NULL;
cfg = NULL;
Modified: GNUnet/src/applications/datastore/prefetch.h
===================================================================
--- GNUnet/src/applications/datastore/prefetch.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/datastore/prefetch.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -33,11 +33,10 @@
/**
* Initialize the migration module.
*/
-void initPrefetch(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- SQstore_ServiceAPI * sq);
+void initPrefetch (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, SQstore_ServiceAPI * sq);
-void donePrefetch(void);
+void donePrefetch (void);
/**
* Get a random value from the datastore that has
@@ -50,11 +49,10 @@
* for any type.
* @return OK if a value was found, SYSERR if not
*/
-int getRandom(const HashCode512 * receiver,
- unsigned int sizeLimit,
- HashCode512 * key,
- Datastore_Value ** value,
- unsigned int type);
+int getRandom (const HashCode512 * receiver,
+ unsigned int sizeLimit,
+ HashCode512 * key,
+ Datastore_Value ** value, unsigned int type);
/* end of prefetch.h */
Modified: GNUnet/src/applications/dht/module/cs.c
===================================================================
--- GNUnet/src/applications/dht/module/cs.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/dht/module/cs.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -38,166 +38,155 @@
/**
* Global core API.
*/
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
/**
* Reference to the DHT service API.
*/
-static DHT_ServiceAPI * dhtAPI;
+static DHT_ServiceAPI *dhtAPI;
-typedef struct {
+typedef struct
+{
- struct ClientHandle * client;
+ struct ClientHandle *client;
- struct DHT_GET_RECORD * get_record;
+ struct DHT_GET_RECORD *get_record;
} DHT_CLIENT_GET_RECORD;
-static DHT_CLIENT_GET_RECORD ** getRecords;
+static DHT_CLIENT_GET_RECORD **getRecords;
static unsigned int getRecordsSize;
/**
* Lock.
*/
-static struct MUTEX * lock;
+static struct MUTEX *lock;
/**
* CS handler for inserting <key,value>-pair into DHT-table.
*/
-static int csPut(struct ClientHandle * client,
- const MESSAGE_HEADER * message) {
- const CS_dht_request_put_MESSAGE * req;
+static int
+csPut (struct ClientHandle *client, const MESSAGE_HEADER * message)
+{
+ const CS_dht_request_put_MESSAGE *req;
unsigned int size;
- if (ntohs(message->size) < sizeof(CS_dht_request_put_MESSAGE)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- req = (const CS_dht_request_put_MESSAGE*) message;
- size = ntohs(req->header.size)
- - sizeof(CS_dht_request_put_MESSAGE);
- GE_ASSERT(NULL,
- size < MAX_BUFFER_SIZE);
+ if (ntohs (message->size) < sizeof (CS_dht_request_put_MESSAGE))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ req = (const CS_dht_request_put_MESSAGE *) message;
+ size = ntohs (req->header.size) - sizeof (CS_dht_request_put_MESSAGE);
+ GE_ASSERT (NULL, size < MAX_BUFFER_SIZE);
#if DEBUG_CS
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "`%s' at %s:%d processes put '%.*s'\n",
- __FUNCTION__,
- __FILE__,
- __LINE__,
- size,
- &req[1]);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "`%s' at %s:%d processes put '%.*s'\n",
+ __FUNCTION__, __FILE__, __LINE__, size, &req[1]);
#endif
- dhtAPI->put(&req->key,
- ntohl(req->type),
- size,
- ntohll(req->expire) + get_time(), /* convert to absolute time */
- (const char*) &req[1]);
+ dhtAPI->put (&req->key, ntohl (req->type), size, ntohll (req->expire) +
get_time (), /* convert to absolute time */
+ (const char *) &req[1]);
return OK;
}
-int get_result(const HashCode512 * key,
- const DataContainer * value,
- void * cls) {
- DHT_CLIENT_GET_RECORD * record = cls;
- CS_dht_request_put_MESSAGE * msg;
+int
+get_result (const HashCode512 * key, const DataContainer * value, void *cls)
+{
+ DHT_CLIENT_GET_RECORD *record = cls;
+ CS_dht_request_put_MESSAGE *msg;
size_t n;
- GE_ASSERT(NULL, ntohl(value->size) >= sizeof(DataContainer));
- n = sizeof(CS_dht_request_put_MESSAGE) + ntohl(value->size) -
sizeof(DataContainer);
- if (n > MAX_BUFFER_SIZE) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- msg = MALLOC(n);
- msg->header.size = htons(n);
- msg->header.type = htons(CS_PROTO_dht_REQUEST_PUT);
- msg->expire = 0; /* unknown */
+ GE_ASSERT (NULL, ntohl (value->size) >= sizeof (DataContainer));
+ n =
+ sizeof (CS_dht_request_put_MESSAGE) + ntohl (value->size) -
+ sizeof (DataContainer);
+ if (n > MAX_BUFFER_SIZE)
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ msg = MALLOC (n);
+ msg->header.size = htons (n);
+ msg->header.type = htons (CS_PROTO_dht_REQUEST_PUT);
+ msg->expire = 0; /* unknown */
msg->key = *key;
- memcpy(&msg[1],
- &value[1],
- ntohl(value->size) - sizeof(DataContainer));
+ memcpy (&msg[1], &value[1], ntohl (value->size) - sizeof (DataContainer));
#if DEBUG_CS
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "`%s' at %s:%d processes reply '%.*s'\n",
- __FUNCTION__,
- __FILE__,
- __LINE__,
- ntohl(value->size) - sizeof(DataContainer),
- &value[1]);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "`%s' at %s:%d processes reply '%.*s'\n",
+ __FUNCTION__,
+ __FILE__,
+ __LINE__, ntohl (value->size) - sizeof (DataContainer), &value[1]);
#endif
- if (OK != coreAPI->sendToClient(record->client,
- &msg->header)) {
- GE_LOG(coreAPI->ectx,
- GE_ERROR | GE_IMMEDIATE | GE_USER,
- _("`%s' failed. Terminating connection to client.\n"),
- "sendToClient");
- coreAPI->terminateClientConnection(record->client);
- }
- FREE(msg);
+ if (OK != coreAPI->sendToClient (record->client, &msg->header))
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_ERROR | GE_IMMEDIATE | GE_USER,
+ _("`%s' failed. Terminating connection to client.\n"),
+ "sendToClient");
+ coreAPI->terminateClientConnection (record->client);
+ }
+ FREE (msg);
return OK;
}
-
-static void get_timeout(void * cls) {
- DHT_CLIENT_GET_RECORD * record = cls;
+
+static void
+get_timeout (void *cls)
+{
+ DHT_CLIENT_GET_RECORD *record = cls;
int i;
int found;
found = NO;
- MUTEX_LOCK(lock);
- for (i=getRecordsSize-1;i>=0;i--)
- if (getRecords[i] == record) {
- getRecords[i] = getRecords[getRecordsSize-1];
- GROW(getRecords,
- getRecordsSize,
- getRecordsSize-1);
- found = YES;
- break;
+ MUTEX_LOCK (lock);
+ for (i = getRecordsSize - 1; i >= 0; i--)
+ if (getRecords[i] == record)
+ {
+ getRecords[i] = getRecords[getRecordsSize - 1];
+ GROW (getRecords, getRecordsSize, getRecordsSize - 1);
+ found = YES;
+ break;
+ }
+ MUTEX_UNLOCK (lock);
+ if (found == YES)
+ {
+ dhtAPI->get_stop (record->get_record);
+ FREE (record);
}
- MUTEX_UNLOCK(lock);
- if (found == YES) {
- dhtAPI->get_stop(record->get_record);
- FREE(record);
- }
}
/**
* CS handler for inserting <key,value>-pair into DHT-table.
*/
-static int csGet(struct ClientHandle * client,
- const MESSAGE_HEADER * message) {
- const CS_dht_request_get_MESSAGE * get;
- DHT_CLIENT_GET_RECORD * cpc;
+static int
+csGet (struct ClientHandle *client, const MESSAGE_HEADER * message)
+{
+ const CS_dht_request_get_MESSAGE *get;
+ DHT_CLIENT_GET_RECORD *cpc;
- if (ntohs(message->size) != sizeof(CS_dht_request_get_MESSAGE)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
+ if (ntohs (message->size) != sizeof (CS_dht_request_get_MESSAGE))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
#if DEBUG_CS
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "`%s' at %s:%d processes get\n",
- __FUNCTION__,
- __FILE__,
- __LINE__);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "`%s' at %s:%d processes get\n", __FUNCTION__, __FILE__, __LINE__);
#endif
get = (const CS_dht_request_get_MESSAGE *) message;
- cpc = MALLOC(sizeof(DHT_CLIENT_GET_RECORD));
+ cpc = MALLOC (sizeof (DHT_CLIENT_GET_RECORD));
cpc->client = client;
- cpc->get_record = dhtAPI->get_start(ntohl(get->type),
- &get->key,
- ntohll(get->timeout),
- &get_result,
- cpc,
- &get_timeout,
- cpc);
- MUTEX_LOCK(lock);
- APPEND(getRecords,
- getRecordsSize,
- cpc);
- MUTEX_UNLOCK(lock);
+ cpc->get_record = dhtAPI->get_start (ntohl (get->type),
+ &get->key,
+ ntohll (get->timeout),
+ &get_result, cpc, &get_timeout, cpc);
+ MUTEX_LOCK (lock);
+ APPEND (getRecords, getRecordsSize, cpc);
+ MUTEX_UNLOCK (lock);
return OK;
}
@@ -205,93 +194,90 @@
* CS handler for handling exiting client. Triggers
* get_stop for all operations that rely on this client.
*/
-static void csClientExit(struct ClientHandle * client) {
+static void
+csClientExit (struct ClientHandle *client)
+{
int i;
- struct DHT_GET_RECORD * gr;
- DHT_CLIENT_GET_RECORD * cgr;
- MUTEX_LOCK(lock);
- for (i=0;i<getRecordsSize;i++) {
- cgr = getRecords[i];
- if (cgr->client == client) {
- gr = cgr->get_record;
- getRecords[i] = getRecords[getRecordsSize-1];
- GROW(getRecords,
- getRecordsSize,
- getRecordsSize-1);
- MUTEX_UNLOCK(lock);
- dhtAPI->get_stop(gr);
- FREE(cgr);
- MUTEX_LOCK(lock);
- i--;
+ struct DHT_GET_RECORD *gr;
+ DHT_CLIENT_GET_RECORD *cgr;
+ MUTEX_LOCK (lock);
+ for (i = 0; i < getRecordsSize; i++)
+ {
+ cgr = getRecords[i];
+ if (cgr->client == client)
+ {
+ gr = cgr->get_record;
+ getRecords[i] = getRecords[getRecordsSize - 1];
+ GROW (getRecords, getRecordsSize, getRecordsSize - 1);
+ MUTEX_UNLOCK (lock);
+ dhtAPI->get_stop (gr);
+ FREE (cgr);
+ MUTEX_LOCK (lock);
+ i--;
+ }
}
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
-int initialize_module_dht(CoreAPIForApplication * capi) {
+int
+initialize_module_dht (CoreAPIForApplication * capi)
+{
int status;
- dhtAPI = capi->requestService("dht");
+ dhtAPI = capi->requestService ("dht");
if (dhtAPI == NULL)
return SYSERR;
coreAPI = capi;
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _("`%s' registering client handlers: %d %d\n"),
- "dht",
- CS_PROTO_dht_REQUEST_PUT,
- CS_PROTO_dht_REQUEST_GET);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ _("`%s' registering client handlers: %d %d\n"),
+ "dht", CS_PROTO_dht_REQUEST_PUT, CS_PROTO_dht_REQUEST_GET);
status = OK;
- lock = MUTEX_CREATE(NO);
- if (SYSERR == capi->registerClientHandler(CS_PROTO_dht_REQUEST_PUT,
- &csPut))
+ lock = MUTEX_CREATE (NO);
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_dht_REQUEST_PUT,
+ &csPut))
status = SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_dht_REQUEST_GET,
- &csGet))
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_dht_REQUEST_GET,
+ &csGet))
status = SYSERR;
- if (SYSERR == capi->registerClientExitHandler(&csClientExit))
+ if (SYSERR == capi->registerClientExitHandler (&csClientExit))
status = SYSERR;
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "dht",
- gettext_noop("Enables efficient
non-anonymous routing")));
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "dht",
+ gettext_noop
+ ("Enables efficient
non-anonymous routing")));
return status;
}
/**
* Unregisters handlers, cleans memory structures etc when node exits.
*/
-int done_module_dht() {
+int
+done_module_dht ()
+{
int status;
status = OK;
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "DHT: shutdown\n");
- if (OK != coreAPI->unregisterClientHandler(CS_PROTO_dht_REQUEST_PUT,
- &csPut))
+ GE_LOG (coreAPI->ectx, GE_DEBUG | GE_REQUEST | GE_USER, "DHT: shutdown\n");
+ if (OK != coreAPI->unregisterClientHandler (CS_PROTO_dht_REQUEST_PUT,
+ &csPut))
status = SYSERR;
- if (OK != coreAPI->unregisterClientHandler(CS_PROTO_dht_REQUEST_GET,
- &csGet))
+ if (OK != coreAPI->unregisterClientHandler (CS_PROTO_dht_REQUEST_GET,
+ &csGet))
status = SYSERR;
- if (OK != coreAPI->unregisterClientExitHandler(&csClientExit))
+ if (OK != coreAPI->unregisterClientExitHandler (&csClientExit))
status = SYSERR;
while (getRecordsSize > 0)
- get_timeout(getRecords[0]);
- coreAPI->releaseService(dhtAPI);
+ get_timeout (getRecords[0]);
+ coreAPI->releaseService (dhtAPI);
dhtAPI = NULL;
coreAPI = NULL;
- MUTEX_DESTROY(lock);
+ MUTEX_DESTROY (lock);
return status;
}
/* end of cs.c */
-
-
-
-
-
-
Modified: GNUnet/src/applications/dht/module/dstore.c
===================================================================
--- GNUnet/src/applications/dht/module/dstore.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/dht/module/dstore.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,47 +30,40 @@
#define DEBUG_DSTORE NO
-static Dstore_ServiceAPI * dstore;
+static Dstore_ServiceAPI *dstore;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
/**
* Lookup in the local datastore.
* @return total number of results found
*/
-int dht_store_get(const HashCode512 * key,
- unsigned int type,
- ResultHandler handler,
- void * cls) {
- return dstore->get(key,
- type,
- handler,
- cls);
+int
+dht_store_get (const HashCode512 * key,
+ unsigned int type, ResultHandler handler, void *cls)
+{
+ return dstore->get (key, type, handler, cls);
}
/**
* Store the given data in the local datastore.
*/
-void dht_store_put(unsigned int type,
- const HashCode512 * key,
- cron_t discard_time,
- unsigned int size,
- const char * data) {
- if (discard_time < get_time()) {
+void
+dht_store_put (unsigned int type,
+ const HashCode512 * key,
+ cron_t discard_time, unsigned int size, const char *data)
+{
+ if (discard_time < get_time ())
+ {
#if DEBUG_DSTORE
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Content already expired (%llu < %llu), will not keep.\n",
- discard_time,
- get_time());
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Content already expired (%llu < %llu), will not keep.\n",
+ discard_time, get_time ());
#endif
- return;
- }
- dstore->put(key,
- type,
- discard_time,
- size,
- data);
+ return;
+ }
+ dstore->put (key, type, discard_time, size, data);
}
/**
@@ -79,10 +72,11 @@
* @param capi the core API
* @return OK on success
*/
-int init_dht_store(size_t max_size,
- CoreAPIForApplication * capi) {
+int
+init_dht_store (size_t max_size, CoreAPIForApplication * capi)
+{
coreAPI = capi;
- dstore = coreAPI->requestService("dstore");
+ dstore = coreAPI->requestService ("dstore");
if (dstore == NULL)
return SYSERR;
return OK;
@@ -93,8 +87,10 @@
*
* @return OK on success
*/
-int done_dht_store() {
- coreAPI->releaseService(dstore);
+int
+done_dht_store ()
+{
+ coreAPI->releaseService (dstore);
coreAPI = NULL;
dstore = NULL;
return OK;
Modified: GNUnet/src/applications/dht/module/dstore.h
===================================================================
--- GNUnet/src/applications/dht/module/dstore.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/dht/module/dstore.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -34,19 +34,15 @@
* Lookup in the local datastore.
* @return total number of results found
*/
-int dht_store_get(const HashCode512 * key,
- unsigned int type,
- ResultHandler handler,
- void * cls);
+int dht_store_get (const HashCode512 * key,
+ unsigned int type, ResultHandler handler, void *cls);
/**
* Store the given data in the local datastore.
*/
-void dht_store_put(unsigned int type,
- const HashCode512 * key,
- cron_t discard_time,
- unsigned int size,
- const char * data);
+void dht_store_put (unsigned int type,
+ const HashCode512 * key,
+ cron_t discard_time, unsigned int size, const char *data);
/**
* Initialize dstore DHT component.
@@ -54,14 +50,13 @@
* @param capi the core API
* @return OK on success
*/
-int init_dht_store(size_t max_size,
- CoreAPIForApplication * capi);
+int init_dht_store (size_t max_size, CoreAPIForApplication * capi);
/**
* Shutdown dstore DHT component.
*
* @return OK on success
*/
-int done_dht_store(void);
+int done_dht_store (void);
#endif
Modified: GNUnet/src/applications/dht/module/routing.c
===================================================================
--- GNUnet/src/applications/dht/module/routing.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/dht/module/routing.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -42,12 +42,13 @@
/**
* @brief record used for sending response back
*/
-typedef struct DHT_Source_Route {
+typedef struct DHT_Source_Route
+{
/**
* This is a linked list.
*/
- struct DHT_Source_Route * next;
+ struct DHT_Source_Route *next;
/**
* Source of the request. Replies should be forwarded to
@@ -61,14 +62,15 @@
*/
ResultHandler receiver;
- void * receiver_closure;
+ void *receiver_closure;
} DHT_Source_Route;
/**
* @brief message send for DHT lookup
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
@@ -99,7 +101,8 @@
*
* Message is followed by the data.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
@@ -125,7 +128,8 @@
*
* Message is followed by the data.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
@@ -144,7 +148,8 @@
/**
* Entry in the DHT routing table.
*/
-typedef struct DHTQueryRecord {
+typedef struct DHTQueryRecord
+{
/**
* When do we stop forwarding this request?
@@ -154,18 +159,18 @@
/**
* Information about where to send the results back to.
*/
- DHT_Source_Route * sources;
+ DHT_Source_Route *sources;
/**
* GET message of this record.
*/
- DHT_GET_MESSAGE * get;
+ DHT_GET_MESSAGE *get;
/**
* Hashcodes of the results that we have send back
* so far.
*/
- HashCode512 * results;
+ HashCode512 *results;
/**
* Number of entries in results.
@@ -183,7 +188,7 @@
/**
* Linked list of active records.
*/
-static DHTQueryRecord ** records;
+static DHTQueryRecord **records;
/**
* Size of records
@@ -193,11 +198,11 @@
/**
* Statistics service.
*/
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
static unsigned int stat_replies_routed;
@@ -213,181 +218,177 @@
* Given a result, lookup in the routing table
* where to send it next.
*/
-static void routeResult(const HashCode512 * key,
- unsigned int type,
- unsigned int size,
- const char * data,
- void * cls) {
- DHTQueryRecord * q;
+static void
+routeResult (const HashCode512 * key,
+ unsigned int type,
+ unsigned int size, const char *data, void *cls)
+{
+ DHTQueryRecord *q;
int i;
int j;
int found;
HashCode512 hc;
- DHT_RESULT_MESSAGE * result;
+ DHT_RESULT_MESSAGE *result;
unsigned int routed;
unsigned int tracked;
- DHT_Source_Route * pos;
+ DHT_Source_Route *pos;
- if (cls != NULL) {
- result = cls;
- } else {
- result = MALLOC(sizeof(DHT_RESULT_MESSAGE) + size);
- result->header.size = htons(sizeof(DHT_RESULT_MESSAGE) + size);
- result->header.type = htons(P2P_PROTO_DHT_RESULT);
- result->type = htonl(type);
- result->key = *key;
- memcpy(&result[1],
- data,
- size);
- }
- hash(data,
- size,
- &hc);
+ if (cls != NULL)
+ {
+ result = cls;
+ }
+ else
+ {
+ result = MALLOC (sizeof (DHT_RESULT_MESSAGE) + size);
+ result->header.size = htons (sizeof (DHT_RESULT_MESSAGE) + size);
+ result->header.type = htons (P2P_PROTO_DHT_RESULT);
+ result->type = htonl (type);
+ result->key = *key;
+ memcpy (&result[1], data, size);
+ }
+ hash (data, size, &hc);
routed = 0;
tracked = 0;
- MUTEX_LOCK(lock);
- for (i=0;i<rt_size;i++) {
- q = records[i];
- if (q == NULL)
- continue;
- tracked++;
- if ( (ntohl(q->get->type) != type) ||
- (0 != memcmp(key,
- &q->get->key,
- sizeof(HashCode512))) )
- continue;
- found = NO;
- for (j=0;j<q->result_count;j++)
- if (0 == memcmp(&hc,
- &q->results[j],
- sizeof(HashCode512))) {
- found = YES;
- break;
- }
- if (found == YES)
- continue;
- GROW(q->results,
- q->result_count,
- q->result_count + 1);
- routed++;
- q->results[q->result_count-1] = hc;
- pos = q->sources;
- while (pos != NULL) {
- if (0 != memcmp(&pos->source,
- coreAPI->myIdentity,
- sizeof(PeerIdentity))) {
+ MUTEX_LOCK (lock);
+ for (i = 0; i < rt_size; i++)
+ {
+ q = records[i];
+ if (q == NULL)
+ continue;
+ tracked++;
+ if ((ntohl (q->get->type) != type) ||
+ (0 != memcmp (key, &q->get->key, sizeof (HashCode512))))
+ continue;
+ found = NO;
+ for (j = 0; j < q->result_count; j++)
+ if (0 == memcmp (&hc, &q->results[j], sizeof (HashCode512)))
+ {
+ found = YES;
+ break;
+ }
+ if (found == YES)
+ continue;
+ GROW (q->results, q->result_count, q->result_count + 1);
+ routed++;
+ q->results[q->result_count - 1] = hc;
+ pos = q->sources;
+ while (pos != NULL)
+ {
+ if (0 != memcmp (&pos->source,
+ coreAPI->myIdentity, sizeof (PeerIdentity)))
+ {
#if DEBUG_ROUTING
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Routing result to other peer\n");
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Routing result to other peer\n");
#endif
- coreAPI->unicast(&pos->source,
- &result->header,
- 0, /* FIXME: priority */
- 5 * cronSECONDS); /* FIXME */
- if (stats != NULL)
- stats->change(stat_replies_routed, 1);
- } else if (pos->receiver != NULL) {
+ coreAPI->unicast (&pos->source, &result->header, 0, /*
FIXME: priority */
+ 5 * cronSECONDS); /* FIXME */
+ if (stats != NULL)
+ stats->change (stat_replies_routed, 1);
+ }
+ else if (pos->receiver != NULL)
+ {
#if DEBUG_ROUTING
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Routing result to local client\n");
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Routing result to local client\n");
#endif
- pos->receiver(key,
- type,
- size,
- data,
- pos->receiver_closure);
- if (stats != NULL)
- stats->change(stat_replies_routed, 1);
- }
- pos = pos->next;
+ pos->receiver (key, type, size, data, pos->receiver_closure);
+ if (stats != NULL)
+ stats->change (stat_replies_routed, 1);
+ }
+ pos = pos->next;
+ }
}
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
#if DEBUG_ROUTING
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Routed result to %u out of %u pending requests\n",
- routed,
- tracked);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Routed result to %u out of %u pending requests\n",
+ routed, tracked);
#endif
if (cls == NULL)
- FREE(result);
+ FREE (result);
}
/**
* @return OK if route was added, SYSERR if not
*/
-static int addRoute(const PeerIdentity * sender,
- ResultHandler handler,
- void * cls,
- const DHT_GET_MESSAGE * get) {
- DHTQueryRecord * q;
+static int
+addRoute (const PeerIdentity * sender,
+ ResultHandler handler, void *cls, const DHT_GET_MESSAGE * get)
+{
+ DHTQueryRecord *q;
unsigned int i;
unsigned int rt_pos;
cron_t expire;
cron_t now;
int ttl;
- struct DHT_Source_Route * pos;
+ struct DHT_Source_Route *pos;
- ttl = ntohl(get->ttl);
+ ttl = ntohl (get->ttl);
if (ttl > MAX_TTL)
- ttl = 0; /* implausibly high */
- now = get_time();
+ ttl = 0; /* implausibly high */
+ now = get_time ();
expire = now + ttl;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
rt_pos = rt_size;
- for (i=0;i<rt_size;i++) {
- if ( (sender != NULL) &&
- (records[i] != NULL) &&
- (0 == memcmp(&records[i]->get->key,
- &get->key,
- sizeof(HashCode512))) &&
- (records[i]->get->type == get->type) &&
- (records[i]->expires > now - MAX_TTL) ) {
- /* do not route, same request already (recently)
- active (possibly from other initiator) */
- /* FIXME: support sending replies back to
- multiple peers!? */
- MUTEX_UNLOCK(lock);
+ for (i = 0; i < rt_size; i++)
+ {
+ if ((sender != NULL) &&
+ (records[i] != NULL) &&
+ (0 == memcmp (&records[i]->get->key,
+ &get->key,
+ sizeof (HashCode512))) &&
+ (records[i]->get->type == get->type) &&
+ (records[i]->expires > now - MAX_TTL))
+ {
+ /* do not route, same request already (recently)
+ active (possibly from other initiator) */
+ /* FIXME: support sending replies back to
+ multiple peers!? */
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ if (records[i] == NULL)
+ {
+ rt_pos = i;
+ expire = 0;
+ }
+ else if (records[i]->expires < expire)
+ {
+ expire = records[i]->expires;
+ rt_pos = i;
+ }
+ }
+ if (rt_pos == rt_size)
+ {
+ /* do not route, expiration time too high */
+ MUTEX_UNLOCK (lock);
return SYSERR;
}
- if (records[i] == NULL) {
- rt_pos = i;
- expire = 0;
- } else if (records[i]->expires < expire) {
- expire = records[i]->expires;
- rt_pos = i;
+ if (records[rt_pos] == NULL)
+ {
+ records[rt_pos] = MALLOC (sizeof (DHTQueryRecord));
+ records[rt_pos]->get = NULL;
}
- }
- if (rt_pos == rt_size) {
- /* do not route, expiration time too high */
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- if (records[rt_pos] == NULL) {
- records[rt_pos] = MALLOC(sizeof(DHTQueryRecord));
- records[rt_pos]->get = NULL;
- }
- if (records[rt_pos]->get != NULL) {
- FREE(records[rt_pos]->get);
- while (records[rt_pos]->sources != NULL) {
- pos = records[rt_pos]->sources;
- records[rt_pos]->sources = pos->next;
- FREE(pos);
+ if (records[rt_pos]->get != NULL)
+ {
+ FREE (records[rt_pos]->get);
+ while (records[rt_pos]->sources != NULL)
+ {
+ pos = records[rt_pos]->sources;
+ records[rt_pos]->sources = pos->next;
+ FREE (pos);
+ }
}
- }
q = records[rt_pos];
- memset(q,
- 0,
- sizeof(DHTQueryRecord));
+ memset (q, 0, sizeof (DHTQueryRecord));
q->expires = now + ttl;
- q->get = MALLOC(ntohs(get->header.size));
- memcpy(q->get,
- get,
- ntohs(get->header.size));
- pos = MALLOC(sizeof(DHT_Source_Route));
+ q->get = MALLOC (ntohs (get->header.size));
+ memcpy (q->get, get, ntohs (get->header.size));
+ pos = MALLOC (sizeof (DHT_Source_Route));
pos->next = q->sources;
q->sources = pos;
if (sender != NULL)
@@ -397,15 +398,14 @@
pos->receiver = handler;
pos->receiver_closure = cls;
#if DEBUG_ROUTING
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Tracking request in slot %u\n",
- rt_pos);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Tracking request in slot %u\n", rt_pos);
#endif
rt_pos = (rt_pos + 1) % rt_size;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
if (stats != NULL)
- stats->change(stat_requests_routed, 1);
+ stats->change (stat_requests_routed, 1);
return OK;
}
@@ -419,10 +419,11 @@
/**
* Handle GET message.
*/
-static int handleGet(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg) {
+static int
+handleGet (const PeerIdentity * sender, const MESSAGE_HEADER * msg)
+{
PeerIdentity next[GET_TRIES];
- const DHT_GET_MESSAGE * get;
+ const DHT_GET_MESSAGE *get;
DHT_GET_MESSAGE aget;
int total;
int ttl;
@@ -431,65 +432,56 @@
EncName enc;
#endif
- if (ntohs(msg->size) != sizeof(DHT_GET_MESSAGE)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- get = (const DHT_GET_MESSAGE*) msg;
+ if (ntohs (msg->size) != sizeof (DHT_GET_MESSAGE))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ get = (const DHT_GET_MESSAGE *) msg;
#if DEBUG_ROUTING
- hash2enc(&get->key, &enc);
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Received DHT GET for key `%s'.\n",
- &enc);
+ hash2enc (&get->key, &enc);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Received DHT GET for key `%s'.\n", &enc);
#endif
if (stats != NULL)
- stats->change(stat_get_requests_received, 1);
- if ( (sender != NULL) &&
- (OK != addRoute(sender,
- NULL,
- NULL,
- get)) )
- return OK; /* could not route */
- total = dht_store_get(&get->key,
- ntohl(get->type),
- &routeResult,
- NULL);
- if ( (total > GET_TRIES) &&
- (sender != NULL) ) {
+ stats->change (stat_get_requests_received, 1);
+ if ((sender != NULL) && (OK != addRoute (sender, NULL, NULL, get)))
+ return OK; /* could not route */
+ total = dht_store_get (&get->key, ntohl (get->type), &routeResult, NULL);
+ if ((total > GET_TRIES) && (sender != NULL))
+ {
#if DEBUG_ROUTING
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Found %d results locally, will not route GET any further\n",
- total);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Found %d results locally, will not route GET any further\n",
+ total);
#endif
- return OK;
- }
+ return OK;
+ }
total = 0;
- for (i=0;i<GET_TRIES;i++) {
- if (OK != select_dht_peer(&next[i],
- &get->key,
- &next[0],
- i))
- break;
- if (-1 == hashCodeCompareDistance(&next[i].hashPubKey,
- &coreAPI->myIdentity->hashPubKey,
- &get->key)) {
- if (total == 0) {
- aget = *get;
- ttl = ntohl(get->ttl);
- if (ttl > MAX_TTL)
- ttl = MAX_TTL;
- ttl -= 5 * cronSECONDS;
- aget.ttl = htonl(ttl);
- total = 1;
- }
- coreAPI->unicast(&next[i],
- msg,
- 0, /* FIXME: priority */
- 5 * cronSECONDS); /* FIXME */
+ for (i = 0; i < GET_TRIES; i++)
+ {
+ if (OK != select_dht_peer (&next[i], &get->key, &next[0], i))
+ break;
+ if (-1 == hashCodeCompareDistance (&next[i].hashPubKey,
+ &coreAPI->myIdentity->hashPubKey,
+ &get->key))
+ {
+ if (total == 0)
+ {
+ aget = *get;
+ ttl = ntohl (get->ttl);
+ if (ttl > MAX_TTL)
+ ttl = MAX_TTL;
+ ttl -= 5 * cronSECONDS;
+ aget.ttl = htonl (ttl);
+ total = 1;
+ }
+ coreAPI->unicast (&next[i], msg, 0, /* FIXME: priority */
+ 5 * cronSECONDS); /* FIXME */
+ }
}
- }
return OK;
}
@@ -504,10 +496,11 @@
/**
* Handle PUT message.
*/
-static int handlePut(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg) {
+static int
+handlePut (const PeerIdentity * sender, const MESSAGE_HEADER * msg)
+{
PeerIdentity next[PUT_TRIES];
- const DHT_PUT_MESSAGE * put;
+ const DHT_PUT_MESSAGE *put;
cron_t now;
int store;
int i;
@@ -515,169 +508,164 @@
EncName enc;
#endif
- if (ntohs(msg->size) < sizeof(DHT_PUT_MESSAGE)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
+ if (ntohs (msg->size) < sizeof (DHT_PUT_MESSAGE))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
if (stats != NULL)
- stats->change(stat_put_requests_received, 1);
- put = (const DHT_PUT_MESSAGE*) msg;
+ stats->change (stat_put_requests_received, 1);
+ put = (const DHT_PUT_MESSAGE *) msg;
#if DEBUG_ROUTING
- hash2enc(&put->key,
- &enc);
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Received DHT PUT for key `%s'.\n",
- &enc);
+ hash2enc (&put->key, &enc);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Received DHT PUT for key `%s'.\n", &enc);
#endif
store = 0;
- for (i=0;i<PUT_TRIES;i++) {
- if (OK != select_dht_peer(&next[i],
- &put->key,
- &next[0],
- i)) {
- store = 1;
- break;
+ for (i = 0; i < PUT_TRIES; i++)
+ {
+ if (OK != select_dht_peer (&next[i], &put->key, &next[0], i))
+ {
+ store = 1;
+ break;
+ }
+ if (1 == hashCodeCompareDistance (&next[i].hashPubKey,
+ &coreAPI->myIdentity->hashPubKey,
+ &put->key))
+ store = 1; /* we're closer than the selected target */
+ else
+ coreAPI->unicast (&next[i], msg, 0, /* FIXME: priority */
+ 5 * cronSECONDS); /* FIXME */
}
- if (1 == hashCodeCompareDistance(&next[i].hashPubKey,
- &coreAPI->myIdentity->hashPubKey,
- &put->key))
- store = 1; /* we're closer than the selected target */
- else
- coreAPI->unicast(&next[i],
- msg,
- 0, /* FIXME: priority */
- 5 * cronSECONDS); /* FIXME */
- }
- if (store != 0) {
- now = get_time();
+ if (store != 0)
+ {
+ now = get_time ();
#if DEBUG_ROUTING
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Decided to cache data `%.*s' locally until %llu (for %llu ms)\n",
- ntohs(put->header.size) - sizeof(DHT_PUT_MESSAGE),
- &put[1],
- ntohll(put->timeout) + now,
- ntohll(put->timeout));
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Decided to cache data `%.*s' locally until %llu (for %llu
ms)\n",
+ ntohs (put->header.size) - sizeof (DHT_PUT_MESSAGE),
+ &put[1], ntohll (put->timeout) + now, ntohll (put->timeout));
#endif
- dht_store_put(ntohl(put->type),
- &put->key,
- ntohll(put->timeout) + now,
- ntohs(put->header.size) - sizeof(DHT_PUT_MESSAGE),
- (const char*) &put[1]);
- } else {
+ dht_store_put (ntohl (put->type),
+ &put->key,
+ ntohll (put->timeout) + now,
+ ntohs (put->header.size) - sizeof (DHT_PUT_MESSAGE),
+ (const char *) &put[1]);
+ }
+ else
+ {
#if DEBUG_ROUTING
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Decided NOT to cache data `%.*s' locally\n",
- ntohs(put->header.size) - sizeof(DHT_PUT_MESSAGE),
- &put[1]);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Decided NOT to cache data `%.*s' locally\n",
+ ntohs (put->header.size) - sizeof (DHT_PUT_MESSAGE), &put[1]);
#endif
- }
+ }
return OK;
}
/**
* Handle RESULT message.
*/
-static int handleResult(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg) {
- const DHT_RESULT_MESSAGE * result;
+static int
+handleResult (const PeerIdentity * sender, const MESSAGE_HEADER * msg)
+{
+ const DHT_RESULT_MESSAGE *result;
#if DEBUG_ROUTING
EncName enc;
#endif
- if (ntohs(msg->size) < sizeof(DHT_RESULT_MESSAGE)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
+ if (ntohs (msg->size) < sizeof (DHT_RESULT_MESSAGE))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
if (stats != NULL)
- stats->change(stat_results_received, 1);
- result = (const DHT_RESULT_MESSAGE*) msg;
+ stats->change (stat_results_received, 1);
+ result = (const DHT_RESULT_MESSAGE *) msg;
#if DEBUG_ROUTING
- hash2enc(&result->key, &enc);
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Received DHT RESULT for key `%s'.\n",
- &enc);
+ hash2enc (&result->key, &enc);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Received DHT RESULT for key `%s'.\n", &enc);
#endif
- routeResult(&result->key,
- ntohl(result->type),
- ntohs(result->header.size) - sizeof(DHT_RESULT_MESSAGE),
- (const char*) &result[1],
- (void*) msg);
+ routeResult (&result->key,
+ ntohl (result->type),
+ ntohs (result->header.size) - sizeof (DHT_RESULT_MESSAGE),
+ (const char *) &result[1], (void *) msg);
return OK;
}
/**
* Start a DHT get operation.
*/
-void dht_get_start(const HashCode512 * key,
- unsigned int type,
- ResultHandler handler,
- void * cls) {
+void
+dht_get_start (const HashCode512 * key,
+ unsigned int type, ResultHandler handler, void *cls)
+{
DHT_GET_MESSAGE get;
- get.header.size = htons(sizeof(DHT_GET_MESSAGE));
- get.header.type = htons(P2P_PROTO_DHT_GET);
- get.type = htonl(type);
- get.prio = htonl(0); /* FIXME */
- get.ttl = htonl(MAX_TTL); /* FIXME? */
+ get.header.size = htons (sizeof (DHT_GET_MESSAGE));
+ get.header.type = htons (P2P_PROTO_DHT_GET);
+ get.type = htonl (type);
+ get.prio = htonl (0); /* FIXME */
+ get.ttl = htonl (MAX_TTL); /* FIXME? */
get.key = *key;
- if (OK == addRoute(NULL,
- handler,
- cls,
- &get))
- handleGet(NULL,
- &get.header);
+ if (OK == addRoute (NULL, handler, cls, &get))
+ handleGet (NULL, &get.header);
}
/**
* Stop a DHT get operation (prevents calls to
* the given iterator).
*/
-void dht_get_stop(const HashCode512 * key,
- unsigned int type,
- ResultHandler handler,
- void * cls) {
+void
+dht_get_stop (const HashCode512 * key,
+ unsigned int type, ResultHandler handler, void *cls)
+{
int i;
- struct DHT_Source_Route * pos;
- struct DHT_Source_Route * prev;
+ struct DHT_Source_Route *pos;
+ struct DHT_Source_Route *prev;
int done;
done = NO;
- MUTEX_LOCK(lock);
- for (i=0;i<rt_size;i++) {
- if (records[i] == NULL)
- continue;
- prev = NULL;
- pos = records[i]->sources;
- while (pos != NULL) {
- if ( (pos->receiver == handler) &&
- (pos->receiver_closure == cls) &&
- (0 == memcmp(key,
- &records[i]->get->key,
- sizeof(HashCode512))) ) {
- if (prev == NULL)
- records[i]->sources = pos->next;
- else
- prev->next = pos->next;
- FREE(pos);
- done = YES;
- break;
- }
- prev = pos;
- pos = prev->next;
+ MUTEX_LOCK (lock);
+ for (i = 0; i < rt_size; i++)
+ {
+ if (records[i] == NULL)
+ continue;
+ prev = NULL;
+ pos = records[i]->sources;
+ while (pos != NULL)
+ {
+ if ((pos->receiver == handler) &&
+ (pos->receiver_closure == cls) &&
+ (0 == memcmp (key,
+ &records[i]->get->key, sizeof (HashCode512))))
+ {
+ if (prev == NULL)
+ records[i]->sources = pos->next;
+ else
+ prev->next = pos->next;
+ FREE (pos);
+ done = YES;
+ break;
+ }
+ prev = pos;
+ pos = prev->next;
+ }
+ if (records[i]->sources == NULL)
+ {
+ FREE (records[i]->get);
+ FREE (records[i]);
+ records[i] = NULL;
+ }
+ if (done == YES)
+ break;
}
- if (records[i]->sources == NULL) {
- FREE(records[i]->get);
- FREE(records[i]);
- records[i] = NULL;
- }
- if (done == YES)
- break;
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
/**
@@ -689,25 +677,22 @@
*
* @param expirationTime absolute expiration time
*/
-void dht_put(const HashCode512 * key,
- unsigned int type,
- unsigned int size,
- cron_t expirationTime,
- const char * data) {
- DHT_PUT_MESSAGE * put;
+void
+dht_put (const HashCode512 * key,
+ unsigned int type,
+ unsigned int size, cron_t expirationTime, const char *data)
+{
+ DHT_PUT_MESSAGE *put;
- put = MALLOC(sizeof(DHT_PUT_MESSAGE) + size);
- put->header.size = htons(sizeof(DHT_PUT_MESSAGE) + size);
- put->header.type = htons(P2P_PROTO_DHT_PUT);
+ put = MALLOC (sizeof (DHT_PUT_MESSAGE) + size);
+ put->header.size = htons (sizeof (DHT_PUT_MESSAGE) + size);
+ put->header.type = htons (P2P_PROTO_DHT_PUT);
put->key = *key;
- put->type = htonl(type);
- put->timeout = htonll(expirationTime - get_time()); /* convert to relative
time */
- memcpy(&put[1],
- data,
- size);
- handlePut(NULL,
- &put->header);
- FREE(put);
+ put->type = htonl (type);
+ put->timeout = htonll (expirationTime - get_time ()); /* convert to relative
time */
+ memcpy (&put[1], data, size);
+ handlePut (NULL, &put->header);
+ FREE (put);
}
/**
@@ -719,9 +704,9 @@
* @return number of bytes added at position
*/
static unsigned int
-extra_get_callback(const PeerIdentity * receiver,
- void * position,
- unsigned int padding) {
+extra_get_callback (const PeerIdentity * receiver,
+ void *position, unsigned int padding)
+{
return 0;
}
@@ -731,45 +716,42 @@
* @param capi the core API
* @return OK on success
*/
-int init_dht_routing(CoreAPIForApplication * capi) {
+int
+init_dht_routing (CoreAPIForApplication * capi)
+{
unsigned long long rts;
coreAPI = capi;
rts = 65536;
- GC_get_configuration_value_number(coreAPI->cfg,
- "DHT",
- "TABLESIZE",
- 128,
- 1024 * 1024,
- 1024,
- &rts);
- GROW(records,
- rt_size,
- rts);
- lock = MUTEX_CREATE(NO);
- stats = capi->requestService("stats");
- if (stats != NULL) {
- stat_replies_routed = stats->create(gettext_noop("# dht replies routed"));
- stat_requests_routed = stats->create(gettext_noop("# dht requests
routed"));
- stat_get_requests_received = stats->create(gettext_noop("# dht get
requests received"));
- stat_put_requests_received = stats->create(gettext_noop("# dht put
requests received"));
- stat_results_received = stats->create(gettext_noop("# dht results
received"));
- }
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _("`%s' registering p2p handlers: %d %d %d\n"),
- "dht",
- P2P_PROTO_DHT_GET,
- P2P_PROTO_DHT_PUT,
- P2P_PROTO_DHT_RESULT);
- coreAPI->registerHandler(P2P_PROTO_DHT_GET,
- &handleGet);
- coreAPI->registerHandler(P2P_PROTO_DHT_PUT,
- &handlePut);
- coreAPI->registerHandler(P2P_PROTO_DHT_RESULT,
- &handleResult);
- coreAPI->registerSendCallback(sizeof(DHT_GET_MESSAGE),
- &extra_get_callback);
+ GC_get_configuration_value_number (coreAPI->cfg,
+ "DHT",
+ "TABLESIZE",
+ 128, 1024 * 1024, 1024, &rts);
+ GROW (records, rt_size, rts);
+ lock = MUTEX_CREATE (NO);
+ stats = capi->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_replies_routed =
+ stats->create (gettext_noop ("# dht replies routed"));
+ stat_requests_routed =
+ stats->create (gettext_noop ("# dht requests routed"));
+ stat_get_requests_received =
+ stats->create (gettext_noop ("# dht get requests received"));
+ stat_put_requests_received =
+ stats->create (gettext_noop ("# dht put requests received"));
+ stat_results_received =
+ stats->create (gettext_noop ("# dht results received"));
+ }
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ _("`%s' registering p2p handlers: %d %d %d\n"),
+ "dht", P2P_PROTO_DHT_GET, P2P_PROTO_DHT_PUT, P2P_PROTO_DHT_RESULT);
+ coreAPI->registerHandler (P2P_PROTO_DHT_GET, &handleGet);
+ coreAPI->registerHandler (P2P_PROTO_DHT_PUT, &handlePut);
+ coreAPI->registerHandler (P2P_PROTO_DHT_RESULT, &handleResult);
+ coreAPI->registerSendCallback (sizeof (DHT_GET_MESSAGE),
+ &extra_get_callback);
return OK;
}
@@ -778,31 +760,31 @@
*
* @return OK on success
*/
-int done_dht_routing() {
+int
+done_dht_routing ()
+{
unsigned int i;
- coreAPI->unregisterSendCallback(sizeof(DHT_GET_MESSAGE),
- &extra_get_callback);
- coreAPI->unregisterHandler(P2P_PROTO_DHT_GET,
- &handleGet);
- coreAPI->unregisterHandler(P2P_PROTO_DHT_PUT,
- &handlePut);
- coreAPI->unregisterHandler(P2P_PROTO_DHT_RESULT,
- &handleResult);
- if (stats != NULL) {
- coreAPI->releaseService(stats);
- stats = NULL;
- }
- MUTEX_DESTROY(lock);
- for (i=0;i<rt_size;i++) {
- if (records[i] != NULL) {
- FREE(records[i]->get);
- FREE(records[i]);
+ coreAPI->unregisterSendCallback (sizeof (DHT_GET_MESSAGE),
+ &extra_get_callback);
+ coreAPI->unregisterHandler (P2P_PROTO_DHT_GET, &handleGet);
+ coreAPI->unregisterHandler (P2P_PROTO_DHT_PUT, &handlePut);
+ coreAPI->unregisterHandler (P2P_PROTO_DHT_RESULT, &handleResult);
+ if (stats != NULL)
+ {
+ coreAPI->releaseService (stats);
+ stats = NULL;
}
- }
- GROW(records,
- rt_size,
- 0);
+ MUTEX_DESTROY (lock);
+ for (i = 0; i < rt_size; i++)
+ {
+ if (records[i] != NULL)
+ {
+ FREE (records[i]->get);
+ FREE (records[i]);
+ }
+ }
+ GROW (records, rt_size, 0);
return OK;
}
Modified: GNUnet/src/applications/dht/module/routing.h
===================================================================
--- GNUnet/src/applications/dht/module/routing.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/dht/module/routing.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -35,19 +35,15 @@
/**
* Start a DHT get operation.
*/
-void dht_get_start(const HashCode512 * key,
- unsigned int type,
- ResultHandler handler,
- void * cls);
+void dht_get_start (const HashCode512 * key,
+ unsigned int type, ResultHandler handler, void *cls);
/**
* Stop a DHT get operation (prevents calls to
* the given iterator).
*/
-void dht_get_stop(const HashCode512 * key,
- unsigned int type,
- ResultHandler handler,
- void * cls);
+void dht_get_stop (const HashCode512 * key,
+ unsigned int type, ResultHandler handler, void *cls);
/**
* Perform a DHT put operation. Note that PUT operations always
@@ -58,11 +54,9 @@
*
* @param expirationTime absolute expiration time
*/
-void dht_put(const HashCode512 * key,
- unsigned int type,
- unsigned int size,
- cron_t expirationTime,
- const char * data);
+void dht_put (const HashCode512 * key,
+ unsigned int type,
+ unsigned int size, cron_t expirationTime, const char *data);
/**
* Initialize routing DHT component.
@@ -70,13 +64,13 @@
* @param capi the core API
* @return OK on success
*/
-int init_dht_routing(CoreAPIForApplication * capi);
+int init_dht_routing (CoreAPIForApplication * capi);
/**
* Shutdown routing DHT component.
*
* @return OK on success
*/
-int done_dht_routing(void);
+int done_dht_routing (void);
#endif
Modified: GNUnet/src/applications/dht/module/service.c
===================================================================
--- GNUnet/src/applications/dht/module/service.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/dht/module/service.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -33,11 +33,12 @@
/**
* Global core API.
*/
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static struct CronManager * cron;
+static struct CronManager *cron;
-typedef struct DHT_GET_RECORD {
+typedef struct DHT_GET_RECORD
+{
/**
* Key that we are looking for.
*/
@@ -51,7 +52,7 @@
/**
* Extra argument to callback.
*/
- void * cls;
+ void *cls;
/**
* Function to call once we are done
@@ -61,7 +62,7 @@
/**
* Extra argument to callbackComplete
*/
- void * closure;
+ void *closure;
/**
* Type of the content that we are looking for.
@@ -70,32 +71,30 @@
} DHT_GET_RECORD;
-static void client_result_converter(const HashCode512 * key,
- unsigned int type,
- unsigned int size,
- const char * data,
- void * cls) {
- struct DHT_GET_RECORD * get = cls;
- DataContainer * dc;
+static void
+client_result_converter (const HashCode512 * key,
+ unsigned int type,
+ unsigned int size, const char *data, void *cls)
+{
+ struct DHT_GET_RECORD *get = cls;
+ DataContainer *dc;
- dc = MALLOC(sizeof(DataContainer) + size);
- dc->size = ntohl(sizeof(DataContainer) + size);
- memcpy(&dc[1],
- data,
- size);
- get->callback(key,
- dc,
- get->cls);
- FREE(dc);
+ dc = MALLOC (sizeof (DataContainer) + size);
+ dc->size = ntohl (sizeof (DataContainer) + size);
+ memcpy (&dc[1], data, size);
+ get->callback (key, dc, get->cls);
+ FREE (dc);
}
/**
* Cron job that notifies the client.
*/
-static void timeout_callback(void * cls) {
- struct DHT_GET_RECORD * rec = cls;
+static void
+timeout_callback (void *cls)
+{
+ struct DHT_GET_RECORD *rec = cls;
- rec->callbackComplete(rec->closure);
+ rec->callbackComplete (rec->closure);
}
/**
@@ -117,31 +116,24 @@
* @return handle to stop the async get
*/
static struct DHT_GET_RECORD *
-dht_get_async_start(unsigned int type,
- const HashCode512 * key,
- cron_t timeout,
- DataProcessor callback,
- void * cls,
- DHT_OP_Complete callbackComplete,
- void * closure) {
- struct DHT_GET_RECORD * ret;
+dht_get_async_start (unsigned int type,
+ const HashCode512 * key,
+ cron_t timeout,
+ DataProcessor callback,
+ void *cls,
+ DHT_OP_Complete callbackComplete, void *closure)
+{
+ struct DHT_GET_RECORD *ret;
- ret = MALLOC(sizeof(DHT_GET_RECORD));
+ ret = MALLOC (sizeof (DHT_GET_RECORD));
ret->key = *key;
ret->callback = callback;
ret->cls = cls;
ret->callbackComplete = callbackComplete;
ret->closure = closure;
ret->type = type;
- cron_add_job(cron,
- &timeout_callback,
- timeout,
- 0,
- ret);
- dht_get_start(key,
- type,
- &client_result_converter,
- ret);
+ cron_add_job (cron, &timeout_callback, timeout, 0, ret);
+ dht_get_start (key, type, &client_result_converter, ret);
return ret;
}
@@ -149,20 +141,13 @@
* Stop async DHT-get. Frees associated resources.
*/
static int
-dht_get_async_stop(struct DHT_GET_RECORD * record) {
- cron_suspend(cron,
- YES);
- cron_del_job(cron,
- &timeout_callback,
- 0,
- record);
- cron_resume_jobs(cron,
- YES);
- dht_get_stop(&record->key,
- record->type,
- &client_result_converter,
- record);
- FREE(record);
+dht_get_async_stop (struct DHT_GET_RECORD *record)
+{
+ cron_suspend (cron, YES);
+ cron_del_job (cron, &timeout_callback, 0, record);
+ cron_resume_jobs (cron, YES);
+ dht_get_stop (&record->key, record->type, &client_result_converter, record);
+ FREE (record);
return OK;
}
@@ -174,23 +159,25 @@
* @return NULL on errors, DHT_API otherwise
*/
DHT_ServiceAPI *
-provide_module_dht(CoreAPIForApplication * capi) {
+provide_module_dht (CoreAPIForApplication * capi)
+{
static DHT_ServiceAPI api;
- cron = cron_create(capi->ectx);
- cron_start(cron);
- if (OK != init_dht_store(1024 * 1024,
- capi))
+ cron = cron_create (capi->ectx);
+ cron_start (cron);
+ if (OK != init_dht_store (1024 * 1024, capi))
return NULL;
- if (OK != init_dht_table(capi)) {
- done_dht_store();
- return NULL;
- }
- if (OK != init_dht_routing(capi)) {
- done_dht_table();
- done_dht_store();
- return NULL;
- }
+ if (OK != init_dht_table (capi))
+ {
+ done_dht_store ();
+ return NULL;
+ }
+ if (OK != init_dht_routing (capi))
+ {
+ done_dht_table ();
+ done_dht_store ();
+ return NULL;
+ }
coreAPI = capi;
api.get_start = &dht_get_async_start;
api.get_stop = &dht_get_async_stop;
@@ -201,12 +188,14 @@
/**
* Shutdown DHT service.
*/
-int release_module_dht() {
- cron_stop(cron);
- done_dht_routing();
- done_dht_table();
- done_dht_store();
- cron_destroy(cron);
+int
+release_module_dht ()
+{
+ cron_stop (cron);
+ done_dht_routing ();
+ done_dht_table ();
+ done_dht_store ();
+ cron_destroy (cron);
return OK;
}
Modified: GNUnet/src/applications/dht/module/table.c
===================================================================
--- GNUnet/src/applications/dht/module/table.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/dht/module/table.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -85,7 +85,8 @@
/**
* Per-peer information.
*/
-typedef struct {
+typedef struct
+{
/**
* What was the last time we received a message from this peer?
@@ -122,12 +123,13 @@
/**
* Peers are grouped into buckets.
*/
-typedef struct {
+typedef struct
+{
/**
* Peers in this bucket. NULL is used if no peer is known.
*/
- PeerInfo ** peers;
+ PeerInfo **peers;
/**
* Peers in this bucket fall into the distance-range
@@ -148,12 +150,12 @@
/**
* Global core API.
*/
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
/**
* The buckets (Kademlia style routing table).
*/
-static PeerBucket * buckets;
+static PeerBucket *buckets;
/**
* Total number of active buckets.
@@ -168,22 +170,22 @@
/**
* Mutex to synchronize access to tables.
*/
-static struct MUTEX * lock;
+static struct MUTEX *lock;
/**
* Identity service.
*/
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
/**
* Statistics service.
*/
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
/**
* Pingpong service.
*/
-static Pingpong_ServiceAPI * pingpong;
+static Pingpong_ServiceAPI *pingpong;
static int stat_dht_total_peers;
@@ -198,7 +200,8 @@
* PeerIdentities that the sender knows to
* be participating in the DHT.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
@@ -211,7 +214,8 @@
* DHT. Receiver is expected to send back a HELLO for the peer that
* is being requested.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
@@ -225,35 +229,36 @@
* Get the index of the lowest bit of the two hash codes that
* differs.
*/
-static unsigned int get_bit_distance(const HashCode512 * h1,
- const HashCode512 * h2) {
+static unsigned int
+get_bit_distance (const HashCode512 * h1, const HashCode512 * h2)
+{
unsigned int i;
int diff;
- for (i=0;i<sizeof(HashCode512)*8;i++) {
- diff = getHashCodeBit(h1, i) - getHashCodeBit(h2, i);
- if (diff != 0)
- return i;
- }
- return sizeof(HashCode512)*8;
+ for (i = 0; i < sizeof (HashCode512) * 8; i++)
+ {
+ diff = getHashCodeBit (h1, i) - getHashCodeBit (h2, i);
+ if (diff != 0)
+ return i;
+ }
+ return sizeof (HashCode512) * 8;
}
/**
* @return NULL if peer is the current host
*/
static PeerBucket *
-findBucketFor(const PeerIdentity * peer) {
+findBucketFor (const PeerIdentity * peer)
+{
unsigned int index;
int i;
- index = get_bit_distance(&peer->hashPubKey,
- &coreAPI->myIdentity->hashPubKey);
- i = bucketCount-1;
- while ( (buckets[i].bstart >= index) &&
- (i > 0) )
+ index = get_bit_distance (&peer->hashPubKey,
+ &coreAPI->myIdentity->hashPubKey);
+ i = bucketCount - 1;
+ while ((buckets[i].bstart >= index) && (i > 0))
i--;
- if ( (buckets[i].bstart < index) &&
- (buckets[i].bend >= index) )
+ if ((buckets[i].bstart < index) && (buckets[i].bend >= index))
return &buckets[i];
return NULL;
}
@@ -263,16 +268,14 @@
* in our DHT routing table.
*/
static PeerInfo *
-findPeerEntryInBucket(PeerBucket * bucket,
- const PeerIdentity * peer) {
+findPeerEntryInBucket (PeerBucket * bucket, const PeerIdentity * peer)
+{
unsigned int i;
if (bucket == NULL)
return NULL;
- for (i=0;i<bucket->peers_size;i++)
- if (0 == memcmp(peer,
- &bucket->peers[i]->id,
- sizeof(PeerIdentity)))
+ for (i = 0; i < bucket->peers_size; i++)
+ if (0 == memcmp (peer, &bucket->peers[i]->id, sizeof (PeerIdentity)))
return bucket->peers[i];
return NULL;
}
@@ -282,9 +285,9 @@
* in our DHT routing table.
*/
static PeerInfo *
-findPeerEntry(const PeerIdentity * peer) {
- return findPeerEntryInBucket(findBucketFor(peer),
- peer);
+findPeerEntry (const PeerIdentity * peer)
+{
+ return findPeerEntryInBucket (findBucketFor (peer), peer);
}
/**
@@ -297,16 +300,16 @@
*
* @return inverse distance metric, non-zero.
*/
-static unsigned int inverse_distance(const HashCode512 * target,
- const HashCode512 * have) {
+static unsigned int
+inverse_distance (const HashCode512 * target, const HashCode512 * have)
+{
unsigned int bucket;
double d;
- bucket = get_bit_distance(target,
- have);
+ bucket = get_bit_distance (target, have);
d = bucket * 32;
- d = exp2(d / (sizeof(HashCode512)*8));
- if (d > ((unsigned int)-1))
+ d = exp2 (d / (sizeof (HashCode512) * 8));
+ if (d > ((unsigned int) -1))
return -1;
return (unsigned int) d;
}
@@ -323,10 +326,11 @@
*
* @return OK on success, SYSERR on error
*/
-int select_dht_peer(PeerIdentity * set,
- const HashCode512 * target,
- const PeerIdentity * blocked,
- unsigned int blocked_size) {
+int
+select_dht_peer (PeerIdentity * set,
+ const HashCode512 * target,
+ const PeerIdentity * blocked, unsigned int blocked_size)
+{
unsigned long long total_distance;
unsigned long long selected;
unsigned int distance;
@@ -334,64 +338,68 @@
unsigned int ec;
unsigned int i;
int match;
- PeerBucket * bucket;
- PeerInfo * pi;
+ PeerBucket *bucket;
+ PeerInfo *pi;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
if (stats != NULL)
- stats->change(stat_dht_route_looks, 1);
+ stats->change (stat_dht_route_looks, 1);
total_distance = 0;
- for (bc=0;bc<bucketCount;bc++) {
- bucket = &buckets[bc];
- for (ec=0;ec<bucket->peers_size;ec++) {
- pi = bucket->peers[ec];
- match = NO;
- for (i=0;i<blocked_size;i++) {
- if (0 == memcmp(&pi->id,
- &blocked[i],
- sizeof(PeerIdentity))) {
- match = YES;
- break;
- }
- }
- if (match == YES)
- continue;
- total_distance += inverse_distance(target,
- &pi->id.hashPubKey);
+ for (bc = 0; bc < bucketCount; bc++)
+ {
+ bucket = &buckets[bc];
+ for (ec = 0; ec < bucket->peers_size; ec++)
+ {
+ pi = bucket->peers[ec];
+ match = NO;
+ for (i = 0; i < blocked_size; i++)
+ {
+ if (0 == memcmp (&pi->id, &blocked[i], sizeof (PeerIdentity)))
+ {
+ match = YES;
+ break;
+ }
+ }
+ if (match == YES)
+ continue;
+ total_distance += inverse_distance (target, &pi->id.hashPubKey);
+ }
}
- }
- if (total_distance == 0) {
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- selected = weak_randomi64(total_distance);
- for (bc=0;bc<bucketCount;bc++) {
- bucket = &buckets[bc];
- for (ec=0;ec<bucket->peers_size;ec++) {
- pi = bucket->peers[ec];
- match = NO;
- for (i=0;i<blocked_size;i++) {
- if (0 == memcmp(&pi->id,
- &blocked[i],
- sizeof(PeerIdentity))) {
- match = YES;
- break;
- }
- }
- if (match == YES)
- continue;
- distance = inverse_distance(target,
- &pi->id.hashPubKey);
- if (distance > selected) {
- *set = pi->id;
- MUTEX_UNLOCK(lock);
- return OK;
- }
- selected -= distance;
+ if (total_distance == 0)
+ {
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
}
- }
- GE_BREAK(NULL, 0);
- MUTEX_UNLOCK(lock);
+ selected = weak_randomi64 (total_distance);
+ for (bc = 0; bc < bucketCount; bc++)
+ {
+ bucket = &buckets[bc];
+ for (ec = 0; ec < bucket->peers_size; ec++)
+ {
+ pi = bucket->peers[ec];
+ match = NO;
+ for (i = 0; i < blocked_size; i++)
+ {
+ if (0 == memcmp (&pi->id, &blocked[i], sizeof (PeerIdentity)))
+ {
+ match = YES;
+ break;
+ }
+ }
+ if (match == YES)
+ continue;
+ distance = inverse_distance (target, &pi->id.hashPubKey);
+ if (distance > selected)
+ {
+ *set = pi->id;
+ MUTEX_UNLOCK (lock);
+ return OK;
+ }
+ selected -= distance;
+ }
+ }
+ GE_BREAK (NULL, 0);
+ MUTEX_UNLOCK (lock);
return SYSERR;
}
@@ -400,114 +408,120 @@
*
* @param cls NULL or pre-build discovery message
*/
-static void broadcast_dht_discovery(const PeerIdentity * other,
- void * cls) {
- P2P_DHT_Discovery * disco = cls;
+static void
+broadcast_dht_discovery (const PeerIdentity * other, void *cls)
+{
+ P2P_DHT_Discovery *disco = cls;
unsigned int pc;
unsigned int i;
- PeerIdentity * pos;
+ PeerIdentity *pos;
if (stats != NULL)
- stats->change(stat_dht_advertisements, 1);
- if (disco != NULL) {
- coreAPI->unicast(other,
- &disco->header,
- EXTREME_PRIORITY/4,
- MAINTAIN_FREQUENCY * MAINTAIN_CHANCE / 2);
- return;
- }
+ stats->change (stat_dht_advertisements, 1);
+ if (disco != NULL)
+ {
+ coreAPI->unicast (other,
+ &disco->header,
+ EXTREME_PRIORITY / 4,
+ MAINTAIN_FREQUENCY * MAINTAIN_CHANCE / 2);
+ return;
+ }
pc = total_peers;
if (pc > MAINTAIN_ADV_CAP)
pc = MAINTAIN_ADV_CAP;
if (pc == 0)
pc = 1;
- disco = MALLOC(pc * sizeof(PeerIdentity) + sizeof(P2P_DHT_Discovery));
- disco->header.type = htons(P2P_PROTO_DHT_DISCOVERY);
- disco->space_available = -1; /* FIXME */
- pos = (PeerIdentity*) &disco[1];
+ disco = MALLOC (pc * sizeof (PeerIdentity) + sizeof (P2P_DHT_Discovery));
+ disco->header.type = htons (P2P_PROTO_DHT_DISCOVERY);
+ disco->space_available = -1; /* FIXME */
+ pos = (PeerIdentity *) & disco[1];
i = 0;
- if (total_peers == 0) {
- /* put in our own identity (otherwise we get into a
- storm of empty discovery messages) */
- pos[0] = *coreAPI->myIdentity;
- i = 1;
- }
- while (i < pc) {
- if (OK != select_dht_peer(&pos[i],
- &other->hashPubKey,
- pos,
- i))
- pc--;
- else
- i++;
- }
- disco->header.size = htons(pc * sizeof(PeerIdentity) +
sizeof(P2P_DHT_Discovery));
- coreAPI->unicast(other,
- &disco->header,
- 0,
- MAINTAIN_FREQUENCY * MAINTAIN_CHANCE / 2);
- FREE(disco);
+ if (total_peers == 0)
+ {
+ /* put in our own identity (otherwise we get into a
+ storm of empty discovery messages) */
+ pos[0] = *coreAPI->myIdentity;
+ i = 1;
+ }
+ while (i < pc)
+ {
+ if (OK != select_dht_peer (&pos[i], &other->hashPubKey, pos, i))
+ pc--;
+ else
+ i++;
+ }
+ disco->header.size =
+ htons (pc * sizeof (PeerIdentity) + sizeof (P2P_DHT_Discovery));
+ coreAPI->unicast (other, &disco->header, 0,
+ MAINTAIN_FREQUENCY * MAINTAIN_CHANCE / 2);
+ FREE (disco);
}
-static void broadcast_dht_discovery_prob(const PeerIdentity * other,
- void * cls) {
- if (weak_randomi(MAINTAIN_CHANCE) != 0)
+static void
+broadcast_dht_discovery_prob (const PeerIdentity * other, void *cls)
+{
+ if (weak_randomi (MAINTAIN_CHANCE) != 0)
return;
- broadcast_dht_discovery(other, cls);
+ broadcast_dht_discovery (other, cls);
}
/**
* Cron job to maintain DHT routing table.
*/
-static void maintain_dht_job(void * unused) {
+static void
+maintain_dht_job (void *unused)
+{
P2P_DHT_Discovery disc;
- if (total_peers == 0) {
- disc.header.size = htons(sizeof(P2P_DHT_Discovery));
- disc.header.type = htons(P2P_PROTO_DHT_DISCOVERY);
- disc.space_available = -1; /* FIXME */
- coreAPI->forAllConnectedNodes(&broadcast_dht_discovery_prob,
- &disc);
- } else {
- coreAPI->forAllConnectedNodes(&broadcast_dht_discovery_prob,
- NULL);
- }
+ if (total_peers == 0)
+ {
+ disc.header.size = htons (sizeof (P2P_DHT_Discovery));
+ disc.header.type = htons (P2P_PROTO_DHT_DISCOVERY);
+ disc.space_available = -1; /* FIXME */
+ coreAPI->forAllConnectedNodes (&broadcast_dht_discovery_prob, &disc);
+ }
+ else
+ {
+ coreAPI->forAllConnectedNodes (&broadcast_dht_discovery_prob, NULL);
+ }
}
/**
* We have received a pong from a peer and know it is still
* there.
*/
-static void pongNotify(void * cls) {
- PeerIdentity * peer = cls;
- PeerInfo * pi;
+static void
+pongNotify (void *cls)
+{
+ PeerIdentity *peer = cls;
+ PeerInfo *pi;
- pi = findPeerEntry(peer);
- if (pi != NULL) {
- pi->lastActivity = get_time();
- pi->expected_latency = pi->lastActivity - pi->lastTimePingSend;
- pi->response_count++;
- }
- FREE(peer);
+ pi = findPeerEntry (peer);
+ if (pi != NULL)
+ {
+ pi->lastActivity = get_time ();
+ pi->expected_latency = pi->lastActivity - pi->lastTimePingSend;
+ pi->response_count++;
+ }
+ FREE (peer);
}
/**
* Send a ping to the given peer to check if it is still
* running.
*/
-static void pingPeer(PeerInfo * pi) {
- PeerIdentity * p;
+static void
+pingPeer (PeerInfo * pi)
+{
+ PeerIdentity *p;
- p = MALLOC(sizeof(PeerIdentity));
+ p = MALLOC (sizeof (PeerIdentity));
*p = pi->id;
- if (OK == pingpong->ping(p,
- &pongNotify,
- p,
- NO,
- rand())) {
- pi->lastTimePingSend = get_time();
- pi->request_count++;
- }
+ if (OK == pingpong->ping (p, &pongNotify, p, NO, rand ()))
+ {
+ pi->lastTimePingSend = get_time ();
+ pi->request_count++;
+ }
}
/**
@@ -516,160 +530,158 @@
*
* @return YES if the peer should be removed from the DHT table
*/
-static int checkExpired(PeerInfo * pi) {
+static int
+checkExpired (PeerInfo * pi)
+{
cron_t now;
- now = get_time();
+ now = get_time ();
if (pi->lastActivity >= now)
return NO;
if (now - pi->lastActivity > MAINTAIN_PEER_TIMEOUT)
return YES;
if (now - pi->lastActivity > MAINTAIN_PEER_TIMEOUT / 2)
- pingPeer(pi);
+ pingPeer (pi);
return NO;
}
/**
* Check for expired peers in the given bucket.
*/
-static void checkExpiration(PeerBucket * bucket) {
+static void
+checkExpiration (PeerBucket * bucket)
+{
unsigned int i;
- PeerInfo * peer;
+ PeerInfo *peer;
- for (i=0;i<bucket->peers_size;i++) {
- peer = bucket->peers[i];
- if (checkExpired(peer) == YES) {
- total_peers--;
- if (stats != NULL)
- stats->change(stat_dht_total_peers, -1);
- FREE(peer);
- bucket->peers[i] = bucket->peers[bucket->peers_size-1];
- GROW(bucket->peers,
- bucket->peers_size,
- bucket->peers_size - 1);
+ for (i = 0; i < bucket->peers_size; i++)
+ {
+ peer = bucket->peers[i];
+ if (checkExpired (peer) == YES)
+ {
+ total_peers--;
+ if (stats != NULL)
+ stats->change (stat_dht_total_peers, -1);
+ FREE (peer);
+ bucket->peers[i] = bucket->peers[bucket->peers_size - 1];
+ GROW (bucket->peers, bucket->peers_size, bucket->peers_size - 1);
+ }
}
- }
}
/**
* Consider adding the given peer to the DHT.
*/
-static void considerPeer(const PeerIdentity * sender,
- const PeerIdentity * peer) {
- PeerInfo * pi;
- PeerBucket * bucket;
+static void
+considerPeer (const PeerIdentity * sender, const PeerIdentity * peer)
+{
+ PeerInfo *pi;
+ PeerBucket *bucket;
P2P_DHT_ASK_HELLO ask;
- P2P_hello_MESSAGE * hello;
+ P2P_hello_MESSAGE *hello;
- bucket = findBucketFor(peer);
+ bucket = findBucketFor (peer);
if (bucket == NULL)
- return; /* peers[i] == self */
+ return; /* peers[i] == self */
if (bucket->peers_size >= MAINTAIN_BUCKET_SIZE)
- checkExpiration(bucket);
+ checkExpiration (bucket);
if (bucket->peers_size >= MAINTAIN_BUCKET_SIZE)
- return; /* do not care */
- if (NULL != findPeerEntryInBucket(bucket,
- peer))
- return; /* already have this peer in buckets */
+ return; /* do not care */
+ if (NULL != findPeerEntryInBucket (bucket, peer))
+ return; /* already have this peer in buckets */
/* do we know how to contact this peer? */
- hello = identity->identity2Hello(peer,
- ANY_PROTOCOL_NUMBER,
- NO);
- if (hello == NULL) {
- /* if identity not known, ask sender for HELLO of other peer */
- ask.header.size = htons(sizeof(P2P_DHT_ASK_HELLO));
- ask.header.type = htons(sizeof(P2P_PROTO_DHT_ASK_HELLO));
- ask.reserved = 0;
- ask.peer = *peer;
- coreAPI->unicast(sender,
- &ask.header,
- 0, /* FIXME: priority */
- 5 * cronSECONDS);
- return;
- }
- FREE(hello);
+ hello = identity->identity2Hello (peer, ANY_PROTOCOL_NUMBER, NO);
+ if (hello == NULL)
+ {
+ /* if identity not known, ask sender for HELLO of other peer */
+ ask.header.size = htons (sizeof (P2P_DHT_ASK_HELLO));
+ ask.header.type = htons (sizeof (P2P_PROTO_DHT_ASK_HELLO));
+ ask.reserved = 0;
+ ask.peer = *peer;
+ coreAPI->unicast (sender, &ask.header, 0, /* FIXME: priority */
+ 5 * cronSECONDS);
+ return;
+ }
+ FREE (hello);
/* check if connected, if not, send discovery */
- if (OK != coreAPI->queryPeerStatus(peer, NULL, NULL)) {
- /* not yet connected; connect sending DISCOVERY */
- broadcast_dht_discovery(peer,
- NULL);
- return;
- }
+ if (OK != coreAPI->queryPeerStatus (peer, NULL, NULL))
+ {
+ /* not yet connected; connect sending DISCOVERY */
+ broadcast_dht_discovery (peer, NULL);
+ return;
+ }
/* we are connected (in core), add to bucket */
- pi = MALLOC(sizeof(PeerInfo));
- memset(pi,
- 0,
- sizeof(PeerInfo));
+ pi = MALLOC (sizeof (PeerInfo));
+ memset (pi, 0, sizeof (PeerInfo));
pi->id = *peer;
- pingPeer(pi);
- GROW(bucket->peers,
- bucket->peers_size,
- bucket->peers_size + 1);
- bucket->peers[bucket->peers_size-1] = pi;
+ pingPeer (pi);
+ GROW (bucket->peers, bucket->peers_size, bucket->peers_size + 1);
+ bucket->peers[bucket->peers_size - 1] = pi;
total_peers++;
if (stats != NULL)
- stats->change(stat_dht_total_peers, 1);
+ stats->change (stat_dht_total_peers, 1);
}
/**
* Handle discovery message.
*/
-static int handleDiscovery(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg) {
+static int
+handleDiscovery (const PeerIdentity * sender, const MESSAGE_HEADER * msg)
+{
unsigned int pc;
unsigned int i;
- const P2P_DHT_Discovery * disco;
- const PeerIdentity * peers;
+ const P2P_DHT_Discovery *disco;
+ const PeerIdentity *peers;
- pc = (ntohs(msg->size) - sizeof(P2P_DHT_Discovery)) / sizeof(PeerIdentity);
- if (pc > MAINTAIN_ADV_CAP * 8) {
- GE_BREAK(coreAPI->ectx, 0);
- return SYSERR; /* far too big */
- }
- if (ntohs(msg->size) != sizeof(P2P_DHT_Discovery) + pc *
sizeof(PeerIdentity)) {
- GE_BREAK(coreAPI->ectx, 0);
- return SYSERR; /* malformed */
- }
- disco = (const P2P_DHT_Discovery*) msg;
+ pc =
+ (ntohs (msg->size) - sizeof (P2P_DHT_Discovery)) / sizeof (PeerIdentity);
+ if (pc > MAINTAIN_ADV_CAP * 8)
+ {
+ GE_BREAK (coreAPI->ectx, 0);
+ return SYSERR; /* far too big */
+ }
+ if (ntohs (msg->size) !=
+ sizeof (P2P_DHT_Discovery) + pc * sizeof (PeerIdentity))
+ {
+ GE_BREAK (coreAPI->ectx, 0);
+ return SYSERR; /* malformed */
+ }
+ disco = (const P2P_DHT_Discovery *) msg;
if (stats != NULL)
- stats->change(stat_dht_discoveries, 1);
- if (pc == 0) {
- /* if peer has 0 connections, be sure to send discovery back */
- broadcast_dht_discovery(sender,
- NULL);
- }
- MUTEX_LOCK(lock);
- considerPeer(sender, sender);
- peers = (const PeerIdentity*) &disco[1];
- for (i=0;i<pc;i++)
- considerPeer(sender, &peers[i]);
- MUTEX_UNLOCK(lock);
+ stats->change (stat_dht_discoveries, 1);
+ if (pc == 0)
+ {
+ /* if peer has 0 connections, be sure to send discovery back */
+ broadcast_dht_discovery (sender, NULL);
+ }
+ MUTEX_LOCK (lock);
+ considerPeer (sender, sender);
+ peers = (const PeerIdentity *) &disco[1];
+ for (i = 0; i < pc; i++)
+ considerPeer (sender, &peers[i]);
+ MUTEX_UNLOCK (lock);
return OK;
}
/**
* Handle ask hello message.
*/
-static int handleAskHello(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg) {
- const P2P_DHT_ASK_HELLO * ask;
- P2P_hello_MESSAGE * hello;
+static int
+handleAskHello (const PeerIdentity * sender, const MESSAGE_HEADER * msg)
+{
+ const P2P_DHT_ASK_HELLO *ask;
+ P2P_hello_MESSAGE *hello;
- if (ntohs(msg->size) != sizeof(P2P_DHT_ASK_HELLO))
+ if (ntohs (msg->size) != sizeof (P2P_DHT_ASK_HELLO))
return SYSERR;
ask = (const P2P_DHT_ASK_HELLO *) msg;
- if (NULL == findBucketFor(&ask->peer))
+ if (NULL == findBucketFor (&ask->peer))
return OK;
- hello = identity->identity2Hello(&ask->peer,
- ANY_PROTOCOL_NUMBER,
- NO);
+ hello = identity->identity2Hello (&ask->peer, ANY_PROTOCOL_NUMBER, NO);
if (hello == NULL)
return OK;
- coreAPI->unicast(sender,
- &hello->header,
- 0,
- 5 * cronSECONDS);
- FREE(hello);
+ coreAPI->unicast (sender, &hello->header, 0, 5 * cronSECONDS);
+ FREE (hello);
return OK;
}
@@ -679,43 +691,45 @@
* @param capi the core API
* @return OK on success
*/
-int init_dht_table(CoreAPIForApplication * capi) {
+int
+init_dht_table (CoreAPIForApplication * capi)
+{
unsigned long long i;
coreAPI = capi;
/* use less than 50% of peer's ideal number of
connections for DHT table size */
- i = coreAPI->getSlotCount() / MAINTAIN_BUCKET_SIZE / 2;
+ i = coreAPI->getSlotCount () / MAINTAIN_BUCKET_SIZE / 2;
if (i < 4)
i = 4;
- GROW(buckets,
- bucketCount,
- i);
- for (i=0;i<bucketCount;i++) {
- buckets[i].bstart = 512 * i / bucketCount;
- buckets[i].bend = 512 * (i+1) / bucketCount;
- }
- lock = capi->getConnectionModuleLock();
- stats = capi->requestService("stats");
- if (stats != NULL) {
- stat_dht_total_peers = stats->create(gettext_noop("# dht connections"));
- stat_dht_discoveries = stats->create(gettext_noop("# dht discovery
messages received"));
- stat_dht_route_looks = stats->create(gettext_noop("# dht route host
lookups performed"));
- stat_dht_advertisements = stats->create(gettext_noop("# dht discovery
messages sent"));
- }
- identity = coreAPI->requestService("identity");
- GE_ASSERT(coreAPI->ectx, identity != NULL);
- pingpong = coreAPI->requestService("pingpong");
- GE_ASSERT(coreAPI->ectx, pingpong != NULL);
- capi->registerHandler(P2P_PROTO_DHT_DISCOVERY,
- &handleDiscovery);
- capi->registerHandler(P2P_PROTO_DHT_ASK_HELLO,
- &handleAskHello);
- cron_add_job(coreAPI->cron,
- &maintain_dht_job,
- MAINTAIN_FREQUENCY,
- MAINTAIN_FREQUENCY,
- NULL);
+ GROW (buckets, bucketCount, i);
+ for (i = 0; i < bucketCount; i++)
+ {
+ buckets[i].bstart = 512 * i / bucketCount;
+ buckets[i].bend = 512 * (i + 1) / bucketCount;
+ }
+ lock = capi->getConnectionModuleLock ();
+ stats = capi->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_dht_total_peers =
+ stats->create (gettext_noop ("# dht connections"));
+ stat_dht_discoveries =
+ stats->create (gettext_noop ("# dht discovery messages received"));
+ stat_dht_route_looks =
+ stats->create (gettext_noop ("# dht route host lookups performed"));
+ stat_dht_advertisements =
+ stats->create (gettext_noop ("# dht discovery messages sent"));
+ }
+ identity = coreAPI->requestService ("identity");
+ GE_ASSERT (coreAPI->ectx, identity != NULL);
+ pingpong = coreAPI->requestService ("pingpong");
+ GE_ASSERT (coreAPI->ectx, pingpong != NULL);
+ capi->registerHandler (P2P_PROTO_DHT_DISCOVERY, &handleDiscovery);
+ capi->registerHandler (P2P_PROTO_DHT_ASK_HELLO, &handleAskHello);
+ cron_add_job (coreAPI->cron,
+ &maintain_dht_job,
+ MAINTAIN_FREQUENCY, MAINTAIN_FREQUENCY, NULL);
return OK;
}
@@ -724,36 +738,31 @@
*
* @return OK on success
*/
-int done_dht_table() {
+int
+done_dht_table ()
+{
unsigned int i;
unsigned int j;
- coreAPI->unregisterHandler(P2P_PROTO_DHT_DISCOVERY,
- &handleDiscovery);
- coreAPI->unregisterHandler(P2P_PROTO_DHT_ASK_HELLO,
- &handleAskHello);
- cron_del_job(coreAPI->cron,
- &maintain_dht_job,
- MAINTAIN_FREQUENCY,
- NULL);
- if (stats != NULL) {
- coreAPI->releaseService(stats);
- stats = NULL;
- }
- coreAPI->releaseService(identity);
+ coreAPI->unregisterHandler (P2P_PROTO_DHT_DISCOVERY, &handleDiscovery);
+ coreAPI->unregisterHandler (P2P_PROTO_DHT_ASK_HELLO, &handleAskHello);
+ cron_del_job (coreAPI->cron, &maintain_dht_job, MAINTAIN_FREQUENCY, NULL);
+ if (stats != NULL)
+ {
+ coreAPI->releaseService (stats);
+ stats = NULL;
+ }
+ coreAPI->releaseService (identity);
identity = NULL;
- coreAPI->releaseService(pingpong);
+ coreAPI->releaseService (pingpong);
pingpong = NULL;
- for (i=0;i<bucketCount;i++) {
- for (j=0;j<buckets[i].peers_size;j++)
- FREE(buckets[i].peers[j]);
- GROW(buckets[i].peers,
- buckets[i].peers_size,
- 0);
- }
- GROW(buckets,
- bucketCount,
- 0);
+ for (i = 0; i < bucketCount; i++)
+ {
+ for (j = 0; j < buckets[i].peers_size; j++)
+ FREE (buckets[i].peers[j]);
+ GROW (buckets[i].peers, buckets[i].peers_size, 0);
+ }
+ GROW (buckets, bucketCount, 0);
lock = NULL;
return OK;
}
Modified: GNUnet/src/applications/dht/module/table.h
===================================================================
--- GNUnet/src/applications/dht/module/table.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/dht/module/table.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -42,10 +42,9 @@
*
* @return OK on success, SYSERR on error
*/
-int select_dht_peer(PeerIdentity * set,
- const HashCode512 * target,
- const PeerIdentity * blocked,
- unsigned int blocked_size);
+int select_dht_peer (PeerIdentity * set,
+ const HashCode512 * target,
+ const PeerIdentity * blocked, unsigned int blocked_size);
/**
* Initialize table DHT component.
@@ -53,13 +52,13 @@
* @param capi the core API
* @return OK on success
*/
-int init_dht_table(CoreAPIForApplication * capi);
+int init_dht_table (CoreAPIForApplication * capi);
/**
* Shutdown table DHT component.
*
* @return OK on success
*/
-int done_dht_table(void);
+int done_dht_table (void);
#endif
Modified: GNUnet/src/applications/dht/tools/dht-query.c
===================================================================
--- GNUnet/src/applications/dht/tools/dht-query.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/dht/tools/dht-query.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -41,174 +41,158 @@
*/
static cron_t timeout;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static char * cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
+static char *cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
/**
* All gnunet-dht-query command line options
*/
static struct CommandLineOption gnunetqueryOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- COMMAND_LINE_OPTION_HELP(gettext_noop("Query (get KEY, put KEY VALUE) DHT
table.")), /* -h */
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Query (get KEY, put KEY VALUE) DHT
table.")), /* -h */
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'T', "timeout", "TIME",
- gettext_noop("allow TIME ms to process a GET command or expire PUT content
after ms TIME"),
- 1, &gnunet_getopt_configure_set_ulong, &timeout },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'T', "timeout", "TIME",
+ gettext_noop
+ ("allow TIME ms to process a GET command or expire PUT content after ms
TIME"),
+ 1, &gnunet_getopt_configure_set_ulong, &timeout},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_VERBOSE,
COMMAND_LINE_OPTION_END,
};
-static int printCallback(const HashCode512 * hash,
- const DataContainer * data,
- void * cls) {
- char * key = cls;
- printf("%s(%s): '%.*s'\n",
- "get",
- key,
- ntohl(data->size) - sizeof(DataContainer),
- (char*)&data[1]);
+static int
+printCallback (const HashCode512 * hash,
+ const DataContainer * data, void *cls)
+{
+ char *key = cls;
+ printf ("%s(%s): '%.*s'\n",
+ "get",
+ key,
+ ntohl (data->size) - sizeof (DataContainer), (char *) &data[1]);
return OK;
}
-static void do_get(struct ClientServerConnection * sock,
- const char * key) {
+static void
+do_get (struct ClientServerConnection *sock, const char *key)
+{
int ret;
HashCode512 hc;
- hash(key,
- strlen(key),
- &hc);
+ hash (key, strlen (key), &hc);
#if DEBUG_DHT_QUERY
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Issuing '%s(%s)' command.\n",
- "get",
- key);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Issuing '%s(%s)' command.\n", "get", key);
#endif
if (timeout == 0)
timeout = 30 * cronSECONDS;
- ret = DHT_LIB_get(cfg,
- ectx,
- DHT_STRING2STRING_BLOCK,
- &hc,
- timeout,
- &printCallback,
- (void*) key);
+ ret = DHT_LIB_get (cfg,
+ ectx,
+ DHT_STRING2STRING_BLOCK,
+ &hc, timeout, &printCallback, (void *) key);
if (ret == 0)
- printf(_("%s(%s) operation returned no results.\n"),
- "get",
- key);
+ printf (_("%s(%s) operation returned no results.\n"), "get", key);
}
-static void do_put(struct ClientServerConnection * sock,
- const char * key,
- const char * value) {
- DataContainer * dc;
+static void
+do_put (struct ClientServerConnection *sock,
+ const char *key, const char *value)
+{
+ DataContainer *dc;
HashCode512 hc;
- hash(key, strlen(key), &hc);
- dc = MALLOC(sizeof(DataContainer)
- + strlen(value));
- dc->size = htonl(strlen(value)
- + sizeof(DataContainer));
- memcpy(&dc[1],
- value,
- strlen(value));
+ hash (key, strlen (key), &hc);
+ dc = MALLOC (sizeof (DataContainer) + strlen (value));
+ dc->size = htonl (strlen (value) + sizeof (DataContainer));
+ memcpy (&dc[1], value, strlen (value));
#if DEBUG_DHT_QUERY
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _("Issuing '%s(%s,%s)' command.\n"),
- "put",
- key,
- value);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ _("Issuing '%s(%s,%s)' command.\n"), "put", key, value);
#endif
if (timeout == 0)
timeout = 30 * cronMINUTES;
- if (OK == DHT_LIB_put(cfg,
- ectx,
- &hc,
- DHT_STRING2STRING_BLOCK,
- timeout + get_time(), /* convert to absolute time */
- dc)) {
- printf(_("'%s(%s,%s)' succeeded\n"),
- "put",
- key,
- value);
- } else {
- printf(_("'%s(%s,%s)' failed.\n"),
- "put",
- key,
- value);
- }
- FREE(dc);
+ if (OK == DHT_LIB_put (cfg, ectx, &hc, DHT_STRING2STRING_BLOCK, timeout +
get_time (), /* convert to absolute time */
+ dc))
+ {
+ printf (_("'%s(%s,%s)' succeeded\n"), "put", key, value);
+ }
+ else
+ {
+ printf (_("'%s(%s,%s)' failed.\n"), "put", key, value);
+ }
+ FREE (dc);
}
-int main(int argc,
- char * const * argv) {
+int
+main (int argc, char *const *argv)
+{
int i;
- struct ClientServerConnection * handle;
+ struct ClientServerConnection *handle;
- i = GNUNET_init(argc,
- argv,
- "gnunet-dht-query",
- &cfgFilename,
- gnunetqueryOptions,
- &ectx,
- &cfg);
- if (i == -1) {
- GNUNET_fini(ectx, cfg);
- return -1;
- }
+ i = GNUNET_init (argc,
+ argv,
+ "gnunet-dht-query",
+ &cfgFilename, gnunetqueryOptions, &ectx, &cfg);
+ if (i == -1)
+ {
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
- handle = client_connection_create(ectx, cfg);
- if (handle == NULL) {
- fprintf(stderr,
- _("Failed to connect to gnunetd.\n"));
- GC_free(cfg);
- GE_free_context(ectx);
- return 1;
- }
+ handle = client_connection_create (ectx, cfg);
+ if (handle == NULL)
+ {
+ fprintf (stderr, _("Failed to connect to gnunetd.\n"));
+ GC_free (cfg);
+ GE_free_context (ectx);
+ return 1;
+ }
- while (i < argc) {
- if (0 == strcmp("get", argv[i])) {
- if (i+2 > argc) {
- fprintf(stderr,
- _("Command `%s' requires an argument (`%s').\n"),
- "get",
- "key");
- break;
- } else {
- do_get(handle, argv[i+1]);
- i += 2;
- }
- continue;
+ while (i < argc)
+ {
+ if (0 == strcmp ("get", argv[i]))
+ {
+ if (i + 2 > argc)
+ {
+ fprintf (stderr,
+ _("Command `%s' requires an argument (`%s').\n"),
+ "get", "key");
+ break;
+ }
+ else
+ {
+ do_get (handle, argv[i + 1]);
+ i += 2;
+ }
+ continue;
+ }
+ if (0 == strcmp ("put", argv[i]))
+ {
+ if (i + 3 > argc)
+ {
+ fprintf (stderr,
+ _
+ ("Command `%s' requires two arguments (`%s' and
`%s').\n"),
+ "put", "key", "value");
+ break;
+ }
+ else
+ {
+ do_put (handle, argv[i + 1], argv[i + 2]);
+ i += 3;
+ }
+ continue;
+ }
+ fprintf (stderr, _("Unsupported command `%s'. Aborting.\n"), argv[i]);
+ break;
}
- if (0 == strcmp("put", argv[i])) {
- if (i+3 > argc) {
- fprintf(stderr,
- _("Command `%s' requires two arguments (`%s' and `%s').\n"),
- "put",
- "key",
- "value");
- break;
- } else {
- do_put(handle, argv[i+1], argv[i+2]);
- i += 3;
- }
- continue;
- }
- fprintf(stderr,
- _("Unsupported command `%s'. Aborting.\n"),
- argv[i]);
- break;
- }
- connection_destroy(handle);
- GNUNET_fini(ectx, cfg);
+ connection_destroy (handle);
+ GNUNET_fini (ectx, cfg);
return 0;
}
Modified: GNUnet/src/applications/dht/tools/dht_api.c
===================================================================
--- GNUnet/src/applications/dht/tools/dht_api.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/dht/tools/dht_api.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,12 +35,13 @@
/**
* Data exchanged between main thread and GET thread.
*/
-typedef struct {
+typedef struct
+{
/**
* Connection with gnunetd.
*/
- struct ClientServerConnection * sock;
+ struct ClientServerConnection *sock;
/**
* Callback to call for each result.
@@ -50,7 +51,7 @@
/**
* Extra argument for processor.
*/
- void * closure;
+ void *closure;
/**
* Parent thread that is waiting for the
@@ -59,7 +60,7 @@
* connection or the processor callback requesting
* it).
*/
- struct PTHREAD * parent;
+ struct PTHREAD *parent;
/**
* Are we done (for whichever reason)?
@@ -74,44 +75,44 @@
static void *
-poll_thread(void * cls) {
- GetInfo * info = cls;
- MESSAGE_HEADER * reply;
- CS_dht_request_put_MESSAGE * put;
- DataContainer * cont;
+poll_thread (void *cls)
+{
+ GetInfo *info = cls;
+ MESSAGE_HEADER *reply;
+ CS_dht_request_put_MESSAGE *put;
+ DataContainer *cont;
unsigned short size;
- while (info->aborted == NO) {
- if (connection_test_open(info->sock) == 0)
- break;
- reply = NULL;
- if (OK != connection_read(info->sock,
- &reply))
- break;
- if ( (sizeof(CS_dht_request_put_MESSAGE) > ntohs(reply->size)) ||
- (CS_PROTO_dht_REQUEST_PUT != ntohs(reply->type)) ) {
- GE_BREAK(NULL, 0);
- info->total = SYSERR;
- break; /* invalid reply */
- }
+ while (info->aborted == NO)
+ {
+ if (connection_test_open (info->sock) == 0)
+ break;
+ reply = NULL;
+ if (OK != connection_read (info->sock, &reply))
+ break;
+ if ((sizeof (CS_dht_request_put_MESSAGE) > ntohs (reply->size)) ||
+ (CS_PROTO_dht_REQUEST_PUT != ntohs (reply->type)))
+ {
+ GE_BREAK (NULL, 0);
+ info->total = SYSERR;
+ break; /* invalid reply */
+ }
- put = (CS_dht_request_put_MESSAGE*) reply;
- /* re-use "expire" field of the reply (which is 0 anyway)
- for the header of DataContainer (which fits) to avoid
- copying -- go C pointer arithmetic! */
- cont = (DataContainer*) &((char *) &put[1])[-sizeof(DataContainer)];
- size = ntohs(reply->size) - sizeof(CS_dht_request_put_MESSAGE);
- cont->size = htonl(size + sizeof(DataContainer));
- if ( (info->processor != NULL) &&
- (OK != info->processor(&put->key,
- cont,
- info->closure)) )
- info->aborted = YES;
- info->total++;
- FREE(reply);
- }
+ put = (CS_dht_request_put_MESSAGE *) reply;
+ /* re-use "expire" field of the reply (which is 0 anyway)
+ for the header of DataContainer (which fits) to avoid
+ copying -- go C pointer arithmetic! */
+ cont = (DataContainer *) & ((char *) &put[1])[-sizeof (DataContainer)];
+ size = ntohs (reply->size) - sizeof (CS_dht_request_put_MESSAGE);
+ cont->size = htonl (size + sizeof (DataContainer));
+ if ((info->processor != NULL) &&
+ (OK != info->processor (&put->key, cont, info->closure)))
+ info->aborted = YES;
+ info->total++;
+ FREE (reply);
+ }
info->aborted = YES;
- PTHREAD_STOP_SLEEP(info->parent);
+ PTHREAD_STOP_SLEEP (info->parent);
return NULL;
}
@@ -135,60 +136,57 @@
* @param results where to store the results (on success)
* @return number of results on success, SYSERR on error (i.e. timeout)
*/
-int DHT_LIB_get(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- unsigned int type,
- const HashCode512 * key,
- cron_t timeout,
- DataProcessor processor,
- void * closure) {
- struct ClientServerConnection * sock;
+int
+DHT_LIB_get (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ unsigned int type,
+ const HashCode512 * key,
+ cron_t timeout, DataProcessor processor, void *closure)
+{
+ struct ClientServerConnection *sock;
CS_dht_request_get_MESSAGE req;
- struct PTHREAD * thread;
+ struct PTHREAD *thread;
cron_t start;
cron_t now;
cron_t delta;
GetInfo info;
- void * unused;
+ void *unused;
- sock = client_connection_create(ectx,
- cfg);
+ sock = client_connection_create (ectx, cfg);
if (sock == NULL)
return SYSERR;
- req.header.size = htons(sizeof(CS_dht_request_get_MESSAGE));
- req.header.type = htons(CS_PROTO_dht_REQUEST_GET);
- req.type = htonl(type);
- req.timeout = htonll(timeout);
+ req.header.size = htons (sizeof (CS_dht_request_get_MESSAGE));
+ req.header.type = htons (CS_PROTO_dht_REQUEST_GET);
+ req.type = htonl (type);
+ req.timeout = htonll (timeout);
req.key = *key;
- if (OK != connection_write(sock,
- &req.header)) {
- connection_destroy(sock);
- return SYSERR;
- }
+ if (OK != connection_write (sock, &req.header))
+ {
+ connection_destroy (sock);
+ return SYSERR;
+ }
info.sock = sock;
info.processor = processor;
info.closure = closure;
- info.parent = PTHREAD_GET_SELF();
+ info.parent = PTHREAD_GET_SELF ();
info.aborted = NO;
info.total = 0;
- thread = PTHREAD_CREATE(&poll_thread,
- &info,
- 1024 * 8);
- start = get_time();
- while ( (start + timeout > (now = get_time())) &&
- (GNUNET_SHUTDOWN_TEST() == NO) &&
- (info.aborted == NO) ) {
- delta =(start + timeout) - now;
- if (delta > 100 * cronMILLIS)
- delta = 100 * cronMILLIS; /* in case we miss SIGINT
- on CTRL-C */
- PTHREAD_SLEEP(delta);
- }
+ thread = PTHREAD_CREATE (&poll_thread, &info, 1024 * 8);
+ start = get_time ();
+ while ((start + timeout > (now = get_time ())) &&
+ (GNUNET_SHUTDOWN_TEST () == NO) && (info.aborted == NO))
+ {
+ delta = (start + timeout) - now;
+ if (delta > 100 * cronMILLIS)
+ delta = 100 * cronMILLIS; /* in case we miss SIGINT
+ on CTRL-C */
+ PTHREAD_SLEEP (delta);
+ }
info.aborted = YES;
- connection_close_forever(sock);
- PTHREAD_JOIN(thread, &unused);
- PTHREAD_REL_SELF(info.parent);
- connection_destroy(sock);
+ connection_close_forever (sock);
+ PTHREAD_JOIN (thread, &unused);
+ PTHREAD_REL_SELF (info.parent);
+ connection_destroy (sock);
return info.total;
}
@@ -202,54 +200,46 @@
* @param value what to store
* @return OK on success, SYSERR on error
*/
-int DHT_LIB_put(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const HashCode512 * key,
- unsigned int type,
- cron_t expire,
- const DataContainer * value) {
- struct ClientServerConnection * sock;
- CS_dht_request_put_MESSAGE * req;
+int
+DHT_LIB_put (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const HashCode512 * key,
+ unsigned int type, cron_t expire, const DataContainer * value)
+{
+ struct ClientServerConnection *sock;
+ CS_dht_request_put_MESSAGE *req;
int ret;
cron_t now;
- now = get_time();
- if (expire < now) {
- GE_BREAK(ectx, 0); /* content already expired!? */
- return SYSERR;
- }
+ now = get_time ();
+ if (expire < now)
+ {
+ GE_BREAK (ectx, 0); /* content already expired!? */
+ return SYSERR;
+ }
#if DEBUG_DHT_API
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "DHT_LIB_put called with value '%.*s'\n",
- ntohl(value->size),
- &value[1]);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "DHT_LIB_put called with value '%.*s'\n",
+ ntohl (value->size), &value[1]);
#endif
- sock = client_connection_create(ectx,
- cfg);
+ sock = client_connection_create (ectx, cfg);
if (sock == NULL)
return SYSERR;
- GE_ASSERT(NULL,
- ntohl(value->size) >= sizeof(DataContainer));
- req = MALLOC(sizeof(CS_dht_request_put_MESSAGE) +
- ntohl(value->size) -
- sizeof(DataContainer));
+ GE_ASSERT (NULL, ntohl (value->size) >= sizeof (DataContainer));
+ req = MALLOC (sizeof (CS_dht_request_put_MESSAGE) +
+ ntohl (value->size) - sizeof (DataContainer));
req->header.size
- = htons(sizeof(CS_dht_request_put_MESSAGE) +
- ntohl(value->size) -
- sizeof(DataContainer));
- req->header.type
- = htons(CS_PROTO_dht_REQUEST_PUT);
+ = htons (sizeof (CS_dht_request_put_MESSAGE) +
+ ntohl (value->size) - sizeof (DataContainer));
+ req->header.type = htons (CS_PROTO_dht_REQUEST_PUT);
req->key = *key;
- req->type = htonl(type);
- req->expire = htonll(expire - now); /* convert to relative time */
- memcpy(&req[1],
- &value[1],
- ntohl(value->size) - sizeof(DataContainer));
- ret = connection_write(sock,
- &req->header);
- connection_destroy(sock);
- FREE(req);
+ req->type = htonl (type);
+ req->expire = htonll (expire - now); /* convert to relative time */
+ memcpy (&req[1], &value[1], ntohl (value->size) - sizeof (DataContainer));
+ ret = connection_write (sock, &req->header);
+ connection_destroy (sock);
+ FREE (req);
return ret;
}
Modified: GNUnet/src/applications/dht/tools/dhttest.c
===================================================================
--- GNUnet/src/applications/dht/tools/dhttest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/dht/tools/dhttest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -39,15 +39,14 @@
static int ok;
-static int waitForConnect(const char * name,
- unsigned long long value,
- void * cls) {
- if ( (value > 0) &&
- (0 == strcmp(_("# dht connections"),
- name)) ) {
- ok = 1;
- return SYSERR;
- }
+static int
+waitForConnect (const char *name, unsigned long long value, void *cls)
+{
+ if ((value > 0) && (0 == strcmp (_("# dht connections"), name)))
+ {
+ ok = 1;
+ return SYSERR;
+ }
return OK;
}
@@ -57,15 +56,16 @@
* Testcase to test DHT routing (many peers).
* @return 0: ok, -1: error
*/
-int main(int argc,
- const char ** argv) {
- struct DaemonContext * peers;
+int
+main (int argc, const char **argv)
+{
+ struct DaemonContext *peers;
int ret = 0;
HashCode512 key;
- DataContainer * value;
- struct GE_Context * ectx;
- struct GC_Configuration * cfg;
- struct ClientServerConnection * sock;
+ DataContainer *value;
+ struct GE_Context *ectx;
+ struct GC_Configuration *cfg;
+ struct ClientServerConnection *sock;
int left;
int i;
int j;
@@ -74,130 +74,111 @@
char buf[128];
ectx = NULL;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- peers = gnunet_testing_start_daemons("tcp",
- "advertising dht stats",
- "/tmp/gnunet-dht-test",
- 2087,
- 10,
- NUM_PEERS);
- if (peers == NULL) {
- GC_free(cfg);
- return -1;
- }
- for (i=0;i<NUM_PEERS;i++) {
- for (j=0;j<i;j++) {
- if (OK != gnunet_testing_connect_daemons(2087 + 10*i,
- 2087 + 10*j)) {
- gnunet_testing_stop_daemons(peers);
- fprintf(stderr,
- "Failed to connect the peers!\n");
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
}
- }
+ peers = gnunet_testing_start_daemons ("tcp",
+ "advertising dht stats",
+ "/tmp/gnunet-dht-test",
+ 2087, 10, NUM_PEERS);
+ if (peers == NULL)
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ for (i = 0; i < NUM_PEERS; i++)
+ {
+ for (j = 0; j < i; j++)
+ {
+ if (OK != gnunet_testing_connect_daemons (2087 + 10 * i,
+ 2087 + 10 * j))
+ {
+ gnunet_testing_stop_daemons (peers);
+ fprintf (stderr, "Failed to connect the peers!\n");
+ GC_free (cfg);
+ return -1;
+ }
+ }
+ }
/* wait for some DHT's to find each other! */
- sock = client_connection_create(NULL,
- cfg);
- left = 30; /* how many iterations should we wait? */
- while (OK == STATS_getStatistics(NULL,
- sock,
- &waitForConnect,
- NULL)) {
- printf("Waiting for peers to DHT-connect (%u iterations left)...\n",
- left);
- sleep(5);
- left--;
- if (left == 0)
- break;
- }
- connection_destroy(sock);
- if (ok == 0) {
- gnunet_testing_stop_daemons(peers);
- fprintf(stderr,
- "Peers' DHTs failed to DHT-connect!\n");
- GC_free(cfg);
- return -1;
- }
+ sock = client_connection_create (NULL, cfg);
+ left = 30; /* how many iterations should we wait? */
+ while (OK == STATS_getStatistics (NULL, sock, &waitForConnect, NULL))
+ {
+ printf ("Waiting for peers to DHT-connect (%u iterations left)...\n",
+ left);
+ sleep (5);
+ left--;
+ if (left == 0)
+ break;
+ }
+ connection_destroy (sock);
+ if (ok == 0)
+ {
+ gnunet_testing_stop_daemons (peers);
+ fprintf (stderr, "Peers' DHTs failed to DHT-connect!\n");
+ GC_free (cfg);
+ return -1;
+ }
/* put loop */
- for (i=0;i<NUM_PEERS;i++) {
- SNPRINTF(buf,
- 128,
- "localhost:%u",
- 2087 + i * 10);
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- buf);
- hash(buf, 4, &key);
- value = MALLOC(8);
- value->size = ntohl(8);
- memset(&value[1],
- 'A' + i,
- 4);
- CHECK(OK == DHT_LIB_put(cfg,
- ectx,
- &key,
- DHT_STRING2STRING_BLOCK,
- get_time() + 15 * cronMINUTES * NUM_ROUNDS * NUM_PEERS *
NUM_PEERS,
- value));
- }
+ for (i = 0; i < NUM_PEERS; i++)
+ {
+ SNPRINTF (buf, 128, "localhost:%u", 2087 + i * 10);
+ GC_set_configuration_value_string (cfg, ectx, "NETWORK", "HOST", buf);
+ hash (buf, 4, &key);
+ value = MALLOC (8);
+ value->size = ntohl (8);
+ memset (&value[1], 'A' + i, 4);
+ CHECK (OK == DHT_LIB_put (cfg,
+ ectx,
+ &key,
+ DHT_STRING2STRING_BLOCK,
+ get_time () +
+ 15 * cronMINUTES * NUM_ROUNDS * NUM_PEERS *
+ NUM_PEERS, value));
+ }
/* get loops */
- for (k=0;k<NUM_ROUNDS;k++) {
- found = 0;
- for (i=0;i<NUM_PEERS;i++) {
- SNPRINTF(buf,
- 128,
- "localhost:%u",
- 2087 + i * 10);
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- buf);
- for (j=0;j<NUM_PEERS;j++) {
- SNPRINTF(buf,
- 128,
- "localhost:%u",
- 2087 + j * 10);
- hash(buf, 4, &key);
- fprintf(stderr,
- "Peer %d gets key %d", i, j);
- if (0 < DHT_LIB_get(cfg,
- ectx,
- DHT_STRING2STRING_BLOCK,
- &key,
- (NUM_ROUNDS - k) * cronSECONDS,
- NULL,
- NULL)) {
- fprintf(stderr,
- " - found!\n");
- found++;
- } else
- fprintf(stderr,
- " - NOT found!\n");
- }
+ for (k = 0; k < NUM_ROUNDS; k++)
+ {
+ found = 0;
+ for (i = 0; i < NUM_PEERS; i++)
+ {
+ SNPRINTF (buf, 128, "localhost:%u", 2087 + i * 10);
+ GC_set_configuration_value_string (cfg,
+ ectx, "NETWORK", "HOST", buf);
+ for (j = 0; j < NUM_PEERS; j++)
+ {
+ SNPRINTF (buf, 128, "localhost:%u", 2087 + j * 10);
+ hash (buf, 4, &key);
+ fprintf (stderr, "Peer %d gets key %d", i, j);
+ if (0 < DHT_LIB_get (cfg,
+ ectx,
+ DHT_STRING2STRING_BLOCK,
+ &key,
+ (NUM_ROUNDS - k) * cronSECONDS,
+ NULL, NULL))
+ {
+ fprintf (stderr, " - found!\n");
+ found++;
+ }
+ else
+ fprintf (stderr, " - NOT found!\n");
+ }
+ }
+ /* end of actual test code */
+ fprintf (stderr,
+ "Found %u out of %u attempts in round %u.\n",
+ found, NUM_PEERS * NUM_PEERS, k);
}
- /* end of actual test code */
- fprintf(stderr,
- "Found %u out of %u attempts in round %u.\n",
- found,
- NUM_PEERS * NUM_PEERS,
- k);
- }
- FAILURE:
- gnunet_testing_stop_daemons(peers);
- GC_free(cfg);
+FAILURE:
+ gnunet_testing_stop_daemons (peers);
+ GC_free (cfg);
return ret;
}
Modified: GNUnet/src/applications/dht/tools/dhttest2.c
===================================================================
--- GNUnet/src/applications/dht/tools/dhttest2.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/dht/tools/dhttest2.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -39,15 +39,14 @@
static int ok;
-static int waitForConnect(const char * name,
- unsigned long long value,
- void * cls) {
- if ( (value > 0) &&
- (0 == strcmp(_("# dht connections"),
- name)) ) {
- ok = 1;
- return SYSERR;
- }
+static int
+waitForConnect (const char *name, unsigned long long value, void *cls)
+{
+ if ((value > 0) && (0 == strcmp (_("# dht connections"), name)))
+ {
+ ok = 1;
+ return SYSERR;
+ }
return OK;
}
@@ -57,190 +56,157 @@
* Testcase to test DHT routing (2 peers only).
* @return 0: ok, -1: error
*/
-int main(int argc,
- const char ** argv) {
+int
+main (int argc, const char **argv)
+{
#if START_PEERS
- struct DaemonContext * peers;
+ struct DaemonContext *peers;
#endif
int ret = 0;
HashCode512 key;
- DataContainer * value;
- struct GE_Context * ectx;
- struct GC_Configuration * cfg;
- struct ClientServerConnection * sock;
+ DataContainer *value;
+ struct GE_Context *ectx;
+ struct GC_Configuration *cfg;
+ struct ClientServerConnection *sock;
int left;
ectx = NULL;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_PEERS
- peers = gnunet_testing_start_daemons("tcp",
- "advertising dht stats",
- "/tmp/gnunet-dht-test",
- 2087,
- 10000,
- 2);
- if (peers == NULL) {
- GC_free(cfg);
- return -1;
- }
+ peers = gnunet_testing_start_daemons ("tcp",
+ "advertising dht stats",
+ "/tmp/gnunet-dht-test",
+ 2087, 10000, 2);
+ if (peers == NULL)
+ {
+ GC_free (cfg);
+ return -1;
+ }
#endif
- if (OK != gnunet_testing_connect_daemons(2087,
- 12087)) {
- gnunet_testing_stop_daemons(peers);
- fprintf(stderr,
- "Failed to connect the peers!\n");
- GC_free(cfg);
- return -1;
- }
+ if (OK != gnunet_testing_connect_daemons (2087, 12087))
+ {
+ gnunet_testing_stop_daemons (peers);
+ fprintf (stderr, "Failed to connect the peers!\n");
+ GC_free (cfg);
+ return -1;
+ }
/* wait for DHT's to find each other! */
- sock = client_connection_create(NULL,
- cfg);
- left = 30; /* how many iterations should we wait? */
- while (OK == STATS_getStatistics(NULL,
- sock,
- &waitForConnect,
- NULL)) {
- printf("Waiting for peers to DHT-connect (%u iterations left)...\n",
- left);
- sleep(5);
- left--;
- if (left == 0)
- break;
- }
- connection_destroy(sock);
- if (ok == 0) {
- gnunet_testing_stop_daemons(peers);
- fprintf(stderr,
- "Peers' DHTs failed to DHT-connect!\n");
- GC_free(cfg);
- return -1;
- }
+ sock = client_connection_create (NULL, cfg);
+ left = 30; /* how many iterations should we wait? */
+ while (OK == STATS_getStatistics (NULL, sock, &waitForConnect, NULL))
+ {
+ printf ("Waiting for peers to DHT-connect (%u iterations left)...\n",
+ left);
+ sleep (5);
+ left--;
+ if (left == 0)
+ break;
+ }
+ connection_destroy (sock);
+ if (ok == 0)
+ {
+ gnunet_testing_stop_daemons (peers);
+ fprintf (stderr, "Peers' DHTs failed to DHT-connect!\n");
+ GC_free (cfg);
+ return -1;
+ }
/* switch to peer2 */
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- "localhost:12087");
+ GC_set_configuration_value_string (cfg,
+ ectx,
+ "NETWORK", "HOST", "localhost:12087");
/* verify that peer2 also sees the other DHT! */
ok = 0;
- sock = client_connection_create(NULL,
- cfg);
- left = 30; /* how many iterations should we wait? */
- while (OK == STATS_getStatistics(NULL,
- sock,
- &waitForConnect,
- NULL)) {
- printf("Waiting for peers to DHT-connect (%u iterations left)...\n",
- left);
- sleep(5);
- left--;
- if (left == 0)
- break;
- }
- connection_destroy(sock);
- if (ok == 0) {
- gnunet_testing_stop_daemons(peers);
- fprintf(stderr,
- "Peers' DHTs failed to DHT-connect!\n");
- GC_free(cfg);
- return -1;
- }
+ sock = client_connection_create (NULL, cfg);
+ left = 30; /* how many iterations should we wait? */
+ while (OK == STATS_getStatistics (NULL, sock, &waitForConnect, NULL))
+ {
+ printf ("Waiting for peers to DHT-connect (%u iterations left)...\n",
+ left);
+ sleep (5);
+ left--;
+ if (left == 0)
+ break;
+ }
+ connection_destroy (sock);
+ if (ok == 0)
+ {
+ gnunet_testing_stop_daemons (peers);
+ fprintf (stderr, "Peers' DHTs failed to DHT-connect!\n");
+ GC_free (cfg);
+ return -1;
+ }
/* switch to peer1 */
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- "localhost:2087");
+ GC_set_configuration_value_string (cfg,
+ ectx,
+ "NETWORK", "HOST", "localhost:2087");
/* actual test code */
- hash("key2", 4, &key);
- value = MALLOC(8);
- value->size = ntohl(8);
- memset(&value[1],
- 'A',
- 4);
- printf("Peer1 stores key2\n");
- CHECK(OK == DHT_LIB_put(cfg,
- ectx,
- &key,
- DHT_STRING2STRING_BLOCK,
- get_time() + 5 * cronMINUTES,
- value));
- printf("Peer1 gets key2\n");
- CHECK(1 == DHT_LIB_get(cfg,
- ectx,
- DHT_STRING2STRING_BLOCK,
- &key,
- 2 * cronSECONDS,
- NULL,
- NULL));
+ hash ("key2", 4, &key);
+ value = MALLOC (8);
+ value->size = ntohl (8);
+ memset (&value[1], 'A', 4);
+ printf ("Peer1 stores key2\n");
+ CHECK (OK == DHT_LIB_put (cfg,
+ ectx,
+ &key,
+ DHT_STRING2STRING_BLOCK,
+ get_time () + 5 * cronMINUTES, value));
+ printf ("Peer1 gets key2\n");
+ CHECK (1 == DHT_LIB_get (cfg,
+ ectx,
+ DHT_STRING2STRING_BLOCK,
+ &key, 2 * cronSECONDS, NULL, NULL));
/* switch to peer2 */
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- "localhost:12087");
- hash("key", 3, &key);
- value = MALLOC(8);
- value->size = ntohl(8);
- memset(&value[1],
- 'B',
- 4);
- printf("Peer2 stores key.\n");
- CHECK(OK == DHT_LIB_put(cfg,
- ectx,
- &key,
- DHT_STRING2STRING_BLOCK,
- get_time() + 5 * cronMINUTES,
- value));
- printf("Peer2 gets key.\n");
- CHECK(1 == DHT_LIB_get(cfg,
- ectx,
- DHT_STRING2STRING_BLOCK,
- &key,
- 2 * cronSECONDS,
- NULL,
- NULL));
+ GC_set_configuration_value_string (cfg,
+ ectx,
+ "NETWORK", "HOST", "localhost:12087");
+ hash ("key", 3, &key);
+ value = MALLOC (8);
+ value->size = ntohl (8);
+ memset (&value[1], 'B', 4);
+ printf ("Peer2 stores key.\n");
+ CHECK (OK == DHT_LIB_put (cfg,
+ ectx,
+ &key,
+ DHT_STRING2STRING_BLOCK,
+ get_time () + 5 * cronMINUTES, value));
+ printf ("Peer2 gets key.\n");
+ CHECK (1 == DHT_LIB_get (cfg,
+ ectx,
+ DHT_STRING2STRING_BLOCK,
+ &key, 2 * cronSECONDS, NULL, NULL));
- hash("key2", 4, &key);
- printf("Peer2 gets key2.\n");
- CHECK(1 == DHT_LIB_get(cfg,
- ectx,
- DHT_STRING2STRING_BLOCK,
- &key,
- 30 * cronSECONDS,
- NULL,
- NULL));
+ hash ("key2", 4, &key);
+ printf ("Peer2 gets key2.\n");
+ CHECK (1 == DHT_LIB_get (cfg,
+ ectx,
+ DHT_STRING2STRING_BLOCK,
+ &key, 30 * cronSECONDS, NULL, NULL));
/* switch to peer1 */
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- "localhost:2087");
- printf("Peer1 gets key\n");
- CHECK(1 == DHT_LIB_get(cfg,
- ectx,
- DHT_STRING2STRING_BLOCK,
- &key,
- 30 * cronSECONDS,
- NULL,
- NULL));
+ GC_set_configuration_value_string (cfg,
+ ectx,
+ "NETWORK", "HOST", "localhost:2087");
+ printf ("Peer1 gets key\n");
+ CHECK (1 == DHT_LIB_get (cfg,
+ ectx,
+ DHT_STRING2STRING_BLOCK,
+ &key, 30 * cronSECONDS, NULL, NULL));
/* end of actual test code */
- FAILURE:
+FAILURE:
#if START_PEERS
- gnunet_testing_stop_daemons(peers);
+ gnunet_testing_stop_daemons (peers);
#endif
- GC_free(cfg);
+ GC_free (cfg);
return ret;
}
Modified: GNUnet/src/applications/dstore/dstore.c
===================================================================
--- GNUnet/src/applications/dstore/dstore.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/dstore/dstore.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -54,16 +54,16 @@
/**
* Filename of this database
*/
-static char * fn;
+static char *fn;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
/**
* Statistics service.
*/
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static unsigned int stat_dstore_size;
@@ -72,73 +72,71 @@
*/
#define OVERHEAD ((4+4+8+8*2+sizeof(HashCode512)*2+32))
-struct Bloomfilter * bloom;
+struct Bloomfilter *bloom;
-static char * bloom_name;
+static char *bloom_name;
/**
* @brief Prepare a SQL statement
*/
-static int sq_prepare(sqlite3 * dbh,
- const char *zSql, /* SQL statement, UTF-8 encoded */
- sqlite3_stmt **ppStmt) { /* OUT: Statement handle */
- char * dummy;
- return sqlite3_prepare(dbh,
- zSql,
- strlen(zSql),
- ppStmt,
- (const char**) &dummy);
+static int
+sq_prepare (sqlite3 * dbh, const char *zSql, /* SQL statement, UTF-8
encoded */
+ sqlite3_stmt ** ppStmt)
+{ /* OUT: Statement handle */
+ char *dummy;
+ return sqlite3_prepare (dbh,
+ zSql,
+ strlen (zSql), ppStmt, (const char **) &dummy);
}
#define SQLITE3_EXEC(db, cmd) do { if (SQLITE_OK != sqlite3_exec(db, cmd,
NULL, NULL, &emsg)) { GE_LOG(coreAPI->ectx, GE_ERROR | GE_ADMIN | GE_BULK,
_("`%s' failed at %s:%d with error: %s\n"), "sqlite3_exec", __FILE__, __LINE__,
emsg); sqlite3_free(emsg); } } while(0);
-static void db_init(sqlite3 * dbh) {
- char * emsg;
+static void
+db_init (sqlite3 * dbh)
+{
+ char *emsg;
- SQLITE3_EXEC(dbh,
- "PRAGMA temp_store=MEMORY");
- SQLITE3_EXEC(dbh,
- "PRAGMA synchronous=OFF");
- SQLITE3_EXEC(dbh,
- "PRAGMA count_changes=OFF");
- SQLITE3_EXEC(dbh,
- "PRAGMA page_size=4092");
- SQLITE3_EXEC(dbh,
- "CREATE TABLE ds071 ("
- " size INTEGER NOT NULL DEFAULT 0,"
- " type INTEGER NOT NULL DEFAULT 0,"
- " puttime INTEGER NOT NULL DEFAULT 0,"
- " expire INTEGER NOT NULL DEFAULT 0,"
- " key TEXT NOT NULL DEFAULT '',"
- " value BLOB NOT NULL DEFAULT '')");
- SQLITE3_EXEC(dbh,
- "CREATE INDEX idx_key ON ds071 (key)");
- SQLITE3_EXEC(dbh,
- "CREATE INDEX idx_puttime ON ds071 (puttime)");
+ SQLITE3_EXEC (dbh, "PRAGMA temp_store=MEMORY");
+ SQLITE3_EXEC (dbh, "PRAGMA synchronous=OFF");
+ SQLITE3_EXEC (dbh, "PRAGMA count_changes=OFF");
+ SQLITE3_EXEC (dbh, "PRAGMA page_size=4092");
+ SQLITE3_EXEC (dbh,
+ "CREATE TABLE ds071 ("
+ " size INTEGER NOT NULL DEFAULT 0,"
+ " type INTEGER NOT NULL DEFAULT 0,"
+ " puttime INTEGER NOT NULL DEFAULT 0,"
+ " expire INTEGER NOT NULL DEFAULT 0,"
+ " key TEXT NOT NULL DEFAULT '',"
+ " value BLOB NOT NULL DEFAULT '')");
+ SQLITE3_EXEC (dbh, "CREATE INDEX idx_key ON ds071 (key)");
+ SQLITE3_EXEC (dbh, "CREATE INDEX idx_puttime ON ds071 (puttime)");
}
-static int db_reset() {
+static int
+db_reset ()
+{
int fd;
- sqlite3 * dbh;
+ sqlite3 *dbh;
- if (fn != NULL) {
- UNLINK(fn);
- FREE(fn);
- }
- fn = STRDUP("/tmp/dstoreXXXXXX");
- fd = mkstemp(fn);
- if (fd == -1) {
- GE_BREAK(NULL, 0);
- FREE(fn);
- fn = NULL;
+ if (fn != NULL)
+ {
+ UNLINK (fn);
+ FREE (fn);
+ }
+ fn = STRDUP ("/tmp/dstoreXXXXXX");
+ fd = mkstemp (fn);
+ if (fd == -1)
+ {
+ GE_BREAK (NULL, 0);
+ FREE (fn);
+ fn = NULL;
+ return SYSERR;
+ }
+ CLOSE (fd);
+ if (SQLITE_OK != sqlite3_open (fn, &dbh))
return SYSERR;
- }
- CLOSE(fd);
- if (SQLITE_OK != sqlite3_open(fn,
- &dbh))
- return SYSERR;
- db_init(dbh);
- sqlite3_close(dbh);
+ db_init (dbh);
+ sqlite3_close (dbh);
return OK;
}
@@ -146,138 +144,112 @@
* Check that we are within quota.
* @return OK if we are.
*/
-static int checkQuota(sqlite3 * dbh) {
+static int
+checkQuota (sqlite3 * dbh)
+{
HashCode512 dkey;
unsigned int dsize;
unsigned int dtype;
cron_t dputtime;
cron_t dexpire;
- char * dcontent;
- sqlite3_stmt * stmt;
- sqlite3_stmt * dstmt;
+ char *dcontent;
+ sqlite3_stmt *stmt;
+ sqlite3_stmt *dstmt;
int err;
if (payload * 10 <= quota * 9)
- return OK; /* we seem to be about 10% off */
+ return OK; /* we seem to be about 10% off */
#if DEBUG_DSTORE
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "DStore above qutoa (have %llu, allowed %llu), will delete some data.\n",
- payload,
- quota);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "DStore above qutoa (have %llu, allowed %llu), will delete some
data.\n",
+ payload, quota);
#endif
stmt = NULL;
dstmt = NULL;
- if ( (sq_prepare(dbh,
- "SELECT size, type, puttime, expire, key, value FROM ds071 ORDER BY
puttime ASC",
- &stmt) != SQLITE_OK) ||
- (sq_prepare(dbh,
- "DELETE FROM ds071 "
- "WHERE size = ? AND type = ? AND puttime = ? AND expire = ? AND key
= ? AND value = ?",
- &dstmt) != SQLITE_OK) ) {
- GE_LOG(coreAPI->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- _("`%s' failed at %s:%d with error: %s\n"),
- "sq_prepare",
- __FILE__,
- __LINE__,
- sqlite3_errmsg(dbh));
- GE_BREAK(NULL, 0);
- if (dstmt != NULL)
- sqlite3_finalize(dstmt);
- if (stmt != NULL)
- sqlite3_finalize(stmt);
- return SYSERR;
- }
- dcontent = MALLOC(MAX_CONTENT_SIZE);
- err = SQLITE_DONE;
- while ( (payload * 10 > quota * 9) && /* we seem to be about 10% off */
- ((err = sqlite3_step(stmt)) == SQLITE_ROW) ) {
- dsize = sqlite3_column_int(stmt, 0);
- dtype = sqlite3_column_int(stmt, 1);
- dputtime = sqlite3_column_int64(stmt, 2);
- dexpire = sqlite3_column_int64(stmt, 3);
- GE_BREAK(NULL,
- sqlite3_column_bytes(stmt, 4) == sizeof(HashCode512));
- GE_BREAK(NULL,
- dsize == sqlite3_column_bytes(stmt, 5));
- memcpy(&dkey,
- sqlite3_column_blob(stmt, 4),
- sizeof(HashCode512));
- if (dsize >= MAX_CONTENT_SIZE) {
- GE_BREAK(NULL, 0);
- dsize = MAX_CONTENT_SIZE;
+ if ((sq_prepare (dbh,
+ "SELECT size, type, puttime, expire, key, value FROM ds071
ORDER BY puttime ASC",
+ &stmt) != SQLITE_OK) ||
+ (sq_prepare (dbh,
+ "DELETE FROM ds071 "
+ "WHERE size = ? AND type = ? AND puttime = ? AND expire = ?
AND key = ? AND value = ?",
+ &dstmt) != SQLITE_OK))
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "sq_prepare", __FILE__, __LINE__, sqlite3_errmsg (dbh));
+ GE_BREAK (NULL, 0);
+ if (dstmt != NULL)
+ sqlite3_finalize (dstmt);
+ if (stmt != NULL)
+ sqlite3_finalize (stmt);
+ return SYSERR;
}
- memcpy(dcontent,
- sqlite3_column_blob(stmt, 5),
- dsize);
- sqlite3_reset(stmt);
- sqlite3_bind_int(dstmt,
- 1,
- dsize);
- sqlite3_bind_int(dstmt,
- 2,
- dtype);
- sqlite3_bind_int64(dstmt,
- 3,
- dputtime);
- sqlite3_bind_int64(dstmt,
- 4,
- dexpire);
- sqlite3_bind_blob(dstmt,
- 5,
- &dkey,
- sizeof(HashCode512),
- SQLITE_TRANSIENT);
- sqlite3_bind_blob(dstmt,
- 6,
- dcontent,
- dsize,
- SQLITE_TRANSIENT);
- if ((err = sqlite3_step(dstmt)) != SQLITE_DONE) {
- GE_LOG(coreAPI->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- _("`%s' failed at %s:%d with error: %s\n"),
- "sqlite3_step",
- __FILE__,
- __LINE__,
- sqlite3_errmsg(dbh));
- sqlite3_reset(dstmt);
- GE_BREAK(NULL, 0); /* should delete but cannot!? */
- break;
- }
- payload -= (dsize + OVERHEAD);
+ dcontent = MALLOC (MAX_CONTENT_SIZE);
+ err = SQLITE_DONE;
+ while ((payload * 10 > quota * 9) && /* we seem to be about 10% off */
+ ((err = sqlite3_step (stmt)) == SQLITE_ROW))
+ {
+ dsize = sqlite3_column_int (stmt, 0);
+ dtype = sqlite3_column_int (stmt, 1);
+ dputtime = sqlite3_column_int64 (stmt, 2);
+ dexpire = sqlite3_column_int64 (stmt, 3);
+ GE_BREAK (NULL, sqlite3_column_bytes (stmt, 4) == sizeof (HashCode512));
+ GE_BREAK (NULL, dsize == sqlite3_column_bytes (stmt, 5));
+ memcpy (&dkey, sqlite3_column_blob (stmt, 4), sizeof (HashCode512));
+ if (dsize >= MAX_CONTENT_SIZE)
+ {
+ GE_BREAK (NULL, 0);
+ dsize = MAX_CONTENT_SIZE;
+ }
+ memcpy (dcontent, sqlite3_column_blob (stmt, 5), dsize);
+ sqlite3_reset (stmt);
+ sqlite3_bind_int (dstmt, 1, dsize);
+ sqlite3_bind_int (dstmt, 2, dtype);
+ sqlite3_bind_int64 (dstmt, 3, dputtime);
+ sqlite3_bind_int64 (dstmt, 4, dexpire);
+ sqlite3_bind_blob (dstmt,
+ 5, &dkey, sizeof (HashCode512), SQLITE_TRANSIENT);
+ sqlite3_bind_blob (dstmt, 6, dcontent, dsize, SQLITE_TRANSIENT);
+ if ((err = sqlite3_step (dstmt)) != SQLITE_DONE)
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "sqlite3_step", __FILE__, __LINE__, sqlite3_errmsg (dbh));
+ sqlite3_reset (dstmt);
+ GE_BREAK (NULL, 0); /* should delete but cannot!? */
+ break;
+ }
+ payload -= (dsize + OVERHEAD);
#if DEBUG_DSTORE
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Deleting %u bytes decreases DStore payload to %llu out of %llu\n",
- dsize,
- payload,
- quota);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Deleting %u bytes decreases DStore payload to %llu out of
%llu\n",
+ dsize, payload, quota);
#endif
- sqlite3_reset(dstmt);
- }
- if (err != SQLITE_DONE) {
- GE_LOG(coreAPI->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- _("`%s' failed at %s:%d with error: %s\n"),
- "sqlite3_step",
- __FILE__,
- __LINE__,
- sqlite3_errmsg(dbh));
- }
- FREE(dcontent);
- sqlite3_finalize(dstmt);
- sqlite3_finalize(stmt);
- if (payload * 10 > quota * 9) {
- /* we seem to be about 10% off */
- GE_LOG(coreAPI->ectx,
- GE_ERROR | GE_BULK | GE_DEVELOPER,
- "Failed to delete content to drop below quota (bug?).\n",
- payload,
- quota);
- return SYSERR;
- }
+ sqlite3_reset (dstmt);
+ }
+ if (err != SQLITE_DONE)
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "sqlite3_step", __FILE__, __LINE__, sqlite3_errmsg (dbh));
+ }
+ FREE (dcontent);
+ sqlite3_finalize (dstmt);
+ sqlite3_finalize (stmt);
+ if (payload * 10 > quota * 9)
+ {
+ /* we seem to be about 10% off */
+ GE_LOG (coreAPI->ectx,
+ GE_ERROR | GE_BULK | GE_DEVELOPER,
+ "Failed to delete content to drop below quota (bug?).\n",
+ payload, quota);
+ return SYSERR;
+ }
return OK;
}
@@ -286,142 +258,101 @@
*
* @return OK on success, SYSERR on error
*/
-static int d_put(const HashCode512 * key,
- unsigned int type,
- cron_t discard_time,
- unsigned int size,
- const char * data) {
- sqlite3 * dbh;
- sqlite3_stmt * stmt;
+static int
+d_put (const HashCode512 * key,
+ unsigned int type,
+ cron_t discard_time, unsigned int size, const char *data)
+{
+ sqlite3 *dbh;
+ sqlite3_stmt *stmt;
int ret;
if (size > MAX_CONTENT_SIZE)
return SYSERR;
- MUTEX_LOCK(lock);
- if ( (fn == NULL) ||
- (SQLITE_OK != sqlite3_open(fn,
- &dbh)) ) {
- db_reset(dbh);
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
+ MUTEX_LOCK (lock);
+ if ((fn == NULL) || (SQLITE_OK != sqlite3_open (fn, &dbh)))
+ {
+ db_reset (dbh);
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
#if DEBUG_DSTORE
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "dstore processes put `%.*s\n",
- size,
- data);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "dstore processes put `%.*s\n", size, data);
#endif
/* first try UPDATE */
- if (sq_prepare(dbh,
- "UPDATE ds071 SET puttime=?, expire=? "
- "WHERE key=? AND type=? AND size=? AND value=?",
- &stmt) != SQLITE_OK) {
- GE_LOG(coreAPI->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- _("`%s' failed at %s:%d with error: %s\n"),
- "sq_prepare",
- __FILE__,
- __LINE__,
- sqlite3_errmsg(dbh));
- sqlite3_close(dbh);
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- sqlite3_bind_int64(stmt,
- 1,
- get_time());
- sqlite3_bind_int64(stmt,
- 2,
- discard_time);
- sqlite3_bind_blob(stmt,
- 3,
- key,
- sizeof(HashCode512),
- SQLITE_TRANSIENT);
- sqlite3_bind_int(stmt,
- 4,
- type);
- sqlite3_bind_int(stmt,
- 5,
- size);
- sqlite3_bind_blob(stmt,
- 6,
- data,
- size,
- SQLITE_TRANSIENT);
- sqlite3_step(stmt);
- ret = sqlite3_changes(dbh);
- sqlite3_finalize(stmt);
- if (ret > 0) {
- sqlite3_close(dbh);
- MUTEX_UNLOCK(lock);
- return OK;
- }
+ if (sq_prepare (dbh,
+ "UPDATE ds071 SET puttime=?, expire=? "
+ "WHERE key=? AND type=? AND size=? AND value=?",
+ &stmt) != SQLITE_OK)
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "sq_prepare", __FILE__, __LINE__, sqlite3_errmsg (dbh));
+ sqlite3_close (dbh);
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ sqlite3_bind_int64 (stmt, 1, get_time ());
+ sqlite3_bind_int64 (stmt, 2, discard_time);
+ sqlite3_bind_blob (stmt, 3, key, sizeof (HashCode512), SQLITE_TRANSIENT);
+ sqlite3_bind_int (stmt, 4, type);
+ sqlite3_bind_int (stmt, 5, size);
+ sqlite3_bind_blob (stmt, 6, data, size, SQLITE_TRANSIENT);
+ sqlite3_step (stmt);
+ ret = sqlite3_changes (dbh);
+ sqlite3_finalize (stmt);
+ if (ret > 0)
+ {
+ sqlite3_close (dbh);
+ MUTEX_UNLOCK (lock);
+ return OK;
+ }
if (bloom != NULL)
- addToBloomfilter(bloom,
- key);
+ addToBloomfilter (bloom, key);
- if (OK != checkQuota(dbh)) {
- sqlite3_close(dbh);
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- if (sq_prepare(dbh,
- "INSERT INTO ds071 "
- "(size, type, puttime, expire, key, value) "
- "VALUES (?, ?, ?, ?, ?, ?)",
- &stmt) != SQLITE_OK) {
- GE_LOG(coreAPI->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- _("`%s' failed at %s:%d with error: %s\n"),
- "sq_prepare",
- __FILE__,
- __LINE__,
- sqlite3_errmsg(dbh));
- sqlite3_close(dbh);
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- sqlite3_bind_int(stmt,
- 1,
- size);
- sqlite3_bind_int(stmt,
- 2,
- type);
- sqlite3_bind_int64(stmt,
- 3,
- get_time());
- sqlite3_bind_int64(stmt,
- 4,
- discard_time);
- sqlite3_bind_blob(stmt,
- 5,
- key,
- sizeof(HashCode512),
- SQLITE_TRANSIENT);
- sqlite3_bind_blob(stmt,
- 6,
- data,
- size,
- SQLITE_TRANSIENT);
- sqlite3_step(stmt);
- sqlite3_finalize(stmt);
+ if (OK != checkQuota (dbh))
+ {
+ sqlite3_close (dbh);
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ if (sq_prepare (dbh,
+ "INSERT INTO ds071 "
+ "(size, type, puttime, expire, key, value) "
+ "VALUES (?, ?, ?, ?, ?, ?)", &stmt) != SQLITE_OK)
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "sq_prepare", __FILE__, __LINE__, sqlite3_errmsg (dbh));
+ sqlite3_close (dbh);
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ sqlite3_bind_int (stmt, 1, size);
+ sqlite3_bind_int (stmt, 2, type);
+ sqlite3_bind_int64 (stmt, 3, get_time ());
+ sqlite3_bind_int64 (stmt, 4, discard_time);
+ sqlite3_bind_blob (stmt, 5, key, sizeof (HashCode512), SQLITE_TRANSIENT);
+ sqlite3_bind_blob (stmt, 6, data, size, SQLITE_TRANSIENT);
+ sqlite3_step (stmt);
+ sqlite3_finalize (stmt);
payload += size + OVERHEAD;
#if DEBUG_DSTORE
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Storing %u bytes increases DStore payload to %llu out of %llu\n",
- size,
- payload,
- quota);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Storing %u bytes increases DStore payload to %llu out of %llu\n",
+ size, payload, quota);
#endif
- checkQuota(dbh);
- sqlite3_close(dbh);
- MUTEX_UNLOCK(lock);
+ checkQuota (dbh);
+ sqlite3_close (dbh);
+ MUTEX_UNLOCK (lock);
if (stats != NULL)
- stats->set(stat_dstore_size, payload);
+ stats->set (stat_dstore_size, payload);
return OK;
}
@@ -435,151 +366,135 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int d_get(const HashCode512 * key,
- unsigned int type,
- ResultHandler handler,
- void * closure) {
- sqlite3 * dbh;
- sqlite3_stmt * stmt;
+static int
+d_get (const HashCode512 * key,
+ unsigned int type, ResultHandler handler, void *closure)
+{
+ sqlite3 *dbh;
+ sqlite3_stmt *stmt;
cron_t now;
unsigned int size;
- const char * dat;
+ const char *dat;
unsigned int cnt;
- MUTEX_LOCK(lock);
- if ( (bloom != NULL) &&
- (NO == testBloomfilter(bloom,
- key)) ) {
- MUTEX_UNLOCK(lock);
- return 0;
- }
- if ( (fn == NULL) ||
- (SQLITE_OK != sqlite3_open(fn,
- &dbh)) ) {
- db_reset(dbh);
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
+ MUTEX_LOCK (lock);
+ if ((bloom != NULL) && (NO == testBloomfilter (bloom, key)))
+ {
+ MUTEX_UNLOCK (lock);
+ return 0;
+ }
+ if ((fn == NULL) || (SQLITE_OK != sqlite3_open (fn, &dbh)))
+ {
+ db_reset (dbh);
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
#if DEBUG_DSTORE
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "dstore processes get\n");
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER, "dstore processes get\n");
#endif
- now = get_time();
- if (sq_prepare(dbh,
- "SELECT size, value FROM ds071 WHERE key=? AND type=? AND expire >= ?",
- &stmt) != SQLITE_OK) {
- GE_LOG(coreAPI->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- _("`%s' failed at %s:%d with error: %s\n"),
- "sq_prepare",
- __FILE__,
- __LINE__,
- sqlite3_errmsg(dbh));
- sqlite3_close(dbh);
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- sqlite3_bind_blob(stmt,
- 1,
- key,
- sizeof(HashCode512),
- SQLITE_TRANSIENT);
- sqlite3_bind_int(stmt,
- 2,
- type);
- sqlite3_bind_int(stmt,
- 3,
- now);
+ now = get_time ();
+ if (sq_prepare (dbh,
+ "SELECT size, value FROM ds071 WHERE key=? AND type=? AND
expire >= ?",
+ &stmt) != SQLITE_OK)
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "sq_prepare", __FILE__, __LINE__, sqlite3_errmsg (dbh));
+ sqlite3_close (dbh);
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ sqlite3_bind_blob (stmt, 1, key, sizeof (HashCode512), SQLITE_TRANSIENT);
+ sqlite3_bind_int (stmt, 2, type);
+ sqlite3_bind_int (stmt, 3, now);
cnt = 0;
- while (sqlite3_step(stmt) == SQLITE_ROW) {
- size = sqlite3_column_int(stmt, 0);
- if (size != sqlite3_column_bytes(stmt, 1)) {
- GE_BREAK(NULL, 0);
- continue;
+ while (sqlite3_step (stmt) == SQLITE_ROW)
+ {
+ size = sqlite3_column_int (stmt, 0);
+ if (size != sqlite3_column_bytes (stmt, 1))
+ {
+ GE_BREAK (NULL, 0);
+ continue;
+ }
+ dat = sqlite3_column_blob (stmt, 1);
+ handler (key, type, size, dat, closure);
+ cnt++;
}
- dat = sqlite3_column_blob(stmt, 1);
- handler(key,
- type,
- size,
- dat,
- closure);
- cnt++;
- }
- sqlite3_finalize(stmt);
- sqlite3_close(dbh);
- MUTEX_UNLOCK(lock);
+ sqlite3_finalize (stmt);
+ sqlite3_close (dbh);
+ MUTEX_UNLOCK (lock);
return cnt;
}
Dstore_ServiceAPI *
-provide_module_dstore(CoreAPIForApplication * capi) {
+provide_module_dstore (CoreAPIForApplication * capi)
+{
static Dstore_ServiceAPI api;
int fd;
#if DEBUG_SQLITE
- GE_LOG(capi->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite Dstore: initializing database\n");
+ GE_LOG (capi->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "SQLite Dstore: initializing database\n");
#endif
- if (OK != db_reset())
+ if (OK != db_reset ())
return NULL;
- lock = MUTEX_CREATE(NO);
+ lock = MUTEX_CREATE (NO);
coreAPI = capi;
api.get = &d_get;
api.put = &d_put;
- GC_get_configuration_value_number(coreAPI->cfg,
- "DSTORE",
- "QUOTA",
- 1,
- 1024,
- 1,
- "a);
- if (quota == 0) /* error */
+ GC_get_configuration_value_number (coreAPI->cfg,
+ "DSTORE", "QUOTA", 1, 1024, 1, "a);
+ if (quota == 0) /* error */
quota = 1;
quota *= 1024 * 1024;
- bloom_name = STRDUP("/tmp/dbloomXXXXXX");
- fd = mkstemp(bloom_name);
- if (fd != -1) {
- bloom = loadBloomfilter(coreAPI->ectx,
- bloom_name,
- quota / (OVERHEAD + 1024), /* 8 bit per entry in DB, expect
1k entries */
- 5);
- CLOSE(fd);
- }
- stats = capi->requestService("stats");
+ bloom_name = STRDUP ("/tmp/dbloomXXXXXX");
+ fd = mkstemp (bloom_name);
+ if (fd != -1)
+ {
+ bloom = loadBloomfilter (coreAPI->ectx, bloom_name, quota / (OVERHEAD +
1024), /* 8 bit per entry in DB, expect 1k entries */
+ 5);
+ CLOSE (fd);
+ }
+ stats = capi->requestService ("stats");
if (stats != NULL)
- stat_dstore_size = stats->create(gettext_noop("# bytes in dstore"));
+ stat_dstore_size = stats->create (gettext_noop ("# bytes in dstore"));
return &api;
}
/**
* Shutdown the module.
*/
-void release_module_dstore() {
- UNLINK(fn);
- FREE(fn);
+void
+release_module_dstore ()
+{
+ UNLINK (fn);
+ FREE (fn);
fn = NULL;
- if (bloom != NULL) {
- freeBloomfilter(bloom);
- bloom = NULL;
- }
- UNLINK(bloom_name);
- FREE(bloom_name);
+ if (bloom != NULL)
+ {
+ freeBloomfilter (bloom);
+ bloom = NULL;
+ }
+ UNLINK (bloom_name);
+ FREE (bloom_name);
bloom_name = NULL;
- if (stats != NULL) {
- coreAPI->releaseService(stats);
- stats = NULL;
- }
+ if (stats != NULL)
+ {
+ coreAPI->releaseService (stats);
+ stats = NULL;
+ }
#if DEBUG_SQLITE
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite Dstore: database shutdown\n");
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "SQLite Dstore: database shutdown\n");
#endif
- MUTEX_DESTROY(lock);
+ MUTEX_DESTROY (lock);
coreAPI = NULL;
}
Modified: GNUnet/src/applications/dstore/dstore_test.c
===================================================================
--- GNUnet/src/applications/dstore/dstore_test.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/dstore/dstore_test.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -35,89 +35,82 @@
static int error;
-static void checkIt(const HashCode512 * key,
- unsigned int type,
- unsigned int size,
- const char * data,
- void * cls) {
- if (size != sizeof(HashCode512)) {
- printf("ERROR: Invalid size\n");
- error = 2;
- }
- if (0 != memcmp(data, cls, size)) {
- printf("ERROR: Invalid data\n");
- error = 3;
- }
+static void
+checkIt (const HashCode512 * key,
+ unsigned int type, unsigned int size, const char *data, void *cls)
+{
+ if (size != sizeof (HashCode512))
+ {
+ printf ("ERROR: Invalid size\n");
+ error = 2;
+ }
+ if (0 != memcmp (data, cls, size))
+ {
+ printf ("ERROR: Invalid data\n");
+ error = 3;
+ }
}
/**
* Add testcode here!
*/
-static int test(Dstore_ServiceAPI * api) {
+static int
+test (Dstore_ServiceAPI * api)
+{
HashCode512 k;
HashCode512 n;
cron_t exp;
unsigned int i;
- exp = get_time() + 5 * cronMINUTES;
- memset(&k,
- 0,
- sizeof(HashCode512));
- for (i=0;i<100;i++) {
- hash(&k,
- sizeof(HashCode512),
- &n);
- ASSERT(OK == api->put(&k,
- i % 2,
- exp,
- sizeof(HashCode512),
- (const char*) &n));
- k = n;
- }
- memset(&k,
- 0,
- sizeof(HashCode512));
- for (i=0;i<100;i++) {
- hash(&k,
- sizeof(HashCode512),
- &n);
- ASSERT(1 == api->get(&k,
- i % 2,
- &checkIt,
- &n));
- k = n;
- }
+ exp = get_time () + 5 * cronMINUTES;
+ memset (&k, 0, sizeof (HashCode512));
+ for (i = 0; i < 100; i++)
+ {
+ hash (&k, sizeof (HashCode512), &n);
+ ASSERT (OK == api->put (&k,
+ i % 2,
+ exp, sizeof (HashCode512), (const char *) &n));
+ k = n;
+ }
+ memset (&k, 0, sizeof (HashCode512));
+ for (i = 0; i < 100; i++)
+ {
+ hash (&k, sizeof (HashCode512), &n);
+ ASSERT (1 == api->get (&k, i % 2, &checkIt, &n));
+ k = n;
+ }
return OK;
- FAILURE:
+FAILURE:
return SYSERR;
}
#define TEST_DB "/tmp/GNUnet_dstore_test/"
-int main(int argc, char *argv[]) {
- Dstore_ServiceAPI * api;
+int
+main (int argc, char *argv[])
+{
+ Dstore_ServiceAPI *api;
int ok;
- struct GC_Configuration * cfg;
- struct CronManager * cron;
+ struct GC_Configuration *cfg;
+ struct CronManager *cron;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- cron = cron_create(NULL);
- initCore(NULL,
- cfg,
- cron,
- NULL);
- api = requestService("dstore");
- if (api != NULL) {
- ok = test(api);
- releaseService(api);
- } else
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ cron = cron_create (NULL);
+ initCore (NULL, cfg, cron, NULL);
+ api = requestService ("dstore");
+ if (api != NULL)
+ {
+ ok = test (api);
+ releaseService (api);
+ }
+ else
ok = SYSERR;
- doneCore();
+ doneCore ();
if (ok == SYSERR)
return 1;
return error;
Modified: GNUnet/src/applications/fragmentation/fragmentation.c
===================================================================
--- GNUnet/src/applications/fragmentation/fragmentation.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/fragmentation/fragmentation.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -41,7 +41,8 @@
/**
* Message fragment.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -77,17 +78,19 @@
/**
* Entry in the linked list of fragments.
*/
-typedef struct FL {
- struct FL * link;
- P2P_fragmentation_MESSAGE * frag;
+typedef struct FL
+{
+ struct FL *link;
+ P2P_fragmentation_MESSAGE *frag;
} FL;
/**
* Entry in the hash table of fragments.
*/
-typedef struct FC {
- struct FC * next;
- FL * head;
+typedef struct FC
+{
+ struct FC *next;
+ FL *head;
PeerIdentity sender;
int id;
cron_t ttl;
@@ -95,9 +98,9 @@
#define FRAGSIZE(fl)
((ntohs(fl->frag->header.size)-sizeof(P2P_fragmentation_MESSAGE)))
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static int stat_defragmented;
@@ -108,23 +111,25 @@
/**
* Hashtable *with* collision management!
*/
-static FC * defragmentationCache[DEFRAG_BUCKET_COUNT];
+static FC *defragmentationCache[DEFRAG_BUCKET_COUNT];
/**
* Lock for the defragmentation cache.
*/
-static struct MUTEX * defragCacheLock;
+static struct MUTEX *defragCacheLock;
-static void freeFL(FL * fl,
- int c) {
- while (fl != NULL) {
- FL * link = fl->link;
- if (stats != NULL)
- stats->change(stat_discarded, c);
- FREE(fl->frag);
- FREE(fl);
- fl = link;
- }
+static void
+freeFL (FL * fl, int c)
+{
+ while (fl != NULL)
+ {
+ FL *link = fl->link;
+ if (stats != NULL)
+ stats->change (stat_discarded, c);
+ FREE (fl->frag);
+ FREE (fl);
+ fl = link;
+ }
}
/**
@@ -137,34 +142,41 @@
* belong to the entry). It's a bit more complicated as the
* collision list is also collapsed.
*/
-static void defragmentationPurgeCron(void * unused) {
+static void
+defragmentationPurgeCron (void *unused)
+{
int i;
- FC * smf;
- FC * next;
- FC * last;
+ FC *smf;
+ FC *next;
+ FC *last;
- MUTEX_LOCK(defragCacheLock);
- for (i=0;i<DEFRAG_BUCKET_COUNT;i++) {
- last = NULL;
- smf = defragmentationCache[i];
- while (smf != NULL) {
- if (smf->ttl < get_time()) {
- /* free linked list of fragments */
- freeFL(smf->head, 1);
- next = smf->next;
- FREE(smf);
- if (last == NULL)
- defragmentationCache[i] = next;
- else
- last->next = next;
- smf = next;
- } else {
- last = smf;
- smf = smf->next;
- }
- } /* while smf != NULL */
- } /* for all buckets */
- MUTEX_UNLOCK(defragCacheLock);
+ MUTEX_LOCK (defragCacheLock);
+ for (i = 0; i < DEFRAG_BUCKET_COUNT; i++)
+ {
+ last = NULL;
+ smf = defragmentationCache[i];
+ while (smf != NULL)
+ {
+ if (smf->ttl < get_time ())
+ {
+ /* free linked list of fragments */
+ freeFL (smf->head, 1);
+ next = smf->next;
+ FREE (smf);
+ if (last == NULL)
+ defragmentationCache[i] = next;
+ else
+ last->next = next;
+ smf = next;
+ }
+ else
+ {
+ last = smf;
+ smf = smf->next;
+ }
+ } /* while smf != NULL */
+ } /* for all buckets */
+ MUTEX_UNLOCK (defragCacheLock);
}
/**
@@ -175,56 +187,53 @@
*
* @param pep the entry in the hash table
*/
-static void checkComplete(FC * pep) {
- FL * pos;
+static void
+checkComplete (FC * pep)
+{
+ FL *pos;
unsigned short off;
unsigned short len;
- char * msg;
+ char *msg;
- GE_ASSERT(NULL, pep != NULL);
+ GE_ASSERT (NULL, pep != NULL);
pos = pep->head;
if (pos == NULL)
return;
- len = ntohs(pos->frag->len);
+ len = ntohs (pos->frag->len);
if (len == 0)
- goto CLEANUP; /* really bad error! */
+ goto CLEANUP; /* really bad error! */
off = 0;
- while ( (pos != NULL) &&
- (ntohs(pos->frag->off) <= off) ) {
- if (off >= off + FRAGSIZE(pos))
- goto CLEANUP; /* error! */
- if (ntohs(pos->frag->off) + FRAGSIZE(pos) > off)
- off = ntohs(pos->frag->off) + FRAGSIZE(pos);
- else
- goto CLEANUP; /* error! */
- pos = pos->link;
- }
+ while ((pos != NULL) && (ntohs (pos->frag->off) <= off))
+ {
+ if (off >= off + FRAGSIZE (pos))
+ goto CLEANUP; /* error! */
+ if (ntohs (pos->frag->off) + FRAGSIZE (pos) > off)
+ off = ntohs (pos->frag->off) + FRAGSIZE (pos);
+ else
+ goto CLEANUP; /* error! */
+ pos = pos->link;
+ }
if (off < len)
- return; /* some fragment is still missing */
+ return; /* some fragment is still missing */
- msg = MALLOC(len);
+ msg = MALLOC (len);
pos = pep->head;
- while (pos != NULL) {
- memcpy(&msg[ntohs(pos->frag->off)],
- &pos->frag[1],
- FRAGSIZE(pos));
- pos = pos->link;
- }
+ while (pos != NULL)
+ {
+ memcpy (&msg[ntohs (pos->frag->off)], &pos->frag[1], FRAGSIZE (pos));
+ pos = pos->link;
+ }
if (stats != NULL)
- stats->change(stat_defragmented, 1);
+ stats->change (stat_defragmented, 1);
#if 0
- printf("Finished defragmentation!\n");
+ printf ("Finished defragmentation!\n");
#endif
/* handle message! */
- coreAPI->injectMessage(&pep->sender,
- msg,
- len,
- YES,
- NULL);
- FREE(msg);
- CLEANUP:
+ coreAPI->injectMessage (&pep->sender, msg, len, YES, NULL);
+ FREE (msg);
+CLEANUP:
/* free fragment buffers */
- freeFL(pep->head, 0);
+ freeFL (pep->head, 0);
pep->head = NULL;
pep->ttl = 0;
}
@@ -240,138 +249,140 @@
* @param pep the new entry
* @param packet the ip part in the new entry
*/
-static int tryJoin(FC * entry,
- const PeerIdentity * sender,
- const P2P_fragmentation_MESSAGE * packet) {
+static int
+tryJoin (FC * entry,
+ const PeerIdentity * sender,
+ const P2P_fragmentation_MESSAGE * packet)
+{
/* frame before ours; may end in the middle of
our frame or before it starts; NULL if we are
the earliest position we have received so far */
- FL * before;
+ FL *before;
/* frame after ours; may start in the middle of
our frame or after it; NULL if we are the last
fragment we have received so far */
- FL * after;
+ FL *after;
/* current position in the frame-list */
- FL * pos;
+ FL *pos;
/* the new entry that we're inserting */
- FL * pep;
- FL * tmp;
+ FL *pep;
+ FL *tmp;
unsigned short end;
- GE_ASSERT(NULL, entry != NULL);
- if (0 != memcmp(sender,
- &entry->sender,
- sizeof(PeerIdentity)))
- return SYSERR; /* wrong fragment list, try another! */
- if (ntohl(packet->id) != entry->id)
- return SYSERR; /* wrong fragment list, try another! */
+ GE_ASSERT (NULL, entry != NULL);
+ if (0 != memcmp (sender, &entry->sender, sizeof (PeerIdentity)))
+ return SYSERR; /* wrong fragment list, try another! */
+ if (ntohl (packet->id) != entry->id)
+ return SYSERR; /* wrong fragment list, try another! */
#if 0
- printf("Received fragment %u from %u to %u\n",
- ntohl(packet->id),
- ntohs(packet->off),
- ntohs(packet->off) + ntohs(packet->header.size) -
sizeof(P2P_fragmentation_MESSAGE));
+ printf ("Received fragment %u from %u to %u\n",
+ ntohl (packet->id),
+ ntohs (packet->off),
+ ntohs (packet->off) + ntohs (packet->header.size) -
+ sizeof (P2P_fragmentation_MESSAGE));
#endif
pos = entry->head;
- if ( (pos != NULL) &&
- (packet->len != pos->frag->len) )
- return SYSERR; /* wrong fragment size */
+ if ((pos != NULL) && (packet->len != pos->frag->len))
+ return SYSERR; /* wrong fragment size */
before = NULL;
/* find the before-frame */
- while ( (pos != NULL) &&
- (ntohs(pos->frag->off) <
- ntohs(packet->off)) ) {
- before = pos;
- pos = pos->link;
- }
+ while ((pos != NULL) && (ntohs (pos->frag->off) < ntohs (packet->off)))
+ {
+ before = pos;
+ pos = pos->link;
+ }
/* find the after-frame */
- end = ntohs(packet->off) + ntohs(packet->header.size) -
sizeof(P2P_fragmentation_MESSAGE);
- if (end <= ntohs(packet->off)) {
- GE_LOG(NULL,
- GE_DEVELOPER | GE_DEBUG | GE_BULK,
- "Received invalid fragment at %s:%d\n",
- __FILE__, __LINE__);
- return SYSERR; /* yuck! integer overflow! */
- }
+ end =
+ ntohs (packet->off) + ntohs (packet->header.size) -
+ sizeof (P2P_fragmentation_MESSAGE);
+ if (end <= ntohs (packet->off))
+ {
+ GE_LOG (NULL,
+ GE_DEVELOPER | GE_DEBUG | GE_BULK,
+ "Received invalid fragment at %s:%d\n", __FILE__, __LINE__);
+ return SYSERR; /* yuck! integer overflow! */
+ }
if (before != NULL)
after = before;
else
after = entry->head;
- while ( (after != NULL) &&
- (ntohs(after->frag->off)<end) )
+ while ((after != NULL) && (ntohs (after->frag->off) < end))
after = after->link;
- if ( (before != NULL) &&
- (before == after) ) {
- /* this implies after or before != NULL and thereby the new
- fragment is redundant as it is fully enclosed in an earlier
- fragment */
- if (stats != NULL)
- stats->change(stat_defragmented, 1);
- return OK; /* drop, there is a packet that spans our range! */
- }
+ if ((before != NULL) && (before == after))
+ {
+ /* this implies after or before != NULL and thereby the new
+ fragment is redundant as it is fully enclosed in an earlier
+ fragment */
+ if (stats != NULL)
+ stats->change (stat_defragmented, 1);
+ return OK; /* drop, there is a packet that spans our
range! */
+ }
- if ( (before != NULL) &&
- (after != NULL) &&
- ( (htons(before->frag->off) +
- FRAGSIZE(before))
- >= htons(after->frag->off)) ) {
- /* this implies that the fragment that starts before us and the
- fragment that comes after this one leave no space in the middle
- or even overlap; thus we can drop this redundant piece */
- if (stats != NULL)
- stats->change(stat_defragmented, 1);
- return OK;
- }
+ if ((before != NULL) &&
+ (after != NULL) &&
+ ((htons (before->frag->off) +
+ FRAGSIZE (before)) >= htons (after->frag->off)))
+ {
+ /* this implies that the fragment that starts before us and the
+ fragment that comes after this one leave no space in the middle
+ or even overlap; thus we can drop this redundant piece */
+ if (stats != NULL)
+ stats->change (stat_defragmented, 1);
+ return OK;
+ }
/* allocate pep */
- pep = MALLOC(sizeof(FC));
- pep->frag = MALLOC(ntohs(packet->header.size));
- memcpy(pep->frag,
- packet,
- ntohs(packet->header.size));
+ pep = MALLOC (sizeof (FC));
+ pep->frag = MALLOC (ntohs (packet->header.size));
+ memcpy (pep->frag, packet, ntohs (packet->header.size));
pep->link = NULL;
- if (before == NULL) {
- pep->link = after;
- pos = entry->head;
- while (pos != after) {
- tmp = pos->link;
- FREE(pos->frag);
- FREE(pos);
- pos = tmp;
+ if (before == NULL)
+ {
+ pep->link = after;
+ pos = entry->head;
+ while (pos != after)
+ {
+ tmp = pos->link;
+ FREE (pos->frag);
+ FREE (pos);
+ pos = tmp;
+ }
+ entry->head = pep;
+ goto FINISH;
+ /* end of insert first */
}
- entry->head = pep;
- goto FINISH;
- /* end of insert first */
- }
- if (after == NULL) {
- /* insert last: find the end, free everything after it */
- freeFL(before->link, 1);
- before->link = pep;
- goto FINISH;
- }
+ if (after == NULL)
+ {
+ /* insert last: find the end, free everything after it */
+ freeFL (before->link, 1);
+ before->link = pep;
+ goto FINISH;
+ }
/* ok, we are filling the middle between two fragments; insert. If
there is anything else in the middle, it can be dropped as we're
bigger & cover that area as well */
/* free everything between before and after */
pos = before->link;
- while (pos != after) {
- tmp = pos->link;
- FREE(pos->frag);
- FREE(pos);
- pos = tmp;
- }
+ while (pos != after)
+ {
+ tmp = pos->link;
+ FREE (pos->frag);
+ FREE (pos);
+ pos = tmp;
+ }
before->link = pep;
pep->link = after;
- FINISH:
- entry->ttl = get_time() + DEFRAGMENTATION_TIMEOUT;
- checkComplete(entry);
+FINISH:
+ entry->ttl = get_time () + DEFRAGMENTATION_TIMEOUT;
+ checkComplete (entry);
return OK;
}
@@ -382,52 +393,52 @@
* @param frag the packet to defragment
* @return SYSERR if the fragment is invalid
*/
-static int processFragment(const PeerIdentity * sender,
- const MESSAGE_HEADER * frag) {
+static int
+processFragment (const PeerIdentity * sender, const MESSAGE_HEADER * frag)
+{
unsigned int hash;
- FC * smf;
+ FC *smf;
- if (ntohs(frag->size) < sizeof(P2P_fragmentation_MESSAGE))
+ if (ntohs (frag->size) < sizeof (P2P_fragmentation_MESSAGE))
return SYSERR;
- MUTEX_LOCK(defragCacheLock);
+ MUTEX_LOCK (defragCacheLock);
hash = sender->hashPubKey.bits[0] % DEFRAG_BUCKET_COUNT;
smf = defragmentationCache[hash];
- while (smf != NULL) {
- if (OK == tryJoin(smf,
- sender,
- (P2P_fragmentation_MESSAGE*) frag)) {
- MUTEX_UNLOCK(defragCacheLock);
- return OK;
+ while (smf != NULL)
+ {
+ if (OK == tryJoin (smf, sender, (P2P_fragmentation_MESSAGE *) frag))
+ {
+ MUTEX_UNLOCK (defragCacheLock);
+ return OK;
+ }
+ if (0 == memcmp (sender, &smf->sender, sizeof (PeerIdentity)))
+ {
+ freeFL (smf->head, 1);
+ break;
+ }
+ smf = smf->next;
}
- if (0 == memcmp(sender,
- &smf->sender,
- sizeof(PeerIdentity))) {
- freeFL(smf->head, 1);
- break;
+ if (smf == NULL)
+ {
+ smf = MALLOC (sizeof (FC));
+ smf->next = defragmentationCache[hash];
+ defragmentationCache[hash] = smf;
+ smf->ttl = get_time () + DEFRAGMENTATION_TIMEOUT;
+ smf->sender = *sender;
}
- smf = smf->next;
- }
- if (smf == NULL) {
- smf = MALLOC(sizeof(FC));
- smf->next = defragmentationCache[hash];
- defragmentationCache[hash] = smf;
- smf->ttl = get_time() + DEFRAGMENTATION_TIMEOUT;
- smf->sender = *sender;
- }
- smf->id = ntohl(((P2P_fragmentation_MESSAGE*)frag)->id);
- smf->head = MALLOC(sizeof(FL));
+ smf->id = ntohl (((P2P_fragmentation_MESSAGE *) frag)->id);
+ smf->head = MALLOC (sizeof (FL));
smf->head->link = NULL;
- smf->head->frag = MALLOC(ntohs(frag->size));
- memcpy(smf->head->frag,
- frag,
- ntohs(frag->size));
+ smf->head->frag = MALLOC (ntohs (frag->size));
+ memcpy (smf->head->frag, frag, ntohs (frag->size));
- MUTEX_UNLOCK(defragCacheLock);
+ MUTEX_UNLOCK (defragCacheLock);
return OK;
}
-typedef struct {
+typedef struct
+{
PeerIdentity sender;
/* maximums size of each fragment */
unsigned short mtu;
@@ -450,60 +461,59 @@
* and then going to other messages of equal priority would not be
* such a great idea (i.e. would just waste bandwidth).
*/
-static int fragmentBMC(void * buf,
- void * cls,
- unsigned short len) {
- FragmentBMC * ctx = cls;
+static int
+fragmentBMC (void *buf, void *cls, unsigned short len)
+{
+ FragmentBMC *ctx = cls;
static int idGen = 0;
- P2P_fragmentation_MESSAGE * frag;
+ P2P_fragmentation_MESSAGE *frag;
unsigned int pos;
int id;
unsigned short mlen;
- if ( (len < ctx->mtu) ||
- (buf == NULL) ) {
- FREE(ctx);
- return SYSERR;
- }
+ if ((len < ctx->mtu) || (buf == NULL))
+ {
+ FREE (ctx);
+ return SYSERR;
+ }
if (stats != NULL)
- stats->change(stat_fragmented, 1);
- id = (idGen++) + weak_randomi(512);
+ stats->change (stat_fragmented, 1);
+ id = (idGen++) + weak_randomi (512);
/* write first fragment to buf */
- frag = (P2P_fragmentation_MESSAGE*) buf;
- frag->header.size = htons(len);
- frag->header.type = htons(P2P_PROTO_fragment);
+ frag = (P2P_fragmentation_MESSAGE *) buf;
+ frag->header.size = htons (len);
+ frag->header.type = htons (P2P_PROTO_fragment);
frag->id = id;
- frag->off = htons(0);
- frag->len = htons(ctx->len);
- memcpy(&frag[1],
- &ctx[1],
- len - sizeof(P2P_fragmentation_MESSAGE));
+ frag->off = htons (0);
+ frag->len = htons (ctx->len);
+ memcpy (&frag[1], &ctx[1], len - sizeof (P2P_fragmentation_MESSAGE));
/* create remaining fragments, add to queue! */
- pos = len - sizeof(P2P_fragmentation_MESSAGE);
- frag = MALLOC(ctx->mtu);
- while (pos < ctx->len) {
- mlen = sizeof(P2P_fragmentation_MESSAGE) + ctx->len - pos;
- if (mlen > ctx->mtu)
- mlen = ctx->mtu;
- GE_ASSERT(NULL, mlen > sizeof(P2P_fragmentation_MESSAGE));
- frag->header.size = htons(mlen);
- frag->header.type = htons(P2P_PROTO_fragment);
- frag->id = id;
- frag->off = htons(pos);
- frag->len = htons(ctx->len);
- memcpy(&frag[1],
- &((char*)(&ctx[1]))[pos],
- mlen - sizeof(P2P_fragmentation_MESSAGE));
- coreAPI->unicast(&ctx->sender,
- &frag->header,
- EXTREME_PRIORITY,
- ctx->transmissionTime - get_time());
- pos += mlen - sizeof(P2P_fragmentation_MESSAGE);
- }
- GE_ASSERT(NULL, pos == ctx->len);
- FREE(frag);
- FREE(ctx);
+ pos = len - sizeof (P2P_fragmentation_MESSAGE);
+ frag = MALLOC (ctx->mtu);
+ while (pos < ctx->len)
+ {
+ mlen = sizeof (P2P_fragmentation_MESSAGE) + ctx->len - pos;
+ if (mlen > ctx->mtu)
+ mlen = ctx->mtu;
+ GE_ASSERT (NULL, mlen > sizeof (P2P_fragmentation_MESSAGE));
+ frag->header.size = htons (mlen);
+ frag->header.type = htons (P2P_PROTO_fragment);
+ frag->id = id;
+ frag->off = htons (pos);
+ frag->len = htons (ctx->len);
+ memcpy (&frag[1],
+ &((char *) (&ctx[1]))[pos],
+ mlen - sizeof (P2P_fragmentation_MESSAGE));
+ coreAPI->unicast (&ctx->sender,
+ &frag->header,
+ EXTREME_PRIORITY,
+ ctx->transmissionTime - get_time ());
+ pos += mlen - sizeof (P2P_fragmentation_MESSAGE);
+ }
+ GE_ASSERT (NULL, pos == ctx->len);
+ FREE (frag);
+ FREE (ctx);
return OK;
}
@@ -513,75 +523,71 @@
* for transmission, the placeholder should automatically add all of
* the other fragments (with very high priority).
*/
-void fragment(const PeerIdentity * peer,
- unsigned int mtu,
- unsigned int prio,
- unsigned int targetTime,
- unsigned int len,
- BuildMessageCallback bmc,
- void * bmcClosure) {
- FragmentBMC * fbmc;
+void
+fragment (const PeerIdentity * peer,
+ unsigned int mtu,
+ unsigned int prio,
+ unsigned int targetTime,
+ unsigned int len, BuildMessageCallback bmc, void *bmcClosure)
+{
+ FragmentBMC *fbmc;
int xlen;
- GE_ASSERT(NULL, len > mtu);
- GE_ASSERT(NULL, mtu > sizeof(P2P_fragmentation_MESSAGE));
- fbmc = MALLOC(sizeof(FragmentBMC) + len);
+ GE_ASSERT (NULL, len > mtu);
+ GE_ASSERT (NULL, mtu > sizeof (P2P_fragmentation_MESSAGE));
+ fbmc = MALLOC (sizeof (FragmentBMC) + len);
fbmc->mtu = mtu;
fbmc->sender = *peer;
fbmc->transmissionTime = targetTime;
fbmc->len = len;
- if (bmc == NULL) {
- memcpy(&fbmc[1],
- bmcClosure,
- len);
- FREE(bmcClosure);
- } else {
- if (SYSERR == bmc(&fbmc[1],
- bmcClosure,
- len)) {
- FREE(fbmc);
- return;
+ if (bmc == NULL)
+ {
+ memcpy (&fbmc[1], bmcClosure, len);
+ FREE (bmcClosure);
}
- }
- xlen = mtu - sizeof(P2P_fragmentation_MESSAGE);
- coreAPI->unicastCallback(peer,
- &fragmentBMC,
- fbmc,
- mtu,
- prio * xlen / len, /* compute new prio */
- targetTime);
+ else
+ {
+ if (SYSERR == bmc (&fbmc[1], bmcClosure, len))
+ {
+ FREE (fbmc);
+ return;
+ }
+ }
+ xlen = mtu - sizeof (P2P_fragmentation_MESSAGE);
+ coreAPI->unicastCallback (peer, &fragmentBMC, fbmc, mtu, prio * xlen / len,
/* compute new prio */
+ targetTime);
}
/**
* Initialize Fragmentation module.
*/
Fragmentation_ServiceAPI *
-provide_module_fragmentation(CoreAPIForApplication * capi) {
+provide_module_fragmentation (CoreAPIForApplication * capi)
+{
static Fragmentation_ServiceAPI ret;
int i;
coreAPI = capi;
- stats = coreAPI->requestService("stats");
- if (stats != NULL) {
- stat_defragmented = stats->create(gettext_noop("# messages defragmented"));
- stat_fragmented = stats->create(gettext_noop("# messages fragmented"));
- stat_discarded = stats->create(gettext_noop("# fragments discarded"));
- }
- for (i=0;i<DEFRAG_BUCKET_COUNT;i++)
+ stats = coreAPI->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_defragmented =
+ stats->create (gettext_noop ("# messages defragmented"));
+ stat_fragmented =
+ stats->create (gettext_noop ("# messages fragmented"));
+ stat_discarded = stats->create (gettext_noop ("# fragments discarded"));
+ }
+ for (i = 0; i < DEFRAG_BUCKET_COUNT; i++)
defragmentationCache[i] = NULL;
- defragCacheLock = MUTEX_CREATE(NO);
- cron_add_job(coreAPI->cron,
- &defragmentationPurgeCron,
- 60 * cronSECONDS,
- 60 * cronSECONDS,
- NULL);
- GE_LOG(capi->ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- _("`%s' registering handler %d\n"),
- "fragmentation",
- P2P_PROTO_fragment);
- capi->registerHandler(P2P_PROTO_fragment,
- &processFragment);
+ defragCacheLock = MUTEX_CREATE (NO);
+ cron_add_job (coreAPI->cron,
+ &defragmentationPurgeCron,
+ 60 * cronSECONDS, 60 * cronSECONDS, NULL);
+ GE_LOG (capi->ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ _("`%s' registering handler %d\n"),
+ "fragmentation", P2P_PROTO_fragment);
+ capi->registerHandler (P2P_PROTO_fragment, &processFragment);
ret.fragment = &fragment;
return &ret;
@@ -590,29 +596,31 @@
/**
* Shutdown fragmentation.
*/
-void release_module_fragmentation() {
+void
+release_module_fragmentation ()
+{
int i;
- coreAPI->unregisterHandler(P2P_PROTO_fragment,
- &processFragment);
- cron_del_job(coreAPI->cron,
- &defragmentationPurgeCron,
- 60 * cronSECONDS,
- NULL);
- for (i=0;i<DEFRAG_BUCKET_COUNT;i++) {
- FC * pos = defragmentationCache[i];
- while (pos != NULL) {
- FC * next = pos->next;
- freeFL(pos->head, 1);
- FREE(pos);
- pos = next;
+ coreAPI->unregisterHandler (P2P_PROTO_fragment, &processFragment);
+ cron_del_job (coreAPI->cron,
+ &defragmentationPurgeCron, 60 * cronSECONDS, NULL);
+ for (i = 0; i < DEFRAG_BUCKET_COUNT; i++)
+ {
+ FC *pos = defragmentationCache[i];
+ while (pos != NULL)
+ {
+ FC *next = pos->next;
+ freeFL (pos->head, 1);
+ FREE (pos);
+ pos = next;
+ }
}
- }
- if (stats != NULL) {
- coreAPI->releaseService(stats);
- stats = NULL;
- }
- MUTEX_DESTROY(defragCacheLock);
+ if (stats != NULL)
+ {
+ coreAPI->releaseService (stats);
+ stats = NULL;
+ }
+ MUTEX_DESTROY (defragCacheLock);
defragCacheLock = NULL;
coreAPI = NULL;
}
Modified: GNUnet/src/applications/fragmentation/fragmentationtest.c
===================================================================
--- GNUnet/src/applications/fragmentation/fragmentationtest.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/fragmentation/fragmentationtest.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -47,33 +47,32 @@
#include "fragmentation.c"
static PeerIdentity mySender;
-static char * myMsg;
+static char *myMsg;
static unsigned short myMsgLen;
/* static buffers to avoid lots of malloc/free */
static char masterBuffer[65536];
static char resultBuffer[65536];
-static void handleHelper(const PeerIdentity * sender,
- const char * msg,
- const unsigned int len,
- int wasEncrypted,
- TSession * ts) {
- GE_ASSERT(NULL,
- 0 == memcmp(sender,
- &mySender,
- sizeof(PeerIdentity)));
+static void
+handleHelper (const PeerIdentity * sender,
+ const char *msg,
+ const unsigned int len, int wasEncrypted, TSession * ts)
+{
+ GE_ASSERT (NULL, 0 == memcmp (sender, &mySender, sizeof (PeerIdentity)));
myMsg = resultBuffer;
- memcpy(resultBuffer, msg, len);
+ memcpy (resultBuffer, msg, len);
myMsgLen = len;
}
/**
* Wait long enough to force all fragments to timeout.
*/
-static void makeTimeout() {
- PTHREAD_SLEEP(DEFRAGMENTATION_TIMEOUT*2);
- defragmentationPurgeCron(NULL);
+static void
+makeTimeout ()
+{
+ PTHREAD_SLEEP (DEFRAGMENTATION_TIMEOUT * 2);
+ defragmentationPurgeCron (NULL);
}
/**
@@ -86,23 +85,21 @@
* @param length of the data portion
* @param id the identity of the fragment
*/
-static MESSAGE_HEADER * makeFragment(unsigned short start,
- unsigned short size,
- unsigned short tot,
- int id) {
- P2P_fragmentation_MESSAGE * frag;
+static MESSAGE_HEADER *
+makeFragment (unsigned short start,
+ unsigned short size, unsigned short tot, int id)
+{
+ P2P_fragmentation_MESSAGE *frag;
int i;
- frag = (P2P_fragmentation_MESSAGE*) masterBuffer;
- frag->id = htonl(id);
- frag->off = htons(start);
- frag->len = htons(tot);
- frag->header.size
- = htons(sizeof(P2P_fragmentation_MESSAGE) + size);
+ frag = (P2P_fragmentation_MESSAGE *) masterBuffer;
+ frag->id = htonl (id);
+ frag->off = htons (start);
+ frag->len = htons (tot);
+ frag->header.size = htons (sizeof (P2P_fragmentation_MESSAGE) + size);
- for (i=0;i<size;i++)
- ((char*) &frag[1])[i]
- = (char)i+id+start;
+ for (i = 0; i < size; i++)
+ ((char *) &frag[1])[i] = (char) i + id + start;
return &frag->header;
}
@@ -112,14 +109,15 @@
* @param id the expected id
* @param len the expected length
*/
-static void checkPacket(int id,
- unsigned int len) {
+static void
+checkPacket (int id, unsigned int len)
+{
int i;
- GE_ASSERT(NULL, myMsg != NULL);
- GE_ASSERT(NULL, myMsgLen == len);
- for (i=0;i<len;i++)
- GE_ASSERT(NULL, myMsg[i] == (char) (i+id));
+ GE_ASSERT (NULL, myMsg != NULL);
+ GE_ASSERT (NULL, myMsgLen == len);
+ for (i = 0; i < len; i++)
+ GE_ASSERT (NULL, myMsg[i] == (char) (i + id));
myMsgLen = 0;
myMsg = NULL;
}
@@ -127,259 +125,306 @@
/* **************** actual testcases ***************** */
-static void testSimpleFragment() {
- MESSAGE_HEADER * pep;
+static void
+testSimpleFragment ()
+{
+ MESSAGE_HEADER *pep;
- pep = makeFragment(0, 16, 32, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- pep = makeFragment(16, 16, 32, 42);
- processFragment(&mySender, pep);
- checkPacket(42, 32);
+ pep = makeFragment (0, 16, 32, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ pep = makeFragment (16, 16, 32, 42);
+ processFragment (&mySender, pep);
+ checkPacket (42, 32);
}
-static void testSimpleFragmentTimeout() {
- MESSAGE_HEADER * pep;
+static void
+testSimpleFragmentTimeout ()
+{
+ MESSAGE_HEADER *pep;
- pep = makeFragment(0, 16, 32, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- makeTimeout();
- pep = makeFragment(16, 16, 32, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- pep = makeFragment(0, 16, 32, 42);
- processFragment(&mySender, pep);
- checkPacket(42, 32);
+ pep = makeFragment (0, 16, 32, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ makeTimeout ();
+ pep = makeFragment (16, 16, 32, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ pep = makeFragment (0, 16, 32, 42);
+ processFragment (&mySender, pep);
+ checkPacket (42, 32);
}
-static void testSimpleFragmentReverse() {
- MESSAGE_HEADER * pep;
+static void
+testSimpleFragmentReverse ()
+{
+ MESSAGE_HEADER *pep;
- pep = makeFragment(16, 16, 32, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- pep = makeFragment(0, 16, 32, 42);
- processFragment(&mySender, pep);
- checkPacket(42, 32);
+ pep = makeFragment (16, 16, 32, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ pep = makeFragment (0, 16, 32, 42);
+ processFragment (&mySender, pep);
+ checkPacket (42, 32);
}
-static void testManyFragments() {
- MESSAGE_HEADER * pep;
+static void
+testManyFragments ()
+{
+ MESSAGE_HEADER *pep;
int i;
- for (i=0;i<50;i++) {
- pep = makeFragment(i*16, 16, 51*16, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- }
- pep = makeFragment(50*16,16, 51*16, 42);
- processFragment(&mySender, pep);
- checkPacket(42, 51*16);
+ for (i = 0; i < 50; i++)
+ {
+ pep = makeFragment (i * 16, 16, 51 * 16, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ }
+ pep = makeFragment (50 * 16, 16, 51 * 16, 42);
+ processFragment (&mySender, pep);
+ checkPacket (42, 51 * 16);
}
-static void testManyFragmentsMegaLarge() {
- MESSAGE_HEADER * pep;
+static void
+testManyFragmentsMegaLarge ()
+{
+ MESSAGE_HEADER *pep;
int i;
- for (i=0;i<4000;i++) {
- pep = makeFragment(i*16, 16, 4001*16, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- }
- pep = makeFragment(4000*16, 16, 4001*16, 42);
- processFragment(&mySender, pep);
- checkPacket(42, 4001*16);
+ for (i = 0; i < 4000; i++)
+ {
+ pep = makeFragment (i * 16, 16, 4001 * 16, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ }
+ pep = makeFragment (4000 * 16, 16, 4001 * 16, 42);
+ processFragment (&mySender, pep);
+ checkPacket (42, 4001 * 16);
}
-static void testLastFragmentEarly() {
- MESSAGE_HEADER * pep;
+static void
+testLastFragmentEarly ()
+{
+ MESSAGE_HEADER *pep;
int i;
- for (i=0;i<5;i++) {
- pep = makeFragment(i*16, 8, 6*16+8, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- }
- pep = makeFragment(5*16, 24, 6*16+8, 42);
- processFragment(&mySender, pep);
- for (i=0;i<5;i++) {
- pep = makeFragment(i*16+8, 8, 6*16+8, 42);
- processFragment(&mySender, pep);
- }
- checkPacket(42, 6*16+8);
+ for (i = 0; i < 5; i++)
+ {
+ pep = makeFragment (i * 16, 8, 6 * 16 + 8, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ }
+ pep = makeFragment (5 * 16, 24, 6 * 16 + 8, 42);
+ processFragment (&mySender, pep);
+ for (i = 0; i < 5; i++)
+ {
+ pep = makeFragment (i * 16 + 8, 8, 6 * 16 + 8, 42);
+ processFragment (&mySender, pep);
+ }
+ checkPacket (42, 6 * 16 + 8);
}
-static void testManyInterleavedFragments() {
- MESSAGE_HEADER * pep;
+static void
+testManyInterleavedFragments ()
+{
+ MESSAGE_HEADER *pep;
int i;
- for (i=0;i<50;i++) {
- pep = makeFragment(i*16, 8, 51*16+8, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- }
- for (i=0;i<50;i++) {
- pep = makeFragment(i*16+8, 8, 51*16+8, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- }
- pep = makeFragment(50*16, 24, 51*16+8, 42);
- processFragment(&mySender, pep);
- checkPacket(42, 51*16+8);
+ for (i = 0; i < 50; i++)
+ {
+ pep = makeFragment (i * 16, 8, 51 * 16 + 8, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ }
+ for (i = 0; i < 50; i++)
+ {
+ pep = makeFragment (i * 16 + 8, 8, 51 * 16 + 8, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ }
+ pep = makeFragment (50 * 16, 24, 51 * 16 + 8, 42);
+ processFragment (&mySender, pep);
+ checkPacket (42, 51 * 16 + 8);
}
-static void testManyInterleavedOverlappingFragments() {
- MESSAGE_HEADER * pep;
+static void
+testManyInterleavedOverlappingFragments ()
+{
+ MESSAGE_HEADER *pep;
int i;
- for (i=0;i<50;i++) {
- pep = makeFragment(i*32, 16, 51*32, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- }
- for (i=0;i<50;i++) {
- pep = makeFragment(i*32+8, 24, 51*32, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- }
- pep = makeFragment(50*32, 32, 51*32, 42);
- processFragment(&mySender, pep);
- checkPacket(42, 51*32);
+ for (i = 0; i < 50; i++)
+ {
+ pep = makeFragment (i * 32, 16, 51 * 32, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ }
+ for (i = 0; i < 50; i++)
+ {
+ pep = makeFragment (i * 32 + 8, 24, 51 * 32, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ }
+ pep = makeFragment (50 * 32, 32, 51 * 32, 42);
+ processFragment (&mySender, pep);
+ checkPacket (42, 51 * 32);
}
-static void testManyOverlappingFragments() {
- MESSAGE_HEADER * pep;
+static void
+testManyOverlappingFragments ()
+{
+ MESSAGE_HEADER *pep;
int i;
- for (i=0;i<50;i++) {
- pep = makeFragment(0, i*16+16, 51*16, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- }
- pep = makeFragment(50*16,16, 51*16, 42);
- processFragment(&mySender, pep);
- checkPacket(42, 51*16);
+ for (i = 0; i < 50; i++)
+ {
+ pep = makeFragment (0, i * 16 + 16, 51 * 16, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ }
+ pep = makeFragment (50 * 16, 16, 51 * 16, 42);
+ processFragment (&mySender, pep);
+ checkPacket (42, 51 * 16);
}
-static void testManyOverlappingFragmentsTimeout() {
- MESSAGE_HEADER * pep;
+static void
+testManyOverlappingFragmentsTimeout ()
+{
+ MESSAGE_HEADER *pep;
int i;
- for (i=0;i<50;i++) {
- pep = makeFragment(0, i*16+16, 51*16+8, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- }
- makeTimeout();
- pep = makeFragment(50*16, 24, 51*16+8, 42);
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
- for (i=0;i<50;i++) {
- pep = makeFragment(0, i*16+16, 51*16+8, 42);
- processFragment(&mySender, pep);
- }
- checkPacket(42, 51*16+8);
+ for (i = 0; i < 50; i++)
+ {
+ pep = makeFragment (0, i * 16 + 16, 51 * 16 + 8, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ }
+ makeTimeout ();
+ pep = makeFragment (50 * 16, 24, 51 * 16 + 8, 42);
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ for (i = 0; i < 50; i++)
+ {
+ pep = makeFragment (0, i * 16 + 16, 51 * 16 + 8, 42);
+ processFragment (&mySender, pep);
+ }
+ checkPacket (42, 51 * 16 + 8);
}
-static void testManyFragmentsMultiId() {
- MESSAGE_HEADER * pep;
+static void
+testManyFragmentsMultiId ()
+{
+ MESSAGE_HEADER *pep;
int i;
int id;
- for (i=0;i<50;i++) {
- for (id=0;id<DEFRAG_BUCKET_COUNT;id++) {
- pep = makeFragment(i*16, 16, 51*16, id+5);
+ for (i = 0; i < 50; i++)
+ {
+ for (id = 0; id < DEFRAG_BUCKET_COUNT; id++)
+ {
+ pep = makeFragment (i * 16, 16, 51 * 16, id + 5);
+ mySender.hashPubKey.bits[0] = id;
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ }
+ }
+ for (id = 0; id < DEFRAG_BUCKET_COUNT; id++)
+ {
+ pep = makeFragment (50 * 16, 16, 51 * 16, id + 5);
mySender.hashPubKey.bits[0] = id;
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
+ processFragment (&mySender, pep);
+ checkPacket (id + 5, 51 * 16);
}
- }
- for (id=0;id<DEFRAG_BUCKET_COUNT;id++) {
- pep = makeFragment(50*16, 16, 51*16, id+5);
- mySender.hashPubKey.bits[0] = id;
- processFragment(&mySender, pep);
- checkPacket(id+5, 51*16);
- }
}
-static void testManyFragmentsMultiIdCollisions() {
- MESSAGE_HEADER * pep;
+static void
+testManyFragmentsMultiIdCollisions ()
+{
+ MESSAGE_HEADER *pep;
int i;
int id;
- for (i=0;i<5;i++) {
- for (id=0;id<DEFRAG_BUCKET_COUNT*4;id++) {
- pep = makeFragment(i*16, 16, 6*16, id+5);
+ for (i = 0; i < 5; i++)
+ {
+ for (id = 0; id < DEFRAG_BUCKET_COUNT * 4; id++)
+ {
+ pep = makeFragment (i * 16, 16, 6 * 16, id + 5);
+ mySender.hashPubKey.bits[0] = id;
+ processFragment (&mySender, pep);
+ GE_ASSERT (NULL, myMsg == NULL);
+ }
+ }
+ for (id = 0; id < DEFRAG_BUCKET_COUNT * 4; id++)
+ {
+ pep = makeFragment (5 * 16, 16, 6 * 16, id + 5);
mySender.hashPubKey.bits[0] = id;
- processFragment(&mySender, pep);
- GE_ASSERT(NULL, myMsg == NULL);
+ processFragment (&mySender, pep);
+ checkPacket (id + 5, 6 * 16);
}
- }
- for (id=0;id<DEFRAG_BUCKET_COUNT*4;id++) {
- pep = makeFragment(5*16, 16, 6*16, id+5);
- mySender.hashPubKey.bits[0] = id;
- processFragment(&mySender, pep);
- checkPacket(id+5, 6*16);
- }
}
/* ************* driver ****************** */
-static int registerp2pHandler(const unsigned short type,
- MessagePartHandler callback) {
+static int
+registerp2pHandler (const unsigned short type, MessagePartHandler callback)
+{
return OK;
}
-static int unregisterp2pHandler(const unsigned short type,
- MessagePartHandler callback) {
+static int
+unregisterp2pHandler (const unsigned short type, MessagePartHandler callback)
+{
return OK;
}
-static void * requestService(const char * name) {
+static void *
+requestService (const char *name)
+{
return NULL;
}
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
CoreAPIForApplication capi;
- memset(&capi, 0, sizeof(CoreAPIForApplication));
- capi.cron = cron_create(NULL);
+ memset (&capi, 0, sizeof (CoreAPIForApplication));
+ capi.cron = cron_create (NULL);
capi.injectMessage = &handleHelper;
capi.requestService = &requestService;
capi.registerHandler = ®isterp2pHandler;
capi.unregisterHandler = &unregisterp2pHandler;
- provide_module_fragmentation(&capi);
+ provide_module_fragmentation (&capi);
- fprintf(stderr, ".");
- testSimpleFragment();
- fprintf(stderr, ".");
- testSimpleFragmentTimeout();
- fprintf(stderr, ".");
- testSimpleFragmentReverse();
- fprintf(stderr, ".");
- testManyFragments();
- fprintf(stderr, ".");
- testManyFragmentsMegaLarge();
- fprintf(stderr, ".");
- testManyFragmentsMultiId();
- fprintf(stderr, ".");
+ fprintf (stderr, ".");
+ testSimpleFragment ();
+ fprintf (stderr, ".");
+ testSimpleFragmentTimeout ();
+ fprintf (stderr, ".");
+ testSimpleFragmentReverse ();
+ fprintf (stderr, ".");
+ testManyFragments ();
+ fprintf (stderr, ".");
+ testManyFragmentsMegaLarge ();
+ fprintf (stderr, ".");
+ testManyFragmentsMultiId ();
+ fprintf (stderr, ".");
- testManyInterleavedFragments();
- fprintf(stderr, ".");
- testManyInterleavedOverlappingFragments();
- fprintf(stderr, ".");
- testManyOverlappingFragments();
- fprintf(stderr, ".");
- testManyOverlappingFragmentsTimeout();
- fprintf(stderr, ".");
- testLastFragmentEarly();
- fprintf(stderr, ".");
- testManyFragmentsMultiIdCollisions();
- fprintf(stderr, ".");
- release_module_fragmentation();
- fprintf(stderr, "\n");
- cron_destroy(capi.cron);
- return 0; /* testcase passed */
+ testManyInterleavedFragments ();
+ fprintf (stderr, ".");
+ testManyInterleavedOverlappingFragments ();
+ fprintf (stderr, ".");
+ testManyOverlappingFragments ();
+ fprintf (stderr, ".");
+ testManyOverlappingFragmentsTimeout ();
+ fprintf (stderr, ".");
+ testLastFragmentEarly ();
+ fprintf (stderr, ".");
+ testManyFragmentsMultiIdCollisions ();
+ fprintf (stderr, ".");
+ release_module_fragmentation ();
+ fprintf (stderr, "\n");
+ cron_destroy (capi.cron);
+ return 0; /* testcase passed */
}
Modified: GNUnet/src/applications/fs/collection/collection.c
===================================================================
--- GNUnet/src/applications/fs/collection/collection.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/collection/collection.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -54,7 +54,8 @@
/**
* @brief information about a collection
*/
-typedef struct CollectionData {
+typedef struct CollectionData
+{
/**
* What is the last ID for the publication?
@@ -89,24 +90,25 @@
} CollectionData;
-typedef struct {
+typedef struct
+{
CollectionData data;
/**
* Name of the collection
*/
- char * name;
+ char *name;
/**
* Metadata describing the collection
*/
- struct ECRS_MetaData * meta;
+ struct ECRS_MetaData *meta;
/**
* Files in the collection.
*/
- ECRS_FileInfo * files;
+ ECRS_FileInfo *files;
/**
* How many files are in files?
@@ -120,300 +122,280 @@
} CollectionInfo;
-static CollectionInfo * collectionData;
+static CollectionInfo *collectionData;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
static char *
-getCollectionFileName() {
- char * fn;
- char * fnBase;
+getCollectionFileName ()
+{
+ char *fn;
+ char *fnBase;
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &fnBase);
- fn = MALLOC(strlen(fnBase) +
- strlen(COLLECTION) +
- 4);
- strcpy(fn, fnBase);
- disk_directory_create(ectx, fn);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, COLLECTION);
- FREE(fnBase);
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &fnBase);
+ fn = MALLOC (strlen (fnBase) + strlen (COLLECTION) + 4);
+ strcpy (fn, fnBase);
+ disk_directory_create (ectx, fn);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, COLLECTION);
+ FREE (fnBase);
return fn;
}
/**
* Initialize collection module.
*/
-void CO_init(struct GE_Context * e,
- struct GC_Configuration * c) {
- char * fn;
+void
+CO_init (struct GE_Context *e, struct GC_Configuration *c)
+{
+ char *fn;
int len;
unsigned int mlen;
unsigned long long size;
- char * buf;
+ char *buf;
int fd;
- const char * pos;
+ const char *pos;
size_t rsize;
unsigned int i;
- char * tmp;
+ char *tmp;
cfg = c;
ectx = e;
- lock = MUTEX_CREATE(YES);
- fn = getCollectionFileName();
- if (! disk_file_test(ectx, fn)) {
- FREE(fn);
- return;
- }
+ lock = MUTEX_CREATE (YES);
+ fn = getCollectionFileName ();
+ if (!disk_file_test (ectx, fn))
+ {
+ FREE (fn);
+ return;
+ }
/* read collection data */
- if (OK != disk_file_size(ectx,
- fn,
- &size,
- YES)) {
- FREE(fn);
- return;
- }
- if ( (size > 0x7FFFFFFF) ||
- (size < sizeof(CollectionData) + 4 * sizeof(int)) ) {
- GE_BREAK(ectx, 0);
- UNLINK(fn);
- FREE(fn);
- return;
- }
- fd = open(fn, O_RDONLY | O_LARGEFILE);
- if (fd == -1) {
- GE_BREAK(ectx, 0);
- UNLINK(fn);
- FREE(fn);
- return;
- }
+ if (OK != disk_file_size (ectx, fn, &size, YES))
+ {
+ FREE (fn);
+ return;
+ }
+ if ((size > 0x7FFFFFFF) ||
+ (size < sizeof (CollectionData) + 4 * sizeof (int)))
+ {
+ GE_BREAK (ectx, 0);
+ UNLINK (fn);
+ FREE (fn);
+ return;
+ }
+ fd = open (fn, O_RDONLY | O_LARGEFILE);
+ if (fd == -1)
+ {
+ GE_BREAK (ectx, 0);
+ UNLINK (fn);
+ FREE (fn);
+ return;
+ }
rsize = (size_t) size;
- buf = MMAP(NULL,
- rsize,
- PROT_READ,
- MAP_SHARED,
- fd,
- 0);
- if (buf == MAP_FAILED) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "mmap",
- fn);
- CLOSE(fd);
- FREE(fn);
- return;
- }
- collectionData = MALLOC(sizeof(CollectionInfo));
- memcpy(&collectionData->data,
- buf,
- sizeof(CollectionData));
- pos = &buf[sizeof(CollectionData)];
- rsize -= sizeof(CollectionData);
- len = ntohl(*(int*)pos);
- if (len > 1024 * 1024 * 4) {
- GE_BREAK(ectx, 0);
- len = 1024 * 1024 * 4;
- }
- GROW(collectionData->files,
- collectionData->file_count,
- len);
- pos += sizeof(int);
- collectionData->changed = ntohl(*(int*)pos);
- pos += sizeof(int);
- mlen = ntohl(*(int*)pos);
- pos += sizeof(int);
- len = ntohl(*(int*)pos);
- if (len > 1024) {
- GE_BREAK(ectx, 0);
- len = 1024;
- }
- collectionData->name = MALLOC(len+1);
- pos += sizeof(int);
- rsize -= 4 * sizeof(int);
- if (len > rsize) {
- GE_BREAK(ectx, 0);
- len = rsize;
- }
- memcpy(collectionData->name,
- pos,
- len);
+ buf = MMAP (NULL, rsize, PROT_READ, MAP_SHARED, fd, 0);
+ if (buf == MAP_FAILED)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "mmap", fn);
+ CLOSE (fd);
+ FREE (fn);
+ return;
+ }
+ collectionData = MALLOC (sizeof (CollectionInfo));
+ memcpy (&collectionData->data, buf, sizeof (CollectionData));
+ pos = &buf[sizeof (CollectionData)];
+ rsize -= sizeof (CollectionData);
+ len = ntohl (*(int *) pos);
+ if (len > 1024 * 1024 * 4)
+ {
+ GE_BREAK (ectx, 0);
+ len = 1024 * 1024 * 4;
+ }
+ GROW (collectionData->files, collectionData->file_count, len);
+ pos += sizeof (int);
+ collectionData->changed = ntohl (*(int *) pos);
+ pos += sizeof (int);
+ mlen = ntohl (*(int *) pos);
+ pos += sizeof (int);
+ len = ntohl (*(int *) pos);
+ if (len > 1024)
+ {
+ GE_BREAK (ectx, 0);
+ len = 1024;
+ }
+ collectionData->name = MALLOC (len + 1);
+ pos += sizeof (int);
+ rsize -= 4 * sizeof (int);
+ if (len > rsize)
+ {
+ GE_BREAK (ectx, 0);
+ len = rsize;
+ }
+ memcpy (collectionData->name, pos, len);
rsize -= len;
pos += len;
- if (mlen > rsize) {
- GE_BREAK(ectx, 0);
- mlen = rsize;
- }
- collectionData->meta
- = ECRS_deserializeMetaData(ectx,
- pos,
- mlen);
+ if (mlen > rsize)
+ {
+ GE_BREAK (ectx, 0);
+ mlen = rsize;
+ }
+ collectionData->meta = ECRS_deserializeMetaData (ectx, pos, mlen);
rsize -= mlen;
pos += mlen;
- GE_BREAK(ectx,
- collectionData->meta != NULL);
- for (i=0;i<collectionData->file_count;i++) {
- if (rsize < 2 * sizeof(int)) {
- GE_BREAK(ectx, 0);
- break;
+ GE_BREAK (ectx, collectionData->meta != NULL);
+ for (i = 0; i < collectionData->file_count; i++)
+ {
+ if (rsize < 2 * sizeof (int))
+ {
+ GE_BREAK (ectx, 0);
+ break;
+ }
+ len = ntohl (*(int *) pos);
+ pos += sizeof (int);
+ mlen = ntohl (*(int *) pos);
+ pos += sizeof (int);
+ rsize -= 2 * sizeof (int);
+ if (rsize < mlen + len)
+ {
+ GE_BREAK (ectx, 0);
+ break;
+ }
+ if (len > 1024 * 16)
+ {
+ GE_BREAK (ectx, 0);
+ len = 1024 * 16;
+ }
+ tmp = MALLOC (len + 1);
+ tmp[len] = '\0';
+ memcpy (tmp, pos, len);
+ pos += len;
+ rsize -= len;
+ collectionData->files[i].uri = ECRS_stringToUri (ectx, tmp);
+ GE_ASSERT (ectx, collectionData->files[i].uri != NULL);
+ FREE (tmp);
+ collectionData->files[i].meta
+ = ECRS_deserializeMetaData (ectx, pos, mlen);
+ GE_ASSERT (ectx, collectionData->files[i].meta != NULL);
+ pos += mlen;
+ rsize -= mlen;
}
- len = ntohl(*(int*)pos);
- pos += sizeof(int);
- mlen = ntohl(*(int*)pos);
- pos += sizeof(int);
- rsize -= 2 * sizeof(int);
- if (rsize < mlen + len) {
- GE_BREAK(ectx, 0);
- break;
- }
- if (len > 1024 * 16) {
- GE_BREAK(ectx, 0);
- len = 1024 * 16;
- }
- tmp = MALLOC(len + 1);
- tmp[len] = '\0';
- memcpy(tmp,
- pos,
- len);
- pos += len;
- rsize -= len;
- collectionData->files[i].uri
- = ECRS_stringToUri(ectx,
- tmp);
- GE_ASSERT(ectx,
- collectionData->files[i].uri != NULL);
- FREE(tmp);
- collectionData->files[i].meta
- = ECRS_deserializeMetaData(ectx,
- pos,
- mlen);
- GE_ASSERT(ectx,
- collectionData->files[i].meta != NULL);
- pos += mlen;
- rsize -= mlen;
- }
- GE_ASSERT(ectx, rsize == 0);
- MUNMAP(buf, (size_t) size);
- CLOSE(fd);
- FREE(fn);
+ GE_ASSERT (ectx, rsize == 0);
+ MUNMAP (buf, (size_t) size);
+ CLOSE (fd);
+ FREE (fn);
/* kill invalid entries (meta or uri == NULL) */
- for (i=0;i<collectionData->file_count;i++) {
- if ( (collectionData->files[i].uri != NULL) &&
- (collectionData->files[i].meta != NULL) )
- continue;
- if (collectionData->files[i].uri != NULL)
- ECRS_freeUri(collectionData->files[i].uri);
- if (collectionData->files[i].meta != NULL)
- ECRS_freeMetaData(collectionData->files[i].meta);
- collectionData->files[i]
- = collectionData->files[collectionData->file_count-1];
- GROW(collectionData->files,
- collectionData->file_count,
- collectionData->file_count-1);
- }
+ for (i = 0; i < collectionData->file_count; i++)
+ {
+ if ((collectionData->files[i].uri != NULL) &&
+ (collectionData->files[i].meta != NULL))
+ continue;
+ if (collectionData->files[i].uri != NULL)
+ ECRS_freeUri (collectionData->files[i].uri);
+ if (collectionData->files[i].meta != NULL)
+ ECRS_freeMetaData (collectionData->files[i].meta);
+ collectionData->files[i]
+ = collectionData->files[collectionData->file_count - 1];
+ GROW (collectionData->files,
+ collectionData->file_count, collectionData->file_count - 1);
+ }
}
-static void WRITEINT(int fd,
- int val) {
+static void
+WRITEINT (int fd, int val)
+{
int bval;
- bval = htonl(val);
- WRITE(fd,
- &bval,
- sizeof(int));
+ bval = htonl (val);
+ WRITE (fd, &bval, sizeof (int));
}
-static void writeCO() {
- char * fn;
+static void
+writeCO ()
+{
+ char *fn;
unsigned int mlen;
- char * buf;
+ char *buf;
int fd;
unsigned int i;
- char * tmp;
+ char *tmp;
if (collectionData == NULL)
return;
/* write collection data */
- mlen = ECRS_sizeofMetaData(collectionData->meta,
- NO);
- buf = MALLOC(mlen);
- if (mlen != ECRS_serializeMetaData(ectx,
- collectionData->meta,
- buf,
- mlen,
- NO)) {
- GE_BREAK(ectx, 0);
- FREE(buf);
- return;
- }
+ mlen = ECRS_sizeofMetaData (collectionData->meta, NO);
+ buf = MALLOC (mlen);
+ if (mlen != ECRS_serializeMetaData (ectx,
+ collectionData->meta, buf, mlen, NO))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (buf);
+ return;
+ }
- fn = getCollectionFileName();
- fd = open(fn,
- O_CREAT | O_LARGEFILE | O_WRONLY | O_TRUNC,
- S_IRUSR | S_IWUSR);
- if (fd == -1) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_USER | GE_ADMIN | GE_ERROR | GE_BULK,
- "open",
- fn);
- FREE(fn);
- FREE(buf);
- return;
- }
- GE_BREAK(ectx,
- collectionData->file_count <= 1024 * 1024 * 4);
- WRITE(fd,
- collectionData,
- sizeof(CollectionData));
- WRITEINT(fd, collectionData->file_count);
- WRITEINT(fd, collectionData->changed);
- WRITEINT(fd, mlen);
- GE_BREAK(ectx, strlen(collectionData->name) < 1024);
- WRITEINT(fd, strlen(collectionData->name));
- WRITE(fd, collectionData->name, strlen(collectionData->name));
- WRITE(fd, buf, mlen);
- FREE(buf);
- for (i=0;i<collectionData->file_count;i++) {
- mlen = ECRS_sizeofMetaData(collectionData->files[i].meta,
- NO);
- buf = MALLOC(mlen);
- if (mlen != ECRS_serializeMetaData(ectx,
- collectionData->files[i].meta,
- buf,
- mlen,
- NO)) {
- GE_BREAK(ectx, 0);
- FREE(buf);
- break;
+ fn = getCollectionFileName ();
+ fd = open (fn,
+ O_CREAT | O_LARGEFILE | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);
+ if (fd == -1)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_USER | GE_ADMIN | GE_ERROR | GE_BULK,
+ "open", fn);
+ FREE (fn);
+ FREE (buf);
+ return;
}
- tmp = ECRS_uriToString(collectionData->files[i].uri);
- WRITEINT(fd, strlen(tmp));
- WRITEINT(fd, mlen);
- GE_BREAK(ectx, strlen(tmp) < 16 * 1024);
- WRITE(fd, tmp, strlen(tmp));
- FREE(tmp);
- WRITE(fd, buf, mlen);
- FREE(buf);
- }
- CLOSE(fd);
- FREE(fn);
+ GE_BREAK (ectx, collectionData->file_count <= 1024 * 1024 * 4);
+ WRITE (fd, collectionData, sizeof (CollectionData));
+ WRITEINT (fd, collectionData->file_count);
+ WRITEINT (fd, collectionData->changed);
+ WRITEINT (fd, mlen);
+ GE_BREAK (ectx, strlen (collectionData->name) < 1024);
+ WRITEINT (fd, strlen (collectionData->name));
+ WRITE (fd, collectionData->name, strlen (collectionData->name));
+ WRITE (fd, buf, mlen);
+ FREE (buf);
+ for (i = 0; i < collectionData->file_count; i++)
+ {
+ mlen = ECRS_sizeofMetaData (collectionData->files[i].meta, NO);
+ buf = MALLOC (mlen);
+ if (mlen != ECRS_serializeMetaData (ectx,
+ collectionData->files[i].meta,
+ buf, mlen, NO))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (buf);
+ break;
+ }
+ tmp = ECRS_uriToString (collectionData->files[i].uri);
+ WRITEINT (fd, strlen (tmp));
+ WRITEINT (fd, mlen);
+ GE_BREAK (ectx, strlen (tmp) < 16 * 1024);
+ WRITE (fd, tmp, strlen (tmp));
+ FREE (tmp);
+ WRITE (fd, buf, mlen);
+ FREE (buf);
+ }
+ CLOSE (fd);
+ FREE (fn);
}
/**
* Shutdown collection module.
*/
-void CO_done() {
- writeCO();
- CO_stopCollection();
- MUTEX_DESTROY(lock);
+void
+CO_done ()
+{
+ writeCO ();
+ CO_stopCollection ();
+ MUTEX_DESTROY (lock);
lock = NULL;
ectx = NULL;
cfg = NULL;
@@ -429,57 +411,50 @@
* to publish updates when the CO_Context
* is destroyed (i.e. on exit from the UI).
*/
-int CO_startCollection(unsigned int anonymityLevel,
- unsigned int prio,
- TIME_T updateInterval,
- const char * name,
- const struct ECRS_MetaData * meta) {
- struct ECRS_URI * advertisement;
- struct ECRS_URI * rootURI;
+int
+CO_startCollection (unsigned int anonymityLevel,
+ unsigned int prio,
+ TIME_T updateInterval,
+ const char *name, const struct ECRS_MetaData *meta)
+{
+ struct ECRS_URI *advertisement;
+ struct ECRS_URI *rootURI;
HashCode512 nextId;
TIME_T now;
- MUTEX_LOCK(lock);
- CO_stopCollection(); /* cancel old collection */
- GE_ASSERT(ectx, name != NULL);
- advertisement = ECRS_parseCharKeywordURI(ectx,
- COLLECTION);
- GE_ASSERT(ectx, advertisement != NULL);
- TIME(&now);
- makeRandomId(&nextId);
- rootURI = ECRS_createNamespace(ectx,
- cfg,
- name,
- meta,
- anonymityLevel,
- prio,
- get_time() + COLLECTION_ADV_LIFETIME,
- advertisement,
- &nextId);
- if (rootURI == NULL) {
- ECRS_freeUri(advertisement);
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- ECRS_freeUri(advertisement);
- ECRS_freeUri(rootURI);
- collectionData = MALLOC(sizeof(CollectionInfo));
- memset(collectionData,
- 0,
- sizeof(CollectionInfo));
- makeRandomId(&collectionData->data.lastId);
+ MUTEX_LOCK (lock);
+ CO_stopCollection (); /* cancel old collection */
+ GE_ASSERT (ectx, name != NULL);
+ advertisement = ECRS_parseCharKeywordURI (ectx, COLLECTION);
+ GE_ASSERT (ectx, advertisement != NULL);
+ TIME (&now);
+ makeRandomId (&nextId);
+ rootURI = ECRS_createNamespace (ectx,
+ cfg,
+ name,
+ meta,
+ anonymityLevel,
+ prio,
+ get_time () + COLLECTION_ADV_LIFETIME,
+ advertisement, &nextId);
+ if (rootURI == NULL)
+ {
+ ECRS_freeUri (advertisement);
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ ECRS_freeUri (advertisement);
+ ECRS_freeUri (rootURI);
+ collectionData = MALLOC (sizeof (CollectionInfo));
+ memset (collectionData, 0, sizeof (CollectionInfo));
+ makeRandomId (&collectionData->data.lastId);
collectionData->data.nextId = nextId;
- collectionData->data.updateInterval
- = htonl(updateInterval);
- collectionData->data.anonymityLevel
- = htonl(anonymityLevel);
- collectionData->data.priority
- = htonl(prio);
- collectionData->meta
- = ECRS_dupMetaData(meta);
- collectionData->name
- = STRDUP(name);
- MUTEX_UNLOCK(lock);
+ collectionData->data.updateInterval = htonl (updateInterval);
+ collectionData->data.anonymityLevel = htonl (anonymityLevel);
+ collectionData->data.priority = htonl (prio);
+ collectionData->meta = ECRS_dupMetaData (meta);
+ collectionData->name = STRDUP (name);
+ MUTEX_UNLOCK (lock);
return OK;
}
@@ -488,29 +463,29 @@
*
* @return OK on success, SYSERR if no collection is active
*/
-int CO_stopCollection() {
+int
+CO_stopCollection ()
+{
unsigned int i;
- MUTEX_LOCK(lock);
- if (collectionData == NULL) {
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- ECRS_deleteNamespace(ectx,
- cfg,
- collectionData->name);
- ECRS_freeMetaData(collectionData->meta);
- for (i=0;i<collectionData->file_count;i++) {
- ECRS_freeMetaData(collectionData->files[i].meta);
- ECRS_freeUri(collectionData->files[i].uri);
- }
- GROW(collectionData->files,
- collectionData->file_count,
- 0);
- FREE(collectionData->name);
- FREE(collectionData);
+ MUTEX_LOCK (lock);
+ if (collectionData == NULL)
+ {
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ ECRS_deleteNamespace (ectx, cfg, collectionData->name);
+ ECRS_freeMetaData (collectionData->meta);
+ for (i = 0; i < collectionData->file_count; i++)
+ {
+ ECRS_freeMetaData (collectionData->files[i].meta);
+ ECRS_freeUri (collectionData->files[i].uri);
+ }
+ GROW (collectionData->files, collectionData->file_count, 0);
+ FREE (collectionData->name);
+ FREE (collectionData);
collectionData = NULL;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return OK;
}
@@ -519,16 +494,19 @@
*
* @return NULL if there is no collection, otherwise its name
*/
-char * CO_getCollection() {
- char * name;
+char *
+CO_getCollection ()
+{
+ char *name;
- MUTEX_LOCK(lock);
- if (collectionData == NULL) {
- MUTEX_UNLOCK(lock);
- return NULL;
- }
- name = STRDUP(collectionData->name);
- MUTEX_UNLOCK(lock);
+ MUTEX_LOCK (lock);
+ if (collectionData == NULL)
+ {
+ MUTEX_UNLOCK (lock);
+ return NULL;
+ }
+ name = STRDUP (collectionData->name);
+ MUTEX_UNLOCK (lock);
return name;
}
@@ -549,110 +527,107 @@
* explicit publication of an update at another
* time is desired.
*/
-void CO_publishCollectionNow() {
+void
+CO_publishCollectionNow ()
+{
HashCode512 delta;
TIME_T now;
- struct ECRS_URI * uri;
- struct ECRS_URI * directoryURI;
+ struct ECRS_URI *uri;
+ struct ECRS_URI *directoryURI;
unsigned long long dirLen;
- char * tmpName;
+ char *tmpName;
int fd;
- char * dirData;
+ char *dirData;
- MUTEX_LOCK(lock);
- if ( (collectionData == NULL) ||
- (collectionData->changed == NO) ) {
- MUTEX_UNLOCK(lock);
- return;
- }
- TIME(&now);
- if ( (ntohl(collectionData->data.updateInterval) != ECRS_SBLOCK_UPDATE_NONE)
&&
- (ntohl(collectionData->data.updateInterval) !=
ECRS_SBLOCK_UPDATE_SPORADIC) &&
- (ntohl(collectionData->data.lastPublication) +
ntohl(collectionData->data.updateInterval) < now) ) {
- MUTEX_UNLOCK(lock);
- return;
- }
- if ( (ntohl(collectionData->data.updateInterval) != ECRS_SBLOCK_UPDATE_NONE)
&&
- (ntohl(collectionData->data.updateInterval) !=
ECRS_SBLOCK_UPDATE_SPORADIC) ) {
- deltaId(&collectionData->data.nextId,
- &collectionData->data.lastId,
- &delta);
- collectionData->data.lastId = collectionData->data.nextId;
- addHashCodes(&collectionData->data.nextId,
- &delta,
- &collectionData->data.nextId);
- } else {
- collectionData->data.lastId = collectionData->data.nextId;
- makeRandomId(&collectionData->data.nextId);
- }
- tmpName = STRDUP("/tmp/gnunet-collectionXXXXXX");
- fd = mkstemp(tmpName);
- if (fd == -1) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "mkstemp");
- FREE(tmpName);
- MUTEX_UNLOCK(lock);
- return;
- }
+ MUTEX_LOCK (lock);
+ if ((collectionData == NULL) || (collectionData->changed == NO))
+ {
+ MUTEX_UNLOCK (lock);
+ return;
+ }
+ TIME (&now);
+ if ((ntohl (collectionData->data.updateInterval) != ECRS_SBLOCK_UPDATE_NONE)
+ && (ntohl (collectionData->data.updateInterval) !=
+ ECRS_SBLOCK_UPDATE_SPORADIC)
+ && (ntohl (collectionData->data.lastPublication) +
+ ntohl (collectionData->data.updateInterval) < now))
+ {
+ MUTEX_UNLOCK (lock);
+ return;
+ }
+ if ((ntohl (collectionData->data.updateInterval) != ECRS_SBLOCK_UPDATE_NONE)
+ && (ntohl (collectionData->data.updateInterval) !=
+ ECRS_SBLOCK_UPDATE_SPORADIC))
+ {
+ deltaId (&collectionData->data.nextId,
+ &collectionData->data.lastId, &delta);
+ collectionData->data.lastId = collectionData->data.nextId;
+ addHashCodes (&collectionData->data.nextId,
+ &delta, &collectionData->data.nextId);
+ }
+ else
+ {
+ collectionData->data.lastId = collectionData->data.nextId;
+ makeRandomId (&collectionData->data.nextId);
+ }
+ tmpName = STRDUP ("/tmp/gnunet-collectionXXXXXX");
+ fd = mkstemp (tmpName);
+ if (fd == -1)
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_ADMIN | GE_BULK, "mkstemp");
+ FREE (tmpName);
+ MUTEX_UNLOCK (lock);
+ return;
+ }
dirData = NULL;
- GE_ASSERT(ectx,
- OK == ECRS_createDirectory(ectx,
- &dirData,
- &dirLen,
- collectionData->file_count,
- collectionData->files,
- collectionData->meta));
- if (-1 == WRITE(fd,
- dirData,
- dirLen)) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "write");
- FREE(tmpName);
- FREE(dirData);
- MUTEX_UNLOCK(lock);
- return;
- }
- FREE(dirData);
- CLOSE(fd);
- if (OK != ECRS_uploadFile(ectx,
- cfg,
- tmpName,
- NO, /* indexing */
- ntohl(collectionData->data.anonymityLevel),
- ntohl(collectionData->data.priority),
- get_time() + COLLECTION_ADV_LIFETIME,
- NULL,
- NULL,
- NULL,
- NULL,
- &directoryURI)) {
- UNLINK(tmpName);
- FREE(tmpName);
- MUTEX_UNLOCK(lock);
- return;
- }
- UNLINK(tmpName);
- FREE(tmpName);
- uri = ECRS_addToNamespace(ectx,
- cfg,
- collectionData->name,
- ntohl(collectionData->data.anonymityLevel),
- ntohl(collectionData->data.priority),
- get_time() + COLLECTION_ADV_LIFETIME,
- now,
- ntohl(collectionData->data.updateInterval),
- &collectionData->data.lastId,
- &collectionData->data.nextId,
- directoryURI,
- collectionData->meta);
- if (uri != NULL) {
- collectionData->data.lastPublication = htonl(now);
- collectionData->changed = NO;
- ECRS_freeUri(uri);
- }
- MUTEX_UNLOCK(lock);
+ GE_ASSERT (ectx,
+ OK == ECRS_createDirectory (ectx,
+ &dirData,
+ &dirLen,
+ collectionData->file_count,
+ collectionData->files,
+ collectionData->meta));
+ if (-1 == WRITE (fd, dirData, dirLen))
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_ADMIN | GE_BULK, "write");
+ FREE (tmpName);
+ FREE (dirData);
+ MUTEX_UNLOCK (lock);
+ return;
+ }
+ FREE (dirData);
+ CLOSE (fd);
+ if (OK != ECRS_uploadFile (ectx, cfg, tmpName, NO, /* indexing */
+ ntohl (collectionData->data.anonymityLevel),
+ ntohl (collectionData->data.priority),
+ get_time () + COLLECTION_ADV_LIFETIME,
+ NULL, NULL, NULL, NULL, &directoryURI))
+ {
+ UNLINK (tmpName);
+ FREE (tmpName);
+ MUTEX_UNLOCK (lock);
+ return;
+ }
+ UNLINK (tmpName);
+ FREE (tmpName);
+ uri = ECRS_addToNamespace (ectx,
+ cfg,
+ collectionData->name,
+ ntohl (collectionData->data.anonymityLevel),
+ ntohl (collectionData->data.priority),
+ get_time () + COLLECTION_ADV_LIFETIME,
+ now,
+ ntohl (collectionData->data.updateInterval),
+ &collectionData->data.lastId,
+ &collectionData->data.nextId,
+ directoryURI, collectionData->meta);
+ if (uri != NULL)
+ {
+ collectionData->data.lastPublication = htonl (now);
+ collectionData->changed = NO;
+ ECRS_freeUri (uri);
+ }
+ MUTEX_UNLOCK (lock);
}
/**
@@ -668,39 +643,43 @@
* inserting files using libECRS directly or need other
* ways to explicitly extend a collection.
*/
-void CO_publishToCollection(const ECRS_FileInfo * fi) {
+void
+CO_publishToCollection (const ECRS_FileInfo * fi)
+{
unsigned int i;
ECRS_FileInfo fc;
- if ((ECRS_isKeywordUri(fi->uri))) {
- GE_BREAK(ectx, 0);
- return;
- }
- if (lock == NULL) {
- GE_BREAK(ectx, 0);
- return;
- }
- MUTEX_LOCK(lock);
- if (collectionData == NULL) {
- MUTEX_UNLOCK(lock);
- return;
- }
- for (i=0;i<collectionData->file_count;i++) {
- if (ECRS_equalsUri(fi->uri,
- collectionData->files[i].uri)) {
- MUTEX_UNLOCK(lock);
+ if ((ECRS_isKeywordUri (fi->uri)))
+ {
+ GE_BREAK (ectx, 0);
return;
}
- }
- fc.uri = ECRS_dupUri(fi->uri);
- fc.meta = ECRS_dupMetaData(fi->meta);
- APPEND(collectionData->files,
- collectionData->file_count,
- fc);
+ if (lock == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return;
+ }
+ MUTEX_LOCK (lock);
+ if (collectionData == NULL)
+ {
+ MUTEX_UNLOCK (lock);
+ return;
+ }
+ for (i = 0; i < collectionData->file_count; i++)
+ {
+ if (ECRS_equalsUri (fi->uri, collectionData->files[i].uri))
+ {
+ MUTEX_UNLOCK (lock);
+ return;
+ }
+ }
+ fc.uri = ECRS_dupUri (fi->uri);
+ fc.meta = ECRS_dupMetaData (fi->meta);
+ APPEND (collectionData->files, collectionData->file_count, fc);
collectionData->changed = YES;
- if (ntohl(collectionData->data.updateInterval) == ECRS_SBLOCK_UPDATE_NONE)
- CO_publishCollectionNow();
- MUTEX_UNLOCK(lock);
+ if (ntohl (collectionData->data.updateInterval) == ECRS_SBLOCK_UPDATE_NONE)
+ CO_publishCollectionNow ();
+ MUTEX_UNLOCK (lock);
}
/* end of collection.c */
Modified: GNUnet/src/applications/fs/collection/collectiontest.c
===================================================================
--- GNUnet/src/applications/fs/collection/collectiontest.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/fs/collection/collectiontest.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -34,90 +34,80 @@
#define START_DAEMON 1
-int main(int argc,
- char * argv[]){
- struct GC_Configuration * cfg;
+int
+main (int argc, char *argv[])
+{
+ struct GC_Configuration *cfg;
#if START_DAEMON
pid_t daemon;
#endif
int ok;
- struct ClientServerConnection * sock;
- struct ECRS_MetaData * meta;
+ struct ClientServerConnection *sock;
+ struct ECRS_MetaData *meta;
ECRS_FileInfo fi;
- char * have;
+ char *have;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
sock = NULL;
meta = NULL;
#if START_DAEMON
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
- CHECK(OK == connection_wait_for_running(NULL,
- cfg,
- 300 * cronSECONDS));
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
+ CHECK (OK == connection_wait_for_running (NULL, cfg, 300 * cronSECONDS));
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
#endif
ok = YES;
- meta = ECRS_createMetaData();
- ECRS_addToMetaData(meta,
- EXTRACTOR_MIMETYPE,
- "test/foo");
- sock = client_connection_create(NULL, cfg);
- CHECK(sock != NULL);
- CO_init(NULL, cfg);
+ meta = ECRS_createMetaData ();
+ ECRS_addToMetaData (meta, EXTRACTOR_MIMETYPE, "test/foo");
+ sock = client_connection_create (NULL, cfg);
+ CHECK (sock != NULL);
+ CO_init (NULL, cfg);
/* ACTUAL TEST CODE */
- CO_stopCollection();
- ECRS_deleteNamespace(NULL,
- cfg,
- "test-collection");
- CHECK(NULL == CO_getCollection());
- CHECK(OK == CO_startCollection(1,
- 100,
- 60, /* 60s */
- "test-collection",
- meta));
- have = CO_getCollection();
- CHECK(NULL != have);
- CHECK(0 == strcmp(have, "test-collection"));
- FREE(have);
+ CO_stopCollection ();
+ ECRS_deleteNamespace (NULL, cfg, "test-collection");
+ CHECK (NULL == CO_getCollection ());
+ CHECK (OK == CO_startCollection (1, 100, 60, /* 60s */
+ "test-collection", meta));
+ have = CO_getCollection ();
+ CHECK (NULL != have);
+ CHECK (0 == strcmp (have, "test-collection"));
+ FREE (have);
fi.meta = meta;
- fi.uri = ECRS_stringToUri(NULL,
"gnunet://ecrs/chk/0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0");
- CO_publishToCollection(&fi);
- ECRS_freeUri(fi.uri);
- CO_done();
- CO_init(NULL, cfg);
- have = CO_getCollection();
- CHECK(NULL != have);
- CHECK(0 == strcmp(have, "test-collection"));
- FREE(have);
- CO_publishCollectionNow();
- CO_stopCollection();
- ECRS_deleteNamespace(NULL,
- cfg,
- "test-collection");
- CHECK(NULL == CO_getCollection());
+ fi.uri =
+ ECRS_stringToUri (NULL,
+
"gnunet://ecrs/chk/0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0");
+ CO_publishToCollection (&fi);
+ ECRS_freeUri (fi.uri);
+ CO_done ();
+ CO_init (NULL, cfg);
+ have = CO_getCollection ();
+ CHECK (NULL != have);
+ CHECK (0 == strcmp (have, "test-collection"));
+ FREE (have);
+ CO_publishCollectionNow ();
+ CO_stopCollection ();
+ ECRS_deleteNamespace (NULL, cfg, "test-collection");
+ CHECK (NULL == CO_getCollection ());
/* END OF TEST CODE */
- FAILURE:
- if (sock != NULL) {
- CO_done();
- connection_destroy(sock);
- }
+FAILURE:
+ if (sock != NULL)
+ {
+ CO_done ();
+ connection_destroy (sock);
+ }
if (meta != NULL)
- ECRS_freeMetaData(meta);
+ ECRS_freeMetaData (meta);
#if START_DAEMON
- GE_ASSERT(NULL, OK == os_daemon_stop(NULL, daemon));
+ GE_ASSERT (NULL, OK == os_daemon_stop (NULL, daemon));
#endif
- GC_free(cfg);
+ GC_free (cfg);
return (ok == YES) ? 0 : 1;
}
Modified: GNUnet/src/applications/fs/ecrs/bincoder.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/bincoder.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/bincoder.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -28,15 +28,18 @@
/**
* 64 characters for encoding, 6 bits per character
*/
-static char * encTable__ =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=";
+static char *encTable__ =
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=";
-static unsigned int getValue__(unsigned char a) {
- if ( (a >= '0') && (a <= '9') )
+static unsigned int
+getValue__ (unsigned char a)
+{
+ if ((a >= '0') && (a <= '9'))
return a - '0';
- if ( (a >= 'A') && (a <= 'Z') )
+ if ((a >= 'A') && (a <= 'Z'))
return (a - 'A' + 10);
- if ( (a >= 'a') && (a <= 'z') )
+ if ((a >= 'a') && (a <= 'z'))
return (a - 'a' + 36);
if (a == '_')
return 62;
@@ -44,38 +47,41 @@
return 63;
return -1;
}
+
/**
* Convert binary data to a string.
*
* @return converted data
*/
static char *
-bin2enc(const void * data,
- size_t size) {
+bin2enc (const void *data, size_t size)
+{
size_t len;
size_t pos;
unsigned int bits;
unsigned int hbits;
- char * ret;
+ char *ret;
- GE_ASSERT(NULL, strlen(encTable__) == 64);
+ GE_ASSERT (NULL, strlen (encTable__) == 64);
len = size * 8 / 6;
if (((size * 8) % 6) != 0)
len++;
- ret = MALLOC(len+1);
+ ret = MALLOC (len + 1);
ret[len] = '\0';
len = 0;
bits = 0;
hbits = 0;
- for (pos=0;pos<size;pos++) {
- bits |= ((((const unsigned char*)data)[pos]) << hbits);
- hbits += 8;
- while (hbits >= 6) {
- ret[len++] = encTable__[bits & 63];
- bits >>= 6;
- hbits -= 6;
+ for (pos = 0; pos < size; pos++)
+ {
+ bits |= ((((const unsigned char *) data)[pos]) << hbits);
+ hbits += 8;
+ while (hbits >= 6)
+ {
+ ret[len++] = encTable__[bits & 63];
+ bits >>= 6;
+ hbits -= 6;
+ }
}
- }
if (hbits > 0)
ret[len++] = encTable__[bits & 63];
return ret;
@@ -92,9 +98,8 @@
* -1 on error
*/
static int
-enc2bin(const char * input,
- void * data,
- size_t size) {
+enc2bin (const char *input, void *data, size_t size)
+{
size_t len;
size_t pos;
unsigned int bits;
@@ -103,20 +108,22 @@
len = size * 8 / 6;
if (((size * 8) % 6) != 0)
len++;
- if (strlen(input) < len)
- return -1; /* error! */
+ if (strlen (input) < len)
+ return -1; /* error! */
bits = 0;
hbits = 0;
len = 0;
pos = 0;
- for (pos=0;pos<size;pos++) {
- while (hbits < 8) {
- bits |= (getValue__(input[len++]) << hbits);
- hbits += 6;
+ for (pos = 0; pos < size; pos++)
+ {
+ while (hbits < 8)
+ {
+ bits |= (getValue__ (input[len++]) << hbits);
+ hbits += 6;
+ }
+ (((unsigned char *) data)[pos]) = (unsigned char) bits;
+ bits >>= 8;
+ hbits -= 8;
}
- (((unsigned char*)data)[pos]) = (unsigned char) bits;
- bits >>= 8;
- hbits -= 8;
- }
return len;
}
Modified: GNUnet/src/applications/fs/ecrs/bincodertest.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/bincodertest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/ecrs/bincodertest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -29,34 +29,36 @@
#include "bincoder.c"
-static int testBC(int i) {
- char * orig;
- char * enc;
+static int
+testBC (int i)
+{
+ char *orig;
+ char *enc;
char dec[256];
int ret;
- orig = MALLOC(i);
- memset(orig, i, i);
- enc = bin2enc(orig, i);
- ret = enc2bin(enc,
- dec,
- i);
- if ( (ret != strlen(enc)) ||
- (0 != memcmp(orig, dec, i)) ) {
- printf("Failed in iteration %d\n", i);
- ret = -1;
- }
- FREE(enc);
- FREE(orig);
+ orig = MALLOC (i);
+ memset (orig, i, i);
+ enc = bin2enc (orig, i);
+ ret = enc2bin (enc, dec, i);
+ if ((ret != strlen (enc)) || (0 != memcmp (orig, dec, i)))
+ {
+ printf ("Failed in iteration %d\n", i);
+ ret = -1;
+ }
+ FREE (enc);
+ FREE (orig);
return ret != -1 ? 0 : 1;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
int i;
- for (i=0;i<256;i++)
- failureCount += testBC(i);
+ for (i = 0; i < 256; i++)
+ failureCount += testBC (i);
if (failureCount != 0)
return 1;
return 0;
Modified: GNUnet/src/applications/fs/ecrs/directory.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/directory.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/directory.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -49,12 +49,13 @@
* @return number of entries on success, SYSERR if the
* directory is malformed
*/
-int ECRS_listDirectory(struct GE_Context * ectx,
- const char * data,
- unsigned long long len,
- struct ECRS_MetaData ** md,
- ECRS_SearchProgressCallback spcb,
- void * spcbClosure) {
+int
+ECRS_listDirectory (struct GE_Context *ectx,
+ const char *data,
+ unsigned long long len,
+ struct ECRS_MetaData **md,
+ ECRS_SearchProgressCallback spcb, void *spcbClosure)
+{
unsigned long long pos;
unsigned long long align;
unsigned int mdSize;
@@ -65,90 +66,87 @@
count = 0;
*md = NULL;
pos = 0;
- if ( (len >= 8 + sizeof(unsigned int)) &&
- (0 == memcmp(data,
- GNUNET_DIRECTORY_MAGIC,
- 8)) ) {
- memcpy(&mdSize,
- &data[8],
- sizeof(unsigned int));
- mdSize = ntohl(mdSize);
- if (mdSize > len - 8 - sizeof(unsigned int) )
- return SYSERR; /* invalid size */
- *md = ECRS_deserializeMetaData(ectx,
- &data[8 + sizeof(unsigned int)],
- mdSize);
- if (*md == NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR; /* malformed !*/
+ if ((len >= 8 + sizeof (unsigned int)) &&
+ (0 == memcmp (data, GNUNET_DIRECTORY_MAGIC, 8)))
+ {
+ memcpy (&mdSize, &data[8], sizeof (unsigned int));
+ mdSize = ntohl (mdSize);
+ if (mdSize > len - 8 - sizeof (unsigned int))
+ return SYSERR; /* invalid size */
+ *md = ECRS_deserializeMetaData (ectx,
+ &data[8 + sizeof (unsigned int)],
+ mdSize);
+ if (*md == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR; /* malformed ! */
+ }
+ pos = 8 + sizeof (unsigned int) + mdSize;
}
- pos = 8 + sizeof(unsigned int) + mdSize;
- }
- while (pos < len) {
- /* find end of URI */
- if (data[pos] == '\0') {
- /* URI is never empty, must be end of block,
- skip to next alignment */
- align = ((pos / BLOCK_ALIGN_SIZE)+1) * BLOCK_ALIGN_SIZE;
- if (align == pos) {
- /* if we were already aligned, still skip a block! */
- align += BLOCK_ALIGN_SIZE;
- }
- pos = align;
- if (pos >= len) {
- /* malformed - or partial download... */
- break;
- }
- }
- epos = pos;
- while ( (epos < len) &&
- (data[epos] != '\0') )
- epos++;
- if (epos >= len)
- return SYSERR; /* malformed - or partial download */
+ while (pos < len)
+ {
+ /* find end of URI */
+ if (data[pos] == '\0')
+ {
+ /* URI is never empty, must be end of block,
+ skip to next alignment */
+ align = ((pos / BLOCK_ALIGN_SIZE) + 1) * BLOCK_ALIGN_SIZE;
+ if (align == pos)
+ {
+ /* if we were already aligned, still skip a block! */
+ align += BLOCK_ALIGN_SIZE;
+ }
+ pos = align;
+ if (pos >= len)
+ {
+ /* malformed - or partial download... */
+ break;
+ }
+ }
+ epos = pos;
+ while ((epos < len) && (data[epos] != '\0'))
+ epos++;
+ if (epos >= len)
+ return SYSERR; /* malformed - or partial download */
- fi.uri = ECRS_stringToUri(ectx,
- &data[pos]);
- pos = epos+1;
- if (fi.uri == NULL) {
- pos--; /* go back to '\0' to force going to next alignment */
- continue;
- }
- if (ECRS_isKeywordUri(fi.uri)) {
- ECRS_freeUri(fi.uri);
- GE_BREAK(ectx, 0);
- return SYSERR; /* illegal in directory! */
- }
+ fi.uri = ECRS_stringToUri (ectx, &data[pos]);
+ pos = epos + 1;
+ if (fi.uri == NULL)
+ {
+ pos--; /* go back to '\0' to force going to next
alignment */
+ continue;
+ }
+ if (ECRS_isKeywordUri (fi.uri))
+ {
+ ECRS_freeUri (fi.uri);
+ GE_BREAK (ectx, 0);
+ return SYSERR; /* illegal in directory! */
+ }
- memcpy(&mdSize,
- &data[pos],
- sizeof(unsigned int));
- mdSize = ntohl(mdSize);
+ memcpy (&mdSize, &data[pos], sizeof (unsigned int));
+ mdSize = ntohl (mdSize);
- pos += sizeof(unsigned int);
- if (pos + mdSize > len) {
- ECRS_freeUri(fi.uri);
- return SYSERR; /* malformed - or partial download */
- }
+ pos += sizeof (unsigned int);
+ if (pos + mdSize > len)
+ {
+ ECRS_freeUri (fi.uri);
+ return SYSERR; /* malformed - or partial download */
+ }
- fi.meta = ECRS_deserializeMetaData(ectx,
- &data[pos],
- mdSize);
- if (fi.meta == NULL) {
- ECRS_freeUri(fi.uri);
- GE_BREAK(ectx, 0);
- return SYSERR; /* malformed !*/
+ fi.meta = ECRS_deserializeMetaData (ectx, &data[pos], mdSize);
+ if (fi.meta == NULL)
+ {
+ ECRS_freeUri (fi.uri);
+ GE_BREAK (ectx, 0);
+ return SYSERR; /* malformed ! */
+ }
+ pos += mdSize;
+ count++;
+ if (spcb != NULL)
+ spcb (&fi, NULL, NO, spcbClosure);
+ ECRS_freeMetaData (fi.meta);
+ ECRS_freeUri (fi.uri);
}
- pos += mdSize;
- count++;
- if (spcb != NULL)
- spcb(&fi,
- NULL,
- NO,
- spcbClosure);
- ECRS_freeMetaData(fi.meta);
- ECRS_freeUri(fi.uri);
- }
return count;
}
@@ -158,13 +156,12 @@
* after alignment to the BLOCK_ALIGN_SIZE.
*/
static unsigned long long
-do_align(unsigned long long start_position,
- unsigned long long end_position) {
+do_align (unsigned long long start_position, unsigned long long end_position)
+{
unsigned long long align;
align = (end_position / BLOCK_ALIGN_SIZE) * BLOCK_ALIGN_SIZE;
- if ( (start_position < align) &&
- (end_position > align) )
+ if ((start_position < align) && (end_position > align))
return align + end_position - start_position;
return end_position;
}
@@ -178,10 +175,10 @@
* @param sizes the sizes of the individual blocks
* @param perm the permutation of the blocks (updated)
*/
-static void block_align(unsigned long long start,
- unsigned int count,
- const unsigned long long * sizes,
- int * perm) {
+static void
+block_align (unsigned long long start,
+ unsigned int count, const unsigned long long *sizes, int *perm)
+{
int i;
int j;
int tmp;
@@ -193,37 +190,48 @@
int cval;
cpos = start;
- for (i=0;i<count;i++) {
- start = cpos;
- badness = 0x7FFFFFFF;
- best = -1;
- for (j=i;j<count;j++) {
- cval = perm[j];
- cend = cpos + sizes[cval];
- if (cpos % BLOCK_ALIGN_SIZE == 0) {
- /* prefer placing the largest blocks first */
- cbad = - (cend % BLOCK_ALIGN_SIZE);
- } else {
- if (cpos / BLOCK_ALIGN_SIZE == cend / BLOCK_ALIGN_SIZE) {
- /* Data fits into the same block! Prefer small left-overs! */
- cbad = BLOCK_ALIGN_SIZE - cend % BLOCK_ALIGN_SIZE;
- } else {
- /* Would have to waste space to re-align, add big factor, this
- case is a real loss (proportional to space wasted)! */
- cbad = BLOCK_ALIGN_SIZE * (BLOCK_ALIGN_SIZE - cpos % BLOCK_ALIGN_SIZE);
- }
- }
- if (cbad < badness) {
- best = j;
- badness = cbad;
- }
+ for (i = 0; i < count; i++)
+ {
+ start = cpos;
+ badness = 0x7FFFFFFF;
+ best = -1;
+ for (j = i; j < count; j++)
+ {
+ cval = perm[j];
+ cend = cpos + sizes[cval];
+ if (cpos % BLOCK_ALIGN_SIZE == 0)
+ {
+ /* prefer placing the largest blocks first */
+ cbad = -(cend % BLOCK_ALIGN_SIZE);
+ }
+ else
+ {
+ if (cpos / BLOCK_ALIGN_SIZE == cend / BLOCK_ALIGN_SIZE)
+ {
+ /* Data fits into the same block! Prefer small left-overs! */
+ cbad = BLOCK_ALIGN_SIZE - cend % BLOCK_ALIGN_SIZE;
+ }
+ else
+ {
+ /* Would have to waste space to re-align, add big factor,
this
+ case is a real loss (proportional to space wasted)! */
+ cbad =
+ BLOCK_ALIGN_SIZE * (BLOCK_ALIGN_SIZE -
+ cpos % BLOCK_ALIGN_SIZE);
+ }
+ }
+ if (cbad < badness)
+ {
+ best = j;
+ badness = cbad;
+ }
+ }
+ tmp = perm[i];
+ perm[i] = perm[best];
+ perm[best] = tmp;
+ cpos += sizes[perm[i]];
+ cpos = do_align (start, cpos);
}
- tmp = perm[i];
- perm[i] = perm[best];
- perm[best] = tmp;
- cpos += sizes[perm[i]];
- cpos = do_align(start, cpos);
- }
}
/**
@@ -250,116 +258,107 @@
* is extended with the mime-type for a GNUnet directory.
* @return OK on success, SYSERR on error
*/
-int ECRS_createDirectory(struct GE_Context * ectx,
- char ** data,
- unsigned long long * len,
- unsigned int count,
- const ECRS_FileInfo * fis,
- struct ECRS_MetaData * meta) {
+int
+ECRS_createDirectory (struct GE_Context *ectx,
+ char **data,
+ unsigned long long *len,
+ unsigned int count,
+ const ECRS_FileInfo * fis, struct ECRS_MetaData *meta)
+{
int i;
int j;
unsigned long long psize;
unsigned long long size;
unsigned long long pos;
- char ** ucs;
+ char **ucs;
int ret;
- unsigned long long * sizes;
- int * perm;
+ unsigned long long *sizes;
+ int *perm;
- for (i=0;i<count;i++) {
- if (ECRS_isKeywordUri(fis[i].uri)) {
- GE_BREAK(ectx, 0);
- return SYSERR; /* illegal in directory! */
+ for (i = 0; i < count; i++)
+ {
+ if (ECRS_isKeywordUri (fis[i].uri))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR; /* illegal in directory! */
+ }
}
- }
- ucs = MALLOC(sizeof(char*) * count);
- size = 8 + sizeof(unsigned int);
- size += ECRS_sizeofMetaData(meta,
- ECRS_SERIALIZE_FULL);
- sizes = MALLOC(count * sizeof(unsigned long long));
- perm = MALLOC(count * sizeof(int));
- for (i=0;i<count;i++) {
- perm[i] = i;
- ucs[i] = ECRS_uriToString(fis[i].uri);
- GE_ASSERT(ectx,
- ucs[i] != NULL);
- psize = ECRS_sizeofMetaData(fis[i].meta,
- ECRS_SERIALIZE_FULL);
- if (psize == -1) {
- GE_BREAK(ectx, 0);
- FREE(sizes);
- FREE(perm);
- while (i>=0)
- FREE(ucs[i--]);
- FREE(ucs);
- return SYSERR;
+ ucs = MALLOC (sizeof (char *) * count);
+ size = 8 + sizeof (unsigned int);
+ size += ECRS_sizeofMetaData (meta, ECRS_SERIALIZE_FULL);
+ sizes = MALLOC (count * sizeof (unsigned long long));
+ perm = MALLOC (count * sizeof (int));
+ for (i = 0; i < count; i++)
+ {
+ perm[i] = i;
+ ucs[i] = ECRS_uriToString (fis[i].uri);
+ GE_ASSERT (ectx, ucs[i] != NULL);
+ psize = ECRS_sizeofMetaData (fis[i].meta, ECRS_SERIALIZE_FULL);
+ if (psize == -1)
+ {
+ GE_BREAK (ectx, 0);
+ FREE (sizes);
+ FREE (perm);
+ while (i >= 0)
+ FREE (ucs[i--]);
+ FREE (ucs);
+ return SYSERR;
+ }
+ sizes[i] = psize + sizeof (unsigned int) + strlen (ucs[i]) + 1;
}
- sizes[i] = psize + sizeof(unsigned int) + strlen(ucs[i]) + 1;
- }
/* permutate entries to minimize alignment cost */
- block_align(size,
- count,
- sizes,
- perm);
+ block_align (size, count, sizes, perm);
/* compute final size with alignment */
- for (i=0;i<count;i++) {
- psize = size;
- size += sizes[perm[i]];
- size = do_align(psize,
- size);
- }
+ for (i = 0; i < count; i++)
+ {
+ psize = size;
+ size += sizes[perm[i]];
+ size = do_align (psize, size);
+ }
*len = size;
- *data = MALLOC(size);
- memset(*data, 0, size);
+ *data = MALLOC (size);
+ memset (*data, 0, size);
pos = 8;
- memcpy(*data,
- GNUNET_DIRECTORY_MAGIC,
- 8);
+ memcpy (*data, GNUNET_DIRECTORY_MAGIC, 8);
- ret = ECRS_serializeMetaData(ectx,
- meta,
- &(*data)[pos + sizeof(unsigned int)],
- size - pos - sizeof(unsigned int),
- ECRS_SERIALIZE_FULL);
- GE_ASSERT(ectx, ret != SYSERR);
- ret = htonl(ret);
- memcpy(&(*data)[pos],
- &ret,
- sizeof(unsigned int));
- pos += ntohl(ret) + sizeof(unsigned int);
+ ret = ECRS_serializeMetaData (ectx,
+ meta,
+ &(*data)[pos + sizeof (unsigned int)],
+ size - pos - sizeof (unsigned int),
+ ECRS_SERIALIZE_FULL);
+ GE_ASSERT (ectx, ret != SYSERR);
+ ret = htonl (ret);
+ memcpy (&(*data)[pos], &ret, sizeof (unsigned int));
+ pos += ntohl (ret) + sizeof (unsigned int);
- for (j=0;j<count;j++) {
- i = perm[j];
- psize = pos;
- pos += sizes[i];
- pos = do_align(psize, pos);
- pos -= sizes[i]; /* go back to beginning */
- memcpy(&(*data)[pos],
- ucs[i],
- strlen(ucs[i]) + 1);
- pos += strlen(ucs[i]) + 1;
- FREE(ucs[i]);
- ret = ECRS_serializeMetaData(ectx,
- fis[i].meta,
- &(*data)[pos + sizeof(unsigned int)],
- size - pos - sizeof(unsigned int),
- ECRS_SERIALIZE_FULL);
- GE_ASSERT(ectx, ret != SYSERR);
- ret = htonl(ret);
- memcpy(&(*data)[pos],
- &ret,
- sizeof(unsigned int));
- pos += ntohl(ret) + sizeof(unsigned int);
- }
- FREE(sizes);
- FREE(perm);
- FREE(ucs);
- GE_ASSERT(ectx, pos == size);
+ for (j = 0; j < count; j++)
+ {
+ i = perm[j];
+ psize = pos;
+ pos += sizes[i];
+ pos = do_align (psize, pos);
+ pos -= sizes[i]; /* go back to beginning */
+ memcpy (&(*data)[pos], ucs[i], strlen (ucs[i]) + 1);
+ pos += strlen (ucs[i]) + 1;
+ FREE (ucs[i]);
+ ret = ECRS_serializeMetaData (ectx,
+ fis[i].meta,
+ &(*data)[pos + sizeof (unsigned int)],
+ size - pos - sizeof (unsigned int),
+ ECRS_SERIALIZE_FULL);
+ GE_ASSERT (ectx, ret != SYSERR);
+ ret = htonl (ret);
+ memcpy (&(*data)[pos], &ret, sizeof (unsigned int));
+ pos += ntohl (ret) + sizeof (unsigned int);
+ }
+ FREE (sizes);
+ FREE (perm);
+ FREE (ucs);
+ GE_ASSERT (ectx, pos == size);
return OK;
}
/* end of directory.c */
-
Modified: GNUnet/src/applications/fs/ecrs/directorytest.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/directorytest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/ecrs/directorytest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -32,38 +32,42 @@
#define ABORT() { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__);
return 1; }
-struct PCLS {
- ECRS_FileInfo * fi;
+struct PCLS
+{
+ ECRS_FileInfo *fi;
unsigned int pos;
unsigned int max;
};
-static int processor(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * cls) {
- struct PCLS * p = cls;
+static int
+processor (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *cls)
+{
+ struct PCLS *p = cls;
int i;
- for (i=0;i<p->max;i++) {
- if (ECRS_equalsMetaData(p->fi[i].meta,
- fi->meta) &&
- ECRS_equalsUri(p->fi[i].uri,
- fi->uri)) {
- p->pos++;
- return OK;
+ for (i = 0; i < p->max; i++)
+ {
+ if (ECRS_equalsMetaData (p->fi[i].meta,
+ fi->meta) &&
+ ECRS_equalsUri (p->fi[i].uri, fi->uri))
+ {
+ p->pos++;
+ return OK;
+ }
}
- }
- fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__);
+ fprintf (stderr, "Error at %s:%d\n", __FILE__, __LINE__);
return SYSERR;
}
-static int testDirectory(unsigned int i) {
- char * data;
+static int
+testDirectory (unsigned int i)
+{
+ char *data;
unsigned long long dlen;
- ECRS_FileInfo * fis;
- struct ECRS_MetaData * meta;
- struct ECRS_MetaData * meta2;
+ ECRS_FileInfo *fis;
+ struct ECRS_MetaData *meta;
+ struct ECRS_MetaData *meta2;
struct PCLS cls;
int p;
int q;
@@ -72,92 +76,86 @@
int ret = 0;
cls.max = i;
- fis = MALLOC(sizeof(ECRS_FileInfo) * i);
- for (p=0;p<i;p++) {
- fis[p].meta = ECRS_createMetaData();
- for (q=0;q<=p;q++) {
- SNPRINTF(txt,
- 128,
- "%u -- %u\n",
- p, q);
- ECRS_addToMetaData(fis[p].meta,
- q % EXTRACTOR_getHighestKeywordTypeNumber(),
- txt);
+ fis = MALLOC (sizeof (ECRS_FileInfo) * i);
+ for (p = 0; p < i; p++)
+ {
+ fis[p].meta = ECRS_createMetaData ();
+ for (q = 0; q <= p; q++)
+ {
+ SNPRINTF (txt, 128, "%u -- %u\n", p, q);
+ ECRS_addToMetaData (fis[p].meta,
+ q % EXTRACTOR_getHighestKeywordTypeNumber (),
+ txt);
+ }
+ SNPRINTF (uri,
+ 512,
+
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.%u",
+ p);
+ fis[p].uri = ECRS_stringToUri (NULL, uri);
+ if (fis[p].uri == NULL)
+ {
+ ECRS_freeMetaData (fis[p].meta);
+ while (--p > 0)
+ {
+ ECRS_freeMetaData (fis[p].meta);
+ ECRS_freeUri (fis[p].uri);
+ }
+ FREE (fis);
+ ABORT (); /* error in testcase */
+ }
}
- SNPRINTF(uri,
- 512,
-
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.%u",
- p);
- fis[p].uri = ECRS_stringToUri(NULL, uri);
- if (fis[p].uri == NULL) {
- ECRS_freeMetaData(fis[p].meta);
- while (--p > 0) {
- ECRS_freeMetaData(fis[p].meta);
- ECRS_freeUri(fis[p].uri);
- }
- FREE(fis);
- ABORT(); /* error in testcase */
+ meta = ECRS_createMetaData ();
+ ECRS_addToMetaData (meta, EXTRACTOR_TITLE, "A title");
+ ECRS_addToMetaData (meta, EXTRACTOR_AUTHOR, "An author");
+ if (OK != ECRS_createDirectory (NULL, &data, &dlen, i, fis, meta))
+ {
+ ECRS_freeMetaData (meta);
+ for (p = 0; p < i; p++)
+ {
+ ECRS_freeMetaData (fis[p].meta);
+ ECRS_freeUri (fis[p].uri);
+ }
+ FREE (fis);
+ ABORT ();
}
- }
- meta = ECRS_createMetaData();
- ECRS_addToMetaData(meta,
- EXTRACTOR_TITLE,
- "A title");
- ECRS_addToMetaData(meta,
- EXTRACTOR_AUTHOR,
- "An author");
- if (OK != ECRS_createDirectory(NULL,
- &data,
- &dlen,
- i,
- fis,
- meta)) {
- ECRS_freeMetaData(meta);
- for (p=0;p<i;p++) {
- ECRS_freeMetaData(fis[p].meta);
- ECRS_freeUri(fis[p].uri);
- }
- FREE(fis);
- ABORT();
- }
cls.pos = 0;
cls.fi = fis;
- if (i != ECRS_listDirectory(NULL,
- data,
- dlen,
- &meta2,
- &processor,
- &cls)) {
- printf("expected %u\n", i);
- ret = 1;
- goto END;
- }
- if (! ECRS_equalsMetaData(meta,
- meta2)) {
- ret = 1;
- goto END;
- }
- END:
- FREE(data);
- ECRS_freeMetaData(meta);
- ECRS_freeMetaData(meta2);
- for (p=0;p<i;p++) {
- ECRS_freeMetaData(fis[p].meta);
- ECRS_freeUri(fis[p].uri);
- }
- FREE(fis);
+ if (i != ECRS_listDirectory (NULL, data, dlen, &meta2, &processor, &cls))
+ {
+ printf ("expected %u\n", i);
+ ret = 1;
+ goto END;
+ }
+ if (!ECRS_equalsMetaData (meta, meta2))
+ {
+ ret = 1;
+ goto END;
+ }
+END:
+ FREE (data);
+ ECRS_freeMetaData (meta);
+ ECRS_freeMetaData (meta2);
+ for (p = 0; p < i; p++)
+ {
+ ECRS_freeMetaData (fis[p].meta);
+ ECRS_freeUri (fis[p].uri);
+ }
+ FREE (fis);
return ret;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
int i;
- for (i=17;i<2000;i*=2) {
- fprintf(stderr, ".");
- failureCount += testDirectory(i);
- }
- fprintf(stderr, "\n");
+ for (i = 17; i < 2000; i *= 2)
+ {
+ fprintf (stderr, ".");
+ failureCount += testDirectory (i);
+ }
+ fprintf (stderr, "\n");
if (failureCount == 0)
return 0;
Modified: GNUnet/src/applications/fs/ecrs/download.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/download.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/download.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -64,24 +64,25 @@
* provide a different mechanism (other than files on the drive) to
* cache the IBlocks.
*/
-typedef struct IOContext {
+typedef struct IOContext
+{
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
/**
* A lock for synchronizing access.
*/
- struct MUTEX * lock;
+ struct MUTEX *lock;
/**
* The file handles for each level in the tree.
*/
- int * handles;
+ int *handles;
/**
* The base-filename
*/
- char * filename;
+ char *filename;
/**
* The depth of the file-tree.
@@ -101,34 +102,39 @@
* are unlinked (removed), set to NO if the download
* is not complete and may be resumed later.
*/
-static void freeIOC(IOContext * this,
- int unlinkTreeFiles) {
+static void
+freeIOC (IOContext * this, int unlinkTreeFiles)
+{
int i;
- char * fn;
+ char *fn;
- for (i=0;i<=this->treedepth;i++) {
- if (this->handles[i] != -1) {
- CLOSE(this->handles[i]);
- this->handles[i] = -1;
+ for (i = 0; i <= this->treedepth; i++)
+ {
+ if (this->handles[i] != -1)
+ {
+ CLOSE (this->handles[i]);
+ this->handles[i] = -1;
+ }
}
- }
- MUTEX_DESTROY(this->lock);
- if (YES == unlinkTreeFiles) {
- for (i=1;i<=this->treedepth;i++) {
- fn = MALLOC(strlen(this->filename) + 3);
- strcpy(fn, this->filename);
- strcat(fn, ".A");
- fn[strlen(fn)-1]+=i;
- if (0 != UNLINK(fn))
- GE_LOG(this->ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Could not unlink temporary file `%s': %s\n"),
- fn, STRERROR(errno));
- FREE(fn);
+ MUTEX_DESTROY (this->lock);
+ if (YES == unlinkTreeFiles)
+ {
+ for (i = 1; i <= this->treedepth; i++)
+ {
+ fn = MALLOC (strlen (this->filename) + 3);
+ strcpy (fn, this->filename);
+ strcat (fn, ".A");
+ fn[strlen (fn) - 1] += i;
+ if (0 != UNLINK (fn))
+ GE_LOG (this->ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Could not unlink temporary file `%s': %s\n"),
+ fn, STRERROR (errno));
+ FREE (fn);
+ }
}
- }
- FREE(this->filename);
- FREE(this->handles);
+ FREE (this->filename);
+ FREE (this->handles);
}
/**
@@ -140,57 +146,61 @@
* @param filename the name of the level-0 file
* @return OK on success, SYSERR on failure
*/
-static int createIOContext(struct GE_Context * ectx,
- IOContext * this,
- int no_temporaries,
- unsigned long long filesize,
- const char * filename) {
+static int
+createIOContext (struct GE_Context *ectx,
+ IOContext * this,
+ int no_temporaries,
+ unsigned long long filesize, const char *filename)
+{
int i;
- char * fn;
+ char *fn;
struct stat st;
this->ectx = ectx;
- GE_ASSERT(ectx, filename != NULL);
- this->treedepth = computeDepth(filesize);
- this->lock = MUTEX_CREATE(NO);
- this->handles = MALLOC(sizeof(int) * (this->treedepth+1));
- this->filename = STRDUP(filename);
+ GE_ASSERT (ectx, filename != NULL);
+ this->treedepth = computeDepth (filesize);
+ this->lock = MUTEX_CREATE (NO);
+ this->handles = MALLOC (sizeof (int) * (this->treedepth + 1));
+ this->filename = STRDUP (filename);
- if ( (0 == STAT(filename, &st)) &&
- ((size_t)st.st_size > filesize ) ) {
- /* if exists and oversized, truncate */
- if (truncate(filename, filesize) != 0) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "truncate",
- filename);
- return SYSERR;
+ if ((0 == STAT (filename, &st)) && ((size_t) st.st_size > filesize))
+ {
+ /* if exists and oversized, truncate */
+ if (truncate (filename, filesize) != 0)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK,
+ "truncate", filename);
+ return SYSERR;
+ }
}
- }
- for (i=0;i<=this->treedepth;i++)
+ for (i = 0; i <= this->treedepth; i++)
this->handles[i] = -1;
- for (i=0;i<=this->treedepth;i++) {
- if ( (i == 0) ||
- (no_temporaries != YES) ) {
- fn = MALLOC(strlen(filename) + 3);
- strcpy(fn, filename);
- if (i > 0) {
- strcat(fn, ".A");
- fn[strlen(fn)-1] += i;
- }
- this->handles[i] = disk_file_open(ectx,
- fn,
- O_CREAT|O_RDWR,
- S_IRUSR|S_IWUSR );
- if (this->handles[i] < 0) {
- freeIOC(this, YES);
- FREE(fn);
- return SYSERR;
- }
- FREE(fn);
+ for (i = 0; i <= this->treedepth; i++)
+ {
+ if ((i == 0) || (no_temporaries != YES))
+ {
+ fn = MALLOC (strlen (filename) + 3);
+ strcpy (fn, filename);
+ if (i > 0)
+ {
+ strcat (fn, ".A");
+ fn[strlen (fn) - 1] += i;
+ }
+ this->handles[i] = disk_file_open (ectx,
+ fn,
+ O_CREAT | O_RDWR,
+ S_IRUSR | S_IWUSR);
+ if (this->handles[i] < 0)
+ {
+ freeIOC (this, YES);
+ FREE (fn);
+ return SYSERR;
+ }
+ FREE (fn);
+ }
}
- }
return OK;
}
@@ -204,33 +214,27 @@
* @param len how many bytes to read or write
* @return number of bytes read, SYSERR on error
*/
-int readFromIOC(IOContext * this,
- unsigned int level,
- unsigned long long pos,
- void * buf,
- unsigned int len) {
+int
+readFromIOC (IOContext * this,
+ unsigned int level,
+ unsigned long long pos, void *buf, unsigned int len)
+{
int ret;
- MUTEX_LOCK(this->lock);
- if (this->handles[level] == -1) {
- MUTEX_UNLOCK(this->lock);
- return SYSERR;
- }
- lseek(this->handles[level],
- pos,
- SEEK_SET);
- ret = READ(this->handles[level],
- buf,
- len);
- MUTEX_UNLOCK(this->lock);
+ MUTEX_LOCK (this->lock);
+ if (this->handles[level] == -1)
+ {
+ MUTEX_UNLOCK (this->lock);
+ return SYSERR;
+ }
+ lseek (this->handles[level], pos, SEEK_SET);
+ ret = READ (this->handles[level], buf, len);
+ MUTEX_UNLOCK (this->lock);
#if DEBUG_DOWNLOAD
- GE_LOG(this->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "IOC read at level %u offset %llu wanted %u got %d\n",
- level,
- pos,
- len,
- ret);
+ GE_LOG (this->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "IOC read at level %u offset %llu wanted %u got %d\n",
+ level, pos, len, ret);
#endif
return ret;
}
@@ -245,42 +249,33 @@
* @param len how many bytes to write
* @return number of bytes written, SYSERR on error
*/
-int writeToIOC(IOContext * this,
- unsigned int level,
- unsigned long long pos,
- void * buf,
- unsigned int len) {
+int
+writeToIOC (IOContext * this,
+ unsigned int level,
+ unsigned long long pos, void *buf, unsigned int len)
+{
int ret;
- MUTEX_LOCK(this->lock);
- if ( (this->handles[level] == -1) &&
- (level > 0) ) {
- MUTEX_UNLOCK(this->lock);
- return len; /* lie -- no temps allowed... */
- }
- lseek(this->handles[level],
- pos,
- SEEK_SET);
- ret = WRITE(this->handles[level],
- buf,
- len);
- if (ret != len) {
- GE_LOG(this->ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Write(%d, %p, %d) failed: %s\n"),
- this->handles[level],
- buf,
- len,
- STRERROR(errno));
- }
- MUTEX_UNLOCK(this->lock);
+ MUTEX_LOCK (this->lock);
+ if ((this->handles[level] == -1) && (level > 0))
+ {
+ MUTEX_UNLOCK (this->lock);
+ return len; /* lie -- no temps allowed... */
+ }
+ lseek (this->handles[level], pos, SEEK_SET);
+ ret = WRITE (this->handles[level], buf, len);
+ if (ret != len)
+ {
+ GE_LOG (this->ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Write(%d, %p, %d) failed: %s\n"),
+ this->handles[level], buf, len, STRERROR (errno));
+ }
+ MUTEX_UNLOCK (this->lock);
#if DEBUG_DOWNLOAD
- GE_LOG(this->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "IOC write at level %u offset %llu writes %u\n",
- level,
- pos,
- len);
+ GE_LOG (this->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "IOC write at level %u offset %llu writes %u\n", level, pos, len);
#endif
return ret;
}
@@ -290,12 +285,13 @@
/**
* Node-specific data (not shared, keep small!). 56 bytes.
*/
-typedef struct {
+typedef struct
+{
/**
* Pointer to shared data between all nodes (request manager,
* progress data, etc.).
*/
- struct CommonCtx * ctx;
+ struct CommonCtx *ctx;
/**
* What is the CHK for this block?
*/
@@ -325,18 +321,19 @@
* Design question: why not union RequestEntry and NodeClosure (would
* save yet another 4 bytes / entry)?
*/
-typedef struct RequestEntry {
+typedef struct RequestEntry
+{
/**
* The node for which this entry keeps data.
*/
- NodeClosure * node;
+ NodeClosure *node;
/**
* Search handle of the last request (NULL if never
* requested).
*/
- struct FS_SEARCH_HANDLE * searchHandle;
+ struct FS_SEARCH_HANDLE *searchHandle;
/**
* Last time the query was send.
@@ -370,25 +367,26 @@
* which queries went out with which priorities and which nodes in
* the merkle-tree are waiting for the replies.
*/
-typedef struct RequestManager {
+typedef struct RequestManager
+{
/**
* Mutex for synchronizing access to this struct
*/
- struct MUTEX * lock;
+ struct MUTEX *lock;
/**
* Current list of all pending requests
*/
- RequestEntry ** requestList;
+ RequestEntry **requestList;
- struct FS_SEARCH_CONTEXT * sctx;
+ struct FS_SEARCH_CONTEXT *sctx;
- struct PTHREAD * requestThread;
+ struct PTHREAD *requestThread;
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
PeerIdentity target;
@@ -451,61 +449,43 @@
* @return NULL on error
*/
static RequestManager *
-createRequestManager(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- RequestManager * rm;
+createRequestManager (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ RequestManager *rm;
- rm = MALLOC(sizeof(RequestManager));
- rm->shutdown
- = NO;
- rm->lock
- = MUTEX_CREATE(YES);
- rm->sctx = FS_SEARCH_makeContext(ectx,
- cfg,
- rm->lock);
- if (rm->sctx == NULL) {
- MUTEX_DESTROY(rm->lock);
- FREE(rm);
- return NULL;
- }
- rm->ectx
- = ectx;
- rm->cfg
- = cfg;
- rm->requestThread
- = PTHREAD_GET_SELF();
- rm->abortFlag
- = NO;
- rm->lastDET
- = 0;
- rm->requestListIndex
- = 0;
- rm->requestListSize
- = 0;
- rm->requestList
- = NULL;
- rm->have_target
- = NO;
- GROW(rm->requestList,
- rm->requestListSize,
- 256);
- rm->initialTTL
- = 5 * cronSECONDS;
+ rm = MALLOC (sizeof (RequestManager));
+ rm->shutdown = NO;
+ rm->lock = MUTEX_CREATE (YES);
+ rm->sctx = FS_SEARCH_makeContext (ectx, cfg, rm->lock);
+ if (rm->sctx == NULL)
+ {
+ MUTEX_DESTROY (rm->lock);
+ FREE (rm);
+ return NULL;
+ }
+ rm->ectx = ectx;
+ rm->cfg = cfg;
+ rm->requestThread = PTHREAD_GET_SELF ();
+ rm->abortFlag = NO;
+ rm->lastDET = 0;
+ rm->requestListIndex = 0;
+ rm->requestListSize = 0;
+ rm->requestList = NULL;
+ rm->have_target = NO;
+ GROW (rm->requestList, rm->requestListSize, 256);
+ rm->initialTTL = 5 * cronSECONDS;
/* RFC 2001 suggests to use 1 segment size initially;
Given 1500 octets per message in GNUnet, we would
have 2-3 queries of maximum size (552); but since
we are multi-casting to many peers at the same
time AND since queries can be much smaller,
we do WHAT??? */
- rm->congestionWindow
- = 1; /* RSS is 1 */
- rm->ssthresh
- = 65535;
+ rm->congestionWindow = 1; /* RSS is 1 */
+ rm->ssthresh = 65535;
#if DEBUG_DOWNLOAD
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "created request manager %p\n",
- rm);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "created request manager %p\n", rm);
#endif
return rm;
}
@@ -517,56 +497,58 @@
*
* @param rm the request manager struct from createRequestManager
*/
-static void destroyRequestManager(RequestManager * rm) {
+static void
+destroyRequestManager (RequestManager * rm)
+{
int i;
#if DEBUG_DOWNLOAD
- GE_LOG(rm->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "destroying request manager %p\n",
- rm);
+ GE_LOG (rm->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "destroying request manager %p\n", rm);
#endif
- MUTEX_LOCK(rm->lock);
+ MUTEX_LOCK (rm->lock);
/* cannot hold lock during shutdown since
fslib may have to aquire it; but we can
flag that we are in the shutdown process
and start to ignore fslib events! */
rm->shutdown = YES;
- MUTEX_UNLOCK(rm->lock);
- for (i=0;i<rm->requestListIndex;i++) {
- if (rm->requestList[i]->searchHandle != NULL)
- FS_stop_search(rm->sctx,
- rm->requestList[i]->searchHandle);
- FREE(rm->requestList[i]->node);
- FREE(rm->requestList[i]);
- }
- GROW(rm->requestList,
- rm->requestListSize,
- 0);
- FS_SEARCH_destroyContext(rm->sctx);
+ MUTEX_UNLOCK (rm->lock);
+ for (i = 0; i < rm->requestListIndex; i++)
+ {
+ if (rm->requestList[i]->searchHandle != NULL)
+ FS_stop_search (rm->sctx, rm->requestList[i]->searchHandle);
+ FREE (rm->requestList[i]->node);
+ FREE (rm->requestList[i]);
+ }
+ GROW (rm->requestList, rm->requestListSize, 0);
+ FS_SEARCH_destroyContext (rm->sctx);
rm->sctx = NULL;
- MUTEX_DESTROY(rm->lock);
- PTHREAD_REL_SELF(rm->requestThread);
- FREE(rm);
+ MUTEX_DESTROY (rm->lock);
+ PTHREAD_REL_SELF (rm->requestThread);
+ FREE (rm);
}
/**
* We are approaching the end of the download. Cut
* all TTLs in half.
*/
-static void requestManagerEndgame(RequestManager * rm) {
+static void
+requestManagerEndgame (RequestManager * rm)
+{
int i;
- MUTEX_LOCK(rm->lock);
- if (rm->shutdown == NO) {
- for (i=0;i<rm->requestListIndex;i++) {
- RequestEntry * entry = rm->requestList[i];
- /* cut TTL in half */
- entry->lasttime
- += (entry->lasttime + entry->lastTimeout) / 2;
+ MUTEX_LOCK (rm->lock);
+ if (rm->shutdown == NO)
+ {
+ for (i = 0; i < rm->requestListIndex; i++)
+ {
+ RequestEntry *entry = rm->requestList[i];
+ /* cut TTL in half */
+ entry->lasttime += (entry->lasttime + entry->lastTimeout) / 2;
+ }
}
- }
- MUTEX_UNLOCK(rm->lock);
+ MUTEX_UNLOCK (rm->lock);
}
/**
@@ -575,52 +557,43 @@
* @param rm the request manager struct from createRequestManager
* @param node the node to call once a reply is received
*/
-static void addRequest(RequestManager * rm,
- NodeClosure * node) {
- RequestEntry * entry;
+static void
+addRequest (RequestManager * rm, NodeClosure * node)
+{
+ RequestEntry *entry;
#if DEBUG_DOWNLOAD
EncName enc;
- IF_GELOG(rm->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&node->chk.query,
- &enc));
- GE_LOG(rm->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Queuing request (query: %s)\n",
- &enc);
+ IF_GELOG (rm->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&node->chk.query, &enc));
+ GE_LOG (rm->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Queuing request (query: %s)\n", &enc);
#endif
- GE_ASSERT(rm->ectx,
- node != NULL);
- entry
- = MALLOC(sizeof(RequestEntry));
- entry->node
- = node;
- entry->lasttime
- = 0; /* never sent */
- entry->lastTimeout
- = 0;
- entry->tries
- = 0; /* not tried so far */
- entry->lastPriority
- = 0;
- entry->searchHandle
- = NULL;
- MUTEX_LOCK(rm->lock);
- if (rm->shutdown == NO) {
- GE_ASSERT(rm->ectx,
- rm->requestListSize > 0);
- if (rm->requestListSize == rm->requestListIndex)
- GROW(rm->requestList,
- rm->requestListSize,
- rm->requestListSize*2);
- rm->requestList[rm->requestListIndex++] = entry;
- } else {
- GE_BREAK(rm->ectx, 0);
- FREE(entry);
- }
- MUTEX_UNLOCK(rm->lock);
+ GE_ASSERT (rm->ectx, node != NULL);
+ entry = MALLOC (sizeof (RequestEntry));
+ entry->node = node;
+ entry->lasttime = 0; /* never sent */
+ entry->lastTimeout = 0;
+ entry->tries = 0; /* not tried so far */
+ entry->lastPriority = 0;
+ entry->searchHandle = NULL;
+ MUTEX_LOCK (rm->lock);
+ if (rm->shutdown == NO)
+ {
+ GE_ASSERT (rm->ectx, rm->requestListSize > 0);
+ if (rm->requestListSize == rm->requestListIndex)
+ GROW (rm->requestList, rm->requestListSize, rm->requestListSize * 2);
+ rm->requestList[rm->requestListIndex++] = entry;
+ }
+ else
+ {
+ GE_BREAK (rm->ectx, 0);
+ FREE (entry);
+ }
+ MUTEX_UNLOCK (rm->lock);
}
@@ -630,31 +603,32 @@
* @param this the request manager struct from createRequestManager
* @param node the block for which the request is canceled
*/
-static void delRequest(RequestManager * rm,
- NodeClosure * node) {
+static void
+delRequest (RequestManager * rm, NodeClosure * node)
+{
int i;
- RequestEntry * re;
+ RequestEntry *re;
- MUTEX_LOCK(rm->lock);
- if (rm->shutdown == NO) {
- for (i=0;i<rm->requestListIndex;i++) {
- re = rm->requestList[i];
- if (re->node == node) {
- rm->requestList[i]
- = rm->requestList[--rm->requestListIndex];
- rm->requestList[rm->requestListIndex]
- = NULL;
- MUTEX_UNLOCK(rm->lock);
- if (NULL != re->searchHandle)
- FS_stop_search(rm->sctx,
- re->searchHandle);
- FREE(re);
- return;
- }
+ MUTEX_LOCK (rm->lock);
+ if (rm->shutdown == NO)
+ {
+ for (i = 0; i < rm->requestListIndex; i++)
+ {
+ re = rm->requestList[i];
+ if (re->node == node)
+ {
+ rm->requestList[i] = rm->requestList[--rm->requestListIndex];
+ rm->requestList[rm->requestListIndex] = NULL;
+ MUTEX_UNLOCK (rm->lock);
+ if (NULL != re->searchHandle)
+ FS_stop_search (rm->sctx, re->searchHandle);
+ FREE (re);
+ return;
+ }
+ }
}
- }
- MUTEX_UNLOCK(rm->lock);
- GE_BREAK(rm->ectx, 0); /* uh uh - at least a memory leak... */
+ MUTEX_UNLOCK (rm->lock);
+ GE_BREAK (rm->ectx, 0); /* uh uh - at least a memory leak... */
}
@@ -664,17 +638,18 @@
* Data shared between all tree nodes.
* Design Question: integrate with IOContext?
*/
-typedef struct CommonCtx {
+typedef struct CommonCtx
+{
unsigned long long total;
unsigned long long completed;
unsigned long long offset;
unsigned long long length;
cron_t startTime;
cron_t TTL_DECREMENT;
- RequestManager * rm;
- IOContext * ioc;
+ RequestManager *rm;
+ IOContext *ioc;
ECRS_DownloadProgressCallback dpcb;
- void * dpcbClosure;
+ void *dpcbClosure;
unsigned int anonymityLevel;
} CommonCtx;
@@ -682,144 +657,145 @@
* Compute how many bytes of data are stored in
* this node.
*/
-static unsigned int getNodeSize(const NodeClosure * node) {
+static unsigned int
+getNodeSize (const NodeClosure * node)
+{
unsigned int i;
unsigned int ret;
unsigned long long rsize;
unsigned long long spos;
unsigned long long epos;
- GE_ASSERT(node->ctx->rm->ectx,
- node->offset < node->ctx->total);
- if (node->level == 0) {
- ret = DBLOCK_SIZE;
- if (node->offset + (unsigned long long) ret
- > node->ctx->total)
- ret = (unsigned int) (node->ctx->total - node->offset);
+ GE_ASSERT (node->ctx->rm->ectx, node->offset < node->ctx->total);
+ if (node->level == 0)
+ {
+ ret = DBLOCK_SIZE;
+ if (node->offset + (unsigned long long) ret > node->ctx->total)
+ ret = (unsigned int) (node->ctx->total - node->offset);
#if DEBUG_DOWNLOAD
- GE_LOG(node->ctx->rm->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Node at offset %llu and level %d has size %u\n",
- node->offset,
- node->level,
- ret);
+ GE_LOG (node->ctx->rm->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Node at offset %llu and level %d has size %u\n",
+ node->offset, node->level, ret);
#endif
- return ret;
- }
+ return ret;
+ }
rsize = DBLOCK_SIZE;
- for (i=0;i<node->level-1;i++)
+ for (i = 0; i < node->level - 1; i++)
rsize *= CHK_PER_INODE;
- spos = rsize * (node->offset / sizeof(CHK));
+ spos = rsize * (node->offset / sizeof (CHK));
epos = spos + rsize * CHK_PER_INODE;
if (epos > node->ctx->total)
epos = node->ctx->total;
ret = (epos - spos) / rsize;
if (ret * rsize < epos - spos)
- ret++; /* need to round up! */
+ ret++; /* need to round up! */
#if DEBUG_DOWNLOAD
- GE_LOG(node->ctx->rm->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Node at offset %llu and level %d has size %u\n",
- node->offset,
- node->level,
- ret * sizeof(CHK));
+ GE_LOG (node->ctx->rm->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Node at offset %llu and level %d has size %u\n",
+ node->offset, node->level, ret * sizeof (CHK));
#endif
- return ret * sizeof(CHK);
+ return ret * sizeof (CHK);
}
/**
* Update progress information. Also updates
* request manager structures, like ttl.
*/
-static void updateProgress(const NodeClosure * node,
- const char * data,
- unsigned int size) {
- RequestManager * rm;
- RequestEntry * entry;
+static void
+updateProgress (const NodeClosure * node, const char *data, unsigned int size)
+{
+ RequestManager *rm;
+ RequestEntry *entry;
int pos;
int i;
/* locking? */
- if (node->level == 0) {
- cron_t eta;
+ if (node->level == 0)
+ {
+ cron_t eta;
- node->ctx->completed += size;
- eta = get_time();
- if (node->ctx->completed > 0) {
- eta = (cron_t) (node->ctx->startTime +
- (((double)(eta -
node->ctx->startTime)/(double)node->ctx->completed))
- * (double)node->ctx->length);
+ node->ctx->completed += size;
+ eta = get_time ();
+ if (node->ctx->completed > 0)
+ {
+ eta = (cron_t) (node->ctx->startTime +
+ (((double) (eta - node->ctx->startTime) /
+ (double) node->ctx->completed)) *
+ (double) node->ctx->length);
+ }
+ if (node->ctx->dpcb != NULL)
+ {
+ node->ctx->dpcb (node->ctx->length,
+ node->ctx->completed,
+ eta,
+ node->offset, data, size, node->ctx->dpcbClosure);
+ }
}
- if (node->ctx->dpcb != NULL) {
- node->ctx->dpcb(node->ctx->length,
- node->ctx->completed,
- eta,
- node->offset,
- data,
- size,
- node->ctx->dpcbClosure);
- }
- }
rm = node->ctx->rm;
- MUTEX_LOCK(rm->lock);
- if (rm->shutdown == YES) {
- MUTEX_UNLOCK(rm->lock);
- return;
- }
+ MUTEX_LOCK (rm->lock);
+ if (rm->shutdown == YES)
+ {
+ MUTEX_UNLOCK (rm->lock);
+ return;
+ }
/* check type of reply msg, fill in query */
pos = -1;
/* find which query matches the reply, call the callback
and recycle the slot */
- for (i=0;i<rm->requestListIndex;i++)
+ for (i = 0; i < rm->requestListIndex; i++)
if (rm->requestList[i]->node == node)
pos = i;
- if (pos == -1) {
- /* GE_BREAK(ectx, 0); */ /* should never happen */
- MUTEX_UNLOCK(rm->lock);
- return;
- }
+ if (pos == -1)
+ {
+ /* GE_BREAK(ectx, 0); *//* should never happen */
+ MUTEX_UNLOCK (rm->lock);
+ return;
+ }
entry = rm->requestList[pos];
- if ( (entry->lasttime < get_time()) &&
- (entry->lasttime != 0) ) {
- unsigned int weight = 15;
- unsigned int ettl = entry->lastTimeout - entry->lasttime;
- if ( (ettl > 4 * rm->initialTTL) &&
- ( (get_time() - entry->lasttime) < rm->initialTTL) ) {
- weight = 127;
- /* eTTL is MUCH bigger than what we currently expect AND the time
- between the last query and the reply was in the range of the
- expected TTL => don't take ettl too much into account! */
+ if ((entry->lasttime < get_time ()) && (entry->lasttime != 0))
+ {
+ unsigned int weight = 15;
+ unsigned int ettl = entry->lastTimeout - entry->lasttime;
+ if ((ettl > 4 * rm->initialTTL) &&
+ ((get_time () - entry->lasttime) < rm->initialTTL))
+ {
+ weight = 127;
+ /* eTTL is MUCH bigger than what we currently expect AND the time
+ between the last query and the reply was in the range of the
+ expected TTL => don't take ettl too much into account! */
+ }
+ rm->initialTTL = ((rm->initialTTL) * weight + ettl) / (weight + 1);
+
+ /* RFC 2001: increase cwnd; note that we can't really discriminate
between
+ slow-start and cong. control mode since our RSS is too small... */
+ if (rm->congestionWindow < rm->ssthresh)
+ rm->congestionWindow += 2; /* slow start */
+ else
+ rm->congestionWindow += 1; /* slower start :-) */
}
- rm->initialTTL = ((rm->initialTTL) * weight + ettl) / (weight+1);
+ if (entry->tries > 1)
+ {
+ TIME_T nowTT;
- /* RFC 2001: increase cwnd; note that we can't really discriminate between
- slow-start and cong. control mode since our RSS is too small... */
- if (rm->congestionWindow < rm->ssthresh)
- rm->congestionWindow += 2; /* slow start */
- else
- rm->congestionWindow += 1; /* slower start :-) */
- }
- if (entry->tries > 1) {
- TIME_T nowTT;
-
- TIME(&nowTT);
- if ( (nowTT - rm->initialTTL) > rm->lastDET) {
- /* only consider congestion control every
- "average" TTL seconds, otherwise the system
- reacts to events that are far too old! */
- /* we performed retransmission, treat as congestion (RFC 2001) */
- rm->ssthresh
- = rm->congestionWindow / 2;
- if (rm->ssthresh < 2)
- rm->ssthresh = 2;
- rm->congestionWindow
- = rm->ssthresh + 1;
- rm->lastDET = nowTT;
+ TIME (&nowTT);
+ if ((nowTT - rm->initialTTL) > rm->lastDET)
+ {
+ /* only consider congestion control every
+ "average" TTL seconds, otherwise the system
+ reacts to events that are far too old! */
+ /* we performed retransmission, treat as congestion (RFC 2001) */
+ rm->ssthresh = rm->congestionWindow / 2;
+ if (rm->ssthresh < 2)
+ rm->ssthresh = 2;
+ rm->congestionWindow = rm->ssthresh + 1;
+ rm->lastDET = nowTT;
+ }
}
- }
- MUTEX_UNLOCK(rm->lock);
+ MUTEX_UNLOCK (rm->lock);
}
@@ -828,9 +804,8 @@
*
* @param rm the node that should downloaded
*/
-static void iblock_download_children(NodeClosure * node,
- char * data,
- unsigned int size);
+static void iblock_download_children (NodeClosure * node,
+ char *data, unsigned int size);
/**
* Check if this block is already present on the drive. If the block
@@ -846,56 +821,49 @@
* @param node that is checked for presence
* @return YES if present, NO if not.
*/
-static int checkPresent(NodeClosure * node) {
+static int
+checkPresent (NodeClosure * node)
+{
int res;
int ret;
- char * data;
+ char *data;
unsigned int size;
HashCode512 hc;
- size = getNodeSize(node);
+ size = getNodeSize (node);
/* first check if node is within range.
For now, keeping it simple, we only do
this for level-0 nodes */
- if ( (node->level == 0) &&
- ( (node->offset + size < node->ctx->offset) ||
- (node->offset > node->ctx->offset + node->ctx->length) ) )
+ if ((node->level == 0) &&
+ ((node->offset + size < node->ctx->offset) ||
+ (node->offset > node->ctx->offset + node->ctx->length)))
return YES;
- data = MALLOC(size);
- res = readFromIOC(node->ctx->ioc,
- node->level,
- node->offset,
- data,
- size);
- if (res == size) {
- hash(data,
- size,
- &hc);
- if (equalsHashCode512(&hc,
- &node->chk.key)) {
- updateProgress(node,
- data,
- size);
- if (node->level > 0)
- iblock_download_children(node,
- data,
- size);
+ data = MALLOC (size);
+ res = readFromIOC (node->ctx->ioc, node->level, node->offset, data, size);
+ if (res == size)
+ {
+ hash (data, size, &hc);
+ if (equalsHashCode512 (&hc, &node->chk.key))
+ {
+ updateProgress (node, data, size);
+ if (node->level > 0)
+ iblock_download_children (node, data, size);
- ret = YES;
- } else
- ret = NO;
- } else
+ ret = YES;
+ }
+ else
+ ret = NO;
+ }
+ else
ret = NO;
- FREE(data);
+ FREE (data);
#if DEBUG_DOWNLOAD
- GE_LOG(node->ctx->rm->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Checked presence of block at %llu level %u. Result: %s\n",
- node->offset,
- node->level,
- ret == YES ? "YES" : "NO");
+ GE_LOG (node->ctx->rm->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Checked presence of block at %llu level %u. Result: %s\n",
+ node->offset, node->level, ret == YES ? "YES" : "NO");
#endif
return ret;
@@ -906,47 +874,50 @@
*
* @param this the node that should downloaded
*/
-static void iblock_download_children(NodeClosure * node,
- char * data,
- unsigned int size) {
- struct GE_Context * ectx = node->ctx->rm->ectx;
+static void
+iblock_download_children (NodeClosure * node, char *data, unsigned int size)
+{
+ struct GE_Context *ectx = node->ctx->rm->ectx;
int i;
- NodeClosure * child;
+ NodeClosure *child;
unsigned int childcount;
- CHK * chks;
+ CHK *chks;
unsigned int levelSize;
unsigned long long baseOffset;
- GE_ASSERT(ectx,
- node->level > 0);
- childcount = size / sizeof(CHK);
- if (size != childcount * sizeof(CHK)) {
- GE_BREAK(ectx, 0);
- return;
- }
- if (node->level == 1) {
- levelSize = DBLOCK_SIZE;
- baseOffset = node->offset / sizeof(CHK) * DBLOCK_SIZE;
- } else {
- levelSize = sizeof(CHK) * CHK_PER_INODE;
- baseOffset = node->offset * CHK_PER_INODE;
- }
- chks = (CHK*) data;
- for (i=0;i<childcount;i++) {
- child = MALLOC(sizeof(NodeClosure));
- child->ctx = node->ctx;
- child->chk = chks[i];
- child->offset = baseOffset + i * levelSize;
- GE_ASSERT(ectx, child->offset < node->ctx->total);
- child->level = node->level - 1;
- GE_ASSERT(ectx, (child->level != 0) ||
- ( (child->offset % DBLOCK_SIZE) == 0) );
- if (NO == checkPresent(child))
- addRequest(node->ctx->rm,
- child);
- else
- FREE(child); /* done already! */
- }
+ GE_ASSERT (ectx, node->level > 0);
+ childcount = size / sizeof (CHK);
+ if (size != childcount * sizeof (CHK))
+ {
+ GE_BREAK (ectx, 0);
+ return;
+ }
+ if (node->level == 1)
+ {
+ levelSize = DBLOCK_SIZE;
+ baseOffset = node->offset / sizeof (CHK) * DBLOCK_SIZE;
+ }
+ else
+ {
+ levelSize = sizeof (CHK) * CHK_PER_INODE;
+ baseOffset = node->offset * CHK_PER_INODE;
+ }
+ chks = (CHK *) data;
+ for (i = 0; i < childcount; i++)
+ {
+ child = MALLOC (sizeof (NodeClosure));
+ child->ctx = node->ctx;
+ child->chk = chks[i];
+ child->offset = baseOffset + i * levelSize;
+ GE_ASSERT (ectx, child->offset < node->ctx->total);
+ child->level = node->level - 1;
+ GE_ASSERT (ectx, (child->level != 0) ||
+ ((child->offset % DBLOCK_SIZE) == 0));
+ if (NO == checkPresent (child))
+ addRequest (node->ctx->rm, child);
+ else
+ FREE (child); /* done already! */
+ }
}
@@ -959,24 +930,17 @@
* @param result where to store the result (encrypted block)
* @returns OK on success, SYSERR on error
*/
-static int decryptContent(const char * data,
- unsigned int size,
- const HashCode512 * hashcode,
- char * result){
+static int
+decryptContent (const char *data,
+ unsigned int size, const HashCode512 * hashcode, char *result)
+{
INITVECTOR iv;
SESSIONKEY skey;
- GE_ASSERT(NULL,
- (data!=NULL) && (hashcode != NULL) && (result != NULL));
+ GE_ASSERT (NULL, (data != NULL) && (hashcode != NULL) && (result != NULL));
/* get key and init value from the hash code */
- hashToKey(hashcode,
- &skey,
- &iv);
- return decryptBlock(&skey,
- data,
- size,
- &iv,
- result);
+ hashToKey (hashcode, &skey, &iv);
+ return decryptBlock (&skey, data, size, &iv, result);
}
@@ -993,95 +957,79 @@
* @param reply the reply
* @return OK if the reply was valid, SYSERR on error
*/
-static int nodeReceive(const HashCode512 * query,
- const Datastore_Value * reply,
- void * cls) {
- NodeClosure * node = cls;
- struct GE_Context * ectx = node->ctx->rm->ectx;
+static int
+nodeReceive (const HashCode512 * query,
+ const Datastore_Value * reply, void *cls)
+{
+ NodeClosure *node = cls;
+ struct GE_Context *ectx = node->ctx->rm->ectx;
HashCode512 hc;
unsigned int size;
int i;
- char * data;
+ char *data;
#if DEBUG_DOWNLOAD
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(query,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Receiving reply to query `%s'\n",
- &enc);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (query, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Receiving reply to query `%s'\n", &enc);
#endif
- GE_ASSERT(ectx,
- equalsHashCode512(query,
- &node->chk.query));
- size = ntohl(reply->size) - sizeof(Datastore_Value);
- if ( (size <= sizeof(DBlock)) ||
- (size - sizeof(DBlock) != getNodeSize(node)) ) {
- GE_BREAK(ectx, 0);
- return SYSERR; /* invalid size! */
- }
- size -= sizeof(DBlock);
- data = MALLOC(size);
- if (SYSERR == decryptContent((char*)&((DBlock*)&reply[1])[1],
- size,
- &node->chk.key,
- data))
- GE_ASSERT(ectx, 0);
- hash(data,
- size,
- &hc);
- if (! equalsHashCode512(&hc,
- &node->chk.key)) {
- delRequest(node->ctx->rm,
- node);
- FREE(data);
- GE_BREAK(ectx, 0);
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Decrypted content does not match key. "
- "This is either a bug or a maliciously inserted "
- "file. Download aborted.\n"));
- node->ctx->rm->abortFlag = YES;
- return SYSERR;
- }
- if (size != writeToIOC(node->ctx->ioc,
- node->level,
- node->offset,
- data,
- size)) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "WRITE");
- node->ctx->rm->abortFlag = YES;
- return SYSERR;
- }
- updateProgress(node,
- data,
- size);
+ GE_ASSERT (ectx, equalsHashCode512 (query, &node->chk.query));
+ size = ntohl (reply->size) - sizeof (Datastore_Value);
+ if ((size <= sizeof (DBlock)) ||
+ (size - sizeof (DBlock) != getNodeSize (node)))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR; /* invalid size! */
+ }
+ size -= sizeof (DBlock);
+ data = MALLOC (size);
+ if (SYSERR == decryptContent ((char *) &((DBlock *) & reply[1])[1],
+ size, &node->chk.key, data))
+ GE_ASSERT (ectx, 0);
+ hash (data, size, &hc);
+ if (!equalsHashCode512 (&hc, &node->chk.key))
+ {
+ delRequest (node->ctx->rm, node);
+ FREE (data);
+ GE_BREAK (ectx, 0);
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Decrypted content does not match key. "
+ "This is either a bug or a maliciously inserted "
+ "file. Download aborted.\n"));
+ node->ctx->rm->abortFlag = YES;
+ return SYSERR;
+ }
+ if (size != writeToIOC (node->ctx->ioc,
+ node->level, node->offset, data, size))
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "WRITE");
+ node->ctx->rm->abortFlag = YES;
+ return SYSERR;
+ }
+ updateProgress (node, data, size);
if (node->level > 0)
- iblock_download_children(node,
- data,
- size);
+ iblock_download_children (node, data, size);
/* request satisfied, stop requesting! */
- delRequest(node->ctx->rm,
- node);
+ delRequest (node->ctx->rm, node);
- for (i=0;i<10;i++) {
- if ( (node->ctx->completed * 10000L >
- node->ctx->length * (10000L - (1024 >> i)) ) &&
- ( (node->ctx->completed-size) * 10000L <=
- node->ctx->length * (10000L - (1024 >> i)) ) ) {
- /* end-game boundary crossed, slaughter TTLs */
- requestManagerEndgame(node->ctx->rm);
+ for (i = 0; i < 10; i++)
+ {
+ if ((node->ctx->completed * 10000L >
+ node->ctx->length * (10000L - (1024 >> i))) &&
+ ((node->ctx->completed - size) * 10000L <=
+ node->ctx->length * (10000L - (1024 >> i))))
+ {
+ /* end-game boundary crossed, slaughter TTLs */
+ requestManagerEndgame (node->ctx->rm);
+ }
}
- }
- GE_ASSERT(node->ctx->rm->ectx,
- node->ctx->rm->requestThread != NULL);
- PTHREAD_STOP_SLEEP(node->ctx->rm->requestThread);
- FREE(data);
- FREE(node);
+ GE_ASSERT (node->ctx->rm->ectx, node->ctx->rm->requestThread != NULL);
+ PTHREAD_STOP_SLEEP (node->ctx->rm->requestThread);
+ FREE (data);
+ FREE (node);
return OK;
}
@@ -1093,11 +1041,12 @@
* @param this the RequestManager
* @param requestIndex the index of the Request to issue
*/
-static void issueRequest(RequestManager * rm,
- int requestIndex) {
+static void
+issueRequest (RequestManager * rm, int requestIndex)
+{
static unsigned int lastmpriority;
static cron_t lastmpritime;
- RequestEntry * entry;
+ RequestEntry *entry;
cron_t now;
unsigned int priority;
unsigned int mpriority;
@@ -1108,128 +1057,130 @@
EncName enc;
#endif
- now = get_time();
+ now = get_time ();
entry = rm->requestList[requestIndex];
/* compute priority */
- if (lastmpritime + 10 * cronSECONDS < now) {
- /* only update avg. priority at most every
- 10 seconds */
- struct ClientServerConnection * sock;
+ if (lastmpritime + 10 * cronSECONDS < now)
+ {
+ /* only update avg. priority at most every
+ 10 seconds */
+ struct ClientServerConnection *sock;
- sock = client_connection_create(rm->ectx,
- rm->cfg);
- lastmpriority = FS_getAveragePriority(sock);
- lastmpritime = now;
- connection_destroy(sock);
- }
+ sock = client_connection_create (rm->ectx, rm->cfg);
+ lastmpriority = FS_getAveragePriority (sock);
+ lastmpritime = now;
+ connection_destroy (sock);
+ }
mpriority = lastmpriority;
- priority
- = entry->lastPriority + weak_randomi(1 + entry->tries);
- if (priority > mpriority) {
- /* mpriority is (2 * (current average priority + 2)) and
- is used as the maximum priority that we use; if the
- calculated tpriority is above it, we reduce tpriority
- to random value between the average (mpriority/2) but
- bounded by mpriority */
- priority = 1 + mpriority / 2 + (weak_randomi(2+mpriority/2));
- }
+ priority = entry->lastPriority + weak_randomi (1 + entry->tries);
+ if (priority > mpriority)
+ {
+ /* mpriority is (2 * (current average priority + 2)) and
+ is used as the maximum priority that we use; if the
+ calculated tpriority is above it, we reduce tpriority
+ to random value between the average (mpriority/2) but
+ bounded by mpriority */
+ priority = 1 + mpriority / 2 + (weak_randomi (2 + mpriority / 2));
+ }
if (priority > 0x0FFFFFF)
- priority = weak_randomi(0xFFFFFF); /* bound! */
+ priority = weak_randomi (0xFFFFFF); /* bound! */
/* compute TTL */
- TTL_DECREMENT
- = entry->node->ctx->TTL_DECREMENT;
+ TTL_DECREMENT = entry->node->ctx->TTL_DECREMENT;
if (entry->lastTimeout + TTL_DECREMENT > now)
- GE_BREAK(rm->ectx, 0);
- if (entry->lasttime == 0) {
- timeout = now + rm->initialTTL;
- } else {
- ttl = entry->lastTimeout - entry->lasttime;
- if (ttl > MAX_TTL) {
- ttl = MAX_TTL + weak_randomi(2*TTL_DECREMENT);
- } else if (ttl > rm->initialTTL) {
- /* switch to slow back-off */
- unsigned int rd;
- if (rm->initialTTL == 0)
- rd = ttl;
+ GE_BREAK (rm->ectx, 0);
+ if (entry->lasttime == 0)
+ {
+ timeout = now + rm->initialTTL;
+ }
+ else
+ {
+ ttl = entry->lastTimeout - entry->lasttime;
+ if (ttl > MAX_TTL)
+ {
+ ttl = MAX_TTL + weak_randomi (2 * TTL_DECREMENT);
+ }
+ else if (ttl > rm->initialTTL)
+ {
+ /* switch to slow back-off */
+ unsigned int rd;
+ if (rm->initialTTL == 0)
+ rd = ttl;
+ else
+ rd = ttl / rm->initialTTL;
+ if (rd == 0)
+ rd = 1; /* how? */
+ rd = TTL_DECREMENT / rd;
+ if (rd == 0)
+ rd = 1;
+ ttl += weak_randomi (50 * cronMILLIS + rd);
+ /* rd == TTL_DECREMENT / (con->ttl / rm->initialTTL) + saveguards
+ 50ms: minimum increment */
+ }
else
- rd = ttl / rm->initialTTL;
- if (rd == 0)
- rd = 1; /* how? */
- rd = TTL_DECREMENT / rd;
- if (rd == 0)
- rd = 1;
- ttl += weak_randomi(50 * cronMILLIS + rd);
- /* rd == TTL_DECREMENT / (con->ttl / rm->initialTTL) + saveguards
- 50ms: minimum increment */
- } else {
- ttl += weak_randomi(ttl + 2 * TTL_DECREMENT); /* exponential backoff
with random factor */
+ {
+ ttl += weak_randomi (ttl + 2 * TTL_DECREMENT); /* exponential
backoff with random factor */
+ }
+ if (ttl > (priority + 8) * TTL_DECREMENT)
+ ttl = (priority + 8) * TTL_DECREMENT; /* see adjustTTL in gap */
+ timeout = now + ttl;
}
- if (ttl > (priority+8)* TTL_DECREMENT)
- ttl = (priority+8) * TTL_DECREMENT; /* see adjustTTL in gap */
- timeout = now + ttl;
- }
#if DEBUG_DOWNLOAD
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&entry->node->chk.query,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Starting FS search for %s:%llu:%u `%s'\n",
- entry->node->ctx->ioc->filename,
- entry->node->offset,
- entry->node->level,
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&entry->node->chk.query, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Starting FS search for %s:%llu:%u `%s'\n",
+ entry->node->ctx->ioc->filename,
+ entry->node->offset, entry->node->level, &enc);
#endif
if (entry->searchHandle != NULL)
- FS_stop_search(rm->sctx,
- entry->searchHandle);
+ FS_stop_search (rm->sctx, entry->searchHandle);
entry->searchHandle
- = FS_start_search(rm->sctx,
- rm->have_target == NO ? NULL : &rm->target,
- D_BLOCK,
- 1,
- &entry->node->chk.query,
- entry->node->ctx->anonymityLevel,
- priority,
- timeout,
- &nodeReceive,
- entry->node);
- if (entry->searchHandle != NULL) {
- entry->lastPriority = priority;
- entry->lastTimeout = timeout;
- entry->lasttime = now + 2 * TTL_DECREMENT;
- if (weak_randomi(1+entry->tries) > 1) {
- /* do linear (in tries) extra back-off (in addition to ttl)
- to avoid repeatedly tie-ing with other peers; rm is somewhat
- equivalent to what ethernet is doing, only that 'tries' is our
- (rough) indicator for collisions. For ethernet back-off, see:
- http://www.industrialethernetuniversity.com/courses/101_4.htm
- */
- entry->lasttime += weak_randomi(TTL_DECREMENT * (1+entry->tries));
+ = FS_start_search (rm->sctx,
+ rm->have_target == NO ? NULL : &rm->target,
+ D_BLOCK,
+ 1,
+ &entry->node->chk.query,
+ entry->node->ctx->anonymityLevel,
+ priority, timeout, &nodeReceive, entry->node);
+ if (entry->searchHandle != NULL)
+ {
+ entry->lastPriority = priority;
+ entry->lastTimeout = timeout;
+ entry->lasttime = now + 2 * TTL_DECREMENT;
+ if (weak_randomi (1 + entry->tries) > 1)
+ {
+ /* do linear (in tries) extra back-off (in addition to ttl)
+ to avoid repeatedly tie-ing with other peers; rm is somewhat
+ equivalent to what ethernet is doing, only that 'tries' is our
+ (rough) indicator for collisions. For ethernet back-off, see:
+ http://www.industrialethernetuniversity.com/courses/101_4.htm
+ */
+ entry->lasttime +=
+ weak_randomi (TTL_DECREMENT * (1 + entry->tries));
+ }
+ entry->tries++;
}
- entry->tries++;
- }
/* warn if number of attempts goes too high */
- if ( (0 == (entry->tries % MAX_TRIES)) &&
- (entry->tries > 0) ) {
- EncName enc;
- IF_GELOG(rm->ectx,
- GE_WARNING | GE_BULK | GE_USER,
- hash2enc(&entry->node->chk.key,
- &enc));
- GE_LOG(rm->ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Content `%s' seems to be not available on the network (tried %u
times).\n"),
- &enc,
- entry->tries);
- }
+ if ((0 == (entry->tries % MAX_TRIES)) && (entry->tries > 0))
+ {
+ EncName enc;
+ IF_GELOG (rm->ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ hash2enc (&entry->node->chk.key, &enc));
+ GE_LOG (rm->ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("Content `%s' seems to be not available on the network (tried
%u times).\n"),
+ &enc, entry->tries);
+ }
}
/**
@@ -1237,70 +1188,79 @@
* (min ttl until next job is ready) and re-schedule itself
* accordingly!
*/
-static cron_t processRequests(RequestManager * rm) {
+static cron_t
+processRequests (RequestManager * rm)
+{
cron_t minSleep;
cron_t now;
cron_t delta;
int i;
unsigned int pending;
- int * perm;
+ int *perm;
unsigned int TTL_DECREMENT;
- MUTEX_LOCK(rm->lock);
- if ( (rm->shutdown == YES) ||
- (rm->requestListIndex == 0) ) {
- MUTEX_UNLOCK(rm->lock);
- return 0;
- }
- now = get_time();
+ MUTEX_LOCK (rm->lock);
+ if ((rm->shutdown == YES) || (rm->requestListIndex == 0))
+ {
+ MUTEX_UNLOCK (rm->lock);
+ return 0;
+ }
+ now = get_time ();
pending = 0;
TTL_DECREMENT = 0;
if (rm->requestListIndex > 0)
TTL_DECREMENT = rm->requestList[0]->node->ctx->TTL_DECREMENT;
- for (i=0;i<rm->requestListIndex;i++) {
- if (rm->requestList[i]->lastTimeout >= now - TTL_DECREMENT) {
- pending++;
- } else if (rm->requestList[i]->searchHandle != NULL) {
- FS_stop_search(rm->sctx,
- rm->requestList[i]->searchHandle);
- rm->requestList[i]->searchHandle = NULL;
+ for (i = 0; i < rm->requestListIndex; i++)
+ {
+ if (rm->requestList[i]->lastTimeout >= now - TTL_DECREMENT)
+ {
+ pending++;
+ }
+ else if (rm->requestList[i]->searchHandle != NULL)
+ {
+ FS_stop_search (rm->sctx, rm->requestList[i]->searchHandle);
+ rm->requestList[i]->searchHandle = NULL;
+ }
}
- }
minSleep = 5000 * cronMILLIS; /* max-sleep! */
- perm = permute(WEAK, rm->requestListIndex);
- for (i=0;i<rm->requestListIndex;i++) {
- int j = perm[i];
- if (rm->requestList[j]->lastTimeout + TTL_DECREMENT < now) {
- int pOCWCubed;
- int pendingOverCWin = pending - rm->congestionWindow;
- if (pendingOverCWin <= 0)
- pendingOverCWin = -1; /* avoid 0! */
- pOCWCubed = pendingOverCWin *
- pendingOverCWin *
- pendingOverCWin;
- if ( (pOCWCubed <= 0) ||
- (pOCWCubed * rm->requestListIndex <= 0) /* see #642 */ ||
- /* avoid no-start: override congestionWindow occasionally... */
- (0 == weak_randomi(rm->requestListIndex *
- pOCWCubed)) ) {
- issueRequest(rm, j);
- delta = (rm->requestList[j]->lastTimeout - now) + TTL_DECREMENT;
- pending++;
- } else {
- delta = 0;
- }
- } else {
- delta = (rm->requestList[j]->lastTimeout + TTL_DECREMENT - now);
+ perm = permute (WEAK, rm->requestListIndex);
+ for (i = 0; i < rm->requestListIndex; i++)
+ {
+ int j = perm[i];
+ if (rm->requestList[j]->lastTimeout + TTL_DECREMENT < now)
+ {
+ int pOCWCubed;
+ int pendingOverCWin = pending - rm->congestionWindow;
+ if (pendingOverCWin <= 0)
+ pendingOverCWin = -1; /* avoid 0! */
+ pOCWCubed = pendingOverCWin * pendingOverCWin * pendingOverCWin;
+ if ((pOCWCubed <= 0) ||
+ (pOCWCubed * rm->requestListIndex <= 0) /* see #642 */ ||
+ /* avoid no-start: override congestionWindow occasionally... */
+ (0 == weak_randomi (rm->requestListIndex * pOCWCubed)))
+ {
+ issueRequest (rm, j);
+ delta = (rm->requestList[j]->lastTimeout - now) + TTL_DECREMENT;
+ pending++;
+ }
+ else
+ {
+ delta = 0;
+ }
+ }
+ else
+ {
+ delta = (rm->requestList[j]->lastTimeout + TTL_DECREMENT - now);
+ }
+ if (delta < minSleep)
+ minSleep = delta;
}
- if (delta < minSleep )
- minSleep = delta;
- }
- FREE(perm);
+ FREE (perm);
if (minSleep < cronMILLIS * 100)
- minSleep = cronMILLIS * 100; /* maximum resolution: 100ms */
- MUTEX_UNLOCK(rm->lock);
+ minSleep = cronMILLIS * 100; /* maximum resolution: 100ms */
+ MUTEX_UNLOCK (rm->lock);
return minSleep;
}
@@ -1314,27 +1274,23 @@
* @param uri the URI of the file (determines what to download)
* @param filename where to store the file
*/
-int ECRS_downloadFile(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri,
- const char * filename,
- unsigned int anonymityLevel,
- ECRS_DownloadProgressCallback dpcb,
- void * dpcbClosure,
- ECRS_TestTerminate tt,
- void * ttClosure) {
- return ECRS_downloadPartialFile(ectx,
- cfg,
- uri,
- filename,
- 0,
- ECRS_fileSize(uri),
- anonymityLevel,
- NO,
- dpcb,
- dpcbClosure,
- tt,
- ttClosure);
+int
+ECRS_downloadFile (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const struct ECRS_URI *uri,
+ const char *filename,
+ unsigned int anonymityLevel,
+ ECRS_DownloadProgressCallback dpcb,
+ void *dpcbClosure, ECRS_TestTerminate tt, void *ttClosure)
+{
+ return ECRS_downloadPartialFile (ectx,
+ cfg,
+ uri,
+ filename,
+ 0,
+ ECRS_fileSize (uri),
+ anonymityLevel,
+ NO, dpcb, dpcbClosure, tt, ttClosure);
}
@@ -1357,212 +1313,217 @@
* @param start starting offset
* @param length length of the download (starting at offset)
*/
-int ECRS_downloadPartialFile(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri,
- const char * filename,
- unsigned long long offset,
- unsigned long long length,
- unsigned int anonymityLevel,
- int no_temporaries,
- ECRS_DownloadProgressCallback dpcb,
- void * dpcbClosure,
- ECRS_TestTerminate tt,
- void * ttClosure) {
+int
+ECRS_downloadPartialFile (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const struct ECRS_URI *uri,
+ const char *filename,
+ unsigned long long offset,
+ unsigned long long length,
+ unsigned int anonymityLevel,
+ int no_temporaries,
+ ECRS_DownloadProgressCallback dpcb,
+ void *dpcbClosure,
+ ECRS_TestTerminate tt, void *ttClosure)
+{
IOContext ioc;
- RequestManager * rm;
+ RequestManager *rm;
int ret;
CommonCtx ctx;
- NodeClosure * top;
+ NodeClosure *top;
FileIdentifier fid;
cron_t minSleep;
- char * realFN;
- char * path;
- char * pos;
+ char *realFN;
+ char *path;
+ char *pos;
struct stat buf;
#if DEBUG_DOWNLOAD
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "`%s' running for file `%s'\n",
- __FUNCTION__,
- filename);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "`%s' running for file `%s'\n", __FUNCTION__, filename);
#endif
- GE_ASSERT(ectx, filename != NULL);
- if ( (filename[strlen(filename)-1] == '/') ||
- (filename[strlen(filename)-1] == '\\') ) {
- realFN = MALLOC(strlen(filename) + strlen(GNUNET_DIRECTORY_EXT));
- strcpy(realFN, filename);
- realFN[strlen(filename)-1] = '\0';
- strcat(realFN, GNUNET_DIRECTORY_EXT);
- } else {
- realFN = STRDUP(filename);
- }
- path = MALLOC(strlen(realFN) * strlen(GNUNET_DIRECTORY_EXT) + 1);
- strcpy(path, realFN);
+ GE_ASSERT (ectx, filename != NULL);
+ if ((filename[strlen (filename) - 1] == '/') ||
+ (filename[strlen (filename) - 1] == '\\'))
+ {
+ realFN = MALLOC (strlen (filename) + strlen (GNUNET_DIRECTORY_EXT));
+ strcpy (realFN, filename);
+ realFN[strlen (filename) - 1] = '\0';
+ strcat (realFN, GNUNET_DIRECTORY_EXT);
+ }
+ else
+ {
+ realFN = STRDUP (filename);
+ }
+ path = MALLOC (strlen (realFN) * strlen (GNUNET_DIRECTORY_EXT) + 1);
+ strcpy (path, realFN);
pos = path;
- while (*pos != '\0') {
- if (*pos == DIR_SEPARATOR) {
- *pos = '\0';
- if ( (0 == STAT(path, &buf)) &&
- (! S_ISDIR(buf.st_mode)) ) {
- *pos = DIR_SEPARATOR;
- memmove(pos + strlen(GNUNET_DIRECTORY_EXT),
- pos,
- strlen(pos));
- memcpy(pos,
- GNUNET_DIRECTORY_EXT,
- strlen(GNUNET_DIRECTORY_EXT));
- pos += strlen(GNUNET_DIRECTORY_EXT);
- } else {
- *pos = DIR_SEPARATOR;
- }
+ while (*pos != '\0')
+ {
+ if (*pos == DIR_SEPARATOR)
+ {
+ *pos = '\0';
+ if ((0 == STAT (path, &buf)) && (!S_ISDIR (buf.st_mode)))
+ {
+ *pos = DIR_SEPARATOR;
+ memmove (pos + strlen (GNUNET_DIRECTORY_EXT),
+ pos, strlen (pos));
+ memcpy (pos,
+ GNUNET_DIRECTORY_EXT, strlen (GNUNET_DIRECTORY_EXT));
+ pos += strlen (GNUNET_DIRECTORY_EXT);
+ }
+ else
+ {
+ *pos = DIR_SEPARATOR;
+ }
+ }
+ pos++;
}
- pos++;
- }
- FREE(realFN);
+ FREE (realFN);
realFN = path;
- if (SYSERR == disk_directory_create_for_file(ectx,
- realFN)) {
- FREE(realFN);
- return SYSERR;
- }
- if (0 == ECRS_fileSize(uri)) {
- ret = disk_file_open(ectx,
- realFN,
- O_CREAT | O_WRONLY | O_TRUNC,
- S_IRUSR|S_IWUSR);
- FREE(realFN);
- if (ret == -1)
+ if (SYSERR == disk_directory_create_for_file (ectx, realFN))
+ {
+ FREE (realFN);
return SYSERR;
- CLOSE(ret);
- dpcb(0, 0, get_time(), 0, NULL, 0, dpcbClosure);
- return OK;
- }
+ }
+ if (0 == ECRS_fileSize (uri))
+ {
+ ret = disk_file_open (ectx,
+ realFN,
+ O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);
+ FREE (realFN);
+ if (ret == -1)
+ return SYSERR;
+ CLOSE (ret);
+ dpcb (0, 0, get_time (), 0, NULL, 0, dpcbClosure);
+ return OK;
+ }
fid = uri->data.fi;
- if ( (! ECRS_isFileUri(uri)) &&
- (! ECRS_isLocationUri(uri))) {
- GE_BREAK(ectx, 0);
- FREE(realFN);
- return SYSERR;
- }
+ if ((!ECRS_isFileUri (uri)) && (!ECRS_isLocationUri (uri)))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (realFN);
+ return SYSERR;
+ }
- if (OK != createIOContext(ectx,
- &ioc,
- no_temporaries,
- ntohll(fid.file_length),
- realFN)) {
+ if (OK != createIOContext (ectx,
+ &ioc,
+ no_temporaries,
+ ntohll (fid.file_length), realFN))
+ {
#if DEBUG_DOWNLOAD
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "`%s' aborted for file `%s'\n",
- __FUNCTION__,
- realFN);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "`%s' aborted for file `%s'\n", __FUNCTION__, realFN);
#endif
- FREE(realFN);
- return SYSERR;
- }
- rm = createRequestManager(ectx,
- cfg);
- if (rm == NULL) {
- freeIOC(&ioc, YES);
- FREE(realFN);
- return SYSERR;
- }
- if (ECRS_isLocationUri(uri)) {
- hash(&uri->data.loc.peer,
- sizeof(PublicKey),
- &rm->target.hashPubKey);
- rm->have_target = YES;
- }
+ FREE (realFN);
+ return SYSERR;
+ }
+ rm = createRequestManager (ectx, cfg);
+ if (rm == NULL)
+ {
+ freeIOC (&ioc, YES);
+ FREE (realFN);
+ return SYSERR;
+ }
+ if (ECRS_isLocationUri (uri))
+ {
+ hash (&uri->data.loc.peer, sizeof (PublicKey), &rm->target.hashPubKey);
+ rm->have_target = YES;
+ }
- ctx.startTime = get_time();
+ ctx.startTime = get_time ();
ctx.anonymityLevel = anonymityLevel;
ctx.offset = offset;
ctx.length = length;
- ctx.TTL_DECREMENT = 5 * cronSECONDS; /* HACK! */
+ ctx.TTL_DECREMENT = 5 * cronSECONDS; /* HACK! */
ctx.rm = rm;
ctx.ioc = &ioc;
ctx.dpcb = dpcb;
ctx.dpcbClosure = dpcbClosure;
- ctx.total = ntohll(fid.file_length);
+ ctx.total = ntohll (fid.file_length);
ctx.completed = 0;
- top = MALLOC(sizeof(NodeClosure));
+ top = MALLOC (sizeof (NodeClosure));
top->ctx = &ctx;
top->chk = fid.chk;
top->offset = 0;
- top->level = computeDepth(ctx.total);
- if (NO == checkPresent(top))
- addRequest(rm, top);
+ top->level = computeDepth (ctx.total);
+ if (NO == checkPresent (top))
+ addRequest (rm, top);
else
- FREE(top);
- while ( (OK == tt(ttClosure)) &&
- (rm->abortFlag == NO) &&
- (rm->requestListIndex != 0) ) {
- minSleep = processRequests(rm);
- if ( (OK == tt(ttClosure)) &&
- (rm->abortFlag == NO) &&
- (rm->requestListIndex != 0) )
- PTHREAD_SLEEP(minSleep);
- }
+ FREE (top);
+ while ((OK == tt (ttClosure)) &&
+ (rm->abortFlag == NO) && (rm->requestListIndex != 0))
+ {
+ minSleep = processRequests (rm);
+ if ((OK == tt (ttClosure)) &&
+ (rm->abortFlag == NO) && (rm->requestListIndex != 0))
+ PTHREAD_SLEEP (minSleep);
+ }
- if ( (rm->requestListIndex == 0) &&
- ( (ctx.completed == ctx.total) ||
- ( (ctx.total != ctx.length) &&
- (ctx.completed >= ctx.length) ) ) &&
- (rm->abortFlag == NO) ) {
- ret = OK;
- } else {
+ if ((rm->requestListIndex == 0) &&
+ ((ctx.completed == ctx.total) ||
+ ((ctx.total != ctx.length) &&
+ (ctx.completed >= ctx.length))) && (rm->abortFlag == NO))
+ {
+ ret = OK;
+ }
+ else
+ {
#if 0
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- "Download ends prematurely: %d %llu == %llu %d TT: %d\n",
- rm->requestListIndex,
- ctx.completed,
- ctx.total,
- rm->abortFlag,
- tt(ttClosure));
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ "Download ends prematurely: %d %llu == %llu %d TT: %d\n",
+ rm->requestListIndex,
+ ctx.completed, ctx.total, rm->abortFlag, tt (ttClosure));
#endif
- ret = SYSERR;
- }
- destroyRequestManager(rm);
- if (ret == OK) {
- freeIOC(&ioc, YES);
- } else if (tt(ttClosure) == SYSERR) {
- freeIOC(&ioc, YES);
- if (0 != UNLINK(realFN)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "unlink",
- realFN);
- } else { /* delete empty directories */
- char * rdir;
- int len;
+ ret = SYSERR;
+ }
+ destroyRequestManager (rm);
+ if (ret == OK)
+ {
+ freeIOC (&ioc, YES);
+ }
+ else if (tt (ttClosure) == SYSERR)
+ {
+ freeIOC (&ioc, YES);
+ if (0 != UNLINK (realFN))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ "unlink", realFN);
+ }
+ else
+ { /* delete empty directories */
+ char *rdir;
+ int len;
- rdir = STRDUP(realFN);
- len = strlen(rdir);
- do {
- while ( (len > 0) &&
- (rdir[len] != DIR_SEPARATOR) )
- len--;
- rdir[len] = '\0';
- } while ( (len > 0) && (0 == rmdir(rdir)) );
- FREE(rdir);
+ rdir = STRDUP (realFN);
+ len = strlen (rdir);
+ do
+ {
+ while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
+ len--;
+ rdir[len] = '\0';
+ }
+ while ((len > 0) && (0 == rmdir (rdir)));
+ FREE (rdir);
+ }
}
- } else {
- freeIOC(&ioc, NO); /* aborted */
- }
+ else
+ {
+ freeIOC (&ioc, NO); /* aborted */
+ }
#if DEBUG_DOWNLOAD
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "`%s' terminating for file `%s' with result %s\n",
- __FUNCTION__,
- filename,
- ret == OK ? "SUCCESS" : "INCOMPLETE");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "`%s' terminating for file `%s' with result %s\n",
+ __FUNCTION__, filename, ret == OK ? "SUCCESS" : "INCOMPLETE");
#endif
- FREE(realFN);
+ FREE (realFN);
return ret;
}
Modified: GNUnet/src/applications/fs/ecrs/ecrs.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/ecrs.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/ecrs.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -29,44 +29,32 @@
#include "platform.h"
#include "ecrs.h"
-void ECRS_encryptInPlace(const HashCode512 * hc,
- void * data,
- unsigned int len) {
- char * tmp;
+void
+ECRS_encryptInPlace (const HashCode512 * hc, void *data, unsigned int len)
+{
+ char *tmp;
SESSIONKEY skey;
INITVECTOR iv;
- hashToKey(hc, &skey, &iv);
- tmp = MALLOC(len);
- GE_ASSERT(NULL,
- len ==
- encryptBlock(data,
- len,
- &skey,
- &iv,
- tmp));
- memcpy(data, tmp, len);
- FREE(tmp);
+ hashToKey (hc, &skey, &iv);
+ tmp = MALLOC (len);
+ GE_ASSERT (NULL, len == encryptBlock (data, len, &skey, &iv, tmp));
+ memcpy (data, tmp, len);
+ FREE (tmp);
}
-void ECRS_decryptInPlace(const HashCode512 * hc,
- void * data,
- unsigned int len) {
- char * tmp;
+void
+ECRS_decryptInPlace (const HashCode512 * hc, void *data, unsigned int len)
+{
+ char *tmp;
SESSIONKEY skey;
INITVECTOR iv;
- hashToKey(hc, &skey, &iv);
- tmp = MALLOC(len);
- GE_ASSERT(NULL,
- len ==
- decryptBlock(&skey,
- data,
- len,
- &iv,
- tmp));
- memcpy(data, tmp, len);
- FREE(tmp);
+ hashToKey (hc, &skey, &iv);
+ tmp = MALLOC (len);
+ GE_ASSERT (NULL, len == decryptBlock (&skey, data, len, &iv, tmp));
+ memcpy (data, tmp, len);
+ FREE (tmp);
}
/* end of ecrs.c */
Modified: GNUnet/src/applications/fs/ecrs/ecrs.h
===================================================================
--- GNUnet/src/applications/fs/ecrs/ecrs.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/ecrs.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -45,7 +45,8 @@
#define BLOCK_ALIGN_SIZE (DBLOCK_SIZE)
-typedef struct Location {
+typedef struct Location
+{
/**
* Information about the shared file.
*/
@@ -71,16 +72,21 @@
} Location;
-enum uri_types { chk, sks, ksk, loc };
+enum uri_types
+{ chk, sks, ksk, loc };
-typedef struct ECRS_URI {
+typedef struct ECRS_URI
+{
enum uri_types type;
- union {
- struct {
- char ** keywords;
+ union
+ {
+ struct
+ {
+ char **keywords;
unsigned int keywordCount;
} ksk;
- struct {
+ struct
+ {
HashCode512 namespace;
HashCode512 identifier;
} sks;
@@ -89,27 +95,27 @@
} data;
} URI;
-typedef struct {
+typedef struct
+{
EXTRACTOR_KeywordType type;
- char * data;
+ char *data;
} Item;
/**
* Meta data to associate with a file, directory or namespace.
*/
-typedef struct ECRS_MetaData {
+typedef struct ECRS_MetaData
+{
unsigned int itemCount;
- Item * items;
+ Item *items;
} MetaData;
-void ECRS_encryptInPlace(const HashCode512 * hc,
- void * data,
- unsigned int len);
+void ECRS_encryptInPlace (const HashCode512 * hc,
+ void *data, unsigned int len);
-void ECRS_decryptInPlace(const HashCode512 * hc,
- void * data,
- unsigned int len);
+void ECRS_decryptInPlace (const HashCode512 * hc,
+ void *data, unsigned int len);
Modified: GNUnet/src/applications/fs/ecrs/ecrstest.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/ecrstest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/ecrstest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -33,208 +33,189 @@
#define CHECK(a) if (!(a)) { ok = NO; GE_BREAK(NULL, 0); goto FAILURE; }
-static int testTerminate(void * unused) {
+static int
+testTerminate (void *unused)
+{
return OK;
}
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static char * makeName(unsigned int i) {
- char * fn;
+static char *
+makeName (unsigned int i)
+{
+ char *fn;
- fn = MALLOC(strlen("/tmp/gnunet-ecrstest/ECRSTEST") + 14);
- SNPRINTF(fn,
- strlen("/tmp/gnunet-ecrstest/ECRSTEST") + 14,
- "/tmp/gnunet-ecrstest/ECRSTEST%u",
- i);
- disk_directory_create_for_file(NULL, fn);
+ fn = MALLOC (strlen ("/tmp/gnunet-ecrstest/ECRSTEST") + 14);
+ SNPRINTF (fn,
+ strlen ("/tmp/gnunet-ecrstest/ECRSTEST") + 14,
+ "/tmp/gnunet-ecrstest/ECRSTEST%u", i);
+ disk_directory_create_for_file (NULL, fn);
return fn;
}
-static struct ECRS_URI * uploadFile(unsigned int size) {
+static struct ECRS_URI *
+uploadFile (unsigned int size)
+{
int ret;
- char * name;
+ char *name;
int fd;
- char * buf;
- struct ECRS_URI * uri;
+ char *buf;
+ struct ECRS_URI *uri;
int i;
- name = makeName(size);
- fd = disk_file_open(NULL,
- name,
- O_WRONLY|O_CREAT, S_IWUSR|S_IRUSR);
- buf = MALLOC(size);
- memset(buf, size + size / 253, size);
- for (i=0;i<(int) (size - 42 - sizeof(HashCode512));i+=sizeof(HashCode512))
- hash(&buf[i],
- 42,
- (HashCode512*) &buf[i+sizeof(HashCode512)]);
- WRITE(fd, buf, size);
- FREE(buf);
- CLOSE(fd);
- ret = ECRS_uploadFile(NULL,
- cfg,
- name,
- YES, /* index */
- 0, /* anon */
- 0, /* prio */
- get_time() + 10 * cronMINUTES, /* expire */
- NULL, /* progress */
- NULL,
- &testTerminate,
- NULL,
- &uri);
- if (ret != SYSERR) {
- struct ECRS_MetaData * meta;
- struct ECRS_URI * key;
- const char * keywords[2];
+ name = makeName (size);
+ fd = disk_file_open (NULL, name, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR);
+ buf = MALLOC (size);
+ memset (buf, size + size / 253, size);
+ for (i = 0; i < (int) (size - 42 - sizeof (HashCode512));
+ i += sizeof (HashCode512))
+ hash (&buf[i], 42, (HashCode512 *) & buf[i + sizeof (HashCode512)]);
+ WRITE (fd, buf, size);
+ FREE (buf);
+ CLOSE (fd);
+ ret = ECRS_uploadFile (NULL, cfg, name, YES, /* index */
+ 0, /* anon */
+ 0, /* prio */
+ get_time () + 10 * cronMINUTES, /* expire */
+ NULL, /* progress */
+ NULL, &testTerminate, NULL, &uri);
+ if (ret != SYSERR)
+ {
+ struct ECRS_MetaData *meta;
+ struct ECRS_URI *key;
+ const char *keywords[2];
- keywords[0] = name;
- keywords[1] = NULL;
+ keywords[0] = name;
+ keywords[1] = NULL;
- meta = ECRS_createMetaData();
- key = ECRS_keywordsToUri(keywords);
- ret = ECRS_addToKeyspace(NULL,
- cfg,
- key,
- 0,
- 0,
- get_time() + 10 * cronMINUTES, /* expire */
- uri,
- meta);
- ECRS_freeMetaData(meta);
- ECRS_freeUri(uri);
- FREE(name);
- if (ret == OK) {
- return key;
- } else {
- ECRS_freeUri(key);
+ meta = ECRS_createMetaData ();
+ key = ECRS_keywordsToUri (keywords);
+ ret = ECRS_addToKeyspace (NULL, cfg, key, 0, 0, get_time () + 10 *
cronMINUTES, /* expire */
+ uri, meta);
+ ECRS_freeMetaData (meta);
+ ECRS_freeUri (uri);
+ FREE (name);
+ if (ret == OK)
+ {
+ return key;
+ }
+ else
+ {
+ ECRS_freeUri (key);
+ return NULL;
+ }
+ }
+ else
+ {
+ FREE (name);
return NULL;
}
- } else {
- FREE(name);
- return NULL;
- }
}
-static int searchCB(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * closure) {
- struct ECRS_URI ** my = closure;
- char * tmp;
+static int
+searchCB (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *closure)
+{
+ struct ECRS_URI **my = closure;
+ char *tmp;
- tmp = ECRS_uriToString(fi->uri);
- GE_LOG(NULL,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Search found URI `%s'\n",
- tmp);
- FREE(tmp);
- GE_ASSERT(NULL, NULL == *my);
- *my = ECRS_dupUri(fi->uri);
- return SYSERR; /* abort search */
+ tmp = ECRS_uriToString (fi->uri);
+ GE_LOG (NULL,
+ GE_DEBUG | GE_REQUEST | GE_USER, "Search found URI `%s'\n", tmp);
+ FREE (tmp);
+ GE_ASSERT (NULL, NULL == *my);
+ *my = ECRS_dupUri (fi->uri);
+ return SYSERR; /* abort search */
}
/**
* @param *uri In: keyword URI, out: file URI
* @return OK on success
*/
-static int searchFile(struct ECRS_URI ** uri) {
+static int
+searchFile (struct ECRS_URI **uri)
+{
int ret;
- struct ECRS_URI * myURI;
+ struct ECRS_URI *myURI;
myURI = NULL;
- ret = ECRS_search(NULL,
- cfg,
- *uri,
- 0,
- 15 * cronSECONDS,
- &searchCB,
- &myURI,
- &testTerminate,
- NULL);
- ECRS_freeUri(*uri);
+ ret = ECRS_search (NULL,
+ cfg,
+ *uri,
+ 0,
+ 15 * cronSECONDS,
+ &searchCB, &myURI, &testTerminate, NULL);
+ ECRS_freeUri (*uri);
*uri = myURI;
- if ( (ret != SYSERR) &&
- (myURI != NULL) )
+ if ((ret != SYSERR) && (myURI != NULL))
return OK;
else
return SYSERR;
}
-static int downloadFile(unsigned int size,
- const struct ECRS_URI * uri) {
+static int
+downloadFile (unsigned int size, const struct ECRS_URI *uri)
+{
int ret;
- char * tmpName;
+ char *tmpName;
int fd;
- char * buf;
- char * in;
+ char *buf;
+ char *in;
int i;
- char * tmp;
+ char *tmp;
- tmp = ECRS_uriToString(uri);
- GE_LOG(NULL,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Starting download of `%s'\n",
- tmp);
- FREE(tmp);
- tmpName = makeName(0);
+ tmp = ECRS_uriToString (uri);
+ GE_LOG (NULL,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Starting download of `%s'\n", tmp);
+ FREE (tmp);
+ tmpName = makeName (0);
ret = SYSERR;
- if (OK == ECRS_downloadFile(NULL,
- cfg,
- uri,
- tmpName,
- 0,
- NULL,
- NULL,
- &testTerminate,
- NULL)) {
+ if (OK == ECRS_downloadFile (NULL,
+ cfg,
+ uri,
+ tmpName, 0, NULL, NULL, &testTerminate, NULL))
+ {
- fd = disk_file_open(NULL,
- tmpName,
- O_RDONLY);
- buf = MALLOC(size);
- in = MALLOC(size);
- memset(buf, size + size / 253, size);
- for (i=0;i<(int) (size - 42 - sizeof(HashCode512));i+=sizeof(HashCode512))
- hash(&buf[i],
- 42,
- (HashCode512*) &buf[i+sizeof(HashCode512)]);
- if (size != READ(fd, in, size))
- ret = SYSERR;
- else if (0 == memcmp(buf,
- in,
- size))
- ret = OK;
- FREE(buf);
- FREE(in);
- CLOSE(fd);
- }
- UNLINK(tmpName);
- FREE(tmpName);
+ fd = disk_file_open (NULL, tmpName, O_RDONLY);
+ buf = MALLOC (size);
+ in = MALLOC (size);
+ memset (buf, size + size / 253, size);
+ for (i = 0; i < (int) (size - 42 - sizeof (HashCode512));
+ i += sizeof (HashCode512))
+ hash (&buf[i], 42, (HashCode512 *) & buf[i + sizeof (HashCode512)]);
+ if (size != READ (fd, in, size))
+ ret = SYSERR;
+ else if (0 == memcmp (buf, in, size))
+ ret = OK;
+ FREE (buf);
+ FREE (in);
+ CLOSE (fd);
+ }
+ UNLINK (tmpName);
+ FREE (tmpName);
return ret;
}
-static int unindexFile(unsigned int size) {
+static int
+unindexFile (unsigned int size)
+{
int ret;
- char * name;
+ char *name;
- name = makeName(size);
- ret = ECRS_unindexFile(NULL,
- cfg,
- name,
- NULL,
- NULL,
- &testTerminate,
- NULL);
- if (0 != UNLINK(name))
+ name = makeName (size);
+ ret = ECRS_unindexFile (NULL, cfg, name, NULL, NULL, &testTerminate, NULL);
+ if (0 != UNLINK (name))
ret = SYSERR;
- FREE(name);
+ FREE (name);
return ret;
}
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
static unsigned int filesizes[] = {
DBLOCK_SIZE - 1,
DBLOCK_SIZE,
@@ -252,53 +233,46 @@
};
pid_t daemon;
int ok;
- struct ClientServerConnection * sock;
- struct ECRS_URI * uri;
+ struct ClientServerConnection *sock;
+ struct ECRS_URI *uri;
int i;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
sock = NULL;
- CHECK(OK == connection_wait_for_running(NULL,
- cfg,
- 30 * cronSECONDS));
+ CHECK (OK == connection_wait_for_running (NULL, cfg, 30 * cronSECONDS));
ok = YES;
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
- sock = client_connection_create(NULL, cfg);
- CHECK(sock != NULL);
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
+ sock = client_connection_create (NULL, cfg);
+ CHECK (sock != NULL);
/* ACTUAL TEST CODE */
i = 0;
- while (filesizes[i] != 0) {
- fprintf(stderr,
- "Testing filesize %u",
- filesizes[i]);
- uri = uploadFile(filesizes[i]);
- CHECK(NULL != uri);
- CHECK(OK == searchFile(&uri));
- CHECK(OK == downloadFile(filesizes[i], uri));
- ECRS_freeUri(uri);
- CHECK(OK == unindexFile(filesizes[i]));
- fprintf(stderr,
- " Ok.\n");
- i++;
- }
+ while (filesizes[i] != 0)
+ {
+ fprintf (stderr, "Testing filesize %u", filesizes[i]);
+ uri = uploadFile (filesizes[i]);
+ CHECK (NULL != uri);
+ CHECK (OK == searchFile (&uri));
+ CHECK (OK == downloadFile (filesizes[i], uri));
+ ECRS_freeUri (uri);
+ CHECK (OK == unindexFile (filesizes[i]));
+ fprintf (stderr, " Ok.\n");
+ i++;
+ }
/* END OF TEST CODE */
- FAILURE:
+FAILURE:
if (sock != NULL)
- connection_destroy(sock);
- GE_ASSERT(NULL, OK == os_daemon_stop(NULL, daemon));
- GC_free(cfg);
+ connection_destroy (sock);
+ GE_ASSERT (NULL, OK == os_daemon_stop (NULL, daemon));
+ GC_free (cfg);
return (ok == YES) ? 0 : 1;
}
Modified: GNUnet/src/applications/fs/ecrs/helper.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/helper.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/helper.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -36,54 +36,63 @@
* @return an ECRS URI for the given keywords, NULL
* if keywords is not legal (i.e. empty).
*/
-struct ECRS_URI * ECRS_parseCharKeywordURI(struct GE_Context * ectx,
- const char * input) {
- char ** keywords;
+struct ECRS_URI *
+ECRS_parseCharKeywordURI (struct GE_Context *ectx, const char *input)
+{
+ char **keywords;
unsigned int num_Words;
int inWord;
- char * c;
- struct ECRS_URI * uri;
- char * searchString;
+ char *c;
+ struct ECRS_URI *uri;
+ char *searchString;
- if (input == NULL) {
- GE_BREAK(ectx, 0);
- return NULL;
- }
- searchString = STRDUP(input);
+ if (input == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
+ searchString = STRDUP (input);
num_Words = 0;
- for (inWord = 0, c = searchString; *c != '\0'; ++c) {
- if (isspace(*c)) {
- inWord = 0;
- } else if (!inWord) {
- inWord = 1;
- ++num_Words;
+ for (inWord = 0, c = searchString; *c != '\0'; ++c)
+ {
+ if (isspace (*c))
+ {
+ inWord = 0;
+ }
+ else if (!inWord)
+ {
+ inWord = 1;
+ ++num_Words;
+ }
}
- }
- if (num_Words == 0) {
- FREENONNULL(searchString);
- GE_LOG(ectx,
- GE_ERROR | GE_IMMEDIATE | GE_USER,
- _("No keywords specified!\n"));
- return NULL;
- }
- keywords = MALLOC(num_Words * sizeof(char *));
+ if (num_Words == 0)
+ {
+ FREENONNULL (searchString);
+ GE_LOG (ectx,
+ GE_ERROR | GE_IMMEDIATE | GE_USER,
+ _("No keywords specified!\n"));
+ return NULL;
+ }
+ keywords = MALLOC (num_Words * sizeof (char *));
num_Words = 0;
- for (inWord = 0, c = searchString; *c != '\0'; ++c) {
- if (isspace(*c)) {
- inWord = 0;
- *c = '\0';
- } else if (!inWord) {
- keywords[num_Words] = c;
- inWord = 1;
- ++num_Words;
+ for (inWord = 0, c = searchString; *c != '\0'; ++c)
+ {
+ if (isspace (*c))
+ {
+ inWord = 0;
+ *c = '\0';
+ }
+ else if (!inWord)
+ {
+ keywords[num_Words] = c;
+ inWord = 1;
+ ++num_Words;
+ }
}
- }
- uri = ECRS_parseArgvKeywordURI(ectx,
- num_Words,
- (const char**) keywords);
- FREE(keywords);
- FREE(searchString);
+ uri = ECRS_parseArgvKeywordURI (ectx, num_Words, (const char **) keywords);
+ FREE (keywords);
+ FREE (searchString);
return uri;
}
@@ -95,50 +104,48 @@
* @return an ECRS URI for the given keywords, NULL
* if keywords is not legal (i.e. empty).
*/
-struct ECRS_URI * ECRS_parseArgvKeywordURI(struct GE_Context * ectx,
- unsigned int num_keywords,
- const char ** keywords) {
+struct ECRS_URI *
+ECRS_parseArgvKeywordURI (struct GE_Context *ectx,
+ unsigned int num_keywords, const char **keywords)
+{
unsigned int i;
unsigned int uriLen;
- char * uriString;
+ char *uriString;
unsigned int uriSize;
- struct ECRS_URI * uri;
+ struct ECRS_URI *uri;
uriString = NULL;
uriSize = 0;
- GROW(uriString,
- uriSize,
- 4096);
- strcpy(uriString, ECRS_URI_PREFIX);
- strcat(uriString, ECRS_SEARCH_INFIX);
- uriLen = 1 + strlen(ECRS_URI_PREFIX) + strlen(ECRS_SEARCH_INFIX);
+ GROW (uriString, uriSize, 4096);
+ strcpy (uriString, ECRS_URI_PREFIX);
+ strcat (uriString, ECRS_SEARCH_INFIX);
+ uriLen = 1 + strlen (ECRS_URI_PREFIX) + strlen (ECRS_SEARCH_INFIX);
- for (i=0;i<num_keywords;i++) {
- if (uriSize < uriLen + strlen(_("AND")) + 1 + strlen(keywords[i]))
- GROW(uriString,
- uriSize,
- uriSize + 4096 + strlen(keywords[i]));
- if ( (i > 0) &&
- (0 == strcmp(keywords[i], _("AND"))) ) {
- strcat(uriString, "+");
- if (i == num_keywords-1)
- strcat(uriString, _("AND")); /* last keyword 'AND'? keep it! */
- uriLen += 1;
- } else {
- if ( (i > 0) &&
- (0 != strcmp(keywords[i-1], _("AND"))) ) {
- strcat(uriString, " ");
- uriLen += 1;
- }
- strcat(uriString, keywords[i]);
- uriLen += strlen(keywords[i]);
+ for (i = 0; i < num_keywords; i++)
+ {
+ if (uriSize < uriLen + strlen (_("AND")) + 1 + strlen (keywords[i]))
+ GROW (uriString, uriSize, uriSize + 4096 + strlen (keywords[i]));
+ if ((i > 0) && (0 == strcmp (keywords[i], _("AND"))))
+ {
+ strcat (uriString, "+");
+ if (i == num_keywords - 1)
+ strcat (uriString, _("AND")); /* last keyword 'AND'? keep
it! */
+ uriLen += 1;
+ }
+ else
+ {
+ if ((i > 0) && (0 != strcmp (keywords[i - 1], _("AND"))))
+ {
+ strcat (uriString, " ");
+ uriLen += 1;
+ }
+ strcat (uriString, keywords[i]);
+ uriLen += strlen (keywords[i]);
+ }
}
- }
- uri = ECRS_stringToUri(ectx, uriString);
- GROW(uriString,
- uriSize,
- 0);
+ uri = ECRS_stringToUri (ectx, uriString);
+ GROW (uriString, uriSize, 0);
return uri;
}
@@ -150,41 +157,38 @@
* @return an ECRS URI for the given keywords, NULL
* if keywords is not legal (i.e. empty).
*/
-struct ECRS_URI * ECRS_parseListKeywordURI(struct GE_Context * ectx,
- unsigned int num_keywords,
- const char ** keywords) {
+struct ECRS_URI *
+ECRS_parseListKeywordURI (struct GE_Context *ectx,
+ unsigned int num_keywords, const char **keywords)
+{
unsigned int i;
unsigned int uriLen;
- char * uriString;
+ char *uriString;
unsigned int uriSize;
- struct ECRS_URI * uri;
+ struct ECRS_URI *uri;
uriString = NULL;
uriSize = 0;
- GROW(uriString,
- uriSize,
- 4096);
- strcpy(uriString, ECRS_URI_PREFIX);
- strcat(uriString, ECRS_SEARCH_INFIX);
- uriLen = 1 + strlen(ECRS_URI_PREFIX) + strlen(ECRS_SEARCH_INFIX);
+ GROW (uriString, uriSize, 4096);
+ strcpy (uriString, ECRS_URI_PREFIX);
+ strcat (uriString, ECRS_SEARCH_INFIX);
+ uriLen = 1 + strlen (ECRS_URI_PREFIX) + strlen (ECRS_SEARCH_INFIX);
- for (i=0;i<num_keywords;i++) {
- if (uriSize < uriLen + 1 + strlen(keywords[i]))
- GROW(uriString,
- uriSize,
- uriSize + 4096 + strlen(keywords[i]));
- if (i > 0) {
- strcat(uriString, "+");
- uriLen++;
+ for (i = 0; i < num_keywords; i++)
+ {
+ if (uriSize < uriLen + 1 + strlen (keywords[i]))
+ GROW (uriString, uriSize, uriSize + 4096 + strlen (keywords[i]));
+ if (i > 0)
+ {
+ strcat (uriString, "+");
+ uriLen++;
+ }
+ strcat (uriString, keywords[i]);
+ uriLen += strlen (keywords[i]);
}
- strcat(uriString, keywords[i]);
- uriLen += strlen(keywords[i]);
- }
- uri = ECRS_stringToUri(ectx, uriString);
- GROW(uriString,
- uriSize,
- 0);
+ uri = ECRS_stringToUri (ectx, uriString);
+ GROW (uriString, uriSize, 0);
return uri;
}
Modified: GNUnet/src/applications/fs/ecrs/indexinfo.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/indexinfo.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/indexinfo.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -38,88 +38,89 @@
* in either case, if SYSERR is returned the user should probably
* be notified that 'something is wrong')
*/
-int ECRS_isFileIndexed(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * filename) {
+int
+ECRS_isFileIndexed (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, const char *filename)
+{
HashCode512 hc;
- struct ClientServerConnection * sock;
+ struct ClientServerConnection *sock;
int ret;
- if (SYSERR == getFileHash(ectx,
- filename,
- &hc))
+ if (SYSERR == getFileHash (ectx, filename, &hc))
return SYSERR;
- sock = client_connection_create(ectx, cfg);
+ sock = client_connection_create (ectx, cfg);
if (sock == NULL)
return SYSERR;
- ret = FS_testIndexed(sock,
- &hc);
- connection_destroy(sock);
+ ret = FS_testIndexed (sock, &hc);
+ connection_destroy (sock);
return ret;
}
-struct iiC {
- struct GE_Context * ectx;
+struct iiC
+{
+ struct GE_Context *ectx;
ECRS_FileIterator iterator;
- void * closure;
+ void *closure;
int cnt;
};
-static int iiHelper(const char * fn,
- const char * dir,
- void * ptr) {
- struct iiC * cls = ptr;
- char * fullName;
- char * lnkName;
+static int
+iiHelper (const char *fn, const char *dir, void *ptr)
+{
+ struct iiC *cls = ptr;
+ char *fullName;
+ char *lnkName;
unsigned int size;
int ret;
- fullName = MALLOC(strlen(dir) + strlen(fn) + 4);
- strcpy(fullName, dir);
- strcat(fullName, DIR_SEPARATOR_STR);
- strcat(fullName, fn);
+ fullName = MALLOC (strlen (dir) + strlen (fn) + 4);
+ strcpy (fullName, dir);
+ strcat (fullName, DIR_SEPARATOR_STR);
+ strcat (fullName, fn);
size = 256;
- lnkName = MALLOC(size);
- while (1) {
- ret = READLINK(fullName,
- lnkName,
- size - 1);
- if (ret == -1) {
- if (errno == ENAMETOOLONG) {
- if (size * 2 < size) {
- FREE(lnkName);
- FREE(fullName);
- return OK; /* error */
- }
- GROW(lnkName,
- size,
- size * 2);
- continue;
- }
- if (errno != EINVAL) {
- GE_LOG_STRERROR_FILE(cls->ectx,
- GE_WARNING | GE_BULK | GE_ADMIN | GE_USER,
- "readlink",
- fullName);
- }
- FREE(lnkName);
- FREE(fullName);
- return OK; /* error */
- } else {
- lnkName[ret] = '\0';
- break;
+ lnkName = MALLOC (size);
+ while (1)
+ {
+ ret = READLINK (fullName, lnkName, size - 1);
+ if (ret == -1)
+ {
+ if (errno == ENAMETOOLONG)
+ {
+ if (size * 2 < size)
+ {
+ FREE (lnkName);
+ FREE (fullName);
+ return OK; /* error */
+ }
+ GROW (lnkName, size, size * 2);
+ continue;
+ }
+ if (errno != EINVAL)
+ {
+ GE_LOG_STRERROR_FILE (cls->ectx,
+ GE_WARNING | GE_BULK | GE_ADMIN | GE_USER,
+ "readlink", fullName);
+ }
+ FREE (lnkName);
+ FREE (fullName);
+ return OK; /* error */
+ }
+ else
+ {
+ lnkName[ret] = '\0';
+ break;
+ }
}
- }
cls->cnt++;
- if (OK != cls->iterator(lnkName,
- cls->closure)) {
- cls->cnt = SYSERR;
- FREE(fullName);
- FREE(lnkName);
- return SYSERR;
- }
- FREE(fullName);
- FREE(lnkName);
+ if (OK != cls->iterator (lnkName, cls->closure))
+ {
+ cls->cnt = SYSERR;
+ FREE (fullName);
+ FREE (lnkName);
+ return SYSERR;
+ }
+ FREE (fullName);
+ FREE (lnkName);
return OK;
}
@@ -135,36 +136,33 @@
*
* @return number of files indexed, SYSERR if iterator aborted
*/
-int ECRS_iterateIndexedFiles(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- ECRS_FileIterator iterator,
- void * closure) {
- char * tmp;
- char * indexDirectory;
- struct ClientServerConnection * sock;
+int
+ECRS_iterateIndexedFiles (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ ECRS_FileIterator iterator, void *closure)
+{
+ char *tmp;
+ char *indexDirectory;
+ struct ClientServerConnection *sock;
struct iiC cls;
- sock = client_connection_create(ectx, cfg);
+ sock = client_connection_create (ectx, cfg);
if (sock == NULL)
return 0;
- tmp = getConfigurationOptionValue(sock,
- "FS",
- "INDEX-DIRECTORY");
- connection_destroy(sock);
- if (tmp == NULL) {
- return 0;
- }
- indexDirectory = string_expandFileName(ectx, tmp);
- FREE(tmp);
+ tmp = getConfigurationOptionValue (sock, "FS", "INDEX-DIRECTORY");
+ connection_destroy (sock);
+ if (tmp == NULL)
+ {
+ return 0;
+ }
+ indexDirectory = string_expandFileName (ectx, tmp);
+ FREE (tmp);
cls.ectx = ectx;
cls.iterator = iterator;
cls.closure = closure;
cls.cnt = 0;
- disk_directory_scan(ectx,
- indexDirectory,
- &iiHelper,
- &cls);
- FREE(indexDirectory);
+ disk_directory_scan (ectx, indexDirectory, &iiHelper, &cls);
+ FREE (indexDirectory);
return cls.cnt;
}
Modified: GNUnet/src/applications/fs/ecrs/keyspace.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/keyspace.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/keyspace.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -51,58 +51,54 @@
*
* @return SYSERR if the entry is malformed
*/
-static int verifyKBlock(struct GE_Context * ectx,
- const HashCode512 * key,
- Datastore_Value * value) {
+static int
+verifyKBlock (struct GE_Context *ectx,
+ const HashCode512 * key, Datastore_Value * value)
+{
unsigned int type;
ECRS_FileInfo fi;
unsigned int size;
HashCode512 query;
- KBlock * kb;
- const char * dstURI;
+ KBlock *kb;
+ const char *dstURI;
int j;
- type = ntohl(value->type);
- size = ntohl(value->size) - sizeof(Datastore_Value);
- if (OK != getQueryFor(size,
- (DBlock*) &value[1],
- YES,
- &query))
+ type = ntohl (value->type);
+ size = ntohl (value->size) - sizeof (Datastore_Value);
+ if (OK != getQueryFor (size, (DBlock *) & value[1], YES, &query))
return SYSERR;
- GE_ASSERT(ectx, type == K_BLOCK);
+ GE_ASSERT (ectx, type == K_BLOCK);
- if (size < sizeof(KBlock))
+ if (size < sizeof (KBlock))
return SYSERR;
- kb = (KBlock*) &value[1];
- ECRS_decryptInPlace(key,
- &kb[1],
- size - sizeof(KBlock));
- j = sizeof(KBlock);
- while ( (j < size) &&
- (((const char*)kb)[j] != '\0') )
+ kb = (KBlock *) & value[1];
+ ECRS_decryptInPlace (key, &kb[1], size - sizeof (KBlock));
+ j = sizeof (KBlock);
+ while ((j < size) && (((const char *) kb)[j] != '\0'))
j++;
- if (j == size) {
- GE_BREAK(NULL, 0); /* kblock malformed */
- return SYSERR;
- }
- dstURI = (const char*) &kb[1];
+ if (j == size)
+ {
+ GE_BREAK (NULL, 0); /* kblock malformed */
+ return SYSERR;
+ }
+ dstURI = (const char *) &kb[1];
j++;
- fi.meta = ECRS_deserializeMetaData(ectx,
- &((const char*)kb)[j],
- size - j);
- if (fi.meta == NULL) {
- GE_BREAK(ectx, 0); /* kblock malformed */
- return SYSERR;
- }
- fi.uri = ECRS_stringToUri(ectx,
- dstURI);
- if (fi.uri == NULL) {
- GE_BREAK(ectx, 0); /* kblock malformed */
- ECRS_freeMetaData(fi.meta);
- return SYSERR;
- }
- ECRS_freeUri(fi.uri);
- ECRS_freeMetaData(fi.meta);
+ fi.meta = ECRS_deserializeMetaData (ectx,
+ &((const char *) kb)[j], size - j);
+ if (fi.meta == NULL)
+ {
+ GE_BREAK (ectx, 0); /* kblock malformed */
+ return SYSERR;
+ }
+ fi.uri = ECRS_stringToUri (ectx, dstURI);
+ if (fi.uri == NULL)
+ {
+ GE_BREAK (ectx, 0); /* kblock malformed */
+ ECRS_freeMetaData (fi.meta);
+ return SYSERR;
+ }
+ ECRS_freeUri (fi.uri);
+ ECRS_freeMetaData (fi.meta);
return OK;
}
@@ -118,23 +114,25 @@
* @param md what meta-data should be associated with the
* entry?
*/
-int ECRS_addToKeyspace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri,
- unsigned int anonymityLevel,
- unsigned int priority,
- cron_t expirationTime,
- const struct ECRS_URI * dst,
- const struct ECRS_MetaData * md) {
- struct ClientServerConnection * sock;
- Datastore_Value * value;
+int
+ECRS_addToKeyspace (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const struct ECRS_URI *uri,
+ unsigned int anonymityLevel,
+ unsigned int priority,
+ cron_t expirationTime,
+ const struct ECRS_URI *dst,
+ const struct ECRS_MetaData *md)
+{
+ struct ClientServerConnection *sock;
+ Datastore_Value *value;
int ret;
unsigned int size;
unsigned int mdsize;
- struct PrivateKey * pk;
- char * dstURI;
- KBlock * kb;
- char ** keywords;
+ struct PrivateKey *pk;
+ char *dstURI;
+ KBlock *kb;
+ char **keywords;
unsigned int keywordCount;
int i;
#if DEBUG_KEYSPACE
@@ -144,124 +142,103 @@
HashCode512 hc;
#endif
HashCode512 key;
- char * cpy; /* copy of the encrypted portion */
- struct ECRS_URI * xuri;
+ char *cpy; /* copy of the encrypted portion */
+ struct ECRS_URI *xuri;
- if (! ECRS_isKeywordUri(uri)) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- mdsize = ECRS_sizeofMetaData(md,
- ECRS_SERIALIZE_PART);
- dstURI = ECRS_uriToString(dst);
- size = mdsize + sizeof(KBlock) + strlen(dstURI) + 1;
- if (size > MAX_KBLOCK_SIZE) {
- size = MAX_KBLOCK_SIZE;
- value = MALLOC(sizeof(Datastore_Value) +
- size);
- kb = (KBlock*) &value[1];
- kb->type = htonl(K_BLOCK);
- memcpy(&kb[1],
- dstURI,
- strlen(dstURI)+1);
- mdsize = size - sizeof(KBlock) - strlen(dstURI) - 1;
- mdsize = ECRS_serializeMetaData(ectx,
- md,
- &((char*)&kb[1])[strlen(dstURI)+1],
- mdsize,
- ECRS_SERIALIZE_PART);
- if (mdsize == -1) {
- GE_BREAK(ectx, 0);
- FREE(dstURI);
+ if (!ECRS_isKeywordUri (uri))
+ {
+ GE_BREAK (ectx, 0);
return SYSERR;
}
- size = sizeof(KBlock) + strlen(dstURI) + 1 + mdsize;
- } else {
- value = MALLOC(sizeof(Datastore_Value) +
- size);
- kb = (KBlock*) &value[1];
- kb->type = htonl(K_BLOCK);
- memcpy(&kb[1],
- dstURI,
- strlen(dstURI)+1);
- GE_ASSERT(ectx,
- mdsize ==
- ECRS_serializeMetaData(ectx,
- md,
- &((char*)&kb[1])[strlen(dstURI)+1],
- mdsize,
- ECRS_SERIALIZE_FULL));
- }
- value->size = htonl(sizeof(Datastore_Value) + size);
- value->type = htonl(K_BLOCK);
- value->prio = htonl(priority);
- value->anonymityLevel = htonl(anonymityLevel);
- value->expirationTime = htonll(expirationTime);
- sock = client_connection_create(ectx, cfg);
+ mdsize = ECRS_sizeofMetaData (md, ECRS_SERIALIZE_PART);
+ dstURI = ECRS_uriToString (dst);
+ size = mdsize + sizeof (KBlock) + strlen (dstURI) + 1;
+ if (size > MAX_KBLOCK_SIZE)
+ {
+ size = MAX_KBLOCK_SIZE;
+ value = MALLOC (sizeof (Datastore_Value) + size);
+ kb = (KBlock *) & value[1];
+ kb->type = htonl (K_BLOCK);
+ memcpy (&kb[1], dstURI, strlen (dstURI) + 1);
+ mdsize = size - sizeof (KBlock) - strlen (dstURI) - 1;
+ mdsize = ECRS_serializeMetaData (ectx,
+ md,
+ &((char *) &kb[1])[strlen (dstURI) +
+ 1], mdsize,
+ ECRS_SERIALIZE_PART);
+ if (mdsize == -1)
+ {
+ GE_BREAK (ectx, 0);
+ FREE (dstURI);
+ return SYSERR;
+ }
+ size = sizeof (KBlock) + strlen (dstURI) + 1 + mdsize;
+ }
+ else
+ {
+ value = MALLOC (sizeof (Datastore_Value) + size);
+ kb = (KBlock *) & value[1];
+ kb->type = htonl (K_BLOCK);
+ memcpy (&kb[1], dstURI, strlen (dstURI) + 1);
+ GE_ASSERT (ectx,
+ mdsize ==
+ ECRS_serializeMetaData (ectx,
+ md,
+ &((char *) &kb[1])[strlen (dstURI) +
+ 1], mdsize,
+ ECRS_SERIALIZE_FULL));
+ }
+ value->size = htonl (sizeof (Datastore_Value) + size);
+ value->type = htonl (K_BLOCK);
+ value->prio = htonl (priority);
+ value->anonymityLevel = htonl (anonymityLevel);
+ value->expirationTime = htonll (expirationTime);
+ sock = client_connection_create (ectx, cfg);
ret = OK;
- if (GC_get_configuration_value_yesno(cfg,
- "FS",
- "DISABLE-CREATION-TIME",
- NO) == YES)
- xuri = ECRS_dupUri(uri);
+ if (GC_get_configuration_value_yesno (cfg,
+ "FS",
+ "DISABLE-CREATION-TIME", NO) == YES)
+ xuri = ECRS_dupUri (uri);
else
- xuri = ECRS_dateExpandKeywordUri(uri);
+ xuri = ECRS_dateExpandKeywordUri (uri);
keywords = xuri->data.ksk.keywords;
keywordCount = xuri->data.ksk.keywordCount;
- cpy = MALLOC(mdsize + strlen(dstURI) + 1);
- memcpy(cpy,
- &kb[1],
- mdsize + strlen(dstURI) + 1);
- for (i=0;i<keywordCount;i++) {
- memcpy(&kb[1], cpy, mdsize + strlen(dstURI) + 1);
- hash(keywords[i],
- strlen(keywords[i]),
- &key);
+ cpy = MALLOC (mdsize + strlen (dstURI) + 1);
+ memcpy (cpy, &kb[1], mdsize + strlen (dstURI) + 1);
+ for (i = 0; i < keywordCount; i++)
+ {
+ memcpy (&kb[1], cpy, mdsize + strlen (dstURI) + 1);
+ hash (keywords[i], strlen (keywords[i]), &key);
#if DEBUG_KEYSPACE
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&key,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Encrypting KBlock with key %s.\n",
- &enc);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (&key, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Encrypting KBlock with key %s.\n", &enc);
#endif
- ECRS_encryptInPlace(&key,
- &kb[1],
- mdsize + strlen(dstURI) + 1);
- pk = makeKblockKey(&key);
- getPublicKey(pk,
- &kb->keyspace);
- GE_ASSERT(ectx,
- OK == sign(pk,
- mdsize + strlen(dstURI) + 1,
- &kb[1],
- &kb->signature));
+ ECRS_encryptInPlace (&key, &kb[1], mdsize + strlen (dstURI) + 1);
+ pk = makeKblockKey (&key);
+ getPublicKey (pk, &kb->keyspace);
+ GE_ASSERT (ectx,
+ OK == sign (pk,
+ mdsize + strlen (dstURI) + 1,
+ &kb[1], &kb->signature));
#if EXTRA_CHECKS
- /* extra check: verify sig */
- GE_ASSERT(ectx,
- OK == getQueryFor(size,
- (DBlock*) kb,
- YES,
- &hc));
+ /* extra check: verify sig */
+ GE_ASSERT (ectx, OK == getQueryFor (size, (DBlock *) kb, YES, &hc));
#endif
- freePrivateKey(pk);
- if (OK != FS_insert(sock, value))
- ret = SYSERR;
+ freePrivateKey (pk);
+ if (OK != FS_insert (sock, value))
+ ret = SYSERR;
#if EXTRA_CHECKS
- GE_ASSERT(ectx,
- OK == verifyKBlock(ectx,
- &key,
- value))
+ GE_ASSERT (ectx, OK == verifyKBlock (ectx, &key, value))
#endif
- }
- ECRS_freeUri(xuri);
- FREE(cpy);
- FREE(dstURI);
- connection_destroy(sock);
- FREE(value);
+ }
+ ECRS_freeUri (xuri);
+ FREE (cpy);
+ FREE (dstURI);
+ connection_destroy (sock);
+ FREE (value);
return ret;
}
Modified: GNUnet/src/applications/fs/ecrs/meta.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/meta.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/meta.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -34,9 +34,11 @@
/**
* Create a fresh MetaData token.
*/
-MetaData * ECRS_createMetaData() {
- MetaData * ret;
- ret = MALLOC(sizeof(MetaData));
+MetaData *
+ECRS_createMetaData ()
+{
+ MetaData *ret;
+ ret = MALLOC (sizeof (MetaData));
ret->items = NULL;
ret->itemCount = 0;
return ret;
@@ -45,57 +47,54 @@
/**
* Free meta data.
*/
-void ECRS_freeMetaData(MetaData * md) {
+void
+ECRS_freeMetaData (MetaData * md)
+{
int i;
- for (i=0;i<md->itemCount;i++)
- FREE(md->items[i].data);
- GROW(md->items,
- md->itemCount,
- 0);
- FREE(md);
+ for (i = 0; i < md->itemCount; i++)
+ FREE (md->items[i].data);
+ GROW (md->items, md->itemCount, 0);
+ FREE (md);
}
/**
* Add the current time as the publication date
* to the meta-data.
*/
-void ECRS_addPublicationDateToMetaData(MetaData * md) {
- char * dat;
+void
+ECRS_addPublicationDateToMetaData (MetaData * md)
+{
+ char *dat;
TIME_T t;
- TIME(&t);
- ECRS_delFromMetaData(md,
- EXTRACTOR_PUBLICATION_DATE,
- NULL);
- dat = GN_CTIME(&t);
- ECRS_addToMetaData(md,
- EXTRACTOR_PUBLICATION_DATE,
- dat);
- FREE(dat);
+ TIME (&t);
+ ECRS_delFromMetaData (md, EXTRACTOR_PUBLICATION_DATE, NULL);
+ dat = GN_CTIME (&t);
+ ECRS_addToMetaData (md, EXTRACTOR_PUBLICATION_DATE, dat);
+ FREE (dat);
}
/**
* Extend metadata.
* @return OK on success, SYSERR if this entry already exists
*/
-int ECRS_addToMetaData(MetaData * md,
- EXTRACTOR_KeywordType type,
- const char * data) {
+int
+ECRS_addToMetaData (MetaData * md,
+ EXTRACTOR_KeywordType type, const char *data)
+{
int idx;
- GE_ASSERT(NULL, data != NULL);
- for (idx=0;idx<md->itemCount;idx++) {
- if ( (md->items[idx].type == type) &&
- (0 == strcmp(md->items[idx].data,
- data)) )
- return SYSERR;
- }
+ GE_ASSERT (NULL, data != NULL);
+ for (idx = 0; idx < md->itemCount; idx++)
+ {
+ if ((md->items[idx].type == type) &&
+ (0 == strcmp (md->items[idx].data, data)))
+ return SYSERR;
+ }
idx = md->itemCount;
- GROW(md->items,
- md->itemCount,
- md->itemCount+1);
+ GROW (md->items, md->itemCount, md->itemCount + 1);
md->items[idx].type = type;
- md->items[idx].data = STRDUP(data);
+ md->items[idx].data = STRDUP (data);
return OK;
}
@@ -103,28 +102,28 @@
* Remove an item.
* @return OK on success, SYSERR if the item does not exist in md
*/
-int ECRS_delFromMetaData(MetaData * md,
- EXTRACTOR_KeywordType type,
- const char * data) {
+int
+ECRS_delFromMetaData (MetaData * md,
+ EXTRACTOR_KeywordType type, const char *data)
+{
int idx;
int ret = SYSERR;
- for (idx=0;idx<md->itemCount;idx++) {
- if ( (md->items[idx].type == type) &&
- ( (data == NULL) ||
- (0 == strcmp(md->items[idx].data,
- data)) ) ) {
- FREE(md->items[idx].data);
- md->items[idx] = md->items[md->itemCount-1];
- GROW(md->items,
- md->itemCount,
- md->itemCount-1);
- if (data == NULL) {
- ret = OK;
- continue;
- }
- return OK;
+ for (idx = 0; idx < md->itemCount; idx++)
+ {
+ if ((md->items[idx].type == type) &&
+ ((data == NULL) || (0 == strcmp (md->items[idx].data, data))))
+ {
+ FREE (md->items[idx].data);
+ md->items[idx] = md->items[md->itemCount - 1];
+ GROW (md->items, md->itemCount, md->itemCount - 1);
+ if (data == NULL)
+ {
+ ret = OK;
+ continue;
+ }
+ return OK;
+ }
}
- }
return ret;
}
@@ -133,23 +132,26 @@
*
* @return number of entries
*/
-int ECRS_getMetaData(const MetaData * md,
- ECRS_MetaDataIterator iterator,
- void * closure) {
+int
+ECRS_getMetaData (const MetaData * md,
+ ECRS_MetaDataIterator iterator, void *closure)
+{
int i;
int sub;
sub = 0;
- for (i=md->itemCount-1;i>=0;i--) {
- if (md->items[i].type != EXTRACTOR_THUMBNAIL_DATA) {
- if ( (iterator != NULL) &&
- (OK != iterator(md->items[i].type,
- md->items[i].data,
- closure)) )
- return SYSERR;
- } else
- sub++;
- }
+ for (i = md->itemCount - 1; i >= 0; i--)
+ {
+ if (md->items[i].type != EXTRACTOR_THUMBNAIL_DATA)
+ {
+ if ((iterator != NULL) &&
+ (OK != iterator (md->items[i].type,
+ md->items[i].data, closure)))
+ return SYSERR;
+ }
+ else
+ sub++;
+ }
return md->itemCount - sub;
}
@@ -158,13 +160,14 @@
*
* @return number of entries
*/
-char * ECRS_getFromMetaData(const MetaData * md,
- EXTRACTOR_KeywordType type) {
+char *
+ECRS_getFromMetaData (const MetaData * md, EXTRACTOR_KeywordType type)
+{
int i;
- for (i=md->itemCount-1;i>=0;i--)
+ for (i = md->itemCount - 1; i >= 0; i--)
if (type == md->items[i].type)
- return STRDUP(md->items[i].data);
+ return STRDUP (md->items[i].data);
return NULL;
}
@@ -173,24 +176,25 @@
*
* @return number of entries
*/
-char * ECRS_getFirstFromMetaData(const MetaData * md,
- ...) {
- char * ret;
+char *
+ECRS_getFirstFromMetaData (const MetaData * md, ...)
+{
+ char *ret;
va_list args;
EXTRACTOR_KeywordType type;
ret = NULL;
- va_start(args, md);
- while (1) {
- type = va_arg(args, EXTRACTOR_KeywordType);
- if (type == -1)
- break;
- ret = ECRS_getFromMetaData(md,
- type);
- if (ret != NULL)
- break;
- }
- va_end(args);
+ va_start (args, md);
+ while (1)
+ {
+ type = va_arg (args, EXTRACTOR_KeywordType);
+ if (type == -1)
+ break;
+ ret = ECRS_getFromMetaData (md, type);
+ if (ret != NULL)
+ break;
+ }
+ va_end (args);
return ret;
}
@@ -202,10 +206,10 @@
* @param in 0-terminated string from the meta-data
* @return 1 on error, 0 on success
*/
-static int decodeThumbnail(const char * in,
- unsigned char ** out,
- size_t * outSize) {
- unsigned char * buf;
+static int
+decodeThumbnail (const char *in, unsigned char **out, size_t * outSize)
+{
+ unsigned char *buf;
size_t pos;
size_t wpos;
unsigned char marker;
@@ -213,27 +217,29 @@
size_t end;
size_t inSize;
- inSize = strlen(in);
- if (inSize == 0) {
- *out = NULL;
- *outSize = 0;
- return 1;
- }
+ inSize = strlen (in);
+ if (inSize == 0)
+ {
+ *out = NULL;
+ *outSize = 0;
+ return 1;
+ }
- buf = malloc(inSize); /* slightly more than needed ;-) */
+ buf = malloc (inSize); /* slightly more than needed ;-) */
*out = buf;
pos = 0;
wpos = 0;
- while (pos < inSize) {
- end = pos + 255; /* 255 here: count the marker! */
- if (end > inSize)
- end = inSize;
- marker = in[pos++];
- for (i=pos;i<end;i++)
- buf[wpos++] = (in[i] == marker) ? 0 : in[i];
- pos = end;
- }
+ while (pos < inSize)
+ {
+ end = pos + 255; /* 255 here: count the marker! */
+ if (end > inSize)
+ end = inSize;
+ marker = in[pos++];
+ for (i = pos; i < end; i++)
+ buf[wpos++] = (in[i] == marker) ? 0 : in[i];
+ pos = end;
+ }
*outSize = wpos;
return 0;
}
@@ -245,25 +251,25 @@
* freed by the caller!
* @return number of bytes in thumbnail, 0 if not available
*/
-size_t ECRS_getThumbnailFromMetaData(const struct ECRS_MetaData * md,
- unsigned char ** thumb) {
- char * encoded;
+size_t
+ECRS_getThumbnailFromMetaData (const struct ECRS_MetaData * md,
+ unsigned char **thumb)
+{
+ char *encoded;
int ret;
size_t size;
- encoded = ECRS_getFromMetaData(md,
- EXTRACTOR_THUMBNAIL_DATA);
+ encoded = ECRS_getFromMetaData (md, EXTRACTOR_THUMBNAIL_DATA);
if (encoded == NULL)
return 0;
- if (strlen(encoded) == 0) {
- FREE(encoded);
- return 0; /* invalid */
- }
+ if (strlen (encoded) == 0)
+ {
+ FREE (encoded);
+ return 0; /* invalid */
+ }
*thumb = NULL;
- ret = decodeThumbnail(encoded,
- thumb,
- &size);
- FREE(encoded);
+ ret = decodeThumbnail (encoded, thumb, &size);
+ FREE (encoded);
if (ret == 0)
return size;
else
@@ -273,17 +279,17 @@
/**
* Duplicate MetaData.
*/
-MetaData * ECRS_dupMetaData(const MetaData * md) {
+MetaData *
+ECRS_dupMetaData (const MetaData * md)
+{
int i;
- MetaData * ret;
+ MetaData *ret;
if (md == NULL)
return NULL;
- ret = ECRS_createMetaData();
- for (i=md->itemCount-1;i>=0;i--)
- ECRS_addToMetaData(ret,
- md->items[i].type,
- md->items[i].data);
+ ret = ECRS_createMetaData ();
+ for (i = md->itemCount - 1; i >= 0; i--)
+ ECRS_addToMetaData (ret, md->items[i].type, md->items[i].data);
return ret;
}
@@ -293,60 +299,60 @@
* @return SYSERR on error, otherwise the number
* of meta-data items obtained
*/
-int ECRS_extractMetaData(struct GE_Context * ectx,
- MetaData * md,
- const char * filename,
- EXTRACTOR_ExtractorList * extractors) {
- EXTRACTOR_KeywordList * head;
- EXTRACTOR_KeywordList * pos;
+int
+ECRS_extractMetaData (struct GE_Context *ectx,
+ MetaData * md,
+ const char *filename,
+ EXTRACTOR_ExtractorList * extractors)
+{
+ EXTRACTOR_KeywordList *head;
+ EXTRACTOR_KeywordList *pos;
int ret;
if (filename == NULL)
return SYSERR;
if (extractors == NULL)
return 0;
- head = EXTRACTOR_getKeywords(extractors,
- filename);
- head = EXTRACTOR_removeDuplicateKeywords(head,
- EXTRACTOR_DUPLICATES_REMOVE_UNKNOWN);
+ head = EXTRACTOR_getKeywords (extractors, filename);
+ head = EXTRACTOR_removeDuplicateKeywords (head,
+
EXTRACTOR_DUPLICATES_REMOVE_UNKNOWN);
pos = head;
ret = 0;
- while (pos != NULL) {
- if (OK == ECRS_addToMetaData(md,
- pos->keywordType,
- pos->keyword))
- ret++;
- pos = pos->next;
- }
- EXTRACTOR_freeKeywords(head);
+ while (pos != NULL)
+ {
+ if (OK == ECRS_addToMetaData (md, pos->keywordType, pos->keyword))
+ ret++;
+ pos = pos->next;
+ }
+ EXTRACTOR_freeKeywords (head);
return ret;
}
-static unsigned int tryCompression(char * data,
- unsigned int oldSize) {
- char * tmp;
+static unsigned int
+tryCompression (char *data, unsigned int oldSize)
+{
+ char *tmp;
uLongf dlen;
#ifdef compressBound
- dlen = compressBound(oldSize);
+ dlen = compressBound (oldSize);
#else
dlen = oldSize + (oldSize / 100) + 20;
/* documentation says 100.1% oldSize + 12 bytes, but we
should be able to overshoot by more to be safe */
#endif
- tmp = MALLOC(dlen);
- if (Z_OK == compress2((Bytef*) tmp,
- &dlen,
- (const Bytef*) data,
- oldSize,
- 9)) {
- if (dlen < oldSize) {
- memcpy(data, tmp, dlen);
- FREE(tmp);
- return dlen;
+ tmp = MALLOC (dlen);
+ if (Z_OK == compress2 ((Bytef *) tmp,
+ &dlen, (const Bytef *) data, oldSize, 9))
+ {
+ if (dlen < oldSize)
+ {
+ memcpy (data, tmp, dlen);
+ FREE (tmp);
+ return dlen;
+ }
}
- }
- FREE(tmp);
+ FREE (tmp);
return oldSize;
}
@@ -357,23 +363,25 @@
*
* @return NULL on error
*/
-static char * decompress(const char * input,
- unsigned int inputSize,
- unsigned int outputSize) {
- char * output;
+static char *
+decompress (const char *input,
+ unsigned int inputSize, unsigned int outputSize)
+{
+ char *output;
uLongf olen;
olen = outputSize;
- output = MALLOC(olen);
- if (Z_OK == uncompress((Bytef*) output,
- &olen,
- (const Bytef*) input,
- inputSize)) {
- return output;
- } else {
- FREE(output);
- return NULL;
- }
+ output = MALLOC (olen);
+ if (Z_OK == uncompress ((Bytef *) output,
+ &olen, (const Bytef *) input, inputSize))
+ {
+ return output;
+ }
+ else
+ {
+ FREE (output);
+ return NULL;
+ }
}
/**
@@ -386,7 +394,8 @@
*/
#define HEADER_VERSION_MASK 0x7FFFFFFF
-typedef struct {
+typedef struct
+{
/**
* The version of the MD serialization.
* The highest bit is used to indicate
@@ -424,83 +433,85 @@
* SYSERR on error (typically: not enough
* space)
*/
-int ECRS_serializeMetaData(struct GE_Context * ectx,
- const MetaData * md,
- char * target,
- unsigned int max,
- int part) {
- MetaDataHeader * hdr;
+int
+ECRS_serializeMetaData (struct GE_Context *ectx,
+ const MetaData * md,
+ char *target, unsigned int max, int part)
+{
+ MetaDataHeader *hdr;
size_t size;
size_t pos;
int i;
int len;
unsigned int ic;
- if (max < sizeof(MetaDataHeader))
- return SYSERR; /* far too small */
+ if (max < sizeof (MetaDataHeader))
+ return SYSERR; /* far too small */
ic = md->itemCount;
hdr = NULL;
- while (1) {
- size = sizeof(MetaDataHeader);
- size += sizeof(unsigned int) * ic;
- for (i=0;i<ic;i++)
- size += 1 + strlen(md->items[i].data);
- while (size % 8 != 0)
- size++;
- hdr = MALLOC(size);
- hdr->version = htonl(0);
- hdr->entries = htonl(ic);
- for (i=0;i<ic;i++)
- ((unsigned int*)&hdr[1])[i] = htonl((unsigned int)md->items[i].type);
- pos = sizeof(MetaDataHeader);
- pos += sizeof(unsigned int) * ic;
- for (i=0;i<ic;i++) {
- len = strlen(md->items[i].data) + 1;
- memcpy(&((char*)hdr)[pos],
- md->items[i].data,
- len);
- pos += len;
- }
+ while (1)
+ {
+ size = sizeof (MetaDataHeader);
+ size += sizeof (unsigned int) * ic;
+ for (i = 0; i < ic; i++)
+ size += 1 + strlen (md->items[i].data);
+ while (size % 8 != 0)
+ size++;
+ hdr = MALLOC (size);
+ hdr->version = htonl (0);
+ hdr->entries = htonl (ic);
+ for (i = 0; i < ic; i++)
+ ((unsigned int *) &hdr[1])[i] =
+ htonl ((unsigned int) md->items[i].type);
+ pos = sizeof (MetaDataHeader);
+ pos += sizeof (unsigned int) * ic;
+ for (i = 0; i < ic; i++)
+ {
+ len = strlen (md->items[i].data) + 1;
+ memcpy (&((char *) hdr)[pos], md->items[i].data, len);
+ pos += len;
+ }
- hdr->size = htonl(size);
- if ((part & ECRS_SERIALIZE_NO_COMPRESS) == 0) {
- pos = tryCompression((char*)&hdr[1],
- size - sizeof(MetaDataHeader));
- } else {
- pos = size - sizeof(MetaDataHeader);
- }
- if (pos < size - sizeof(MetaDataHeader)) {
- hdr->version = htonl(HEADER_COMPRESSED);
- size = pos + sizeof(MetaDataHeader);
- }
- if (size <= max)
- break;
- FREE(hdr);
- hdr = NULL;
+ hdr->size = htonl (size);
+ if ((part & ECRS_SERIALIZE_NO_COMPRESS) == 0)
+ {
+ pos = tryCompression ((char *) &hdr[1],
+ size - sizeof (MetaDataHeader));
+ }
+ else
+ {
+ pos = size - sizeof (MetaDataHeader);
+ }
+ if (pos < size - sizeof (MetaDataHeader))
+ {
+ hdr->version = htonl (HEADER_COMPRESSED);
+ size = pos + sizeof (MetaDataHeader);
+ }
+ if (size <= max)
+ break;
+ FREE (hdr);
+ hdr = NULL;
- if ((part & ECRS_SERIALIZE_PART) == 0) {
- return SYSERR; /* does not fit! */
+ if ((part & ECRS_SERIALIZE_PART) == 0)
+ {
+ return SYSERR; /* does not fit! */
+ }
+ /* partial serialization ok, try again with less meta-data */
+ if (size > 2 * max)
+ ic = ic * 2 / 3; /* still far too big, make big reductions */
+ else
+ ic--; /* small steps, we're close */
}
- /* partial serialization ok, try again with less meta-data */
- if (size > 2 * max)
- ic = ic * 2 / 3; /* still far too big, make big reductions */
- else
- ic--; /* small steps, we're close */
- }
- GE_ASSERT(ectx, size <= max);
- memcpy(target,
- hdr,
- size);
- FREE(hdr);
+ GE_ASSERT (ectx, size <= max);
+ memcpy (target, hdr, size);
+ FREE (hdr);
/* extra check: deserialize! */
#if EXTRA_CHECKS
{
- MetaData * mdx;
- mdx = ECRS_deserializeMetaData(ectx,
- target,
- size);
- GE_ASSERT(ectx, NULL != mdx);
- ECRS_freeMetaData(mdx);
+ MetaData *mdx;
+ mdx = ECRS_deserializeMetaData (ectx, target, size);
+ GE_ASSERT (ectx, NULL != mdx);
+ ECRS_freeMetaData (mdx);
}
#endif
return size;
@@ -511,9 +522,10 @@
* serialized form. The estimate MAY be higher
* than what is strictly needed.
*/
-unsigned int ECRS_sizeofMetaData(const MetaData * md,
- int part) {
- MetaDataHeader * hdr;
+unsigned int
+ECRS_sizeofMetaData (const MetaData * md, int part)
+{
+ MetaDataHeader *hdr;
size_t size;
size_t pos;
int i;
@@ -521,36 +533,37 @@
unsigned int ic;
ic = md->itemCount;
- size = sizeof(MetaDataHeader);
- size += sizeof(unsigned int) * ic;
- for (i=0;i<ic;i++)
- size += 1 + strlen(md->items[i].data);
+ size = sizeof (MetaDataHeader);
+ size += sizeof (unsigned int) * ic;
+ for (i = 0; i < ic; i++)
+ size += 1 + strlen (md->items[i].data);
while (size % 8 != 0)
size++;
- hdr = MALLOC(size);
- hdr->version = htonl(0);
- hdr->entries = htonl(md->itemCount);
- for (i=0;i<ic;i++)
- ((unsigned int*)&hdr[1])[i] = htonl((unsigned int)md->items[i].type);
- pos = sizeof(MetaDataHeader);
- pos += sizeof(unsigned int) * md->itemCount;
- for (i=0;i<ic;i++) {
- len = strlen(md->items[i].data) + 1;
- memcpy(&((char*)hdr)[pos],
- md->items[i].data,
- len);
- pos += len;
- }
- if ((part & ECRS_SERIALIZE_NO_COMPRESS) == 0) {
- pos = tryCompression((char*)&hdr[1],
- size - sizeof(MetaDataHeader));
- } else {
- pos = size - sizeof(MetaDataHeader);
- }
- if (pos < size - sizeof(MetaDataHeader))
- size = pos + sizeof(MetaDataHeader);
+ hdr = MALLOC (size);
+ hdr->version = htonl (0);
+ hdr->entries = htonl (md->itemCount);
+ for (i = 0; i < ic; i++)
+ ((unsigned int *) &hdr[1])[i] = htonl ((unsigned int) md->items[i].type);
+ pos = sizeof (MetaDataHeader);
+ pos += sizeof (unsigned int) * md->itemCount;
+ for (i = 0; i < ic; i++)
+ {
+ len = strlen (md->items[i].data) + 1;
+ memcpy (&((char *) hdr)[pos], md->items[i].data, len);
+ pos += len;
+ }
+ if ((part & ECRS_SERIALIZE_NO_COMPRESS) == 0)
+ {
+ pos = tryCompression ((char *) &hdr[1], size - sizeof (MetaDataHeader));
+ }
+ else
+ {
+ pos = size - sizeof (MetaDataHeader);
+ }
+ if (pos < size - sizeof (MetaDataHeader))
+ size = pos + sizeof (MetaDataHeader);
- FREE(hdr);
+ FREE (hdr);
return size;
}
@@ -562,170 +575,179 @@
* bad format)
*/
struct ECRS_MetaData *
-ECRS_deserializeMetaData(struct GE_Context * ectx,
- const char * input,
- unsigned int size) {
- MetaData * md;
- const MetaDataHeader * hdr;
+ECRS_deserializeMetaData (struct GE_Context *ectx,
+ const char *input, unsigned int size)
+{
+ MetaData *md;
+ const MetaDataHeader *hdr;
unsigned int ic;
- char * data;
+ char *data;
unsigned int dataSize;
int compressed;
int i;
unsigned int pos;
int len;
- if (size < sizeof(MetaDataHeader))
+ if (size < sizeof (MetaDataHeader))
return NULL;
- hdr = (const MetaDataHeader*) input;
- if ( (ntohl(MAKE_UNALIGNED(hdr->version)) & HEADER_VERSION_MASK) != 0)
- return NULL; /* unsupported version */
- ic = ntohl(MAKE_UNALIGNED(hdr->entries));
- compressed = (ntohl(MAKE_UNALIGNED(hdr->version)) & HEADER_COMPRESSED) != 0;
- if (compressed) {
- dataSize = ntohl(MAKE_UNALIGNED(hdr->size)) - sizeof(MetaDataHeader);
- if (dataSize > 2 * 1042 * 1024) {
- GE_BREAK(ectx, 0);
- return NULL; /* only 2 MB allowed [to make sure we don't blow
- our memory limit because of a mal-formed
- message... ]*/
+ hdr = (const MetaDataHeader *) input;
+ if ((ntohl (MAKE_UNALIGNED (hdr->version)) & HEADER_VERSION_MASK) != 0)
+ return NULL; /* unsupported version */
+ ic = ntohl (MAKE_UNALIGNED (hdr->entries));
+ compressed =
+ (ntohl (MAKE_UNALIGNED (hdr->version)) & HEADER_COMPRESSED) != 0;
+ if (compressed)
+ {
+ dataSize = ntohl (MAKE_UNALIGNED (hdr->size)) - sizeof (MetaDataHeader);
+ if (dataSize > 2 * 1042 * 1024)
+ {
+ GE_BREAK (ectx, 0);
+ return NULL; /* only 2 MB allowed [to make sure we don't
blow
+ our memory limit because of a mal-formed
+ message... ] */
+ }
+ data = decompress ((char *) &input[sizeof (MetaDataHeader)],
+ size - sizeof (MetaDataHeader), dataSize);
+ if (data == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
}
- data = decompress((char*)&input[sizeof(MetaDataHeader)],
- size - sizeof(MetaDataHeader),
- dataSize);
- if (data == NULL) {
- GE_BREAK(ectx, 0);
- return NULL;
+ else
+ {
+ data = (char *) &hdr[1];
+ dataSize = size - sizeof (MetaDataHeader);
+ if (size != ntohl (MAKE_UNALIGNED (hdr->size)))
+ {
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
}
- } else {
- data = (char*) &hdr[1];
- dataSize = size - sizeof(MetaDataHeader);
- if (size != ntohl(MAKE_UNALIGNED(hdr->size))) {
- GE_BREAK(ectx, 0);
- return NULL;
+
+ if ((sizeof (unsigned int) * ic + ic) > dataSize)
+ {
+ GE_BREAK (ectx, 0);
+ goto FAILURE;
}
- }
+ if ((ic > 0) && (data[dataSize - 1] != '\0'))
+ {
+ GE_BREAK (ectx, 0);
+ goto FAILURE;
+ }
- if ( (sizeof(unsigned int) * ic + ic) > dataSize) {
- GE_BREAK(ectx, 0);
- goto FAILURE;
- }
- if ( (ic > 0)
- && (data[dataSize-1] != '\0') ) {
- GE_BREAK(ectx, 0);
- goto FAILURE;
- }
-
- md = ECRS_createMetaData();
- GROW(md->items,
- md->itemCount,
- ic);
+ md = ECRS_createMetaData ();
+ GROW (md->items, md->itemCount, ic);
i = 0;
- pos = sizeof(unsigned int) * ic;
- while ( (pos < dataSize) &&
- (i < ic) ) {
- len = strlen(&data[pos])+1;
- md->items[i].type = (EXTRACTOR_KeywordType)
- ntohl(MAKE_UNALIGNED(((unsigned int*)data)[i]));
- md->items[i].data = STRDUP(&data[pos]);
- pos += len;
- i++;
- }
- if (i < ic) { /* oops */
- ECRS_freeMetaData(md);
- goto FAILURE;
- }
+ pos = sizeof (unsigned int) * ic;
+ while ((pos < dataSize) && (i < ic))
+ {
+ len = strlen (&data[pos]) + 1;
+ md->items[i].type = (EXTRACTOR_KeywordType)
+ ntohl (MAKE_UNALIGNED (((unsigned int *) data)[i]));
+ md->items[i].data = STRDUP (&data[pos]);
+ pos += len;
+ i++;
+ }
+ if (i < ic)
+ { /* oops */
+ ECRS_freeMetaData (md);
+ goto FAILURE;
+ }
if (compressed)
- FREE(data);
+ FREE (data);
return md;
- FAILURE:
+FAILURE:
if (compressed)
- FREE(data);
- return NULL; /* size too small */
+ FREE (data);
+ return NULL; /* size too small */
}
/**
* Does the meta-data claim that this is a directory?
* Checks if the mime-type is that of a GNUnet directory.
*/
-int ECRS_isDirectory(const MetaData * md) {
+int
+ECRS_isDirectory (const MetaData * md)
+{
int i;
- for (i=md->itemCount-1;i>=0;i--) {
- if (md->items[i].type == EXTRACTOR_MIMETYPE) {
- if (0 == strcmp(md->items[i].data,
- GNUNET_DIRECTORY_MIME))
- return YES;
- else
- return NO;
+ for (i = md->itemCount - 1; i >= 0; i--)
+ {
+ if (md->items[i].type == EXTRACTOR_MIMETYPE)
+ {
+ if (0 == strcmp (md->items[i].data, GNUNET_DIRECTORY_MIME))
+ return YES;
+ else
+ return NO;
+ }
}
- }
return SYSERR;
}
-static char * mimeMap[][2] = {
- { "application/bz2", ".bz2" },
- { "application/gnunet-directory", ".gnd" },
- { "application/java", ".class" },
- { "application/msword", ".doc" },
- { "application/ogg", ".ogg" },
- { "application/pdf", ".pdf" },
- { "application/pgp-keys", ".key" },
- { "application/pgp-signature", ".pgp" },
- { "application/postscript", ".ps" },
- { "application/rar", ".rar" },
- { "application/rtf", ".rtf" },
- { "application/xml", ".xml" },
- { "application/x-debian-package", ".deb" },
- { "application/x-dvi", ".dvi" },
- { "applixation/x-flac", ".flac" },
- { "applixation/x-gzip", ".gz" },
- { "application/x-java-archive", ".jar" },
- { "application/x-java-vm", ".class" },
- { "application/x-python-code", ".pyc" },
- { "application/x-redhat-package-manager", ".rpm" },
- { "application/x-rpm", ".rpm" },
- { "application/x-tar", ".tar" },
- { "application/x-tex-pk", ".pk" },
- { "application/x-texinfo", ".texinfo" },
- { "application/x-xcf", ".xcf" },
- { "application/x-xfig", ".xfig" },
- { "application/zip", ".zip" },
+static char *mimeMap[][2] = {
+ {"application/bz2", ".bz2"},
+ {"application/gnunet-directory", ".gnd"},
+ {"application/java", ".class"},
+ {"application/msword", ".doc"},
+ {"application/ogg", ".ogg"},
+ {"application/pdf", ".pdf"},
+ {"application/pgp-keys", ".key"},
+ {"application/pgp-signature", ".pgp"},
+ {"application/postscript", ".ps"},
+ {"application/rar", ".rar"},
+ {"application/rtf", ".rtf"},
+ {"application/xml", ".xml"},
+ {"application/x-debian-package", ".deb"},
+ {"application/x-dvi", ".dvi"},
+ {"applixation/x-flac", ".flac"},
+ {"applixation/x-gzip", ".gz"},
+ {"application/x-java-archive", ".jar"},
+ {"application/x-java-vm", ".class"},
+ {"application/x-python-code", ".pyc"},
+ {"application/x-redhat-package-manager", ".rpm"},
+ {"application/x-rpm", ".rpm"},
+ {"application/x-tar", ".tar"},
+ {"application/x-tex-pk", ".pk"},
+ {"application/x-texinfo", ".texinfo"},
+ {"application/x-xcf", ".xcf"},
+ {"application/x-xfig", ".xfig"},
+ {"application/zip", ".zip"},
- { "audio/midi", ".midi" },
- { "audio/mpeg", ".mp3" },
- { "audio/real", ".rm"},
- { "audio/x-wav", ".wav" },
+ {"audio/midi", ".midi"},
+ {"audio/mpeg", ".mp3"},
+ {"audio/real", ".rm"},
+ {"audio/x-wav", ".wav"},
- { "image/gif", ".gif"},
- { "image/jpeg", ".jpg"},
- { "image/pcx", ".pcx"},
- { "image/png", ".png"},
- { "image/tiff", ".tiff" },
- { "image/x-ms-bmp", ".bmp"},
- { "image/x-xpixmap", ".xpm"},
+ {"image/gif", ".gif"},
+ {"image/jpeg", ".jpg"},
+ {"image/pcx", ".pcx"},
+ {"image/png", ".png"},
+ {"image/tiff", ".tiff"},
+ {"image/x-ms-bmp", ".bmp"},
+ {"image/x-xpixmap", ".xpm"},
- { "text/css", ".css" },
- { "text/html", ".html" },
- { "text/plain", ".txt" },
- { "text/rtf", ".rtf" },
- { "text/x-c++hdr", ".h++" },
- { "text/x-c++src", ".c++" },
- { "text/x-chdr", ".h" },
- { "text/x-csrc", ".c" },
- { "text/x-java", ".java" },
- { "text/x-moc", ".moc" },
- { "text/x-pascal", ".pas" },
- { "text/x-perl", ".pl" },
- { "text/x-python", ".py" },
- { "text/x-tex", ".tex" },
+ {"text/css", ".css"},
+ {"text/html", ".html"},
+ {"text/plain", ".txt"},
+ {"text/rtf", ".rtf"},
+ {"text/x-c++hdr", ".h++"},
+ {"text/x-c++src", ".c++"},
+ {"text/x-chdr", ".h"},
+ {"text/x-csrc", ".c"},
+ {"text/x-java", ".java"},
+ {"text/x-moc", ".moc"},
+ {"text/x-pascal", ".pas"},
+ {"text/x-perl", ".pl"},
+ {"text/x-python", ".py"},
+ {"text/x-tex", ".tex"},
- { "video/avi", ".avi" },
- { "video/mpeg", ".mpeg" },
- { "video/quicktime", ".qt" },
- { "video/real", ".rm"},
- { "video/x-msvideo", ".avi"},
- { NULL, NULL },
+ {"video/avi", ".avi"},
+ {"video/mpeg", ".mpeg"},
+ {"video/quicktime", ".qt"},
+ {"video/real", ".rm"},
+ {"video/x-msvideo", ".avi"},
+ {NULL, NULL},
};
@@ -734,164 +756,165 @@
* renaming).
* @return the new filename
*/
-char * ECRS_suggestFilename(struct GE_Context * ectx,
- const char * filename) {
- EXTRACTOR_ExtractorList * l;
- EXTRACTOR_KeywordList * list;
- const char * key;
- const char * mime;
- char * path;
+char *
+ECRS_suggestFilename (struct GE_Context *ectx, const char *filename)
+{
+ EXTRACTOR_ExtractorList *l;
+ EXTRACTOR_KeywordList *list;
+ const char *key;
+ const char *mime;
+ char *path;
int i;
unsigned int j;
- char * renameTo;
- char * ret;
+ char *renameTo;
+ char *ret;
struct stat filestat;
- path = STRDUP(filename);
- i = strlen(path);
- while ( (i > 0) &&
- (path[i] != DIR_SEPARATOR) )
+ path = STRDUP (filename);
+ i = strlen (path);
+ while ((i > 0) && (path[i] != DIR_SEPARATOR))
i--;
path[i] = '\0';
ret = NULL;
- l = EXTRACTOR_loadDefaultLibraries();
- list = EXTRACTOR_getKeywords(l, filename);
- key = EXTRACTOR_extractLast(EXTRACTOR_TITLE,
- list);
+ l = EXTRACTOR_loadDefaultLibraries ();
+ list = EXTRACTOR_getKeywords (l, filename);
+ key = EXTRACTOR_extractLast (EXTRACTOR_TITLE, list);
if (key == NULL)
- key = EXTRACTOR_extractLast(EXTRACTOR_DESCRIPTION,
- list);
+ key = EXTRACTOR_extractLast (EXTRACTOR_DESCRIPTION, list);
if (key == NULL)
- key = EXTRACTOR_extractLast(EXTRACTOR_COMMENT,
- list);
+ key = EXTRACTOR_extractLast (EXTRACTOR_COMMENT, list);
if (key == NULL)
- key = EXTRACTOR_extractLast(EXTRACTOR_SUBJECT,
- list);
+ key = EXTRACTOR_extractLast (EXTRACTOR_SUBJECT, list);
if (key == NULL)
- key = EXTRACTOR_extractLast(EXTRACTOR_ALBUM,
- list);
+ key = EXTRACTOR_extractLast (EXTRACTOR_ALBUM, list);
if (key == NULL)
- key = EXTRACTOR_extractLast(EXTRACTOR_UNKNOWN,
- list);
- mime = EXTRACTOR_extractLast(EXTRACTOR_MIMETYPE,
- list);
- if (mime != NULL) {
- i = 0;
- while ( (mimeMap[i][0] != NULL) &&
- (0 != strcmp(mime, mimeMap[i][0])) )
- i++;
- if (mimeMap[i][1] == NULL)
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Did not find mime type `%s' in extension list.\n",
- mime);
- mime = mimeMap[i][1];
- }
- if (key == NULL) {
- key = &filename[strlen(filename)-1];
- while ( (key != filename) &&
- (key[0] != DIR_SEPARATOR) )
- key--;
- if (key[0] == DIR_SEPARATOR)
- key++;
- }
- if (mime != NULL) {
- if (0 == strcmp(&key[strlen(key)-strlen(mime)],
- mime))
- mime = NULL;
- }
- if (mime == NULL) {
- i = strlen(filename);
- while ( (i>0) &&
- (filename[i] != '.') &&
- (filename[i] != DIR_SEPARATOR) )
- i--;
- if (filename[i] == '.')
- mime = STRDUP(&filename[i]);
- }
- if (mime == NULL) {
- renameTo = MALLOC(strlen(path) + strlen(key) + strlen(DIR_SEPARATOR_STR) +
20);
- strcpy(renameTo, path);
- if (path[strlen(path)-1] != DIR_SEPARATOR)
- strcat(renameTo, DIR_SEPARATOR_STR);
- strcat(renameTo, key);
- } else {
- renameTo = MALLOC(strlen(path) + strlen(key) + strlen(mime) +
strlen(DIR_SEPARATOR_STR) + 20);
- strcpy(renameTo, path);
- if (path[strlen(path)-1] != DIR_SEPARATOR)
- strcat(renameTo, DIR_SEPARATOR_STR);
- strcat(renameTo, key);
- if (strcasecmp(renameTo + strlen(renameTo) - strlen(mime), mime) != 0)
- strcat(renameTo, mime);
- }
- for (i=strlen(renameTo)-1;i>=0;i--)
- if (! isprint(renameTo[i]))
- renameTo[i] = '_';
- else if (renameTo[i] == '.' && i > 0 && renameTo[i-1] == '.') {
- /* remove .. to avoid directory traversal */
- renameTo[i-1] = renameTo[i] = '_';
- i--;
+ key = EXTRACTOR_extractLast (EXTRACTOR_UNKNOWN, list);
+ mime = EXTRACTOR_extractLast (EXTRACTOR_MIMETYPE, list);
+ if (mime != NULL)
+ {
+ i = 0;
+ while ((mimeMap[i][0] != NULL) && (0 != strcmp (mime, mimeMap[i][0])))
+ i++;
+ if (mimeMap[i][1] == NULL)
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Did not find mime type `%s' in extension list.\n", mime);
+ mime = mimeMap[i][1];
}
- if (0 != strcmp(renameTo, filename)) {
- if (0 == STAT(renameTo,
- &filestat)) {
- i = strlen(renameTo);
- j = 0;
- do {
- SNPRINTF(&renameTo[i],
- 19,
- ".%u",
- j++);
- if (j > 100000)
- break;
- } while (0 == STAT(renameTo,
- &filestat));
+ if (key == NULL)
+ {
+ key = &filename[strlen (filename) - 1];
+ while ((key != filename) && (key[0] != DIR_SEPARATOR))
+ key--;
+ if (key[0] == DIR_SEPARATOR)
+ key++;
}
+ if (mime != NULL)
+ {
+ if (0 == strcmp (&key[strlen (key) - strlen (mime)], mime))
+ mime = NULL;
+ }
+ if (mime == NULL)
+ {
+ i = strlen (filename);
+ while ((i > 0) &&
+ (filename[i] != '.') && (filename[i] != DIR_SEPARATOR))
+ i--;
+ if (filename[i] == '.')
+ mime = STRDUP (&filename[i]);
+ }
+ if (mime == NULL)
+ {
+ renameTo =
+ MALLOC (strlen (path) + strlen (key) + strlen (DIR_SEPARATOR_STR) +
+ 20);
+ strcpy (renameTo, path);
+ if (path[strlen (path) - 1] != DIR_SEPARATOR)
+ strcat (renameTo, DIR_SEPARATOR_STR);
+ strcat (renameTo, key);
+ }
+ else
+ {
+ renameTo =
+ MALLOC (strlen (path) + strlen (key) + strlen (mime) +
+ strlen (DIR_SEPARATOR_STR) + 20);
+ strcpy (renameTo, path);
+ if (path[strlen (path) - 1] != DIR_SEPARATOR)
+ strcat (renameTo, DIR_SEPARATOR_STR);
+ strcat (renameTo, key);
+ if (strcasecmp (renameTo + strlen (renameTo) - strlen (mime), mime) !=
+ 0)
+ strcat (renameTo, mime);
+ }
+ for (i = strlen (renameTo) - 1; i >= 0; i--)
+ if (!isprint (renameTo[i]))
+ renameTo[i] = '_';
+ else if (renameTo[i] == '.' && i > 0 && renameTo[i - 1] == '.')
+ {
+ /* remove .. to avoid directory traversal */
+ renameTo[i - 1] = renameTo[i] = '_';
+ i--;
+ }
+ if (0 != strcmp (renameTo, filename))
+ {
+ if (0 == STAT (renameTo, &filestat))
+ {
+ i = strlen (renameTo);
+ j = 0;
+ do
+ {
+ SNPRINTF (&renameTo[i], 19, ".%u", j++);
+ if (j > 100000)
+ break;
+ }
+ while (0 == STAT (renameTo, &filestat));
+ }
- if (0 != STAT(renameTo,
- &filestat)) {
- if (0 != RENAME(filename, renameTo))
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Renaming of file `%s' to `%s' failed: %s\n"),
- filename,
- renameTo,
- STRERROR(errno));
+ if (0 != STAT (renameTo, &filestat))
+ {
+ if (0 != RENAME (filename, renameTo))
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Renaming of file `%s' to `%s' failed: %s\n"),
+ filename, renameTo, STRERROR (errno));
+ else
+ ret = STRDUP (renameTo);
+ }
else
- ret = STRDUP(renameTo);
- } else {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Could not rename file `%s' to `%s': file exists\n"),
- filename,
- renameTo);
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Could not rename file `%s' to `%s': file exists\n"),
+ filename, renameTo);
+ }
}
- }
- FREE(path);
- FREE(renameTo);
- EXTRACTOR_freeKeywords(list);
- EXTRACTOR_removeAll(l);
+ FREE (path);
+ FREE (renameTo);
+ EXTRACTOR_freeKeywords (list);
+ EXTRACTOR_removeAll (l);
return ret;
}
/**
* Test if two MDs are equal.
*/
-int ECRS_equalsMetaData(const struct ECRS_MetaData * md1,
- const struct ECRS_MetaData * md2) {
+int
+ECRS_equalsMetaData (const struct ECRS_MetaData *md1,
+ const struct ECRS_MetaData *md2)
+{
int i;
int j;
int found;
if (md1->itemCount != md2->itemCount)
return NO;
- for (i=0;i<md1->itemCount;i++) {
- found = NO;
- for (j=0;j<md2->itemCount;j++)
- if ( (md1->items[i].type == md2->items[j].type) &&
- (0 == strcmp(md1->items[i].data,
- md2->items[j].data)) )
- found = YES;
- if (found == NO)
- return NO;
- }
+ for (i = 0; i < md1->itemCount; i++)
+ {
+ found = NO;
+ for (j = 0; j < md2->itemCount; j++)
+ if ((md1->items[i].type == md2->items[j].type) &&
+ (0 == strcmp (md1->items[i].data, md2->items[j].data)))
+ found = YES;
+ if (found == NO)
+ return NO;
+ }
return YES;
}
Modified: GNUnet/src/applications/fs/ecrs/metatest.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/metatest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/metatest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -32,146 +32,125 @@
#define ABORT(m) { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); if
(m != NULL) ECRS_freeMetaData(m); return 1; }
-static int testMeta(int i) {
- struct ECRS_MetaData * m;
- char * val;
+static int
+testMeta (int i)
+{
+ struct ECRS_MetaData *m;
+ char *val;
int j;
unsigned int size;
- m = ECRS_createMetaData();
- if (OK != ECRS_addToMetaData(m,
- EXTRACTOR_TITLE,
- "TestTitle"))
- ABORT(m);
- if (OK != ECRS_addToMetaData(m,
- EXTRACTOR_AUTHOR,
- "TestTitle"))
- ABORT(m);
- if (OK == ECRS_addToMetaData(m,
- EXTRACTOR_TITLE,
- "TestTitle")) /* dup! */
- ABORT(m);
- if (OK == ECRS_addToMetaData(m,
- EXTRACTOR_AUTHOR,
- "TestTitle")) /* dup! */
- ABORT(m);
- if (2 != ECRS_getMetaData(m, NULL, NULL))
- ABORT(m);
- if (OK != ECRS_delFromMetaData(m,
- EXTRACTOR_AUTHOR,
- "TestTitle"))
- ABORT(m);
- if (OK == ECRS_delFromMetaData(m,
- EXTRACTOR_AUTHOR,
- "TestTitle")) /* already gone */
- ABORT(m);
- if (1 != ECRS_getMetaData(m, NULL, NULL))
- ABORT(m);
- if (OK != ECRS_delFromMetaData(m,
- EXTRACTOR_TITLE,
- "TestTitle"))
- ABORT(m);
- if (OK == ECRS_delFromMetaData(m,
- EXTRACTOR_TITLE,
- "TestTitle")) /* already gone */
- ABORT(m);
- if (0 != ECRS_getMetaData(m, NULL, NULL))
- ABORT(m);
- val = MALLOC(256);
- for (j=0;j<i;j++) {
- SNPRINTF(val, 256, "%s.%d",
- "A teststring that should compress well.",
- j);
- if (OK != ECRS_addToMetaData(m,
- EXTRACTOR_UNKNOWN,
- val)) {
- FREE(val);
- ABORT(m);
+ m = ECRS_createMetaData ();
+ if (OK != ECRS_addToMetaData (m, EXTRACTOR_TITLE, "TestTitle"))
+ ABORT (m);
+ if (OK != ECRS_addToMetaData (m, EXTRACTOR_AUTHOR, "TestTitle"))
+ ABORT (m);
+ if (OK == ECRS_addToMetaData (m, EXTRACTOR_TITLE, "TestTitle")) /*
dup! */
+ ABORT (m);
+ if (OK == ECRS_addToMetaData (m, EXTRACTOR_AUTHOR, "TestTitle")) /*
dup! */
+ ABORT (m);
+ if (2 != ECRS_getMetaData (m, NULL, NULL))
+ ABORT (m);
+ if (OK != ECRS_delFromMetaData (m, EXTRACTOR_AUTHOR, "TestTitle"))
+ ABORT (m);
+ if (OK == ECRS_delFromMetaData (m, EXTRACTOR_AUTHOR, "TestTitle")) /*
already gone */
+ ABORT (m);
+ if (1 != ECRS_getMetaData (m, NULL, NULL))
+ ABORT (m);
+ if (OK != ECRS_delFromMetaData (m, EXTRACTOR_TITLE, "TestTitle"))
+ ABORT (m);
+ if (OK == ECRS_delFromMetaData (m, EXTRACTOR_TITLE, "TestTitle")) /*
already gone */
+ ABORT (m);
+ if (0 != ECRS_getMetaData (m, NULL, NULL))
+ ABORT (m);
+ val = MALLOC (256);
+ for (j = 0; j < i; j++)
+ {
+ SNPRINTF (val, 256, "%s.%d",
+ "A teststring that should compress well.", j);
+ if (OK != ECRS_addToMetaData (m, EXTRACTOR_UNKNOWN, val))
+ {
+ FREE (val);
+ ABORT (m);
+ }
}
- }
- FREE(val);
- if (i != ECRS_getMetaData(m, NULL, NULL))
- ABORT(m);
+ FREE (val);
+ if (i != ECRS_getMetaData (m, NULL, NULL))
+ ABORT (m);
- size = ECRS_sizeofMetaData(m,
- ECRS_SERIALIZE_FULL);
- val = MALLOC(size);
- if (size != ECRS_serializeMetaData(NULL,
- m,
- val,
- size,
- ECRS_SERIALIZE_FULL)) {
- FREE(val);
- ABORT(m);
- }
- ECRS_freeMetaData(m);
- m = ECRS_deserializeMetaData(NULL,
- val,
- size);
- FREE(val);
+ size = ECRS_sizeofMetaData (m, ECRS_SERIALIZE_FULL);
+ val = MALLOC (size);
+ if (size != ECRS_serializeMetaData (NULL,
+ m, val, size, ECRS_SERIALIZE_FULL))
+ {
+ FREE (val);
+ ABORT (m);
+ }
+ ECRS_freeMetaData (m);
+ m = ECRS_deserializeMetaData (NULL, val, size);
+ FREE (val);
if (m == NULL)
- ABORT(m);
- val = MALLOC(256);
- for (j=0;j<i;j++) {
- SNPRINTF(val, 256, "%s.%d",
- "A teststring that should compress well.",
- j);
- if (OK != ECRS_delFromMetaData(m,
- EXTRACTOR_UNKNOWN,
- val)) {
- FREE(val);
- ABORT(m);
+ ABORT (m);
+ val = MALLOC (256);
+ for (j = 0; j < i; j++)
+ {
+ SNPRINTF (val, 256, "%s.%d",
+ "A teststring that should compress well.", j);
+ if (OK != ECRS_delFromMetaData (m, EXTRACTOR_UNKNOWN, val))
+ {
+ FREE (val);
+ ABORT (m);
+ }
}
- }
- FREE(val);
- if (0 != ECRS_getMetaData(m, NULL, NULL)) {
- ABORT(m);
- }
- ECRS_freeMetaData(m);
+ FREE (val);
+ if (0 != ECRS_getMetaData (m, NULL, NULL))
+ {
+ ABORT (m);
+ }
+ ECRS_freeMetaData (m);
return 0;
}
-int testMetaMore(int i) {
- struct ECRS_MetaData * meta;
+int
+testMetaMore (int i)
+{
+ struct ECRS_MetaData *meta;
int q;
char txt[128];
- char * data;
+ char *data;
unsigned long long size;
- meta = ECRS_createMetaData();
- for (q=0;q<=i;q++) {
- SNPRINTF(txt,
- 128,
- "%u -- %u\n",
- i, q);
- ECRS_addToMetaData(meta,
- q % EXTRACTOR_getHighestKeywordTypeNumber(),
- txt);
- }
- size = ECRS_sizeofMetaData(meta,
- ECRS_SERIALIZE_FULL);
- data = MALLOC(size * 4);
- if (size != ECRS_serializeMetaData(NULL,
- meta,
- data,
- size * 4,
- ECRS_SERIALIZE_FULL)) {
- FREE(data);
- ABORT(meta);
- }
- ECRS_freeMetaData(meta);
- FREE(data);
+ meta = ECRS_createMetaData ();
+ for (q = 0; q <= i; q++)
+ {
+ SNPRINTF (txt, 128, "%u -- %u\n", i, q);
+ ECRS_addToMetaData (meta,
+ q % EXTRACTOR_getHighestKeywordTypeNumber (), txt);
+ }
+ size = ECRS_sizeofMetaData (meta, ECRS_SERIALIZE_FULL);
+ data = MALLOC (size * 4);
+ if (size != ECRS_serializeMetaData (NULL,
+ meta,
+ data, size * 4, ECRS_SERIALIZE_FULL))
+ {
+ FREE (data);
+ ABORT (meta);
+ }
+ ECRS_freeMetaData (meta);
+ FREE (data);
return 0;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
int i;
- for (i=0;i<255;i++)
- failureCount += testMeta(i);
- for (i=1;i<255;i++)
- failureCount += testMetaMore(i);
+ for (i = 0; i < 255; i++)
+ failureCount += testMeta (i);
+ for (i = 1; i < 255; i++)
+ failureCount += testMetaMore (i);
if (failureCount != 0)
return 1;
Modified: GNUnet/src/applications/fs/ecrs/metatest2.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/metatest2.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/metatest2.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -32,51 +32,48 @@
#define ABORT() { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__);
return 1; }
-static int testMeta() {
- struct ECRS_MetaData * m;
- char * val;
+static int
+testMeta ()
+{
+ struct ECRS_MetaData *m;
+ char *val;
unsigned int size;
- m = ECRS_createMetaData();
- if (OK != ECRS_addToMetaData(m,
- EXTRACTOR_UNKNOWN,
- "link")) {
- ECRS_freeMetaData(m);
- ABORT();
- }
- if (OK != ECRS_addToMetaData(m,
- EXTRACTOR_FILENAME,
- "lib-link.m4")) {
- ECRS_freeMetaData(m);
- ABORT();
- }
- size = ECRS_sizeofMetaData(m,
- ECRS_SERIALIZE_FULL);
- val = MALLOC(size);
- if (size != ECRS_serializeMetaData(NULL,
- m,
- val,
- size,
- ECRS_SERIALIZE_FULL)) {
- ECRS_freeMetaData(m);
- FREE(val);
- ABORT();
- }
- ECRS_freeMetaData(m);
- m = ECRS_deserializeMetaData(NULL,
- val,
- size);
- FREE(val);
+ m = ECRS_createMetaData ();
+ if (OK != ECRS_addToMetaData (m, EXTRACTOR_UNKNOWN, "link"))
+ {
+ ECRS_freeMetaData (m);
+ ABORT ();
+ }
+ if (OK != ECRS_addToMetaData (m, EXTRACTOR_FILENAME, "lib-link.m4"))
+ {
+ ECRS_freeMetaData (m);
+ ABORT ();
+ }
+ size = ECRS_sizeofMetaData (m, ECRS_SERIALIZE_FULL);
+ val = MALLOC (size);
+ if (size != ECRS_serializeMetaData (NULL,
+ m, val, size, ECRS_SERIALIZE_FULL))
+ {
+ ECRS_freeMetaData (m);
+ FREE (val);
+ ABORT ();
+ }
+ ECRS_freeMetaData (m);
+ m = ECRS_deserializeMetaData (NULL, val, size);
+ FREE (val);
if (m == NULL)
- ABORT();
- ECRS_freeMetaData(m);
+ ABORT ();
+ ECRS_freeMetaData (m);
return 0;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
- failureCount += testMeta();
+ failureCount += testMeta ();
if (failureCount != 0)
return 1;
Modified: GNUnet/src/applications/fs/ecrs/namespace.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/namespace.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/namespace.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -37,27 +37,27 @@
#define MAX_NBLOCK_SIZE 32000
#define MAX_SBLOCK_SIZE 32000
-static char * getPseudonymFileName(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name) {
- char * gnHome;
- char * fileName;
+static char *
+getPseudonymFileName (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, const char *name)
+{
+ char *gnHome;
+ char *fileName;
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &fileName);
- gnHome = string_expandFileName(ectx, fileName);
- FREE(fileName);
- fileName = MALLOC(strlen(gnHome) + strlen(PSEUDODIR) + strlen(name) + 2);
- strcpy(fileName, gnHome);
- FREE(gnHome);
- strcat(fileName, DIR_SEPARATOR_STR);
- strcat(fileName, PSEUDODIR);
- disk_directory_create(ectx,
- fileName);
- strcat(fileName, name);
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &fileName);
+ gnHome = string_expandFileName (ectx, fileName);
+ FREE (fileName);
+ fileName =
+ MALLOC (strlen (gnHome) + strlen (PSEUDODIR) + strlen (name) + 2);
+ strcpy (fileName, gnHome);
+ FREE (gnHome);
+ strcat (fileName, DIR_SEPARATOR_STR);
+ strcat (fileName, PSEUDODIR);
+ disk_directory_create (ectx, fileName);
+ strcat (fileName, name);
return fileName;
}
@@ -66,26 +66,27 @@
*
* @return OK on success, SYSERR on error
*/
-int ECRS_deleteNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name) {
- char * fileName;
+int
+ECRS_deleteNamespace (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, const char *name)
+{
+ char *fileName;
- fileName = getPseudonymFileName(ectx, cfg, name);
- if (YES != disk_file_test(ectx,
- fileName)) {
- FREE(fileName);
- return SYSERR; /* no such namespace */
- }
- if (0 != UNLINK(fileName)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "unlink",
- fileName);
- FREE(fileName);
- return SYSERR;
- }
- FREE(fileName);
+ fileName = getPseudonymFileName (ectx, cfg, name);
+ if (YES != disk_file_test (ectx, fileName))
+ {
+ FREE (fileName);
+ return SYSERR; /* no such namespace */
+ }
+ if (0 != UNLINK (fileName))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ "unlink", fileName);
+ FREE (fileName);
+ return SYSERR;
+ }
+ FREE (fileName);
return OK;
}
@@ -110,200 +111,183 @@
* @return OK on success, SYSERR on error (namespace already exists)
*/
struct ECRS_URI *
-ECRS_createNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name,
- const struct ECRS_MetaData * meta,
- unsigned int anonymityLevel,
- unsigned int priority,
- cron_t expiration,
- const struct ECRS_URI * advertisementURI,
- const HashCode512 * rootEntry) {
- struct ECRS_URI * rootURI;
- char * fileName;
- struct PrivateKey * hk;
- PrivateKeyEncoded * hke;
- char * dst;
+ECRS_createNamespace (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *name,
+ const struct ECRS_MetaData *meta,
+ unsigned int anonymityLevel,
+ unsigned int priority,
+ cron_t expiration,
+ const struct ECRS_URI *advertisementURI,
+ const HashCode512 * rootEntry)
+{
+ struct ECRS_URI *rootURI;
+ char *fileName;
+ struct PrivateKey *hk;
+ PrivateKeyEncoded *hke;
+ char *dst;
unsigned short len;
HashCode512 hc;
- struct ClientServerConnection * sock;
- Datastore_Value * value;
- Datastore_Value * knvalue;
+ struct ClientServerConnection *sock;
+ Datastore_Value *value;
+ Datastore_Value *knvalue;
unsigned int size;
unsigned int mdsize;
- struct PrivateKey * pk;
- NBlock * nb;
- KNBlock * knb;
- char ** keywords;
+ struct PrivateKey *pk;
+ NBlock *nb;
+ KNBlock *knb;
+ char **keywords;
unsigned int keywordCount;
int i;
- char * cpy;
+ char *cpy;
- if ( (advertisementURI != NULL) &&
- (! ECRS_isKeywordUri(advertisementURI)) ) {
- GE_BREAK(ectx, 0);
- return NULL;
- }
- fileName = getPseudonymFileName(ectx,
- cfg,
- name);
- if (YES == disk_file_test(ectx,
- fileName)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Cannot create pseudonym `%s', file `%s' exists.\n"),
- name,
- fileName);
- FREE(fileName);
- return NULL;
- }
- hk = makePrivateKey();
- hke = encodePrivateKey(hk);
- len = ntohs(hke->len);
- dst = (char*) hke;
- disk_file_write(ectx,
- fileName,
- dst,
- len,
- "600");
- FREE(fileName);
- FREE(dst);
+ if ((advertisementURI != NULL) && (!ECRS_isKeywordUri (advertisementURI)))
+ {
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
+ fileName = getPseudonymFileName (ectx, cfg, name);
+ if (YES == disk_file_test (ectx, fileName))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Cannot create pseudonym `%s', file `%s' exists.\n"),
+ name, fileName);
+ FREE (fileName);
+ return NULL;
+ }
+ hk = makePrivateKey ();
+ hke = encodePrivateKey (hk);
+ len = ntohs (hke->len);
+ dst = (char *) hke;
+ disk_file_write (ectx, fileName, dst, len, "600");
+ FREE (fileName);
+ FREE (dst);
/* create advertisements */
- mdsize = ECRS_sizeofMetaData(meta,
- ECRS_SERIALIZE_PART);
- size = mdsize + sizeof(NBlock);
- if (size > MAX_NBLOCK_SIZE) {
- size = MAX_NBLOCK_SIZE;
- value = MALLOC(sizeof(Datastore_Value) +
- size);
- nb = (NBlock*) &value[1];
- nb->type = htonl(N_BLOCK);
- mdsize = size - sizeof(NBlock);
- mdsize = ECRS_serializeMetaData(ectx,
- meta,
- (char*)&nb[1],
- mdsize,
- ECRS_SERIALIZE_PART);
- if (mdsize == -1) {
- GE_BREAK(ectx, 0);
- ECRS_deleteNamespace(ectx,
- cfg,
- name);
- freePrivateKey(hk);
- return NULL;
+ mdsize = ECRS_sizeofMetaData (meta, ECRS_SERIALIZE_PART);
+ size = mdsize + sizeof (NBlock);
+ if (size > MAX_NBLOCK_SIZE)
+ {
+ size = MAX_NBLOCK_SIZE;
+ value = MALLOC (sizeof (Datastore_Value) + size);
+ nb = (NBlock *) & value[1];
+ nb->type = htonl (N_BLOCK);
+ mdsize = size - sizeof (NBlock);
+ mdsize = ECRS_serializeMetaData (ectx,
+ meta,
+ (char *) &nb[1],
+ mdsize, ECRS_SERIALIZE_PART);
+ if (mdsize == -1)
+ {
+ GE_BREAK (ectx, 0);
+ ECRS_deleteNamespace (ectx, cfg, name);
+ freePrivateKey (hk);
+ return NULL;
+ }
+ size = sizeof (NBlock) + mdsize;
}
- size = sizeof(NBlock) + mdsize;
- } else {
- value = MALLOC(sizeof(Datastore_Value) +
- size);
- nb = (NBlock*) &value[1];
- nb->type = htonl(N_BLOCK);
- ECRS_serializeMetaData(ectx,
- meta,
- (char*)&nb[1],
- mdsize,
- ECRS_SERIALIZE_FULL);
- }
- value->size = htonl(sizeof(Datastore_Value) + size);
- value->type = htonl(N_BLOCK);
- value->prio = htonl(priority);
- value->anonymityLevel = htonl(anonymityLevel);
- value->expirationTime = htonll(expiration);
- sock = client_connection_create(ectx, cfg);
+ else
+ {
+ value = MALLOC (sizeof (Datastore_Value) + size);
+ nb = (NBlock *) & value[1];
+ nb->type = htonl (N_BLOCK);
+ ECRS_serializeMetaData (ectx,
+ meta,
+ (char *) &nb[1], mdsize, ECRS_SERIALIZE_FULL);
+ }
+ value->size = htonl (sizeof (Datastore_Value) + size);
+ value->type = htonl (N_BLOCK);
+ value->prio = htonl (priority);
+ value->anonymityLevel = htonl (anonymityLevel);
+ value->expirationTime = htonll (expiration);
+ sock = client_connection_create (ectx, cfg);
/* publish NBlock */
- memset(&nb->identifier, 0, sizeof(HashCode512));
- getPublicKey(hk,
- &nb->subspace);
- hash(&nb->subspace,
- sizeof(PublicKey),
- &nb->namespace);
- rootURI = MALLOC(sizeof(URI));
+ memset (&nb->identifier, 0, sizeof (HashCode512));
+ getPublicKey (hk, &nb->subspace);
+ hash (&nb->subspace, sizeof (PublicKey), &nb->namespace);
+ rootURI = MALLOC (sizeof (URI));
rootURI->type = sks;
rootURI->data.sks.namespace = nb->namespace;
rootURI->data.sks.identifier = *rootEntry;
nb->rootEntry = *rootEntry;
- GE_ASSERT(ectx,
- OK == sign(hk,
- mdsize + 3 * sizeof(HashCode512),
- &nb->identifier,
- &nb->signature));
- if (OK != FS_insert(sock, value)) {
- GE_BREAK(ectx, 0);
- FREE(rootURI);
- FREE(value);
- connection_destroy(sock);
- freePrivateKey(hk);
- ECRS_deleteNamespace(ectx, cfg, name);
- return NULL;
- }
+ GE_ASSERT (ectx,
+ OK == sign (hk,
+ mdsize + 3 * sizeof (HashCode512),
+ &nb->identifier, &nb->signature));
+ if (OK != FS_insert (sock, value))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (rootURI);
+ FREE (value);
+ connection_destroy (sock);
+ freePrivateKey (hk);
+ ECRS_deleteNamespace (ectx, cfg, name);
+ return NULL;
+ }
/* publish KNBlocks */
- size += sizeof(KNBlock) - sizeof(NBlock);
- knvalue = MALLOC(sizeof(Datastore_Value) + size);
+ size += sizeof (KNBlock) - sizeof (NBlock);
+ knvalue = MALLOC (sizeof (Datastore_Value) + size);
*knvalue = *value;
- knvalue->type = htonl(KN_BLOCK);
- knvalue->size = htonl(sizeof(Datastore_Value) + size);
- knb = (KNBlock*) &knvalue[1];
- knb->type = htonl(KN_BLOCK);
- memcpy(&knb->nblock,
- nb,
- sizeof(NBlock) + mdsize);
+ knvalue->type = htonl (KN_BLOCK);
+ knvalue->size = htonl (sizeof (Datastore_Value) + size);
+ knb = (KNBlock *) & knvalue[1];
+ knb->type = htonl (KN_BLOCK);
+ memcpy (&knb->nblock, nb, sizeof (NBlock) + mdsize);
- if (advertisementURI != NULL) {
- keywords = advertisementURI->data.ksk.keywords;
- keywordCount = advertisementURI->data.ksk.keywordCount;
- cpy = MALLOC(size - sizeof(KBlock) - sizeof(unsigned int));
- memcpy(cpy,
- &knb->nblock,
- size - sizeof(KBlock) - sizeof(unsigned int));
- for (i=0;i<keywordCount;i++) {
- hash(keywords[i],
- strlen(keywords[i]),
- &hc);
- pk = makeKblockKey(&hc);
- getPublicKey(pk,
- &knb->kblock.keyspace);
- GE_ASSERT(ectx, size - sizeof(KBlock) - sizeof(unsigned int)
- == sizeof(NBlock) + mdsize);
- ECRS_encryptInPlace(&hc,
- &knb->nblock,
- size - sizeof(KBlock) - sizeof(unsigned int));
+ if (advertisementURI != NULL)
+ {
+ keywords = advertisementURI->data.ksk.keywords;
+ keywordCount = advertisementURI->data.ksk.keywordCount;
+ cpy = MALLOC (size - sizeof (KBlock) - sizeof (unsigned int));
+ memcpy (cpy,
+ &knb->nblock, size - sizeof (KBlock) - sizeof (unsigned int));
+ for (i = 0; i < keywordCount; i++)
+ {
+ hash (keywords[i], strlen (keywords[i]), &hc);
+ pk = makeKblockKey (&hc);
+ getPublicKey (pk, &knb->kblock.keyspace);
+ GE_ASSERT (ectx, size - sizeof (KBlock) - sizeof (unsigned int)
+ == sizeof (NBlock) + mdsize);
+ ECRS_encryptInPlace (&hc,
+ &knb->nblock,
+ size - sizeof (KBlock) -
+ sizeof (unsigned int));
- GE_ASSERT(ectx,
- OK == sign(pk,
- sizeof(NBlock) + mdsize,
- &knb->nblock,
- &knb->kblock.signature));
- /* extra check: verify sig */
- freePrivateKey(pk);
- if (OK != FS_insert(sock, knvalue)) {
- GE_BREAK(ectx, 0);
- FREE(rootURI);
- ECRS_deleteNamespace(ectx, cfg, name);
- FREE(cpy);
- FREE(knvalue);
- FREE(value);
- connection_destroy(sock);
- freePrivateKey(hk);
- return NULL;
- }
- /* restore nblock to avoid re-encryption! */
- memcpy(&knb->nblock,
- cpy,
- size - sizeof(KBlock) - sizeof(unsigned int));
+ GE_ASSERT (ectx,
+ OK == sign (pk,
+ sizeof (NBlock) + mdsize,
+ &knb->nblock, &knb->kblock.signature));
+ /* extra check: verify sig */
+ freePrivateKey (pk);
+ if (OK != FS_insert (sock, knvalue))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (rootURI);
+ ECRS_deleteNamespace (ectx, cfg, name);
+ FREE (cpy);
+ FREE (knvalue);
+ FREE (value);
+ connection_destroy (sock);
+ freePrivateKey (hk);
+ return NULL;
+ }
+ /* restore nblock to avoid re-encryption! */
+ memcpy (&knb->nblock,
+ cpy, size - sizeof (KBlock) - sizeof (unsigned int));
+ }
+ FREE (cpy);
}
- FREE(cpy);
- }
- FREE(knvalue);
- FREE(value);
- connection_destroy(sock);
- freePrivateKey(hk);
+ FREE (knvalue);
+ FREE (value);
+ connection_destroy (sock);
+ freePrivateKey (hk);
return rootURI;
}
@@ -315,59 +299,53 @@
* hc of the public key
* @return OK if the namespace exists, SYSERR if not
*/
-int ECRS_testNamespaceExists(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name,
- const HashCode512 * hc) {
- struct PrivateKey * hk;
- char * fileName;
- PrivateKeyEncoded * hke;
- char * dst;
+int
+ECRS_testNamespaceExists (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *name, const HashCode512 * hc)
+{
+ struct PrivateKey *hk;
+ char *fileName;
+ PrivateKeyEncoded *hke;
+ char *dst;
unsigned long long len;
HashCode512 namespace;
PublicKey pk;
/* FIRST: read and decrypt pseudonym! */
- fileName = getPseudonymFileName(ectx,
- cfg,
- name);
- if (OK != disk_file_size(ectx,
- fileName,
- &len,
- YES)) {
- FREE(fileName);
- return SYSERR;
- }
- if (len < 2) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("File `%s' does not contain a pseudonym.\n"),
- fileName);
- FREE(fileName);
- return SYSERR;
- }
- dst = MALLOC(len);
- len = disk_file_read(ectx, fileName, len, dst);
- FREE(fileName);
- hke = (PrivateKeyEncoded*) dst;
- if ( ntohs(hke->len) != len ) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Format of pseudonym `%s' is invalid.\n"),
- name);
- FREE(hke);
- return SYSERR;
- }
- hk = decodePrivateKey(hke);
- FREE(hke);
+ fileName = getPseudonymFileName (ectx, cfg, name);
+ if (OK != disk_file_size (ectx, fileName, &len, YES))
+ {
+ FREE (fileName);
+ return SYSERR;
+ }
+ if (len < 2)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("File `%s' does not contain a pseudonym.\n"), fileName);
+ FREE (fileName);
+ return SYSERR;
+ }
+ dst = MALLOC (len);
+ len = disk_file_read (ectx, fileName, len, dst);
+ FREE (fileName);
+ hke = (PrivateKeyEncoded *) dst;
+ if (ntohs (hke->len) != len)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Format of pseudonym `%s' is invalid.\n"), name);
+ FREE (hke);
+ return SYSERR;
+ }
+ hk = decodePrivateKey (hke);
+ FREE (hke);
if (hk == NULL)
return SYSERR;
- getPublicKey(hk,
- &pk);
- freePrivateKey(hk);
- hash(&pk, sizeof(PublicKey), &namespace);
- if ( (hc == NULL) ||
- (equalsHashCode512(hc,
- &namespace)))
+ getPublicKey (hk, &pk);
+ freePrivateKey (hk);
+ hash (&pk, sizeof (PublicKey), &namespace);
+ if ((hc == NULL) || (equalsHashCode512 (hc, &namespace)))
return OK;
else
return SYSERR;
@@ -383,249 +361,226 @@
* entry?
*/
struct ECRS_URI *
-ECRS_addToNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name,
- unsigned int anonymityLevel,
- unsigned int priority,
- cron_t expiration,
- TIME_T creationTime,
- TIME_T updateInterval,
- const HashCode512 * thisId,
- const HashCode512 * nextId,
- const struct ECRS_URI * dstU,
- const struct ECRS_MetaData * md) {
- struct ECRS_URI * uri;
- struct ClientServerConnection * sock;
- Datastore_Value * value;
+ECRS_addToNamespace (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *name,
+ unsigned int anonymityLevel,
+ unsigned int priority,
+ cron_t expiration,
+ TIME_T creationTime,
+ TIME_T updateInterval,
+ const HashCode512 * thisId,
+ const HashCode512 * nextId,
+ const struct ECRS_URI *dstU,
+ const struct ECRS_MetaData *md)
+{
+ struct ECRS_URI *uri;
+ struct ClientServerConnection *sock;
+ Datastore_Value *value;
unsigned int size;
unsigned int mdsize;
- struct PrivateKey * hk;
- SBlock * sb;
+ struct PrivateKey *hk;
+ SBlock *sb;
HashCode512 namespace;
- char * dstURI;
- char * destPos;
- char * fileName;
- PrivateKeyEncoded * hke;
- char * dst;
+ char *dstURI;
+ char *destPos;
+ char *fileName;
+ PrivateKeyEncoded *hke;
+ char *dst;
unsigned long long len;
HashCode512 hc;
int ret;
/* FIRST: read pseudonym! */
- fileName = getPseudonymFileName(ectx, cfg, name);
- if (OK != disk_file_size(ectx,
- fileName,
- &len,
- YES)) {
- FREE(fileName);
- return NULL;
- }
- if (len < 2) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("File `%s' does not contain a pseudonym.\n"),
- fileName);
- FREE(fileName);
- return NULL;
- }
- dst = MALLOC(len);
- len = disk_file_read(ectx, fileName, len, dst);
- FREE(fileName);
- hke = (PrivateKeyEncoded*) dst;
- if ( ntohs(hke->len) != len ) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Format of pseudonym `%s' is invalid.\n"),
- name);
- FREE(hke);
- return NULL;
- }
- hk = decodePrivateKey(hke);
- FREE(hke);
+ fileName = getPseudonymFileName (ectx, cfg, name);
+ if (OK != disk_file_size (ectx, fileName, &len, YES))
+ {
+ FREE (fileName);
+ return NULL;
+ }
+ if (len < 2)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("File `%s' does not contain a pseudonym.\n"), fileName);
+ FREE (fileName);
+ return NULL;
+ }
+ dst = MALLOC (len);
+ len = disk_file_read (ectx, fileName, len, dst);
+ FREE (fileName);
+ hke = (PrivateKeyEncoded *) dst;
+ if (ntohs (hke->len) != len)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Format of pseudonym `%s' is invalid.\n"), name);
+ FREE (hke);
+ return NULL;
+ }
+ hk = decodePrivateKey (hke);
+ FREE (hke);
if (hk == NULL)
return NULL;
/* THEN: construct SBlock */
- dstURI = ECRS_uriToString(dstU);
- mdsize = ECRS_sizeofMetaData(md,
- ECRS_SERIALIZE_PART);
- size = mdsize + sizeof(SBlock) + strlen(dstURI) + 1;
- if (size > MAX_SBLOCK_SIZE) {
- size = MAX_SBLOCK_SIZE;
- value = MALLOC(sizeof(Datastore_Value) +
- size);
- sb = (SBlock*) &value[1];
- sb->type = htonl(S_BLOCK);
- destPos = (char*) &sb[1];
- memcpy(destPos,
- dstURI,
- strlen(dstURI) + 1);
- mdsize = size - sizeof(SBlock) - strlen(dstURI) - 1;
- mdsize = ECRS_serializeMetaData(ectx,
- md,
- &destPos[strlen(dstURI)+1],
- mdsize,
- ECRS_SERIALIZE_PART);
- if (mdsize == -1) {
- GE_BREAK(ectx, 0);
- FREE(dstURI);
- freePrivateKey(hk);
- return NULL;
+ dstURI = ECRS_uriToString (dstU);
+ mdsize = ECRS_sizeofMetaData (md, ECRS_SERIALIZE_PART);
+ size = mdsize + sizeof (SBlock) + strlen (dstURI) + 1;
+ if (size > MAX_SBLOCK_SIZE)
+ {
+ size = MAX_SBLOCK_SIZE;
+ value = MALLOC (sizeof (Datastore_Value) + size);
+ sb = (SBlock *) & value[1];
+ sb->type = htonl (S_BLOCK);
+ destPos = (char *) &sb[1];
+ memcpy (destPos, dstURI, strlen (dstURI) + 1);
+ mdsize = size - sizeof (SBlock) - strlen (dstURI) - 1;
+ mdsize = ECRS_serializeMetaData (ectx,
+ md,
+ &destPos[strlen (dstURI) + 1],
+ mdsize, ECRS_SERIALIZE_PART);
+ if (mdsize == -1)
+ {
+ GE_BREAK (ectx, 0);
+ FREE (dstURI);
+ freePrivateKey (hk);
+ return NULL;
+ }
+ size = sizeof (SBlock) + mdsize + strlen (dstURI) + 1;
}
- size = sizeof(SBlock) + mdsize + strlen(dstURI) + 1;
- } else {
- value = MALLOC(sizeof(Datastore_Value) +
- size);
- sb = (SBlock*) &value[1];
- sb->type = htonl(S_BLOCK);
- destPos = (char*) &sb[1];
- memcpy(destPos,
- dstURI,
- strlen(dstURI) + 1);
- ECRS_serializeMetaData(ectx,
- md,
- &destPos[strlen(dstURI)+1],
- mdsize,
- ECRS_SERIALIZE_FULL);
- }
- value->size = htonl(sizeof(Datastore_Value) + size);
- value->type = htonl(S_BLOCK);
- value->prio = htonl(priority);
- value->anonymityLevel = htonl(anonymityLevel);
- value->expirationTime = htonll(expiration);
+ else
+ {
+ value = MALLOC (sizeof (Datastore_Value) + size);
+ sb = (SBlock *) & value[1];
+ sb->type = htonl (S_BLOCK);
+ destPos = (char *) &sb[1];
+ memcpy (destPos, dstURI, strlen (dstURI) + 1);
+ ECRS_serializeMetaData (ectx,
+ md,
+ &destPos[strlen (dstURI) + 1],
+ mdsize, ECRS_SERIALIZE_FULL);
+ }
+ value->size = htonl (sizeof (Datastore_Value) + size);
+ value->type = htonl (S_BLOCK);
+ value->prio = htonl (priority);
+ value->anonymityLevel = htonl (anonymityLevel);
+ value->expirationTime = htonll (expiration);
/* update SBlock specific data */
- sb->creationTime = htonl(creationTime);
- sb->updateInterval = htonl(updateInterval);
+ sb->creationTime = htonl (creationTime);
+ sb->updateInterval = htonl (updateInterval);
sb->nextIdentifier = *nextId;
- deltaId(thisId,
- nextId,
- &sb->identifierIncrement);
- hash(thisId,
- sizeof(HashCode512),
- &hc);
- getPublicKey(hk,
- &sb->subspace);
- hash(&sb->subspace,
- sizeof(PublicKey),
- &namespace);
- xorHashCodes(&hc,
- &namespace,
- &sb->identifier); /* sb->identifier = primary key in query! */
+ deltaId (thisId, nextId, &sb->identifierIncrement);
+ hash (thisId, sizeof (HashCode512), &hc);
+ getPublicKey (hk, &sb->subspace);
+ hash (&sb->subspace, sizeof (PublicKey), &namespace);
+ xorHashCodes (&hc, &namespace, &sb->identifier); /* sb->identifier =
primary key in query! */
- uri = MALLOC(sizeof(URI));
+ uri = MALLOC (sizeof (URI));
uri->type = sks;
uri->data.sks.namespace = namespace;
uri->data.sks.identifier = *thisId;
- ECRS_encryptInPlace(thisId,
- &sb->creationTime,
- size
- - sizeof(unsigned int)
- - sizeof(Signature)
- - sizeof(PublicKey)
- - sizeof(HashCode512));
+ ECRS_encryptInPlace (thisId,
+ &sb->creationTime,
+ size
+ - sizeof (unsigned int)
+ - sizeof (Signature)
+ - sizeof (PublicKey) - sizeof (HashCode512));
/* FINALLY: sign & publish SBlock */
- GE_ASSERT(ectx,
- OK == sign(hk,
- size
- - sizeof(Signature)
- - sizeof(PublicKey)
- - sizeof(unsigned int),
- &sb->identifier,
- &sb->signature));
- freePrivateKey(hk);
+ GE_ASSERT (ectx,
+ OK == sign (hk,
+ size
+ - sizeof (Signature)
+ - sizeof (PublicKey)
+ - sizeof (unsigned int),
+ &sb->identifier, &sb->signature));
+ freePrivateKey (hk);
- sock = client_connection_create(ectx, cfg);
- ret = FS_insert(sock, value);
- if (ret != OK) {
- FREE(uri);
- uri = NULL;
- }
- connection_destroy(sock);
- FREE(value);
- FREE(dstURI);
+ sock = client_connection_create (ectx, cfg);
+ ret = FS_insert (sock, value);
+ if (ret != OK)
+ {
+ FREE (uri);
+ uri = NULL;
+ }
+ connection_destroy (sock);
+ FREE (value);
+ FREE (dstURI);
return uri;
}
-struct lNCLS {
- struct GE_Context * ectx;
- struct GC_Configuration * cfg;
+struct lNCLS
+{
+ struct GE_Context *ectx;
+ struct GC_Configuration *cfg;
ECRS_NamespaceInfoCallback cb;
- void * cls;
+ void *cls;
int cnt;
};
-static int processFile_(const char * name,
- const char * dirName,
- void * cls) {
- struct lNCLS * c = cls;
- struct PrivateKey * hk;
- char * fileName;
- PrivateKeyEncoded * hke;
- char * dst;
+static int
+processFile_ (const char *name, const char *dirName, void *cls)
+{
+ struct lNCLS *c = cls;
+ struct PrivateKey *hk;
+ char *fileName;
+ PrivateKeyEncoded *hke;
+ char *dst;
unsigned long long len;
HashCode512 namespace;
PublicKey pk;
- fileName = getPseudonymFileName(c->ectx,
- c->cfg,
- name);
- if (OK != disk_file_size(c->ectx,
- fileName,
- &len,
- YES)) {
- FREE(fileName);
- return OK;
- }
- if (len < 2) {
- GE_LOG(c->ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("File `%s' does not contain a pseudonym.\n"),
- fileName);
- FREE(fileName);
- return OK;
- }
- dst = MALLOC(len);
- len = disk_file_read(c->ectx,
- fileName,
- len,
- dst);
- hke = (PrivateKeyEncoded*) dst;
- if ( ntohs(hke->len) != len ) {
- GE_LOG(c->ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Format of file `%s' is invalid.\n"),
- fileName);
- FREE(hke);
- FREE(fileName);
- return OK;
- }
- hk = decodePrivateKey(hke);
- FREE(hke);
- if (hk == NULL) {
- GE_LOG(c->ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Format of file `%s' is invalid.\n"),
- fileName);
- FREE(fileName);
- GE_BREAK(c->ectx, 0);
- return SYSERR;
- }
- FREE(fileName);
- getPublicKey(hk,
- &pk);
- freePrivateKey(hk);
- hash(&pk, sizeof(PublicKey), &namespace);
- if (NULL != c->cb) {
- if (OK == c->cb(&namespace,
- name,
- c->cls))
- c->cnt++;
- else
- c->cnt = SYSERR;
- } else
+ fileName = getPseudonymFileName (c->ectx, c->cfg, name);
+ if (OK != disk_file_size (c->ectx, fileName, &len, YES))
+ {
+ FREE (fileName);
+ return OK;
+ }
+ if (len < 2)
+ {
+ GE_LOG (c->ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("File `%s' does not contain a pseudonym.\n"), fileName);
+ FREE (fileName);
+ return OK;
+ }
+ dst = MALLOC (len);
+ len = disk_file_read (c->ectx, fileName, len, dst);
+ hke = (PrivateKeyEncoded *) dst;
+ if (ntohs (hke->len) != len)
+ {
+ GE_LOG (c->ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Format of file `%s' is invalid.\n"), fileName);
+ FREE (hke);
+ FREE (fileName);
+ return OK;
+ }
+ hk = decodePrivateKey (hke);
+ FREE (hke);
+ if (hk == NULL)
+ {
+ GE_LOG (c->ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Format of file `%s' is invalid.\n"), fileName);
+ FREE (fileName);
+ GE_BREAK (c->ectx, 0);
+ return SYSERR;
+ }
+ FREE (fileName);
+ getPublicKey (hk, &pk);
+ freePrivateKey (hk);
+ hash (&pk, sizeof (PublicKey), &namespace);
+ if (NULL != c->cb)
+ {
+ if (OK == c->cb (&namespace, name, c->cls))
+ c->cnt++;
+ else
+ c->cnt = SYSERR;
+ }
+ else
c->cnt++;
return OK;
}
@@ -636,11 +591,12 @@
* @param list where to store the names (is allocated, caller frees)
* @return SYSERR on error, otherwise the number of pseudonyms in list
*/
-int ECRS_listNamespaces(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- ECRS_NamespaceInfoCallback cb,
- void * cls) {
- char * dirName;
+int
+ECRS_listNamespaces (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ ECRS_NamespaceInfoCallback cb, void *cls)
+{
+ char *dirName;
struct lNCLS myCLS;
myCLS.cls = cls;
@@ -648,12 +604,9 @@
myCLS.cnt = 0;
myCLS.ectx = ectx;
myCLS.cfg = cfg;
- dirName = getPseudonymFileName(ectx, cfg, "");
- disk_directory_scan(ectx,
- dirName,
- &processFile_,
- &myCLS);
- FREE(dirName);
+ dirName = getPseudonymFileName (ectx, cfg, "");
+ disk_directory_scan (ectx, dirName, &processFile_, &myCLS);
+ FREE (dirName);
return myCLS.cnt;
}
Modified: GNUnet/src/applications/fs/ecrs/namespacetest.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/namespacetest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/ecrs/namespacetest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -36,125 +36,101 @@
#define CHECKNAME "gnunet-namespace-test"
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
static int match;
-static int spcb(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * closure) {
- struct ECRS_URI * want = closure;
+static int
+spcb (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *closure)
+{
+ struct ECRS_URI *want = closure;
- if (ECRS_equalsUri(want,
- fi->uri))
+ if (ECRS_equalsUri (want, fi->uri))
match = 1;
else
- fprintf(stderr,
- "Namespace search returned unexpected result: \nHAVE: %s\nWANT: %s...\n",
- ECRS_uriToString(fi->uri),
- ECRS_uriToString(want));
+ fprintf (stderr,
+ "Namespace search returned unexpected result: \nHAVE: %s\nWANT:
%s...\n",
+ ECRS_uriToString (fi->uri), ECRS_uriToString (want));
return OK;
}
-static int testNamespace() {
+static int
+testNamespace ()
+{
HashCode512 root;
HashCode512 thisId;
HashCode512 nextId;
- struct ECRS_URI * adv;
- struct ECRS_URI * uri;
- struct ECRS_URI * advURI;
- struct ECRS_URI * rootURI;
- struct ECRS_MetaData * meta;
- const char * keys[] = {
+ struct ECRS_URI *adv;
+ struct ECRS_URI *uri;
+ struct ECRS_URI *advURI;
+ struct ECRS_URI *rootURI;
+ struct ECRS_MetaData *meta;
+ const char *keys[] = {
"testNamespace",
NULL,
};
- ECRS_deleteNamespace(NULL,
- cfg,
- CHECKNAME); /* make sure old one is deleted */
- meta = ECRS_createMetaData();
- adv = ECRS_keywordsToUri(keys);
- hash("root", 4, &root);
+ ECRS_deleteNamespace (NULL, cfg, CHECKNAME); /* make sure old one is
deleted */
+ meta = ECRS_createMetaData ();
+ adv = ECRS_keywordsToUri (keys);
+ hash ("root", 4, &root);
rootURI =
- ECRS_createNamespace(NULL,
- cfg,
- CHECKNAME,
- meta,
- 0,
- 0,
- get_time() + 15 * cronMINUTES,
- adv,
- &root);
- CHECK(NULL != rootURI);
- hash("this", 4, &thisId);
- hash("next", 4, &nextId);
- uri = rootURI; /* just for fun: NS::this advertises NS::root */
- advURI = ECRS_addToNamespace(NULL,
- cfg,
- CHECKNAME,
- 1, /* anonymity */
- 1000, /* priority */
- 5 * cronMINUTES + get_time(),
- TIME(NULL) + 300,
- 0,
- &thisId,
- &nextId,
- uri,
- meta);
- CHECK(NULL != advURI);
- fprintf(stderr,
- "Starting namespace search...\n");
- CHECK(OK == ECRS_search(NULL,
- cfg,
- advURI,
- 1,
- 60 * cronSECONDS,
- &spcb,
- uri,
- NULL,
- NULL));
- fprintf(stderr,
- "Completed namespace search...\n");
- CHECK(OK == ECRS_deleteNamespace(NULL,
- cfg,
- CHECKNAME));
- CHECK(SYSERR == ECRS_deleteNamespace(NULL,
- cfg,
- CHECKNAME));
- ECRS_freeMetaData(meta);
- ECRS_freeUri(rootURI);
- ECRS_freeUri(advURI);
- CHECK(match == 1);
+ ECRS_createNamespace (NULL,
+ cfg,
+ CHECKNAME,
+ meta,
+ 0, 0, get_time () + 15 * cronMINUTES, adv, &root);
+ CHECK (NULL != rootURI);
+ hash ("this", 4, &thisId);
+ hash ("next", 4, &nextId);
+ uri = rootURI; /* just for fun: NS::this advertises NS::root
*/
+ advURI = ECRS_addToNamespace (NULL, cfg, CHECKNAME, 1, /* anonymity */
+ 1000, /* priority */
+ 5 * cronMINUTES + get_time (),
+ TIME (NULL) + 300,
+ 0, &thisId, &nextId, uri, meta);
+ CHECK (NULL != advURI);
+ fprintf (stderr, "Starting namespace search...\n");
+ CHECK (OK == ECRS_search (NULL,
+ cfg,
+ advURI,
+ 1, 60 * cronSECONDS, &spcb, uri, NULL, NULL));
+ fprintf (stderr, "Completed namespace search...\n");
+ CHECK (OK == ECRS_deleteNamespace (NULL, cfg, CHECKNAME));
+ CHECK (SYSERR == ECRS_deleteNamespace (NULL, cfg, CHECKNAME));
+ ECRS_freeMetaData (meta);
+ ECRS_freeUri (rootURI);
+ ECRS_freeUri (advURI);
+ CHECK (match == 1);
return 0;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
pid_t daemon;
int failureCount = 0;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
- if (OK != connection_wait_for_running(NULL,
- cfg,
- 60 * cronSECONDS)) {
- failureCount++;
- } else {
- PTHREAD_SLEEP(5 * cronSECONDS);
- failureCount += testNamespace();
- }
- GE_ASSERT(NULL, OK == os_daemon_stop(NULL, daemon));
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
+ if (OK != connection_wait_for_running (NULL, cfg, 60 * cronSECONDS))
+ {
+ failureCount++;
+ }
+ else
+ {
+ PTHREAD_SLEEP (5 * cronSECONDS);
+ failureCount += testNamespace ();
+ }
+ GE_ASSERT (NULL, OK == os_daemon_stop (NULL, daemon));
return (failureCount == 0) ? 0 : 1;
}
Modified: GNUnet/src/applications/fs/ecrs/parser.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/parser.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/parser.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -31,26 +31,29 @@
/**
* @param scls must be of type "struct ECRS_URI **"
*/
-int gnunet_getopt_configure_set_keywords(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value) {
- struct ECRS_URI ** uri = scls;
- struct ECRS_URI * u = *uri;
+int
+gnunet_getopt_configure_set_keywords (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option, const char *value)
+{
+ struct ECRS_URI **uri = scls;
+ struct ECRS_URI *u = *uri;
- if (u == NULL) {
- u = MALLOC(sizeof(struct ECRS_URI));
- *uri = u;
- u->type = ksk;
- u->data.ksk.keywordCount = 0;
- u->data.ksk.keywords = NULL;
- } else {
- GE_ASSERT(NULL, u->type == ksk);
- }
- GROW(u->data.ksk.keywords,
- u->data.ksk.keywordCount,
- u->data.ksk.keywordCount + 1);
- u->data.ksk.keywords[u->data.ksk.keywordCount-1] = STRDUP(value);
+ if (u == NULL)
+ {
+ u = MALLOC (sizeof (struct ECRS_URI));
+ *uri = u;
+ u->type = ksk;
+ u->data.ksk.keywordCount = 0;
+ u->data.ksk.keywords = NULL;
+ }
+ else
+ {
+ GE_ASSERT (NULL, u->type == ksk);
+ }
+ GROW (u->data.ksk.keywords,
+ u->data.ksk.keywordCount, u->data.ksk.keywordCount + 1);
+ u->data.ksk.keywords[u->data.ksk.keywordCount - 1] = STRDUP (value);
return OK;
}
@@ -58,71 +61,64 @@
/**
* @param scls must be of type "struct ECRS_MetaData **"
*/
-int gnunet_getopt_configure_set_metadata(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value) {
- struct ECRS_MetaData ** mm = scls;
+int
+gnunet_getopt_configure_set_metadata (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option, const char *value)
+{
+ struct ECRS_MetaData **mm = scls;
EXTRACTOR_KeywordType type;
- const char * typename;
- const char * typename_i18n;
- struct ECRS_MetaData * meta;
- char * tmp;
+ const char *typename;
+ const char *typename_i18n;
+ struct ECRS_MetaData *meta;
+ char *tmp;
meta = *mm;
- if (meta == NULL) {
- meta = ECRS_createMetaData();
- *mm = meta;
- }
+ if (meta == NULL)
+ {
+ meta = ECRS_createMetaData ();
+ *mm = meta;
+ }
- tmp = string_convertToUtf8(NULL,
- value,
- strlen(value),
+ tmp = string_convertToUtf8 (NULL, value, strlen (value),
#if ENABLE_NLS
- nl_langinfo(CODESET)
+ nl_langinfo (CODESET)
#else
- "utf-8"
+ "utf-8"
#endif
- );
- type = EXTRACTOR_getHighestKeywordTypeNumber();
- while (type > 0) {
- type--;
- typename = EXTRACTOR_getKeywordTypeAsString(type);
- typename_i18n = dgettext("libextractor", typename);
- if ( (strlen(tmp) >= strlen(typename)+1) &&
- (tmp[strlen(typename)] == ':') &&
- (0 == strncmp(typename,
- tmp,
- strlen(typename))) ) {
- ECRS_addToMetaData(meta,
- type,
- &tmp[strlen(typename)+1]);
- FREE(tmp);
- tmp = NULL;
- break;
+ );
+ type = EXTRACTOR_getHighestKeywordTypeNumber ();
+ while (type > 0)
+ {
+ type--;
+ typename = EXTRACTOR_getKeywordTypeAsString (type);
+ typename_i18n = dgettext ("libextractor", typename);
+ if ((strlen (tmp) >= strlen (typename) + 1) &&
+ (tmp[strlen (typename)] == ':') &&
+ (0 == strncmp (typename, tmp, strlen (typename))))
+ {
+ ECRS_addToMetaData (meta, type, &tmp[strlen (typename) + 1]);
+ FREE (tmp);
+ tmp = NULL;
+ break;
+ }
+ if ((strlen (tmp) >= strlen (typename_i18n) + 1) &&
+ (tmp[strlen (typename_i18n)] == ':') &&
+ (0 == strncmp (typename_i18n, tmp, strlen (typename_i18n))))
+ {
+ ECRS_addToMetaData (meta, type, &tmp[strlen (typename_i18n) + 1]);
+ FREE (tmp);
+ tmp = NULL;
+ break;
+ }
}
- if ( (strlen(tmp) >= strlen(typename_i18n)+1) &&
- (tmp[strlen(typename_i18n)] == ':') &&
- (0 == strncmp(typename_i18n,
- tmp,
- strlen(typename_i18n))) ) {
- ECRS_addToMetaData(meta,
- type,
- &tmp[strlen(typename_i18n)+1]);
- FREE(tmp);
- tmp = NULL;
- break;
+ if (tmp != NULL)
+ {
+ ECRS_addToMetaData (meta, EXTRACTOR_UNKNOWN, tmp);
+ FREE (tmp);
+ printf (_
+ ("Unknown metadata type in metadata option `%s'. Using metadata
type `unknown' instead.\n"),
+ value);
}
- }
- if (tmp != NULL) {
- ECRS_addToMetaData(meta,
- EXTRACTOR_UNKNOWN,
- tmp);
- FREE(tmp);
- printf(_("Unknown metadata type in metadata option `%s'. Using metadata
type `unknown' instead.\n"),
- value);
- }
return OK;
}
-
-
Modified: GNUnet/src/applications/fs/ecrs/search.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/search.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/search.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -33,17 +33,18 @@
#define DEBUG_SEARCH NO
-typedef struct {
+typedef struct
+{
/**
* The handle for the query.
*/
- struct FS_SEARCH_HANDLE * handle;
+ struct FS_SEARCH_HANDLE *handle;
/**
* The keys (for the search).
*/
- HashCode512 * keys;
+ HashCode512 *keys;
/**
* When does this query time-out (we may want
@@ -82,7 +83,8 @@
/**
* Context of the sendQueries cron-job.
*/
-typedef struct {
+typedef struct
+{
/**
* Time when the cron-job was first started.
*/
@@ -96,22 +98,22 @@
/**
* Search context
*/
- struct FS_SEARCH_CONTEXT * sctx;
+ struct FS_SEARCH_CONTEXT *sctx;
/**
* queryCount pending searches.
*/
- PendingSearch ** queries;
+ PendingSearch **queries;
ECRS_SearchProgressCallback spcb;
- void * spcbClosure;
+ void *spcbClosure;
- struct MUTEX * lock;
+ struct MUTEX *lock;
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
int aborted;
@@ -125,111 +127,97 @@
/**
* Add a query to the SQC.
*/
-static void addPS(unsigned int type,
- unsigned int keyCount,
- const HashCode512 * keys,
- const HashCode512 * dkey,
- SendQueriesContext * sqc) {
- PendingSearch * ps;
+static void
+addPS (unsigned int type,
+ unsigned int keyCount,
+ const HashCode512 * keys,
+ const HashCode512 * dkey, SendQueriesContext * sqc)
+{
+ PendingSearch *ps;
- ps = MALLOC(sizeof(PendingSearch));
+ ps = MALLOC (sizeof (PendingSearch));
ps->timeout = 0;
ps->lastTransmission = 0;
- ps->priority = 5 + weak_randomi(20);
+ ps->priority = 5 + weak_randomi (20);
ps->type = type;
ps->keyCount = keyCount;
- ps->keys = MALLOC(sizeof(HashCode512) * keyCount);
- memcpy(ps->keys,
- keys,
- sizeof(HashCode512) * keyCount);
+ ps->keys = MALLOC (sizeof (HashCode512) * keyCount);
+ memcpy (ps->keys, keys, sizeof (HashCode512) * keyCount);
ps->decryptKey = *dkey;
ps->handle = NULL;
- MUTEX_LOCK(sqc->lock);
- GROW(sqc->queries,
- sqc->queryCount,
- sqc->queryCount+1);
- sqc->queries[sqc->queryCount-1] = ps;
- MUTEX_UNLOCK(sqc->lock);
+ MUTEX_LOCK (sqc->lock);
+ GROW (sqc->queries, sqc->queryCount, sqc->queryCount + 1);
+ sqc->queries[sqc->queryCount - 1] = ps;
+ MUTEX_UNLOCK (sqc->lock);
}
/**
* Add the query that corresponds to the given URI
* to the SQC.
*/
-static void addQueryForURI(const struct ECRS_URI * uri,
- SendQueriesContext * sqc) {
- struct GE_Context * ectx = sqc->ectx;
+static void
+addQueryForURI (const struct ECRS_URI *uri, SendQueriesContext * sqc)
+{
+ struct GE_Context *ectx = sqc->ectx;
- switch (uri->type) {
- case chk:
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("CHK URI not allowed for search.\n"));
- break;
- case sks: {
- HashCode512 keys[2];
- HashCode512 hk; /* hk = hash(identifier) */
+ switch (uri->type)
+ {
+ case chk:
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("CHK URI not allowed for search.\n"));
+ break;
+ case sks:
+ {
+ HashCode512 keys[2];
+ HashCode512 hk; /* hk = hash(identifier) */
- hash(&uri->data.sks.identifier,
- sizeof(HashCode512),
- &hk);
- xorHashCodes(&hk,
- &uri->data.sks.namespace,
- &keys[0]); /* compute routing key r = H(identifier) ^ namespace */
- keys[1] = uri->data.sks.namespace;
- addPS(S_BLOCK,
- 2,
- &keys[0],
- &uri->data.sks.identifier, /* identifier = decryption key */
- sqc);
- break;
- }
- case ksk: {
- HashCode512 hc;
- HashCode512 query;
- struct PrivateKey * pk;
- PublicKey pub;
- int i;
+ hash (&uri->data.sks.identifier, sizeof (HashCode512), &hk);
+ xorHashCodes (&hk, &uri->data.sks.namespace, &keys[0]); /* compute
routing key r = H(identifier) ^ namespace */
+ keys[1] = uri->data.sks.namespace;
+ addPS (S_BLOCK, 2, &keys[0], &uri->data.sks.identifier, /* identifier
= decryption key */
+ sqc);
+ break;
+ }
+ case ksk:
+ {
+ HashCode512 hc;
+ HashCode512 query;
+ struct PrivateKey *pk;
+ PublicKey pub;
+ int i;
#if DEBUG_SEARCH
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Computing queries (this may take a while).\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Computing queries (this may take a while).\n");
#endif
- for (i=0;i<uri->data.ksk.keywordCount;i++) {
- hash(uri->data.ksk.keywords[i],
- strlen(uri->data.ksk.keywords[i]),
- &hc);
- pk = makeKblockKey(&hc);
- getPublicKey(pk,
- &pub);
- hash(&pub,
- sizeof(PublicKey),
- &query);
- addPS(ANY_BLOCK, /* K_BLOCK, N_BLOCK or KN_BLOCK ok */
- 1,
- &query,
- &hc,
- sqc);
- freePrivateKey(pk);
- }
+ for (i = 0; i < uri->data.ksk.keywordCount; i++)
+ {
+ hash (uri->data.ksk.keywords[i],
+ strlen (uri->data.ksk.keywords[i]), &hc);
+ pk = makeKblockKey (&hc);
+ getPublicKey (pk, &pub);
+ hash (&pub, sizeof (PublicKey), &query);
+ addPS (ANY_BLOCK, /* K_BLOCK, N_BLOCK or KN_BLOCK ok */
+ 1, &query, &hc, sqc);
+ freePrivateKey (pk);
+ }
#if DEBUG_SEARCH
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Queries ready.\n");
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, "Queries ready.\n");
#endif
- break;
- }
- case loc:
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("LOC URI not allowed for search.\n"));
- break;
- default:
- GE_BREAK(ectx, 0);
- /* unknown URI type */
- break;
- }
+ break;
+ }
+ case loc:
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("LOC URI not allowed for search.\n"));
+ break;
+ default:
+ GE_BREAK (ectx, 0);
+ /* unknown URI type */
+ break;
+ }
}
/**
@@ -242,43 +230,39 @@
* @param now the time for which the ID should be computed
* @param c the resulting current ID (set)
*/
-static int computeIdAtTime(const SBlock * sb,
- TIME_T now,
- HashCode512 * c) {
+static int
+computeIdAtTime (const SBlock * sb, TIME_T now, HashCode512 * c)
+{
TIME_T pos;
HashCode512 tmp;
unsigned int iter;
- if (ntohl(sb->updateInterval) == SBLOCK_UPDATE_SPORADIC) {
- memcpy(c,
- &sb->nextIdentifier,
- sizeof(HashCode512));
- return OK;
- }
- if (ntohl(sb->updateInterval) == SBLOCK_UPDATE_NONE) {
- /* H(N-I)^S is the current routing key, so N-I = k */
- deltaId(&sb->identifierIncrement,
- &sb->nextIdentifier,
- c);
- return OK;
- }
- GE_ASSERT(NULL, ntohl(sb->updateInterval) != 0);
- pos = ntohl(sb->creationTime);
- deltaId(&sb->identifierIncrement,
- &sb->nextIdentifier,
- c);
+ if (ntohl (sb->updateInterval) == SBLOCK_UPDATE_SPORADIC)
+ {
+ memcpy (c, &sb->nextIdentifier, sizeof (HashCode512));
+ return OK;
+ }
+ if (ntohl (sb->updateInterval) == SBLOCK_UPDATE_NONE)
+ {
+ /* H(N-I)^S is the current routing key, so N-I = k */
+ deltaId (&sb->identifierIncrement, &sb->nextIdentifier, c);
+ return OK;
+ }
+ GE_ASSERT (NULL, ntohl (sb->updateInterval) != 0);
+ pos = ntohl (sb->creationTime);
+ deltaId (&sb->identifierIncrement, &sb->nextIdentifier, c);
- iter = (now - (pos + ntohl(sb->updateInterval))) / ntohl(sb->updateInterval);
+ iter =
+ (now - (pos + ntohl (sb->updateInterval))) / ntohl (sb->updateInterval);
if (iter > 0xFFFF)
/* too many iterators, signal error! */
return SYSERR;
- while (pos + ntohl(sb->updateInterval) < now) {
- pos += ntohl(sb->updateInterval);
- addHashCodes(c,
- &sb->identifierIncrement,
- &tmp);
- *c = tmp;
- }
+ while (pos + ntohl (sb->updateInterval) < now)
+ {
+ pos += ntohl (sb->updateInterval);
+ addHashCodes (c, &sb->identifierIncrement, &tmp);
+ *c = tmp;
+ }
return OK;
}
@@ -287,33 +271,37 @@
* the SQC with the root-URI for the namespace, together with the
* namespace advertisement.
*/
-static int processNBlock(const NBlock * nb,
- const HashCode512 * key,
- unsigned int size,
- SendQueriesContext * sqc) {
- struct GE_Context * ectx = sqc->ectx;
+static int
+processNBlock (const NBlock * nb,
+ const HashCode512 * key,
+ unsigned int size, SendQueriesContext * sqc)
+{
+ struct GE_Context *ectx = sqc->ectx;
ECRS_FileInfo fi;
struct ECRS_URI uri;
int ret;
- fi.meta = ECRS_deserializeMetaData(ectx,
- (const char*)&nb[1],
- size - sizeof(NBlock));
- if (fi.meta == NULL) {
- GE_BREAK(ectx, 0); /* nblock malformed */
- return SYSERR;
- }
+ fi.meta = ECRS_deserializeMetaData (ectx,
+ (const char *) &nb[1],
+ size - sizeof (NBlock));
+ if (fi.meta == NULL)
+ {
+ GE_BREAK (ectx, 0); /* nblock malformed */
+ return SYSERR;
+ }
fi.uri = &uri;
uri.type = sks;
uri.data.sks.namespace = nb->namespace;
uri.data.sks.identifier = nb->rootEntry;
- if (sqc->spcb != NULL) {
- ret = sqc->spcb(&fi, key, YES, sqc->spcbClosure);
- if (ret == SYSERR)
- sqc->aborted = YES;
- } else
+ if (sqc->spcb != NULL)
+ {
+ ret = sqc->spcb (&fi, key, YES, sqc->spcbClosure);
+ if (ret == SYSERR)
+ sqc->aborted = YES;
+ }
+ else
ret = OK;
- ECRS_freeMetaData(fi.meta);
+ ECRS_freeMetaData (fi.meta);
return ret;
}
@@ -324,228 +312,229 @@
*
* @return SYSERR if the entry is malformed
*/
-static int receiveReplies(const HashCode512 * key,
- const Datastore_Value * value,
- SendQueriesContext * sqc) {
- struct GE_Context * ectx = sqc->ectx;
+static int
+receiveReplies (const HashCode512 * key,
+ const Datastore_Value * value, SendQueriesContext * sqc)
+{
+ struct GE_Context *ectx = sqc->ectx;
unsigned int type;
ECRS_FileInfo fi;
int i;
unsigned int size;
- PendingSearch * ps;
+ PendingSearch *ps;
int ret;
HashCode512 query;
- type = ntohl(value->type);
- size = ntohl(value->size) - sizeof(Datastore_Value);
+ type = ntohl (value->type);
+ size = ntohl (value->size) - sizeof (Datastore_Value);
#if DEBUG_SEARCH
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Search received reply of type %u and size %u.\n",
- type, size);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Search received reply of type %u and size %u.\n", type, size);
#endif
- if (OK != getQueryFor(size,
- (const DBlock*) &value[1],
- YES,
- &query))
+ if (OK != getQueryFor (size, (const DBlock *) &value[1], YES, &query))
return SYSERR;
- for (i=0;i<sqc->queryCount;i++) {
- ps = sqc->queries[i];
- if ( equalsHashCode512(&query,
- &ps->keys[0]) &&
- ( (ps->type == type) ||
- (ps->type == ANY_BLOCK) ) &&
- (YES == isDatumApplicable(type,
- size,
- (const DBlock*) &value[1],
- &query,
- ps->keyCount,
- ps->keys)) ) {
- switch (type) {
- case K_BLOCK: {
- KBlock * kb;
- const char * dstURI;
+ for (i = 0; i < sqc->queryCount; i++)
+ {
+ ps = sqc->queries[i];
+ if (equalsHashCode512 (&query,
+ &ps->keys[0]) &&
+ ((ps->type == type) ||
+ (ps->type == ANY_BLOCK)) &&
+ (YES == isDatumApplicable (type,
+ size,
+ (const DBlock *) &value[1],
+ &query, ps->keyCount, ps->keys)))
+ {
+ switch (type)
+ {
+ case K_BLOCK:
+ {
+ KBlock *kb;
+ const char *dstURI;
#if DEBUG_SEARCH
- EncName enc;
+ EncName enc;
#endif
- int j;
+ int j;
- if (size < sizeof(KBlock))
- return SYSERR;
- kb = MALLOC(size);
- memcpy(kb, &value[1], size);
+ if (size < sizeof (KBlock))
+ return SYSERR;
+ kb = MALLOC (size);
+ memcpy (kb, &value[1], size);
#if DEBUG_SEARCH
- IF_GELOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&ps->decryptKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Decrypting KBlock with key %s.\n",
- &enc);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&ps->decryptKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Decrypting KBlock with key %s.\n", &enc);
#endif
- ECRS_decryptInPlace(&ps->decryptKey,
- &kb[1],
- size - sizeof(KBlock));
- j = sizeof(KBlock);
- while ( (j < size) &&
- (((const char*)kb)[j] != '\0') )
- j++;
- if (j == size) {
- GE_BREAK(ectx, 0); /* kblock malformed */
- FREE(kb);
- return SYSERR;
- }
- dstURI = (const char*) &kb[1];
- j++;
- fi.meta = ECRS_deserializeMetaData(ectx,
- &((const char*)kb)[j],
- size - j);
- if (fi.meta == NULL) {
- GE_BREAK(ectx, 0); /* kblock malformed */
- FREE(kb);
- return SYSERR;
- }
- fi.uri = ECRS_stringToUri(ectx,
- dstURI);
- if (fi.uri == NULL) {
- GE_BREAK(ectx, 0); /* kblock malformed */
- ECRS_freeMetaData(fi.meta);
- FREE(kb);
- return SYSERR;
- }
- if (sqc->spcb != NULL) {
- ret = sqc->spcb(&fi,
- &ps->decryptKey,
- NO,
- sqc->spcbClosure);
- if (ret == SYSERR)
- sqc->aborted = YES;
- } else
- ret = OK;
- ECRS_freeUri(fi.uri);
- ECRS_freeMetaData(fi.meta);
- FREE(kb);
- return ret;
- }
- case N_BLOCK: {
- const NBlock * nb;
+ ECRS_decryptInPlace (&ps->decryptKey,
+ &kb[1], size - sizeof (KBlock));
+ j = sizeof (KBlock);
+ while ((j < size) && (((const char *) kb)[j] != '\0'))
+ j++;
+ if (j == size)
+ {
+ GE_BREAK (ectx, 0); /* kblock malformed */
+ FREE (kb);
+ return SYSERR;
+ }
+ dstURI = (const char *) &kb[1];
+ j++;
+ fi.meta = ECRS_deserializeMetaData (ectx,
+ &((const char *) kb)[j],
+ size - j);
+ if (fi.meta == NULL)
+ {
+ GE_BREAK (ectx, 0); /* kblock malformed */
+ FREE (kb);
+ return SYSERR;
+ }
+ fi.uri = ECRS_stringToUri (ectx, dstURI);
+ if (fi.uri == NULL)
+ {
+ GE_BREAK (ectx, 0); /* kblock malformed */
+ ECRS_freeMetaData (fi.meta);
+ FREE (kb);
+ return SYSERR;
+ }
+ if (sqc->spcb != NULL)
+ {
+ ret = sqc->spcb (&fi,
+ &ps->decryptKey, NO, sqc->spcbClosure);
+ if (ret == SYSERR)
+ sqc->aborted = YES;
+ }
+ else
+ ret = OK;
+ ECRS_freeUri (fi.uri);
+ ECRS_freeMetaData (fi.meta);
+ FREE (kb);
+ return ret;
+ }
+ case N_BLOCK:
+ {
+ const NBlock *nb;
- if (size < sizeof(NBlock))
- return SYSERR;
- nb = (const NBlock*) &value[1];
- return processNBlock(nb,
- NULL,
- size,
- sqc);
- }
- case KN_BLOCK: {
- KNBlock * kb;
- int ret;
+ if (size < sizeof (NBlock))
+ return SYSERR;
+ nb = (const NBlock *) &value[1];
+ return processNBlock (nb, NULL, size, sqc);
+ }
+ case KN_BLOCK:
+ {
+ KNBlock *kb;
+ int ret;
- if (size < sizeof(KNBlock))
- return SYSERR;
- kb = MALLOC(size);
- memcpy(kb, &value[1], size);
- ECRS_decryptInPlace(&ps->decryptKey,
- &kb->nblock,
- size - sizeof(KBlock) - sizeof(unsigned int));
- ret = processNBlock(&kb->nblock,
- &ps->decryptKey,
- size - sizeof(KNBlock) + sizeof(NBlock),
- sqc);
- FREE(kb);
- return ret;
- }
- case S_BLOCK: {
- SBlock * sb;
- const char * dstURI;
- int j;
- TIME_T now;
- HashCode512 updateId;
- URI updateURI;
+ if (size < sizeof (KNBlock))
+ return SYSERR;
+ kb = MALLOC (size);
+ memcpy (kb, &value[1], size);
+ ECRS_decryptInPlace (&ps->decryptKey,
+ &kb->nblock,
+ size - sizeof (KBlock) -
+ sizeof (unsigned int));
+ ret =
+ processNBlock (&kb->nblock, &ps->decryptKey,
+ size - sizeof (KNBlock) + sizeof (NBlock),
+ sqc);
+ FREE (kb);
+ return ret;
+ }
+ case S_BLOCK:
+ {
+ SBlock *sb;
+ const char *dstURI;
+ int j;
+ TIME_T now;
+ HashCode512 updateId;
+ URI updateURI;
- if (size < sizeof(SBlock))
- return SYSERR;
- sb = MALLOC(size);
- memcpy(sb, &value[1], size);
- ECRS_decryptInPlace(&ps->decryptKey,
- &sb->creationTime,
- size
- - sizeof(unsigned int)
- - sizeof(Signature)
- - sizeof(PublicKey)
- - sizeof(HashCode512));
- j = 0;
- dstURI = (const char*) &sb[1];
- while ( (j < size - sizeof(SBlock)) &&
- (dstURI[j] != '\0') )
- j++;
- if (j == size - sizeof(SBlock)) {
- GE_BREAK(ectx, 0); /* sblock malformed */
- FREE(sb);
- return SYSERR;
- }
- j++;
- /* j == strlen(dstURI) + 1 */
- fi.meta = ECRS_deserializeMetaData(ectx,
- &dstURI[j],
- size - j - sizeof(SBlock));
- if (fi.meta == NULL) {
- GE_BREAK(ectx, 0); /* sblock malformed */
- FREE(sb);
- return SYSERR;
- }
- fi.uri = ECRS_stringToUri(ectx,
- dstURI);
- if (fi.uri == NULL) {
- GE_BREAK(ectx, 0); /* sblock malformed */
- ECRS_freeMetaData(fi.meta);
- FREE(sb);
- return SYSERR;
- }
- if (sqc->spcb != NULL) {
- ret = sqc->spcb(&fi, NULL, NO, sqc->spcbClosure);
- if (ret == SYSERR)
- sqc->aborted = YES;
- } else
- ret = OK;
- ECRS_freeUri(fi.uri);
- ECRS_freeMetaData(fi.meta);
+ if (size < sizeof (SBlock))
+ return SYSERR;
+ sb = MALLOC (size);
+ memcpy (sb, &value[1], size);
+ ECRS_decryptInPlace (&ps->decryptKey,
+ &sb->creationTime,
+ size
+ - sizeof (unsigned int)
+ - sizeof (Signature)
+ - sizeof (PublicKey)
+ - sizeof (HashCode512));
+ j = 0;
+ dstURI = (const char *) &sb[1];
+ while ((j < size - sizeof (SBlock)) && (dstURI[j] != '\0'))
+ j++;
+ if (j == size - sizeof (SBlock))
+ {
+ GE_BREAK (ectx, 0); /* sblock malformed */
+ FREE (sb);
+ return SYSERR;
+ }
+ j++;
+ /* j == strlen(dstURI) + 1 */
+ fi.meta = ECRS_deserializeMetaData (ectx,
+ &dstURI[j],
+ size - j -
+ sizeof (SBlock));
+ if (fi.meta == NULL)
+ {
+ GE_BREAK (ectx, 0); /* sblock malformed */
+ FREE (sb);
+ return SYSERR;
+ }
+ fi.uri = ECRS_stringToUri (ectx, dstURI);
+ if (fi.uri == NULL)
+ {
+ GE_BREAK (ectx, 0); /* sblock malformed */
+ ECRS_freeMetaData (fi.meta);
+ FREE (sb);
+ return SYSERR;
+ }
+ if (sqc->spcb != NULL)
+ {
+ ret = sqc->spcb (&fi, NULL, NO, sqc->spcbClosure);
+ if (ret == SYSERR)
+ sqc->aborted = YES;
+ }
+ else
+ ret = OK;
+ ECRS_freeUri (fi.uri);
+ ECRS_freeMetaData (fi.meta);
- /* compute current/NEXT URI (if updateable SBlock) and issue
- respective query automatically! */
- TIME(&now);
- if (OK != computeIdAtTime(sb,
- now,
- &updateId)) {
- FREE(sb);
- return SYSERR;
- }
- if (equalsHashCode512(&updateId,
- &ps->decryptKey)) {
- FREE(sb);
- return ret; /* have latest version */
- }
- if (ps->keyCount != 2) {
- GE_BREAK(ectx, 0);
- FREE(sb);
- return SYSERR;
- }
+ /* compute current/NEXT URI (if updateable SBlock) and issue
+ respective query automatically! */
+ TIME (&now);
+ if (OK != computeIdAtTime (sb, now, &updateId))
+ {
+ FREE (sb);
+ return SYSERR;
+ }
+ if (equalsHashCode512 (&updateId, &ps->decryptKey))
+ {
+ FREE (sb);
+ return ret; /* have latest version */
+ }
+ if (ps->keyCount != 2)
+ {
+ GE_BREAK (ectx, 0);
+ FREE (sb);
+ return SYSERR;
+ }
- updateURI.type = sks;
- updateURI.data.sks.namespace = ps->keys[1];
- updateURI.data.sks.identifier = updateId;
- addQueryForURI(&updateURI,
- sqc);
- FREE(sb);
- return ret;
- }
- default:
- GE_BREAK(ectx, 0);
- break;
- } /* end switch */
- } /* for all matches */
- } /* for all pending queries */
+ updateURI.type = sks;
+ updateURI.data.sks.namespace = ps->keys[1];
+ updateURI.data.sks.identifier = updateId;
+ addQueryForURI (&updateURI, sqc);
+ FREE (sb);
+ return ret;
+ }
+ default:
+ GE_BREAK (ectx, 0);
+ break;
+ } /* end switch */
+ } /* for all matches */
+ } /* for all pending queries */
return OK;
}
@@ -557,25 +546,25 @@
* @param uri specifies the search parameters
* @param uri set to the URI of the uploaded file
*/
-int ECRS_search(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri,
- unsigned int anonymityLevel,
- cron_t timeout,
- ECRS_SearchProgressCallback spcb,
- void * spcbClosure,
- ECRS_TestTerminate tt,
- void * ttClosure) {
+int
+ECRS_search (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const struct ECRS_URI *uri,
+ unsigned int anonymityLevel,
+ cron_t timeout,
+ ECRS_SearchProgressCallback spcb,
+ void *spcbClosure, ECRS_TestTerminate tt, void *ttClosure)
+{
SendQueriesContext ctx;
- PendingSearch * ps;
+ PendingSearch *ps;
int i;
cron_t now;
cron_t remTime;
cron_t new_ttl;
unsigned int new_priority;
- ctx.start = get_time();
- now = get_time();
+ ctx.start = get_time ();
+ now = get_time ();
timeout += now;
ctx.ectx = ectx;
ctx.cfg = cfg;
@@ -585,84 +574,74 @@
ctx.spcb = spcb;
ctx.spcbClosure = spcbClosure;
ctx.aborted = NO;
- ctx.lock = MUTEX_CREATE(YES);
- ctx.sctx = FS_SEARCH_makeContext(ectx,
- cfg,
- ctx.lock);
- addQueryForURI(uri,
- &ctx);
- while ( ( (NULL == tt) ||
- (OK == tt(ttClosure)) ) &&
- (NO == GNUNET_SHUTDOWN_TEST()) &&
- (timeout > now) &&
- (ctx.aborted == NO) ) {
- remTime = timeout - now;
+ ctx.lock = MUTEX_CREATE (YES);
+ ctx.sctx = FS_SEARCH_makeContext (ectx, cfg, ctx.lock);
+ addQueryForURI (uri, &ctx);
+ while (((NULL == tt) ||
+ (OK == tt (ttClosure))) &&
+ (NO == GNUNET_SHUTDOWN_TEST ()) &&
+ (timeout > now) && (ctx.aborted == NO))
+ {
+ remTime = timeout - now;
- MUTEX_LOCK(ctx.lock);
- for (i=0;i<ctx.queryCount;i++) {
- ps = ctx.queries[i];
- if ( (now < ps->timeout) &&
- (ps->timeout != 0) )
- continue;
- if (ps->handle != NULL)
- FS_stop_search(ctx.sctx,
- ps->handle);
- /* increase ttl/priority */
- new_ttl = ps->timeout - ps->lastTransmission;
- if (new_ttl < 4 * 5 * cronSECONDS)
- new_ttl = 4 * 5 * cronSECONDS + weak_randomi(5 * cronSECONDS);
- new_ttl = new_ttl + weak_randomi(5 * cronSECONDS + 2 * new_ttl);
- if (new_ttl > 0xFFFFFF)
- new_ttl = weak_randomi(0xFFFFFF); /* if we get to large, reduce! */
- if (remTime < new_ttl)
- new_ttl = remTime;
- ps->timeout = new_ttl + now;
- new_priority = ps->priority;
- new_priority = new_priority + weak_randomi(4 + 2 * new_priority);
- if (new_priority > 0xFFFFFF)
- new_priority = weak_randomi(0xFFFFFF); /* if we get to large, reduce! */
- ps->priority = new_priority;
- ps->lastTransmission = now;
+ MUTEX_LOCK (ctx.lock);
+ for (i = 0; i < ctx.queryCount; i++)
+ {
+ ps = ctx.queries[i];
+ if ((now < ps->timeout) && (ps->timeout != 0))
+ continue;
+ if (ps->handle != NULL)
+ FS_stop_search (ctx.sctx, ps->handle);
+ /* increase ttl/priority */
+ new_ttl = ps->timeout - ps->lastTransmission;
+ if (new_ttl < 4 * 5 * cronSECONDS)
+ new_ttl = 4 * 5 * cronSECONDS + weak_randomi (5 * cronSECONDS);
+ new_ttl = new_ttl + weak_randomi (5 * cronSECONDS + 2 * new_ttl);
+ if (new_ttl > 0xFFFFFF)
+ new_ttl = weak_randomi (0xFFFFFF); /* if we get to large, reduce!
*/
+ if (remTime < new_ttl)
+ new_ttl = remTime;
+ ps->timeout = new_ttl + now;
+ new_priority = ps->priority;
+ new_priority = new_priority + weak_randomi (4 + 2 * new_priority);
+ if (new_priority > 0xFFFFFF)
+ new_priority = weak_randomi (0xFFFFFF); /* if we get to large,
reduce! */
+ ps->priority = new_priority;
+ ps->lastTransmission = now;
#if DEBUG_SEARCH
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "ECRS initiating FS search with timeout %llus and priority %u.\n",
- (ps->timeout - now) / cronSECONDS,
- ps->priority);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "ECRS initiating FS search with timeout %llus and priority
%u.\n",
+ (ps->timeout - now) / cronSECONDS, ps->priority);
#endif
- ps->handle
- = FS_start_search(ctx.sctx,
- NULL,
- ps->type,
- ps->keyCount,
- ps->keys,
- anonymityLevel,
- ps->priority,
- ps->timeout,
- (Datum_Iterator) &receiveReplies,
- &ctx);
+ ps->handle
+ = FS_start_search (ctx.sctx,
+ NULL,
+ ps->type,
+ ps->keyCount,
+ ps->keys,
+ anonymityLevel,
+ ps->priority,
+ ps->timeout,
+ (Datum_Iterator) & receiveReplies, &ctx);
+ }
+ MUTEX_UNLOCK (ctx.lock);
+ if (((NULL != tt) &&
+ (OK != tt (ttClosure))) || (timeout <= now) || (ctx.aborted != NO))
+ break;
+ PTHREAD_SLEEP (100 * cronMILLIS);
+ now = get_time ();
}
- MUTEX_UNLOCK(ctx.lock);
- if ( ( (NULL != tt) &&
- (OK != tt(ttClosure))) ||
- (timeout <= now) ||
- (ctx.aborted != NO) )
- break;
- PTHREAD_SLEEP(100 * cronMILLIS);
- now = get_time();
- }
- for (i=0;i<ctx.queryCount;i++) {
- if (ctx.queries[i]->handle != NULL)
- FS_stop_search(ctx.sctx,
- ctx.queries[i]->handle);
- FREE(ctx.queries[i]->keys);
- FREE(ctx.queries[i]);
- }
- GROW(ctx.queries,
- ctx.queryCount,
- 0);
- FS_SEARCH_destroyContext(ctx.sctx);
- MUTEX_DESTROY(ctx.lock);
+ for (i = 0; i < ctx.queryCount; i++)
+ {
+ if (ctx.queries[i]->handle != NULL)
+ FS_stop_search (ctx.sctx, ctx.queries[i]->handle);
+ FREE (ctx.queries[i]->keys);
+ FREE (ctx.queries[i]);
+ }
+ GROW (ctx.queries, ctx.queryCount, 0);
+ FS_SEARCH_destroyContext (ctx.sctx);
+ MUTEX_DESTROY (ctx.lock);
return OK;
}
Modified: GNUnet/src/applications/fs/ecrs/searchtest.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/searchtest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/ecrs/searchtest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -33,28 +33,29 @@
#define CHECK(a) if (!(a)) { ok = NO; GE_BREAK(NULL, 0); goto FAILURE; }
-static int testTerminate(void * unused) {
+static int
+testTerminate (void *unused)
+{
return OK;
}
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static int searchCB(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * closure) {
- int * cnt = closure;
+static int
+searchCB (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *closure)
+{
+ int *cnt = closure;
#if 1
- char * st;
+ char *st;
- st = ECRS_uriToString(fi->uri);
- printf("Got result `%s'\n",
- st);
- FREE(st);
+ st = ECRS_uriToString (fi->uri);
+ printf ("Got result `%s'\n", st);
+ FREE (st);
#endif
(*cnt)--;
if (0 == *cnt)
- return SYSERR; /* abort search */
+ return SYSERR; /* abort search */
return OK;
}
@@ -62,115 +63,95 @@
* @param *uri In: keyword URI
* @return OK on success, SYSERR on error
*/
-static int searchFile(const struct ECRS_URI * uri,
- int resultCount) {
- ECRS_search(NULL,
- cfg,
- uri,
- 0,
- 60 * 15 * cronSECONDS,
- &searchCB,
- &resultCount,
- &testTerminate,
- NULL);
+static int
+searchFile (const struct ECRS_URI *uri, int resultCount)
+{
+ ECRS_search (NULL,
+ cfg,
+ uri,
+ 0,
+ 60 * 15 * cronSECONDS,
+ &searchCB, &resultCount, &testTerminate, NULL);
if (resultCount > 0)
return SYSERR;
return OK;
}
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
pid_t daemon;
int ok;
- struct ClientServerConnection * sock;
- struct ECRS_URI * uri;
- struct ECRS_MetaData * meta;
- struct ECRS_URI * key;
- const char * keywords[6];
+ struct ClientServerConnection *sock;
+ struct ECRS_URI *uri;
+ struct ECRS_MetaData *meta;
+ struct ECRS_URI *key;
+ const char *keywords[6];
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
sock = NULL;
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
- CHECK(OK == connection_wait_for_running(NULL,
- cfg,
- 30 * cronSECONDS));
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
+ CHECK (OK == connection_wait_for_running (NULL, cfg, 30 * cronSECONDS));
ok = YES;
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
- sock = client_connection_create(NULL, cfg);
- CHECK(sock != NULL);
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
+ sock = client_connection_create (NULL, cfg);
+ CHECK (sock != NULL);
/* ACTUAL TEST CODE */
/* first, simple insertion => one result */
#if 1
- printf("Testing search for 'XXtest' with one result.\n");
+ printf ("Testing search for 'XXtest' with one result.\n");
#endif
- uri = ECRS_stringToUri(NULL,
-
"gnunet://ecrs/sks/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820/test");
- meta = ECRS_createMetaData();
+ uri = ECRS_stringToUri (NULL,
+
"gnunet://ecrs/sks/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820/test");
+ meta = ECRS_createMetaData ();
keywords[0] = "XXtest";
keywords[1] = NULL;
- key = ECRS_keywordsToUri(keywords);
- CHECK(OK == ECRS_addToKeyspace(NULL,
- cfg,
- key,
- 0,
- 0,
- get_time() + 10 * cronMINUTES, /* expire */
- uri,
- meta));
- CHECK(OK == searchFile(key,
- 1));
- ECRS_freeUri(key);
- ECRS_freeUri(uri);
+ key = ECRS_keywordsToUri (keywords);
+ CHECK (OK == ECRS_addToKeyspace (NULL, cfg, key, 0, 0, get_time () + 10 *
cronMINUTES, /* expire */
+ uri, meta));
+ CHECK (OK == searchFile (key, 1));
+ ECRS_freeUri (key);
+ ECRS_freeUri (uri);
/* inserting another URI under the 'XXtest' keyword and under 'binary'
should give both URIs since ECRS knows nothing about 'AND'ing: */
#if 1
- printf("Testing search for 'XXtest AND binary' with two results.\n");
+ printf ("Testing search for 'XXtest AND binary' with two results.\n");
#endif
- uri = ECRS_stringToUri(NULL,
-
"gnunet://ecrs/sks/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820/test-different");
+ uri = ECRS_stringToUri (NULL,
+
"gnunet://ecrs/sks/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820/test-different");
keywords[1] = "binary";
keywords[2] = NULL;
- key = ECRS_keywordsToUri(keywords);
- CHECK(OK == ECRS_addToKeyspace(NULL,
- cfg,
- key,
- 0,
- 0,
- get_time() + 10 * cronMINUTES, /* expire */
- uri,
- meta));
- CHECK(OK == searchFile(key,
- 2));
- ECRS_freeUri(key);
- ECRS_freeUri(uri);
- ECRS_freeMetaData(meta);
+ key = ECRS_keywordsToUri (keywords);
+ CHECK (OK == ECRS_addToKeyspace (NULL, cfg, key, 0, 0, get_time () + 10 *
cronMINUTES, /* expire */
+ uri, meta));
+ CHECK (OK == searchFile (key, 2));
+ ECRS_freeUri (key);
+ ECRS_freeUri (uri);
+ ECRS_freeMetaData (meta);
/* now searching just for 'XXtest' should again give 2 results! */
#if 0
- printf("Testing search for 'XXtest' with two results.\n");
+ printf ("Testing search for 'XXtest' with two results.\n");
#endif
keywords[1] = NULL;
- key = ECRS_keywordsToUri(keywords);
- CHECK(OK == searchFile(key,
- 2));
- ECRS_freeUri(key);
+ key = ECRS_keywordsToUri (keywords);
+ CHECK (OK == searchFile (key, 2));
+ ECRS_freeUri (key);
/* END OF TEST CODE */
- FAILURE:
+FAILURE:
if (sock != NULL)
- connection_destroy(sock);
- GE_ASSERT(NULL, OK == os_daemon_stop(NULL, daemon));
+ connection_destroy (sock);
+ GE_ASSERT (NULL, OK == os_daemon_stop (NULL, daemon));
return (ok == YES) ? 0 : 1;
}
Modified: GNUnet/src/applications/fs/ecrs/tree.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/tree.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/tree.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -27,22 +27,25 @@
* @param flen file length for which to compute the depth
* @return depth of the tree
*/
-unsigned int computeDepth(unsigned long long flen) {
+unsigned int
+computeDepth (unsigned long long flen)
+{
unsigned int treeDepth;
unsigned long long fl;
- GE_ASSERT(NULL, DBLOCK_SIZE < MAX_BUFFER_SIZE);
- GE_ASSERT(NULL, IBLOCK_SIZE < MAX_BUFFER_SIZE);
+ GE_ASSERT (NULL, DBLOCK_SIZE < MAX_BUFFER_SIZE);
+ GE_ASSERT (NULL, IBLOCK_SIZE < MAX_BUFFER_SIZE);
treeDepth = 0;
fl = DBLOCK_SIZE;
- while (fl < flen) {
- treeDepth++;
- if (fl * CHK_PER_INODE < fl) {
- /* integer overflow, this is a HUGE file... */
- return treeDepth;
+ while (fl < flen)
+ {
+ treeDepth++;
+ if (fl * CHK_PER_INODE < fl)
+ {
+ /* integer overflow, this is a HUGE file... */
+ return treeDepth;
+ }
+ fl = fl * CHK_PER_INODE;
}
- fl = fl * CHK_PER_INODE;
- }
return treeDepth;
}
-
Modified: GNUnet/src/applications/fs/ecrs/tree.h
===================================================================
--- GNUnet/src/applications/fs/ecrs/tree.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/tree.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -50,6 +50,6 @@
* @param flen file length for which to compute the depth
* @return depth of the tree
*/
-unsigned int computeDepth(unsigned long long flen);
+unsigned int computeDepth (unsigned long long flen);
#endif
Modified: GNUnet/src/applications/fs/ecrs/unindex.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/unindex.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/unindex.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -52,58 +52,46 @@
* to avoid code duplication (move to block.c, pass
* FS_delete as argument!).
*/
-static int pushBlock(struct ClientServerConnection * sock,
- const CHK * chk,
- unsigned int level,
- Datastore_Value ** iblocks) {
+static int
+pushBlock (struct ClientServerConnection *sock,
+ const CHK * chk, unsigned int level, Datastore_Value ** iblocks)
+{
unsigned int size;
unsigned int present;
- Datastore_Value * value;
- DBlock * db;
+ Datastore_Value *value;
+ DBlock *db;
CHK ichk;
- size = ntohl(iblocks[level]->size) - sizeof(Datastore_Value);
- present = (size - sizeof(DBlock)) / sizeof(CHK);
- db = (DBlock*) &iblocks[level][1];
- if (present == CHK_PER_INODE) {
- fileBlockGetKey(db,
- size,
- &ichk.key);
- fileBlockGetQuery(db,
- size,
- &ichk.query);
- if (OK != pushBlock(sock,
- &ichk,
- level+1,
- iblocks)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- fileBlockEncode(db,
- size,
- &ichk.query,
- &value);
+ size = ntohl (iblocks[level]->size) - sizeof (Datastore_Value);
+ present = (size - sizeof (DBlock)) / sizeof (CHK);
+ db = (DBlock *) & iblocks[level][1];
+ if (present == CHK_PER_INODE)
+ {
+ fileBlockGetKey (db, size, &ichk.key);
+ fileBlockGetQuery (db, size, &ichk.query);
+ if (OK != pushBlock (sock, &ichk, level + 1, iblocks))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ fileBlockEncode (db, size, &ichk.query, &value);
#if STRICT_CHECKS
- if (SYSERR == FS_delete(sock,
- value)) {
- FREE(value);
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
+ if (SYSERR == FS_delete (sock, value))
+ {
+ FREE (value);
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
#else
- FS_delete(sock,
- value);
+ FS_delete (sock, value);
#endif
- FREE(value);
- size = sizeof(DBlock);
- }
+ FREE (value);
+ size = sizeof (DBlock);
+ }
/* append CHK */
- memcpy(&((char*)db)[size],
- chk,
- sizeof(CHK));
- iblocks[level]->size = htonl(size +
- sizeof(CHK) +
- sizeof(Datastore_Value));
+ memcpy (&((char *) db)[size], chk, sizeof (CHK));
+ iblocks[level]->size = htonl (size +
+ sizeof (CHK) + sizeof (Datastore_Value));
return OK;
}
@@ -114,58 +102,52 @@
* a) check if we have a symlink
* b) delete symbolic link
*/
-static int undoSymlinking(struct GE_Context * ectx,
- const char * fn,
- const HashCode512 * fileId,
- struct ClientServerConnection * sock) {
+static int
+undoSymlinking (struct GE_Context *ectx,
+ const char *fn,
+ const HashCode512 * fileId,
+ struct ClientServerConnection *sock)
+{
EncName enc;
- char * serverDir;
- char * serverFN;
+ char *serverDir;
+ char *serverFN;
struct stat buf;
#ifndef S_ISLNK
if (1)
- return OK; /* symlinks do not exist? */
+ return OK; /* symlinks do not exist? */
#endif
- if (0 != LSTAT(fn,
- &buf)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_BULK | GE_USER | GE_ADMIN,
- "stat",
- fn);
- return SYSERR;
- }
+ if (0 != LSTAT (fn, &buf))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_BULK | GE_USER | GE_ADMIN,
+ "stat", fn);
+ return SYSERR;
+ }
#ifdef S_ISLNK
- if (! S_ISLNK(buf.st_mode))
+ if (!S_ISLNK (buf.st_mode))
return OK;
#endif
- serverDir
- = getConfigurationOptionValue(sock,
- "FS",
- "INDEX-DIRECTORY");
+ serverDir = getConfigurationOptionValue (sock, "FS", "INDEX-DIRECTORY");
if (serverDir == NULL)
return OK;
- serverFN = MALLOC(strlen(serverDir) + 2 + sizeof(EncName));
- strcpy(serverFN,
- serverDir);
- FREE(serverDir);
- if (serverFN[strlen(serverFN)-1] != DIR_SEPARATOR)
- strcat(serverFN,
- DIR_SEPARATOR_STR);
- hash2enc(fileId,
- &enc);
- strcat(serverFN,
- (char*)&enc);
+ serverFN = MALLOC (strlen (serverDir) + 2 + sizeof (EncName));
+ strcpy (serverFN, serverDir);
+ FREE (serverDir);
+ if (serverFN[strlen (serverFN) - 1] != DIR_SEPARATOR)
+ strcat (serverFN, DIR_SEPARATOR_STR);
+ hash2enc (fileId, &enc);
+ strcat (serverFN, (char *) &enc);
- if (0 != UNLINK(serverFN)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_BULK | GE_USER | GE_ADMIN,
- "unlink",
- serverFN);
- FREE(serverFN);
- return SYSERR;
- }
- FREE(serverFN);
+ if (0 != UNLINK (serverFN))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_BULK | GE_USER | GE_ADMIN,
+ "unlink", serverFN);
+ FREE (serverFN);
+ return SYSERR;
+ }
+ FREE (serverFN);
return OK;
}
@@ -176,24 +158,24 @@
*
* @return SYSERR if the unindexing failed (i.e. not indexed)
*/
-int ECRS_unindexFile(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * filename,
- ECRS_UploadProgressCallback upcb,
- void * upcbClosure,
- ECRS_TestTerminate tt,
- void * ttClosure) {
+int
+ECRS_unindexFile (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *filename,
+ ECRS_UploadProgressCallback upcb,
+ void *upcbClosure, ECRS_TestTerminate tt, void *ttClosure)
+{
unsigned long long filesize;
unsigned long long pos;
unsigned int treedepth;
int fd;
int i;
unsigned int size;
- Datastore_Value ** iblocks;
- Datastore_Value * dblock;
- DBlock * db;
- Datastore_Value * value;
- struct ClientServerConnection * sock;
+ Datastore_Value **iblocks;
+ Datastore_Value *dblock;
+ DBlock *db;
+ Datastore_Value *value;
+ struct ClientServerConnection *sock;
HashCode512 fileId;
CHK chk;
cron_t eta;
@@ -201,31 +183,27 @@
cron_t now;
int wasIndexed;
- start = get_time();
- if (YES != disk_file_test(ectx,
- filename)) {
- GE_BREAK(ectx, 0);
+ start = get_time ();
+ if (YES != disk_file_test (ectx, filename))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ if (OK != disk_file_size (ectx, filename, &filesize, YES))
return SYSERR;
- }
- if (OK != disk_file_size(ectx,
- filename,
- &filesize,
- YES))
- return SYSERR;
- sock = client_connection_create(ectx, cfg);
+ sock = client_connection_create (ectx, cfg);
if (sock == NULL)
return SYSERR;
eta = 0;
if (upcb != NULL)
- upcb(filesize, 0, eta, upcbClosure);
- if (SYSERR == getFileHash(ectx,
- filename,
- &fileId)) {
- connection_destroy(sock);
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- now = get_time();
+ upcb (filesize, 0, eta, upcbClosure);
+ if (SYSERR == getFileHash (ectx, filename, &fileId))
+ {
+ connection_destroy (sock);
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ now = get_time ();
eta = now + 2 * (now - start);
/* very rough estimate: hash reads once through the file,
we'll do that once more and write it. But of course
@@ -234,175 +212,158 @@
start = now;
/* reset the counter since the formula later does not
take the time for getFileHash into account */
- treedepth = computeDepth(filesize);
+ treedepth = computeDepth (filesize);
/* Test if file is indexed! */
- wasIndexed
- = FS_testIndexed(sock,
- &fileId);
+ wasIndexed = FS_testIndexed (sock, &fileId);
- fd = disk_file_open(ectx,
- filename,
- O_RDONLY | O_LARGEFILE);
+ fd = disk_file_open (ectx, filename, O_RDONLY | O_LARGEFILE);
if (fd == -1)
return SYSERR;
- dblock = MALLOC(sizeof(Datastore_Value) + DBLOCK_SIZE + sizeof(DBlock));
- dblock->size = htonl(sizeof(Datastore_Value) + DBLOCK_SIZE + sizeof(DBlock));
- dblock->anonymityLevel = htonl(0);
- dblock->prio = htonl(0);
- dblock->type = htonl(D_BLOCK);
- dblock->expirationTime = htonll(0);
- db = (DBlock*) &dblock[1];
- db->type = htonl(D_BLOCK);
- iblocks = MALLOC(sizeof(Datastore_Value*) * (treedepth+1));
- for (i=0;i<=treedepth;i++) {
- iblocks[i] = MALLOC(sizeof(Datastore_Value) + IBLOCK_SIZE +
sizeof(DBlock));
- iblocks[i]->size = htonl(sizeof(Datastore_Value) + sizeof(DBlock));
- iblocks[i]->anonymityLevel = htonl(0);
- iblocks[i]->prio = htonl(0);
- iblocks[i]->type = htonl(D_BLOCK);
- iblocks[i]->expirationTime = htonll(0);
- ((DBlock*) &iblocks[i][1])->type = htonl(D_BLOCK);
- }
+ dblock = MALLOC (sizeof (Datastore_Value) + DBLOCK_SIZE + sizeof (DBlock));
+ dblock->size =
+ htonl (sizeof (Datastore_Value) + DBLOCK_SIZE + sizeof (DBlock));
+ dblock->anonymityLevel = htonl (0);
+ dblock->prio = htonl (0);
+ dblock->type = htonl (D_BLOCK);
+ dblock->expirationTime = htonll (0);
+ db = (DBlock *) & dblock[1];
+ db->type = htonl (D_BLOCK);
+ iblocks = MALLOC (sizeof (Datastore_Value *) * (treedepth + 1));
+ for (i = 0; i <= treedepth; i++)
+ {
+ iblocks[i] =
+ MALLOC (sizeof (Datastore_Value) + IBLOCK_SIZE + sizeof (DBlock));
+ iblocks[i]->size = htonl (sizeof (Datastore_Value) + sizeof (DBlock));
+ iblocks[i]->anonymityLevel = htonl (0);
+ iblocks[i]->prio = htonl (0);
+ iblocks[i]->type = htonl (D_BLOCK);
+ iblocks[i]->expirationTime = htonll (0);
+ ((DBlock *) & iblocks[i][1])->type = htonl (D_BLOCK);
+ }
pos = 0;
- while (pos < filesize) {
- if (upcb != NULL)
- upcb(filesize, pos, eta, upcbClosure);
- if (tt != NULL)
- if (OK != tt(ttClosure))
- goto FAILURE;
- size = DBLOCK_SIZE;
- if (size > filesize - pos) {
- size = filesize - pos;
- memset(&db[1],
- 0,
- DBLOCK_SIZE);
- }
- dblock->size = htonl(sizeof(Datastore_Value) + size + sizeof(DBlock));
- if (size != READ(fd,
- &db[1],
- size)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "READ",
- filename);
- goto FAILURE;
- }
- if (tt != NULL)
- if (OK != tt(ttClosure))
- goto FAILURE;
- fileBlockGetKey(db,
- size + sizeof(DBlock),
- &chk.key);
- fileBlockGetQuery(db,
- size + sizeof(DBlock),
- &chk.query);
- if (OK != pushBlock(sock,
- &chk,
- 0, /* dblocks are on level 0 */
- iblocks)) {
- GE_BREAK(ectx, 0);
- goto FAILURE;
- }
- if (! wasIndexed) {
- if (OK ==
- fileBlockEncode(db,
- size,
- &chk.query,
- &value)) {
- *value = *dblock; /* copy options! */
+ while (pos < filesize)
+ {
+ if (upcb != NULL)
+ upcb (filesize, pos, eta, upcbClosure);
+ if (tt != NULL)
+ if (OK != tt (ttClosure))
+ goto FAILURE;
+ size = DBLOCK_SIZE;
+ if (size > filesize - pos)
+ {
+ size = filesize - pos;
+ memset (&db[1], 0, DBLOCK_SIZE);
+ }
+ dblock->size =
+ htonl (sizeof (Datastore_Value) + size + sizeof (DBlock));
+ if (size != READ (fd, &db[1], size))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "READ", filename);
+ goto FAILURE;
+ }
+ if (tt != NULL)
+ if (OK != tt (ttClosure))
+ goto FAILURE;
+ fileBlockGetKey (db, size + sizeof (DBlock), &chk.key);
+ fileBlockGetQuery (db, size + sizeof (DBlock), &chk.query);
+ if (OK != pushBlock (sock, &chk, 0, /* dblocks are on level 0 */
+ iblocks))
+ {
+ GE_BREAK (ectx, 0);
+ goto FAILURE;
+ }
+ if (!wasIndexed)
+ {
+ if (OK == fileBlockEncode (db, size, &chk.query, &value))
+ {
+ *value = *dblock; /* copy options! */
#if STRICT_CHECKS
- if (OK != FS_delete(sock,
- value)) {
- FREE(value);
- GE_BREAK(ectx, 0);
- goto FAILURE;
- }
+ if (OK != FS_delete (sock, value))
+ {
+ FREE (value);
+ GE_BREAK (ectx, 0);
+ goto FAILURE;
+ }
#else
- FS_delete(sock,
- value);
+ FS_delete (sock, value);
#endif
- FREE(value);
- } else {
- goto FAILURE;
- }
+ FREE (value);
+ }
+ else
+ {
+ goto FAILURE;
+ }
+ }
+ pos += size;
+ now = get_time ();
+ eta = (cron_t) (start +
+ (((double) (now - start) / (double) pos))
+ * (double) filesize);
}
- pos += size;
- now = get_time();
- eta = (cron_t) (start +
- (((double)(now - start)/(double)pos))
- * (double)filesize);
- }
if (tt != NULL)
- if (OK != tt(ttClosure))
+ if (OK != tt (ttClosure))
goto FAILURE;
- for (i=0;i<treedepth;i++) {
- size = ntohl(iblocks[i]->size) - sizeof(Datastore_Value);
- db = (DBlock*) &iblocks[i][1];
- fileBlockGetKey(db,
- size,
- &chk.key);
- fileBlockGetQuery(db,
- size,
- &chk.query);
- if (OK != pushBlock(sock,
- &chk,
- i+1,
- iblocks)) {
- GE_BREAK(ectx, 0);
- goto FAILURE;
- }
- fileBlockEncode(db,
- size,
- &chk.query,
- &value);
+ for (i = 0; i < treedepth; i++)
+ {
+ size = ntohl (iblocks[i]->size) - sizeof (Datastore_Value);
+ db = (DBlock *) & iblocks[i][1];
+ fileBlockGetKey (db, size, &chk.key);
+ fileBlockGetQuery (db, size, &chk.query);
+ if (OK != pushBlock (sock, &chk, i + 1, iblocks))
+ {
+ GE_BREAK (ectx, 0);
+ goto FAILURE;
+ }
+ fileBlockEncode (db, size, &chk.query, &value);
#if STRICT_CHECKS
- if (OK != FS_delete(sock,
- value)) {
- FREE(value);
- GE_BREAK(ectx, 0);
- goto FAILURE;
- }
+ if (OK != FS_delete (sock, value))
+ {
+ FREE (value);
+ GE_BREAK (ectx, 0);
+ goto FAILURE;
+ }
#else
- FS_delete(sock,
- value);
+ FS_delete (sock, value);
#endif
- FREE(value);
- FREE(iblocks[i]);
- iblocks[i] = NULL;
- }
+ FREE (value);
+ FREE (iblocks[i]);
+ iblocks[i] = NULL;
+ }
- if (wasIndexed) {
- if (OK == undoSymlinking(ectx,
- filename,
- &fileId,
- sock)) {
- if (OK != FS_unindex(sock,
- DBLOCK_SIZE,
- &fileId)) {
- GE_BREAK(ectx, 0);
- goto FAILURE;
- }
- } else {
- GE_BREAK(ectx, 0);
- goto FAILURE;
+ if (wasIndexed)
+ {
+ if (OK == undoSymlinking (ectx, filename, &fileId, sock))
+ {
+ if (OK != FS_unindex (sock, DBLOCK_SIZE, &fileId))
+ {
+ GE_BREAK (ectx, 0);
+ goto FAILURE;
+ }
+ }
+ else
+ {
+ GE_BREAK (ectx, 0);
+ goto FAILURE;
+ }
}
- }
- FREE(iblocks[treedepth]);
+ FREE (iblocks[treedepth]);
/* free resources */
- FREE(iblocks);
- FREE(dblock);
- CLOSE(fd);
- connection_destroy(sock);
+ FREE (iblocks);
+ FREE (dblock);
+ CLOSE (fd);
+ connection_destroy (sock);
return OK;
- FAILURE:
- for (i=0;i<=treedepth;i++)
- FREENONNULL(iblocks[i]);
- FREE(iblocks);
- FREE(dblock);
- CLOSE(fd);
- connection_destroy(sock);
+FAILURE:
+ for (i = 0; i <= treedepth; i++)
+ FREENONNULL (iblocks[i]);
+ FREE (iblocks);
+ FREE (dblock);
+ CLOSE (fd);
+ connection_destroy (sock);
return SYSERR;
}
Modified: GNUnet/src/applications/fs/ecrs/upload.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/upload.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/upload.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -46,66 +46,56 @@
* level+1 and clear the level. iblocks is guaranteed to be big
* enough.
*/
-static int pushBlock(struct ClientServerConnection * sock,
- const CHK * chk,
- unsigned int level,
- Datastore_Value ** iblocks,
- unsigned int prio,
- cron_t expirationTime) {
+static int
+pushBlock (struct ClientServerConnection *sock,
+ const CHK * chk,
+ unsigned int level,
+ Datastore_Value ** iblocks,
+ unsigned int prio, cron_t expirationTime)
+{
unsigned int size;
unsigned int present;
- Datastore_Value * value;
- DBlock * db;
+ Datastore_Value *value;
+ DBlock *db;
CHK ichk;
#if DEBUG_UPLOAD
EncName enc;
#endif
- size = ntohl(iblocks[level]->size);
- GE_ASSERT(NULL, size > sizeof(Datastore_Value));
- size -= sizeof(Datastore_Value);
- GE_ASSERT(NULL, size - sizeof(DBlock) <= IBLOCK_SIZE);
- present = (size - sizeof(DBlock)) / sizeof(CHK);
- db = (DBlock*) &iblocks[level][1];
- if (present == CHK_PER_INODE) {
- fileBlockGetKey(db,
- size,
- &ichk.key);
- fileBlockGetQuery(db,
- size,
- &ichk.query);
- if (OK != pushBlock(sock,
- &ichk,
- level+1,
- iblocks,
- prio,
- expirationTime))
- return SYSERR;
- fileBlockEncode(db,
- size,
- &ichk.query,
- &value);
- if (value == NULL) {
- GE_BREAK(NULL, 0);
- return SYSERR;
+ size = ntohl (iblocks[level]->size);
+ GE_ASSERT (NULL, size > sizeof (Datastore_Value));
+ size -= sizeof (Datastore_Value);
+ GE_ASSERT (NULL, size - sizeof (DBlock) <= IBLOCK_SIZE);
+ present = (size - sizeof (DBlock)) / sizeof (CHK);
+ db = (DBlock *) & iblocks[level][1];
+ if (present == CHK_PER_INODE)
+ {
+ fileBlockGetKey (db, size, &ichk.key);
+ fileBlockGetQuery (db, size, &ichk.query);
+ if (OK != pushBlock (sock,
+ &ichk, level + 1, iblocks, prio, expirationTime))
+ return SYSERR;
+ fileBlockEncode (db, size, &ichk.query, &value);
+ if (value == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ value->prio = htonl (prio);
+ value->expirationTime = htonll (expirationTime);
+ if (OK != FS_insert (sock, value))
+ {
+ FREE (value);
+ return SYSERR;
+ }
+ FREE (value);
+ size = sizeof (DBlock); /* type */
}
- value->prio = htonl(prio);
- value->expirationTime = htonll(expirationTime);
- if (OK != FS_insert(sock,
- value)) {
- FREE(value);
- return SYSERR;
- }
- FREE(value);
- size = sizeof(DBlock); /* type */
- }
/* append CHK */
- memcpy(&((char*)db)[size],
- chk,
- sizeof(CHK));
- size += sizeof(CHK) + sizeof(Datastore_Value);
- GE_ASSERT(NULL, size < MAX_BUFFER_SIZE);
- iblocks[level]->size = htonl(size);
+ memcpy (&((char *) db)[size], chk, sizeof (CHK));
+ size += sizeof (CHK) + sizeof (Datastore_Value);
+ GE_ASSERT (NULL, size < MAX_BUFFER_SIZE);
+ iblocks[level]->size = htonl (size);
return OK;
}
@@ -121,29 +111,30 @@
* @return SYSERR if the upload failed (i.e. not enough space
* or gnunetd not running)
*/
-int ECRS_uploadFile(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * filename,
- int doIndex,
- unsigned int anonymityLevel,
- unsigned int priority,
- cron_t expirationTime,
- ECRS_UploadProgressCallback upcb,
- void * upcbClosure,
- ECRS_TestTerminate tt,
- void * ttClosure,
- struct ECRS_URI ** uri) {
+int
+ECRS_uploadFile (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *filename,
+ int doIndex,
+ unsigned int anonymityLevel,
+ unsigned int priority,
+ cron_t expirationTime,
+ ECRS_UploadProgressCallback upcb,
+ void *upcbClosure,
+ ECRS_TestTerminate tt,
+ void *ttClosure, struct ECRS_URI **uri)
+{
unsigned long long filesize;
unsigned long long pos;
unsigned int treedepth;
int fd;
int i;
unsigned int size;
- Datastore_Value ** iblocks;
- Datastore_Value * dblock;
- DBlock * db;
- Datastore_Value * value;
- struct ClientServerConnection * sock;
+ Datastore_Value **iblocks;
+ Datastore_Value *dblock;
+ DBlock *db;
+ Datastore_Value *value;
+ struct ClientServerConnection *sock;
HashCode512 fileId;
CHK mchk;
cron_t eta;
@@ -154,314 +145,285 @@
EncName enc;
#endif
- GE_ASSERT(ectx, cfg != NULL);
- start = get_time();
- memset(&mchk, 0, sizeof(CHK));
- if (YES != disk_file_test(ectx,
- filename)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' is not a file.\n"),
- filename);
- return SYSERR;
- }
- if (OK != disk_file_size(ectx,
- filename,
- &filesize,
- YES)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Cannot get size of file `%s'"),
- filename);
+ GE_ASSERT (ectx, cfg != NULL);
+ start = get_time ();
+ memset (&mchk, 0, sizeof (CHK));
+ if (YES != disk_file_test (ectx, filename))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' is not a file.\n"), filename);
+ return SYSERR;
+ }
+ if (OK != disk_file_size (ectx, filename, &filesize, YES))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Cannot get size of file `%s'"), filename);
- return SYSERR;
- }
- sock = client_connection_create(ectx, cfg);
- if (sock == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Failed to connect to gnunetd."));
- return SYSERR;
- }
+ return SYSERR;
+ }
+ sock = client_connection_create (ectx, cfg);
+ if (sock == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Failed to connect to gnunetd."));
+ return SYSERR;
+ }
eta = 0;
if (upcb != NULL)
- upcb(filesize, 0, eta, upcbClosure);
- if (doIndex) {
- if (SYSERR == getFileHash(ectx,
- filename,
- &fileId)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Cannot hash `%s'.\n"),
- filename);
- connection_destroy(sock);
- return SYSERR;
+ upcb (filesize, 0, eta, upcbClosure);
+ if (doIndex)
+ {
+ if (SYSERR == getFileHash (ectx, filename, &fileId))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Cannot hash `%s'.\n"), filename);
+ connection_destroy (sock);
+ return SYSERR;
+ }
+ now = get_time ();
+ eta = now + 2 * (now - start);
+ /* very rough estimate: hash reads once through the file,
+ we'll do that once more and write it. But of course
+ the second read may be cached, and we have the encryption,
+ so a factor of two is really, really just a rough estimate */
+ start = now;
+ /* reset the counter since the formula later does not
+ take the time for getFileHash into account */
+
+ switch (FS_initIndex (sock, &fileId, filename))
+ {
+ case SYSERR:
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Initialization for indexing file `%s' failed.\n"),
+ filename);
+ connection_destroy (sock);
+ return SYSERR;
+ case NO:
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Indexing file `%s' failed. Trying to insert file...\n"),
+ filename);
+ doIndex = YES;
+ break;
+ default:
+ break;
+ }
}
- now = get_time();
- eta = now + 2 * (now - start);
- /* very rough estimate: hash reads once through the file,
- we'll do that once more and write it. But of course
- the second read may be cached, and we have the encryption,
- so a factor of two is really, really just a rough estimate */
- start = now;
- /* reset the counter since the formula later does not
- take the time for getFileHash into account */
+ treedepth = computeDepth (filesize);
+ fd = disk_file_open (ectx, filename, O_RDONLY | O_LARGEFILE);
+ if (fd == -1)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Cannot open file `%s': `%s'"), filename, STRERROR (errno));
- switch (FS_initIndex(sock, &fileId, filename)) {
- case SYSERR:
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Initialization for indexing file `%s' failed.\n"),
- filename);
- connection_destroy(sock);
+ connection_destroy (sock);
return SYSERR;
- case NO:
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Indexing file `%s' failed. Trying to insert file...\n"),
- filename);
- doIndex = YES;
- break;
- default:
- break;
}
- }
- treedepth = computeDepth(filesize);
- fd = disk_file_open(ectx,
- filename,
- O_RDONLY | O_LARGEFILE);
- if (fd == -1) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Cannot open file `%s': `%s'"),
- filename,
- STRERROR(errno));
- connection_destroy(sock);
- return SYSERR;
- }
+ dblock = MALLOC (sizeof (Datastore_Value) + DBLOCK_SIZE + sizeof (DBlock));
+ dblock->size =
+ htonl (sizeof (Datastore_Value) + DBLOCK_SIZE + sizeof (DBlock));
+ dblock->anonymityLevel = htonl (anonymityLevel);
+ dblock->prio = htonl (priority);
+ dblock->type = htonl (D_BLOCK);
+ dblock->expirationTime = htonll (expirationTime);
+ db = (DBlock *) & dblock[1];
+ db->type = htonl (D_BLOCK);
+ iblocks = MALLOC (sizeof (Datastore_Value *) * (treedepth + 1));
+ for (i = 0; i <= treedepth; i++)
+ {
+ iblocks[i] =
+ MALLOC (sizeof (Datastore_Value) + IBLOCK_SIZE + sizeof (DBlock));
+ iblocks[i]->size = htonl (sizeof (Datastore_Value) + sizeof (DBlock));
+ iblocks[i]->anonymityLevel = htonl (anonymityLevel);
+ iblocks[i]->prio = htonl (priority);
+ iblocks[i]->type = htonl (D_BLOCK);
+ iblocks[i]->expirationTime = htonll (expirationTime);
+ ((DBlock *) & iblocks[i][1])->type = htonl (D_BLOCK);
+ }
- dblock = MALLOC(sizeof(Datastore_Value) + DBLOCK_SIZE + sizeof(DBlock));
- dblock->size = htonl(sizeof(Datastore_Value) + DBLOCK_SIZE + sizeof(DBlock));
- dblock->anonymityLevel = htonl(anonymityLevel);
- dblock->prio = htonl(priority);
- dblock->type = htonl(D_BLOCK);
- dblock->expirationTime = htonll(expirationTime);
- db = (DBlock*) &dblock[1];
- db->type = htonl(D_BLOCK);
- iblocks = MALLOC(sizeof(Datastore_Value*) * (treedepth+1));
- for (i=0;i<=treedepth;i++) {
- iblocks[i] = MALLOC(sizeof(Datastore_Value) + IBLOCK_SIZE +
sizeof(DBlock));
- iblocks[i]->size = htonl(sizeof(Datastore_Value) + sizeof(DBlock));
- iblocks[i]->anonymityLevel = htonl(anonymityLevel);
- iblocks[i]->prio = htonl(priority);
- iblocks[i]->type = htonl(D_BLOCK);
- iblocks[i]->expirationTime = htonll(expirationTime);
- ((DBlock*) &iblocks[i][1])->type = htonl(D_BLOCK);
- }
-
pos = 0;
- while (pos < filesize) {
- if (upcb != NULL)
- upcb(filesize, pos, eta, upcbClosure);
- if (tt != NULL)
- if (OK != tt(ttClosure))
- goto FAILURE;
- size = DBLOCK_SIZE;
- if (size > filesize - pos) {
- size = filesize - pos;
- memset(&db[1],
- 0,
- DBLOCK_SIZE);
- }
- GE_ASSERT(ectx,
- sizeof(Datastore_Value) + size + sizeof(DBlock) < MAX_BUFFER_SIZE);
- dblock->size = htonl(sizeof(Datastore_Value) + size + sizeof(DBlock));
- if (size != READ(fd,
- &db[1],
- size)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_BULK | GE_ADMIN | GE_USER,
- "READ",
- filename);
- goto FAILURE;
- }
- if (tt != NULL)
- if (OK != tt(ttClosure))
- goto FAILURE;
- fileBlockGetKey(db,
- size + sizeof(DBlock),
- &mchk.key);
- fileBlockGetQuery(db,
- size + sizeof(DBlock),
- &mchk.query);
+ while (pos < filesize)
+ {
+ if (upcb != NULL)
+ upcb (filesize, pos, eta, upcbClosure);
+ if (tt != NULL)
+ if (OK != tt (ttClosure))
+ goto FAILURE;
+ size = DBLOCK_SIZE;
+ if (size > filesize - pos)
+ {
+ size = filesize - pos;
+ memset (&db[1], 0, DBLOCK_SIZE);
+ }
+ GE_ASSERT (ectx,
+ sizeof (Datastore_Value) + size + sizeof (DBlock) <
+ MAX_BUFFER_SIZE);
+ dblock->size =
+ htonl (sizeof (Datastore_Value) + size + sizeof (DBlock));
+ if (size != READ (fd, &db[1], size))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_BULK | GE_ADMIN | GE_USER,
+ "READ", filename);
+ goto FAILURE;
+ }
+ if (tt != NULL)
+ if (OK != tt (ttClosure))
+ goto FAILURE;
+ fileBlockGetKey (db, size + sizeof (DBlock), &mchk.key);
+ fileBlockGetQuery (db, size + sizeof (DBlock), &mchk.query);
#if DEBUG_UPLOAD
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&mchk.query,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Query for current block of size %u is %s\n",
- size,
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&mchk.query, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Query for current block of size %u is %s\n", size, &enc);
#endif
- if (doIndex) {
- if (SYSERR == FS_index(sock,
- &fileId,
- dblock,
- pos)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Indexing data failed at position %i.\n"), pos);
- goto FAILURE;
- }
- } else {
- value = NULL;
- if (OK !=
- fileBlockEncode(db,
- size + sizeof(DBlock),
- &mchk.query,
- &value)) {
- GE_BREAK(ectx, 0);
- goto FAILURE;
- }
- GE_ASSERT(ectx, value != NULL);
- *value = *dblock; /* copy options! */
+ if (doIndex)
+ {
+ if (SYSERR == FS_index (sock, &fileId, dblock, pos))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Indexing data failed at position %i.\n"), pos);
+ goto FAILURE;
+ }
+ }
+ else
+ {
+ value = NULL;
+ if (OK !=
+ fileBlockEncode (db,
+ size + sizeof (DBlock), &mchk.query, &value))
+ {
+ GE_BREAK (ectx, 0);
+ goto FAILURE;
+ }
+ GE_ASSERT (ectx, value != NULL);
+ *value = *dblock; /* copy options! */
- if (SYSERR == FS_insert(sock,
- value)) {
- GE_BREAK(ectx, 0);
- FREE(value);
- goto FAILURE;
- }
- FREE(value);
+ if (SYSERR == FS_insert (sock, value))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (value);
+ goto FAILURE;
+ }
+ FREE (value);
+ }
+ pos += size;
+ now = get_time ();
+ if (pos > 0)
+ {
+ eta = (cron_t) (start +
+ (((double) (now - start) / (double) pos))
+ * (double) filesize);
+ }
+ if (OK != pushBlock (sock, &mchk, 0, /* dblocks are on level 0 */
+ iblocks, priority, expirationTime))
+ {
+ GE_BREAK (ectx, 0);
+ goto FAILURE;
+ }
}
- pos += size;
- now = get_time();
- if (pos > 0) {
- eta = (cron_t) (start +
- (((double)(now - start)/(double)pos))
- * (double)filesize);
- }
- if (OK != pushBlock(sock,
- &mchk,
- 0, /* dblocks are on level 0 */
- iblocks,
- priority,
- expirationTime)) {
- GE_BREAK(ectx, 0);
- goto FAILURE;
- }
- }
if (tt != NULL)
- if (OK != tt(ttClosure))
+ if (OK != tt (ttClosure))
goto FAILURE;
#if DEBUG_UPLOAD
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Tree depth is %u, walking up tree.\n",
- treedepth);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Tree depth is %u, walking up tree.\n", treedepth);
#endif
- for (i=0;i<treedepth;i++) {
- size = ntohl(iblocks[i]->size) - sizeof(Datastore_Value);
- GE_ASSERT(ectx, size < MAX_BUFFER_SIZE);
- if (size == sizeof(DBlock)) {
+ for (i = 0; i < treedepth; i++)
+ {
+ size = ntohl (iblocks[i]->size) - sizeof (Datastore_Value);
+ GE_ASSERT (ectx, size < MAX_BUFFER_SIZE);
+ if (size == sizeof (DBlock))
+ {
#if DEBUG_UPLOAD
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Level %u is empty\n",
- i);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "Level %u is empty\n", i);
#endif
- continue;
- }
- db = (DBlock*) &iblocks[i][1];
- fileBlockGetKey(db,
- size,
- &mchk.key);
+ continue;
+ }
+ db = (DBlock *) & iblocks[i][1];
+ fileBlockGetKey (db, size, &mchk.key);
#if DEBUG_UPLOAD
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Computing query for %u bytes content.\n",
- size);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Computing query for %u bytes content.\n", size);
#endif
- fileBlockGetQuery(db,
- size,
- &mchk.query);
+ fileBlockGetQuery (db, size, &mchk.query);
#if DEBUG_UPLOAD
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&mchk.query,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Query for current block at level %u is `%s'.\n",
- i,
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&mchk.query, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Query for current block at level %u is `%s'.\n", i, &enc);
#endif
- if (OK != pushBlock(sock,
- &mchk,
- i+1,
- iblocks,
- priority,
- expirationTime)) {
- GE_BREAK(ectx, 0);
- goto FAILURE;
+ if (OK != pushBlock (sock,
+ &mchk, i + 1, iblocks, priority, expirationTime))
+ {
+ GE_BREAK (ectx, 0);
+ goto FAILURE;
+ }
+ fileBlockEncode (db, size, &mchk.query, &value);
+ if (value == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ goto FAILURE;
+ }
+ value->expirationTime = htonll (expirationTime);
+ value->prio = htonl (priority);
+ if (SYSERR == FS_insert (sock, value))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (value);
+ goto FAILURE;
+ }
+ FREE (value);
+ FREE (iblocks[i]);
+ iblocks[i] = NULL;
}
- fileBlockEncode(db,
- size,
- &mchk.query,
- &value);
- if (value == NULL) {
- GE_BREAK(ectx, 0);
- goto FAILURE;
- }
- value->expirationTime = htonll(expirationTime);
- value->prio = htonl(priority);
- if (SYSERR == FS_insert(sock,
- value)) {
- GE_BREAK(ectx, 0);
- FREE(value);
- goto FAILURE;
- }
- FREE(value);
- FREE(iblocks[i]);
- iblocks[i] = NULL;
- }
#if DEBUG_UPLOAD
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&mchk.query,
- &enc));
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Query for top block is %s\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (&mchk.query, &enc));
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Query for top block is %s\n", &enc);
#endif
/* build URI */
- fid.file_length = htonll(filesize);
- db = (DBlock*) &iblocks[treedepth][1];
+ fid.file_length = htonll (filesize);
+ db = (DBlock *) & iblocks[treedepth][1];
- fid.chk = *(CHK*)&(db[1]);
- *uri = MALLOC(sizeof(URI));
+ fid.chk = *(CHK *) & (db[1]);
+ *uri = MALLOC (sizeof (URI));
(*uri)->type = chk;
(*uri)->data.fi = fid;
/* free resources */
- FREENONNULL(iblocks[treedepth]);
- FREE(iblocks);
- FREE(dblock);
+ FREENONNULL (iblocks[treedepth]);
+ FREE (iblocks);
+ FREE (dblock);
if (upcb != NULL)
- upcb(filesize, filesize, eta, upcbClosure);
- CLOSE(fd);
- connection_destroy(sock);
+ upcb (filesize, filesize, eta, upcbClosure);
+ CLOSE (fd);
+ connection_destroy (sock);
return OK;
- FAILURE:
- for (i=0;i<=treedepth;i++)
- FREENONNULL(iblocks[i]);
- FREE(iblocks);
- FREE(dblock);
- CLOSE(fd);
- connection_destroy(sock);
+FAILURE:
+ for (i = 0; i <= treedepth; i++)
+ FREENONNULL (iblocks[i]);
+ FREE (iblocks);
+ FREE (dblock);
+ CLOSE (fd);
+ connection_destroy (sock);
return SYSERR;
}
Modified: GNUnet/src/applications/fs/ecrs/uri.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/uri.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/uri.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -90,23 +90,25 @@
* @return NULL on error (i.e. keywordCount == 0)
*/
static char *
-createKeywordURI(char ** keywords,
- unsigned int keywordCount) {
+createKeywordURI (char **keywords, unsigned int keywordCount)
+{
size_t n;
- char * ret;
+ char *ret;
unsigned int i;
- n = keywordCount + strlen(ECRS_URI_PREFIX) + strlen(ECRS_SEARCH_INFIX) + 1;
- for (i=0;i<keywordCount;i++)
- n += strlen(keywords[i]);
- ret = MALLOC(n);
- strcpy(ret, ECRS_URI_PREFIX);
- strcat(ret, ECRS_SEARCH_INFIX);
- for (i=0;i<keywordCount;i++) {
- strcat(ret, keywords[i]);
- if (i != keywordCount-1)
- strcat(ret, "+");
- }
+ n =
+ keywordCount + strlen (ECRS_URI_PREFIX) + strlen (ECRS_SEARCH_INFIX) + 1;
+ for (i = 0; i < keywordCount; i++)
+ n += strlen (keywords[i]);
+ ret = MALLOC (n);
+ strcpy (ret, ECRS_URI_PREFIX);
+ strcat (ret, ECRS_SEARCH_INFIX);
+ for (i = 0; i < keywordCount; i++)
+ {
+ strcat (ret, keywords[i]);
+ if (i != keywordCount - 1)
+ strcat (ret, "+");
+ }
return ret;
}
@@ -114,23 +116,23 @@
* Generate a subspace URI.
*/
static char *
-createSubspaceURI(const HashCode512 * namespace,
- const HashCode512 * identifier) {
+createSubspaceURI (const HashCode512 * namespace,
+ const HashCode512 * identifier)
+{
size_t n;
- char * ret;
+ char *ret;
EncName ns;
EncName id;
- n = sizeof(EncName) * 2 + strlen(ECRS_URI_PREFIX) +
strlen(ECRS_SUBSPACE_INFIX) + 1;
- ret = MALLOC(n);
- hash2enc(namespace, &ns);
- hash2enc(identifier, &id);
- SNPRINTF(ret, n,
- "%s%s%s/%s",
- ECRS_URI_PREFIX,
- ECRS_SUBSPACE_INFIX,
- (char*) &ns,
- (char*) &id);
+ n =
+ sizeof (EncName) * 2 + strlen (ECRS_URI_PREFIX) +
+ strlen (ECRS_SUBSPACE_INFIX) + 1;
+ ret = MALLOC (n);
+ hash2enc (namespace, &ns);
+ hash2enc (identifier, &id);
+ SNPRINTF (ret, n,
+ "%s%s%s/%s",
+ ECRS_URI_PREFIX, ECRS_SUBSPACE_INFIX, (char *) &ns, (char *) &id);
return ret;
}
@@ -138,27 +140,26 @@
* Generate a file URI.
*/
static char *
-createFileURI(const FileIdentifier * fi) {
- char * ret;
+createFileURI (const FileIdentifier * fi)
+{
+ char *ret;
EncName keyhash;
EncName queryhash;
size_t n;
- hash2enc(&fi->chk.key,
- &keyhash);
- hash2enc(&fi->chk.query,
- &queryhash);
+ hash2enc (&fi->chk.key, &keyhash);
+ hash2enc (&fi->chk.query, &queryhash);
- n =
strlen(ECRS_URI_PREFIX)+2*sizeof(EncName)+8+16+32+strlen(ECRS_FILE_INFIX);
- ret = MALLOC(n);
- SNPRINTF(ret,
- n,
- "%s%s%s.%s.%llu",
- ECRS_URI_PREFIX,
- ECRS_FILE_INFIX,
- (char*)&keyhash,
- (char*)&queryhash,
- ntohll(fi->file_length));
+ n =
+ strlen (ECRS_URI_PREFIX) + 2 * sizeof (EncName) + 8 + 16 + 32 +
+ strlen (ECRS_FILE_INFIX);
+ ret = MALLOC (n);
+ SNPRINTF (ret,
+ n,
+ "%s%s%s.%s.%llu",
+ ECRS_URI_PREFIX,
+ ECRS_FILE_INFIX,
+ (char *) &keyhash, (char *) &queryhash, ntohll (fi->file_length));
return ret;
}
@@ -168,63 +169,62 @@
* Create a (string) location URI from a Location.
*/
static char *
-createLocURI(const Location * loc) {
+createLocURI (const Location * loc)
+{
size_t n;
- char * ret;
+ char *ret;
EncName keyhash;
EncName queryhash;
- char * peerId;
- char * peerSig;
+ char *peerId;
+ char *peerSig;
- hash2enc(&loc->fi.chk.key,
- &keyhash);
- hash2enc(&loc->fi.chk.query,
- &queryhash);
+ hash2enc (&loc->fi.chk.key, &keyhash);
+ hash2enc (&loc->fi.chk.query, &queryhash);
n = 2148;
- peerId = bin2enc(&loc->peer,
- sizeof(PublicKey));
- peerSig = bin2enc(&loc->contentSignature,
- sizeof(Signature));
- ret = MALLOC(n);
- SNPRINTF(ret,
- n,
- "%s%s%s.%s.%llu.%s.%s.%u",
- ECRS_URI_PREFIX,
- ECRS_LOCATION_INFIX,
- (char*)&keyhash,
- (char*)&queryhash,
- ntohll(loc->fi.file_length),
- peerId,
- peerSig,
- loc->expirationTime);
- FREE(peerSig);
- FREE(peerId);
+ peerId = bin2enc (&loc->peer, sizeof (PublicKey));
+ peerSig = bin2enc (&loc->contentSignature, sizeof (Signature));
+ ret = MALLOC (n);
+ SNPRINTF (ret,
+ n,
+ "%s%s%s.%s.%llu.%s.%s.%u",
+ ECRS_URI_PREFIX,
+ ECRS_LOCATION_INFIX,
+ (char *) &keyhash,
+ (char *) &queryhash,
+ ntohll (loc->fi.file_length),
+ peerId, peerSig, loc->expirationTime);
+ FREE (peerSig);
+ FREE (peerId);
return ret;
}
/**
* Convert a URI to a UTF-8 String.
*/
-char * ECRS_uriToString(const struct ECRS_URI * uri) {
- if (uri == NULL) {
- GE_BREAK(NULL, 0);
- return NULL;
- }
- switch (uri->type) {
- case ksk:
- return createKeywordURI(uri->data.ksk.keywords,
- uri->data.ksk.keywordCount);
- case sks:
- return createSubspaceURI(&uri->data.sks.namespace,
- &uri->data.sks.identifier);
- case chk:
- return createFileURI(&uri->data.fi);
- case loc:
- return createLocURI(&uri->data.loc);
- default:
- GE_BREAK(NULL, 0);
- return NULL;
- }
+char *
+ECRS_uriToString (const struct ECRS_URI *uri)
+{
+ if (uri == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ return NULL;
+ }
+ switch (uri->type)
+ {
+ case ksk:
+ return createKeywordURI (uri->data.ksk.keywords,
+ uri->data.ksk.keywordCount);
+ case sks:
+ return createSubspaceURI (&uri->data.sks.namespace,
+ &uri->data.sks.identifier);
+ case chk:
+ return createFileURI (&uri->data.fi);
+ case loc:
+ return createLocURI (&uri->data.loc);
+ default:
+ GE_BREAK (NULL, 0);
+ return NULL;
+ }
}
/**
@@ -235,59 +235,59 @@
* @return SYSERR if this is not a search URI, otherwise
* the number of keywords placed in the array
*/
-static int parseKeywordURI(struct GE_Context * ectx,
- const char * uri,
- char *** keywords) {
+static int
+parseKeywordURI (struct GE_Context *ectx, const char *uri, char ***keywords)
+{
unsigned int pos;
int ret;
int iret;
int i;
size_t slen;
- char * dup;
+ char *dup;
- GE_ASSERT(ectx, uri != NULL);
+ GE_ASSERT (ectx, uri != NULL);
- slen = strlen(uri);
- pos = strlen(ECRS_URI_PREFIX);
+ slen = strlen (uri);
+ pos = strlen (ECRS_URI_PREFIX);
- if (0 != strncmp(uri,
- ECRS_URI_PREFIX,
- pos))
+ if (0 != strncmp (uri, ECRS_URI_PREFIX, pos))
return SYSERR;
- if (0 != strncmp(&uri[pos],
- ECRS_SEARCH_INFIX,
- strlen(ECRS_SEARCH_INFIX)))
+ if (0 != strncmp (&uri[pos], ECRS_SEARCH_INFIX, strlen (ECRS_SEARCH_INFIX)))
return SYSERR;
- pos += strlen(ECRS_SEARCH_INFIX);
- if (slen == pos) {
- /* no keywords */
- (*keywords) = NULL;
- return 0;
- }
- if ( (uri[slen-1] == '+') ||
- (uri[pos] == '+') )
- return SYSERR; /* no keywords / malformed */
+ pos += strlen (ECRS_SEARCH_INFIX);
+ if (slen == pos)
+ {
+ /* no keywords */
+ (*keywords) = NULL;
+ return 0;
+ }
+ if ((uri[slen - 1] == '+') || (uri[pos] == '+'))
+ return SYSERR; /* no keywords / malformed */
ret = 1;
- for (i=pos;i<slen;i++) {
- if (uri[i] == '+') {
- ret++;
- if (uri[i-1] == '+')
- return SYSERR; /* "++" not allowed */
+ for (i = pos; i < slen; i++)
+ {
+ if (uri[i] == '+')
+ {
+ ret++;
+ if (uri[i - 1] == '+')
+ return SYSERR; /* "++" not allowed */
+ }
}
- }
iret = ret;
- dup = STRDUP(uri);
- (*keywords) = MALLOC(ret * sizeof(char*));
- for (i=slen-1;i>=pos;i--) {
- if (dup[i] == '+') {
- (*keywords)[--ret] = STRDUP(&dup[i+1]);
- dup[i] = '\0';
+ dup = STRDUP (uri);
+ (*keywords) = MALLOC (ret * sizeof (char *));
+ for (i = slen - 1; i >= pos; i--)
+ {
+ if (dup[i] == '+')
+ {
+ (*keywords)[--ret] = STRDUP (&dup[i + 1]);
+ dup[i] = '\0';
+ }
}
- }
- (*keywords)[--ret] = STRDUP(&dup[pos]);
- GE_ASSERT(ectx, ret == 0);
- FREE(dup);
+ (*keywords)[--ret] = STRDUP (&dup[pos]);
+ GE_ASSERT (ectx, ret == 0);
+ FREE (dup);
return iret;
}
@@ -299,50 +299,47 @@
* @param identifier set to the ID in the namespace
* @return OK on success, SYSERR if this is not a namespace URI
*/
-static int parseSubspaceURI(struct GE_Context * ectx,
- const char * uri,
- HashCode512 * namespace,
- HashCode512 * identifier) {
+static int
+parseSubspaceURI (struct GE_Context *ectx,
+ const char *uri,
+ HashCode512 * namespace, HashCode512 * identifier)
+{
unsigned int pos;
size_t slen;
- char * up;
+ char *up;
- GE_ASSERT(ectx, uri != NULL);
+ GE_ASSERT (ectx, uri != NULL);
- slen = strlen(uri);
- pos = strlen(ECRS_URI_PREFIX);
+ slen = strlen (uri);
+ pos = strlen (ECRS_URI_PREFIX);
- if (0 != strncmp(uri,
- ECRS_URI_PREFIX,
- pos))
+ if (0 != strncmp (uri, ECRS_URI_PREFIX, pos))
return SYSERR;
- if (0 != strncmp(&uri[pos],
- ECRS_SUBSPACE_INFIX,
- strlen(ECRS_SUBSPACE_INFIX)))
+ if (0 != strncmp (&uri[pos],
+ ECRS_SUBSPACE_INFIX, strlen (ECRS_SUBSPACE_INFIX)))
return SYSERR;
- pos += strlen(ECRS_SUBSPACE_INFIX);
- if ( (slen < pos+sizeof(EncName)+1) ||
- (! ( (uri[pos+sizeof(EncName)-1] == '/') ||
- (uri[pos+sizeof(EncName)-1] == '\\') ) ) )
+ pos += strlen (ECRS_SUBSPACE_INFIX);
+ if ((slen < pos + sizeof (EncName) + 1) ||
+ (!((uri[pos + sizeof (EncName) - 1] == '/') ||
+ (uri[pos + sizeof (EncName) - 1] == '\\'))))
return SYSERR;
- up = STRDUP(uri);
- up[pos+sizeof(EncName)-1] = '\0';
- if ( (OK != enc2hash(&up[pos],
- namespace)) ) {
- FREE(up);
- return SYSERR;
- }
- if ( (slen != pos+2*sizeof(EncName)-1) ||
- (OK != enc2hash(&up[pos+sizeof(EncName)],
- identifier)) ) {
- if (up[slen-1] == '\\')
- up[--slen] = '\0';
- hash(&up[pos+sizeof(EncName)],
- slen - (pos+sizeof(EncName)),
- identifier);
- }
- FREE(up);
+ up = STRDUP (uri);
+ up[pos + sizeof (EncName) - 1] = '\0';
+ if ((OK != enc2hash (&up[pos], namespace)))
+ {
+ FREE (up);
+ return SYSERR;
+ }
+ if ((slen != pos + 2 * sizeof (EncName) - 1) ||
+ (OK != enc2hash (&up[pos + sizeof (EncName)], identifier)))
+ {
+ if (up[slen - 1] == '\\')
+ up[--slen] = '\0';
+ hash (&up[pos + sizeof (EncName)],
+ slen - (pos + sizeof (EncName)), identifier);
+ }
+ FREE (up);
return OK;
}
@@ -353,47 +350,43 @@
* @param fi the file identifier
* @return OK on success, SYSERR if this is not a file URI
*/
-static int parseFileURI(struct GE_Context * ectx,
- const char * uri,
- FileIdentifier * fi) {
+static int
+parseFileURI (struct GE_Context *ectx, const char *uri, FileIdentifier * fi)
+{
unsigned int pos;
size_t slen;
- char * dup;
+ char *dup;
- GE_ASSERT(ectx, uri != NULL);
+ GE_ASSERT (ectx, uri != NULL);
- slen = strlen(uri);
- pos = strlen(ECRS_URI_PREFIX);
+ slen = strlen (uri);
+ pos = strlen (ECRS_URI_PREFIX);
- if (0 != strncmp(uri,
- ECRS_URI_PREFIX,
- pos))
+ if (0 != strncmp (uri, ECRS_URI_PREFIX, pos))
return SYSERR;
- if (0 != strncmp(&uri[pos],
- ECRS_FILE_INFIX,
- strlen(ECRS_FILE_INFIX)))
+ if (0 != strncmp (&uri[pos], ECRS_FILE_INFIX, strlen (ECRS_FILE_INFIX)))
return SYSERR;
- pos += strlen(ECRS_FILE_INFIX);
- if ( (slen < pos+2*sizeof(EncName)+1) ||
- (uri[pos+sizeof(EncName)-1] != '.') ||
- (uri[pos+sizeof(EncName)*2-1] != '.') )
+ pos += strlen (ECRS_FILE_INFIX);
+ if ((slen < pos + 2 * sizeof (EncName) + 1) ||
+ (uri[pos + sizeof (EncName) - 1] != '.') ||
+ (uri[pos + sizeof (EncName) * 2 - 1] != '.'))
return SYSERR;
- dup = STRDUP(uri);
- dup[pos+sizeof(EncName)-1] = '\0';
- dup[pos+sizeof(EncName)*2-1] = '\0';
- if ( (OK != enc2hash(&dup[pos],
- &fi->chk.key)) ||
- (OK != enc2hash(&dup[pos+sizeof(EncName)],
- &fi->chk.query)) ||
- (1 != SSCANF(&dup[pos+sizeof(EncName)*2],
- "%llu",
- &fi->file_length)) ) {
- FREE(dup);
- return SYSERR;
- }
- FREE(dup);
- fi->file_length = htonll(fi->file_length);
+ dup = STRDUP (uri);
+ dup[pos + sizeof (EncName) - 1] = '\0';
+ dup[pos + sizeof (EncName) * 2 - 1] = '\0';
+ if ((OK != enc2hash (&dup[pos],
+ &fi->chk.key)) ||
+ (OK != enc2hash (&dup[pos + sizeof (EncName)],
+ &fi->chk.query)) ||
+ (1 != SSCANF (&dup[pos + sizeof (EncName) * 2],
+ "%llu", &fi->file_length)))
+ {
+ FREE (dup);
+ return SYSERR;
+ }
+ FREE (dup);
+ fi->file_length = htonll (fi->file_length);
return OK;
}
@@ -405,160 +398,148 @@
* @param loc where to store the location
* @return OK on success, SYSERR if this is not a file URI
*/
-static int parseLocationURI(struct GE_Context * ectx,
- const char * uri,
- Location * loc) {
+static int
+parseLocationURI (struct GE_Context *ectx, const char *uri, Location * loc)
+{
unsigned int pos;
unsigned int npos;
int ret;
size_t slen;
- char * dup;
- char * addr;
+ char *dup;
+ char *addr;
- GE_ASSERT(ectx, uri != NULL);
+ GE_ASSERT (ectx, uri != NULL);
addr = NULL;
- slen = strlen(uri);
- pos = strlen(ECRS_URI_PREFIX);
+ slen = strlen (uri);
+ pos = strlen (ECRS_URI_PREFIX);
- if (0 != strncmp(uri,
- ECRS_URI_PREFIX,
- pos))
+ if (0 != strncmp (uri, ECRS_URI_PREFIX, pos))
return SYSERR;
- if (0 != strncmp(&uri[pos],
- ECRS_LOCATION_INFIX,
- strlen(ECRS_LOCATION_INFIX)))
+ if (0 != strncmp (&uri[pos],
+ ECRS_LOCATION_INFIX, strlen (ECRS_LOCATION_INFIX)))
return SYSERR;
- pos += strlen(ECRS_LOCATION_INFIX);
- if ( (slen < pos+2*sizeof(EncName)+1) ||
- (uri[pos+sizeof(EncName)-1] != '.') ||
- (uri[pos+sizeof(EncName)*2-1] != '.') )
+ pos += strlen (ECRS_LOCATION_INFIX);
+ if ((slen < pos + 2 * sizeof (EncName) + 1) ||
+ (uri[pos + sizeof (EncName) - 1] != '.') ||
+ (uri[pos + sizeof (EncName) * 2 - 1] != '.'))
return SYSERR;
- dup = STRDUP(uri);
- dup[pos+sizeof(EncName)-1] = '\0';
- dup[pos+sizeof(EncName)*2-1] = '\0';
- npos = pos +sizeof(EncName)*2;
- while ( (uri[npos] != '\0') &&
- (uri[npos] != '.') )
+ dup = STRDUP (uri);
+ dup[pos + sizeof (EncName) - 1] = '\0';
+ dup[pos + sizeof (EncName) * 2 - 1] = '\0';
+ npos = pos + sizeof (EncName) * 2;
+ while ((uri[npos] != '\0') && (uri[npos] != '.'))
npos++;
if (dup[npos] == '\0')
goto ERR;
dup[npos++] = '\0';
- if ( (OK != enc2hash(&dup[pos],
- &loc->fi.chk.key)) ||
- (OK != enc2hash(&dup[pos+sizeof(EncName)],
- &loc->fi.chk.query)) ||
- (1 != SSCANF(&dup[pos+sizeof(EncName)*2],
- "%llu",
- &loc->fi.file_length)) )
+ if ((OK != enc2hash (&dup[pos],
+ &loc->fi.chk.key)) ||
+ (OK != enc2hash (&dup[pos + sizeof (EncName)],
+ &loc->fi.chk.query)) ||
+ (1 != SSCANF (&dup[pos + sizeof (EncName) * 2],
+ "%llu", &loc->fi.file_length)))
goto ERR;
- loc->fi.file_length = htonll(loc->fi.file_length);
- ret = enc2bin(&dup[npos],
- &loc->peer,
- sizeof(PublicKey));
+ loc->fi.file_length = htonll (loc->fi.file_length);
+ ret = enc2bin (&dup[npos], &loc->peer, sizeof (PublicKey));
if (ret == -1)
goto ERR;
npos += ret;
if (dup[npos++] != '.')
goto ERR;
- ret = enc2bin(&dup[npos],
- &loc->contentSignature,
- sizeof(Signature));
+ ret = enc2bin (&dup[npos], &loc->contentSignature, sizeof (Signature));
if (ret == -1)
goto ERR;
npos += ret;
if (dup[npos++] != '.')
goto ERR;
- if (1 != SSCANF(&dup[npos],
- "%u",
- &loc->expirationTime))
+ if (1 != SSCANF (&dup[npos], "%u", &loc->expirationTime))
goto ERR;
/* Finally: verify sigs! */
- if (OK != verifySig(&loc->fi,
- sizeof(FileIdentifier) +
- sizeof(PeerIdentity) +
- sizeof(TIME_T),
- &loc->contentSignature,
- &loc->peer))
+ if (OK != verifySig (&loc->fi,
+ sizeof (FileIdentifier) +
+ sizeof (PeerIdentity) +
+ sizeof (TIME_T), &loc->contentSignature, &loc->peer))
goto ERR;
- FREE(dup);
+ FREE (dup);
return OK;
- ERR:
- FREE(dup);
- FREENONNULL(addr);
+ERR:
+ FREE (dup);
+ FREENONNULL (addr);
return SYSERR;
}
/**
* Convert a UTF-8 String to a URI.
*/
-URI * ECRS_stringToUri(struct GE_Context * ectx,
- const char * uri) {
- URI * ret;
+URI *
+ECRS_stringToUri (struct GE_Context * ectx, const char *uri)
+{
+ URI *ret;
int len;
- ret = MALLOC(sizeof(URI));
- if (OK == parseFileURI(ectx,
- uri,
- &ret->data.fi)) {
- ret->type = chk;
- return ret;
- }
- if (OK == parseSubspaceURI(ectx,
- uri,
- &ret->data.sks.namespace,
- &ret->data.sks.identifier)) {
- ret->type = sks;
- return ret;
- }
- if (OK == parseLocationURI(ectx,
- uri,
- &ret->data.loc)) {
- ret->type = loc;
- return ret;
- }
- len = parseKeywordURI(ectx,
- uri,
- &ret->data.ksk.keywords);
- if (len < 0) {
- FREE(ret);
- return NULL;
- }
+ ret = MALLOC (sizeof (URI));
+ if (OK == parseFileURI (ectx, uri, &ret->data.fi))
+ {
+ ret->type = chk;
+ return ret;
+ }
+ if (OK == parseSubspaceURI (ectx,
+ uri,
+ &ret->data.sks.namespace,
+ &ret->data.sks.identifier))
+ {
+ ret->type = sks;
+ return ret;
+ }
+ if (OK == parseLocationURI (ectx, uri, &ret->data.loc))
+ {
+ ret->type = loc;
+ return ret;
+ }
+ len = parseKeywordURI (ectx, uri, &ret->data.ksk.keywords);
+ if (len < 0)
+ {
+ FREE (ret);
+ return NULL;
+ }
ret->type = ksk;
- ret->data.ksk.keywordCount
- = len;
+ ret->data.ksk.keywordCount = len;
return ret;
}
/**
* Free URI.
*/
-void ECRS_freeUri(struct ECRS_URI * uri) {
+void
+ECRS_freeUri (struct ECRS_URI *uri)
+{
int i;
- GE_ASSERT(NULL, uri != NULL);
- switch(uri->type) {
- case ksk:
- for (i=0;i<uri->data.ksk.keywordCount;i++)
- FREE(uri->data.ksk.keywords[i]);
- GROW(uri->data.ksk.keywords,
- uri->data.ksk.keywordCount,
- 0);
- break;
- case loc:
- break;
- default:
- /* do nothing */
- break;
- }
- FREE(uri);
+ GE_ASSERT (NULL, uri != NULL);
+ switch (uri->type)
+ {
+ case ksk:
+ for (i = 0; i < uri->data.ksk.keywordCount; i++)
+ FREE (uri->data.ksk.keywords[i]);
+ GROW (uri->data.ksk.keywords, uri->data.ksk.keywordCount, 0);
+ break;
+ case loc:
+ break;
+ default:
+ /* do nothing */
+ break;
+ }
+ FREE (uri);
}
/**
* Is this a namespace URI?
*/
-int ECRS_isNamespaceUri(const struct ECRS_URI * uri) {
+int
+ECRS_isNamespaceUri (const struct ECRS_URI *uri)
+{
return uri->type == sks;
}
@@ -568,12 +549,13 @@
* @return the name (hash) of the namespace, caller
* must free it.
*/
-char * ECRS_getNamespaceName(const HashCode512 * id) {
- char * ret;
+char *
+ECRS_getNamespaceName (const HashCode512 * id)
+{
+ char *ret;
- ret = MALLOC(sizeof(EncName));
- hash2enc(id,
- (EncName*)ret);
+ ret = MALLOC (sizeof (EncName));
+ hash2enc (id, (EncName *) ret);
return ret;
}
@@ -583,12 +565,14 @@
*
* @return OK on success
*/
-int ECRS_getNamespaceId(const struct ECRS_URI * uri,
- HashCode512 * id) {
- if (! ECRS_isNamespaceUri(uri)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
+int
+ECRS_getNamespaceId (const struct ECRS_URI *uri, HashCode512 * id)
+{
+ if (!ECRS_isNamespaceUri (uri))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
*id = uri->data.sks.namespace;
return OK;
}
@@ -598,12 +582,14 @@
*
* @return OK on success
*/
-int ECRS_getSKSContentHash(const struct ECRS_URI * uri,
- HashCode512 * id) {
- if (! ECRS_isNamespaceUri(uri)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
+int
+ECRS_getSKSContentHash (const struct ECRS_URI *uri, HashCode512 * id)
+{
+ if (!ECRS_isNamespaceUri (uri))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
*id = uri->data.sks.identifier;
return OK;
}
@@ -611,14 +597,17 @@
/**
* Is this a keyword URI?
*/
-int ECRS_isKeywordUri(const struct ECRS_URI * uri) {
+int
+ECRS_isKeywordUri (const struct ECRS_URI *uri)
+{
#if EXTRA_CHECKS
int i;
- if (uri->type == ksk) {
- for (i=uri->data.ksk.keywordCount-1;i>=0;i--)
- GE_ASSERT(NULL, uri->data.ksk.keywords[i] != NULL);
- }
+ if (uri->type == ksk)
+ {
+ for (i = uri->data.ksk.keywordCount - 1; i >= 0; i--)
+ GE_ASSERT (NULL, uri->data.ksk.keywords[i] != NULL);
+ }
#endif
return uri->type == ksk;
}
@@ -628,7 +617,9 @@
* How many keywords are ANDed in this keyword URI?
* @return 0 if this is not a keyword URI
*/
-unsigned int ECRS_countKeywordsOfUri(const struct ECRS_URI * uri) {
+unsigned int
+ECRS_countKeywordsOfUri (const struct ECRS_URI *uri)
+{
if (uri->type != ksk)
return 0;
return uri->data.ksk.keywordCount;
@@ -639,34 +630,41 @@
* @return -1 if this is not a keyword URI, otherwise number of
* keywords iterated over until iterator aborted
*/
-int ECRS_getKeywordsFromUri(const struct ECRS_URI * uri,
- ECRS_KeywordIterator iterator,
- void * cls) {
+int
+ECRS_getKeywordsFromUri (const struct ECRS_URI *uri,
+ ECRS_KeywordIterator iterator, void *cls)
+{
int i;
- if (uri->type != ksk) {
- return -1;
- } else {
- for (i=0;i<uri->data.ksk.keywordCount;i++)
- if (iterator != NULL)
- if (OK != iterator(uri->data.ksk.keywords[i],
- cls))
- return i;
- return i;
- }
+ if (uri->type != ksk)
+ {
+ return -1;
+ }
+ else
+ {
+ for (i = 0; i < uri->data.ksk.keywordCount; i++)
+ if (iterator != NULL)
+ if (OK != iterator (uri->data.ksk.keywords[i], cls))
+ return i;
+ return i;
+ }
}
/**
* Is this a file (or directory) URI?
*/
-int ECRS_isFileUri(const struct ECRS_URI * uri) {
+int
+ECRS_isFileUri (const struct ECRS_URI *uri)
+{
return uri->type == chk;
}
/**
* Is this a location URI? (DHT specific!)
*/
-int ECRS_isLocationUri(const struct ECRS_URI * uri) {
+int
+ECRS_isLocationUri (const struct ECRS_URI *uri)
+{
return uri->type == loc;
}
@@ -675,45 +673,49 @@
* What is the size of the file that this URI
* refers to?
*/
-unsigned long long ECRS_fileSize(const struct ECRS_URI * uri) {
- switch (uri->type) {
- case chk:
- return ntohll(uri->data.fi.file_length);
- case loc:
- return ntohll(uri->data.loc.fi.file_length);
- default:
- GE_ASSERT(NULL, 0);
- }
- return 0; /* unreachable */
+unsigned long long
+ECRS_fileSize (const struct ECRS_URI *uri)
+{
+ switch (uri->type)
+ {
+ case chk:
+ return ntohll (uri->data.fi.file_length);
+ case loc:
+ return ntohll (uri->data.loc.fi.file_length);
+ default:
+ GE_ASSERT (NULL, 0);
+ }
+ return 0; /* unreachable */
}
/**
* Duplicate URI.
*/
-URI * ECRS_dupUri(const URI * uri) {
- struct ECRS_URI * ret;
+URI *
+ECRS_dupUri (const URI * uri)
+{
+ struct ECRS_URI *ret;
int i;
- ret = MALLOC(sizeof(URI));
- memcpy(ret,
- uri,
- sizeof(URI));
- switch (ret->type) {
- case ksk:
- if (ret->data.ksk.keywordCount > 0) {
- ret->data.ksk.keywords
- = MALLOC(ret->data.ksk.keywordCount * sizeof(char*));
- for (i=0;i<ret->data.ksk.keywordCount;i++)
- ret->data.ksk.keywords[i]
- = STRDUP(uri->data.ksk.keywords[i]);
+ ret = MALLOC (sizeof (URI));
+ memcpy (ret, uri, sizeof (URI));
+ switch (ret->type)
+ {
+ case ksk:
+ if (ret->data.ksk.keywordCount > 0)
+ {
+ ret->data.ksk.keywords
+ = MALLOC (ret->data.ksk.keywordCount * sizeof (char *));
+ for (i = 0; i < ret->data.ksk.keywordCount; i++)
+ ret->data.ksk.keywords[i] = STRDUP (uri->data.ksk.keywords[i]);
+ }
+ break;
+ case loc:
+ break;
+ default:
+ break;
}
- break;
- case loc:
- break;
- default:
- break;
- }
return ret;
}
@@ -722,45 +724,45 @@
* adding the current date (YYYY-MM-DD) after each
* keyword.
*/
-URI * ECRS_dateExpandKeywordUri(const URI * uri) {
- URI * ret;
+URI *
+ECRS_dateExpandKeywordUri (const URI * uri)
+{
+ URI *ret;
int i;
- char * key;
- char * kd;
+ char *key;
+ char *kd;
struct tm t;
time_t now;
unsigned int keywordCount;
- GE_ASSERT(NULL, uri->type == ksk);
- time(&now);
+ GE_ASSERT (NULL, uri->type == ksk);
+ time (&now);
#ifdef HAVE_GMTIME_R
- gmtime_r(&now, &t);
+ gmtime_r (&now, &t);
#else
- t = *gmtime(&now);
+ t = *gmtime (&now);
#endif
- ret = MALLOC(sizeof(URI));
+ ret = MALLOC (sizeof (URI));
ret->type = ksk;
keywordCount = uri->data.ksk.keywordCount;
ret->data.ksk.keywordCount = 2 * keywordCount;
- if (keywordCount > 0) {
- ret->data.ksk.keywords = MALLOC(sizeof(char*) * keywordCount * 2);
- for (i=0;i<keywordCount;i++) {
- key = uri->data.ksk.keywords[i];
- GE_ASSERT(NULL, key != NULL);
- ret->data.ksk.keywords[2*i]
- = STRDUP(key);
- kd = MALLOC(strlen(key) + 13);
- memset(kd, 0, strlen(key) + 13);
- strcpy(kd, key);
- strftime(&kd[strlen(key)],
- 13,
- "-%Y-%m-%d",
- &t);
- ret->data.ksk.keywords[2*i+1]
- = kd;
+ if (keywordCount > 0)
+ {
+ ret->data.ksk.keywords = MALLOC (sizeof (char *) * keywordCount * 2);
+ for (i = 0; i < keywordCount; i++)
+ {
+ key = uri->data.ksk.keywords[i];
+ GE_ASSERT (NULL, key != NULL);
+ ret->data.ksk.keywords[2 * i] = STRDUP (key);
+ kd = MALLOC (strlen (key) + 13);
+ memset (kd, 0, strlen (key) + 13);
+ strcpy (kd, key);
+ strftime (&kd[strlen (key)], 13, "-%Y-%m-%d", &t);
+ ret->data.ksk.keywords[2 * i + 1] = kd;
+ }
}
- } else
+ else
ret->data.ksk.keywords = NULL;
return ret;
@@ -772,8 +774,10 @@
* in the meta-data and construct one large keyword URI
* that lists all keywords that can be found in the meta-data).
*/
-URI * ECRS_metaDataToUri(const MetaData * md) {
- URI * ret;
+URI *
+ECRS_metaDataToUri (const MetaData * md)
+{
+ URI *ret;
int i;
int j;
int havePreview;
@@ -781,47 +785,57 @@
if (md == NULL)
return NULL;
- ret = MALLOC(sizeof(URI));
+ ret = MALLOC (sizeof (URI));
ret->type = ksk;
ret->data.ksk.keywordCount = 0;
ret->data.ksk.keywords = NULL;
havePreview = 0;
- for (i=md->itemCount-1;i>=0;i--) {
- if (md->items[i].type == EXTRACTOR_THUMBNAIL_DATA) {
- havePreview++;
- } else {
- for (j=md->itemCount-1;j>i;j--) {
- if (0 == strcmp(md->items[i].data,
- md->items[j].data)) {
- havePreview++; /* duplicate! */
- break;
- }
- }
+ for (i = md->itemCount - 1; i >= 0; i--)
+ {
+ if (md->items[i].type == EXTRACTOR_THUMBNAIL_DATA)
+ {
+ havePreview++;
+ }
+ else
+ {
+ for (j = md->itemCount - 1; j > i; j--)
+ {
+ if (0 == strcmp (md->items[i].data, md->items[j].data))
+ {
+ havePreview++; /* duplicate! */
+ break;
+ }
+ }
+ }
}
- }
- GROW(ret->data.ksk.keywords,
- ret->data.ksk.keywordCount,
- md->itemCount - havePreview);
- for (i=md->itemCount-1;i>=0;i--) {
- if (md->items[i].type == EXTRACTOR_THUMBNAIL_DATA) {
- havePreview--;
- } else {
- add = 1;
- for (j=md->itemCount-1;j>i;j--) {
- if (0 == strcmp(md->items[i].data,
- md->items[j].data)) {
- havePreview--;
- add = 0;
- break;
- }
- }
- if (add == 1) {
- GE_ASSERT(NULL, md->items[i].data != NULL);
- ret->data.ksk.keywords[i-havePreview]
- = STRDUP(md->items[i].data);
- }
+ GROW (ret->data.ksk.keywords,
+ ret->data.ksk.keywordCount, md->itemCount - havePreview);
+ for (i = md->itemCount - 1; i >= 0; i--)
+ {
+ if (md->items[i].type == EXTRACTOR_THUMBNAIL_DATA)
+ {
+ havePreview--;
+ }
+ else
+ {
+ add = 1;
+ for (j = md->itemCount - 1; j > i; j--)
+ {
+ if (0 == strcmp (md->items[i].data, md->items[j].data))
+ {
+ havePreview--;
+ add = 0;
+ break;
+ }
+ }
+ if (add == 1)
+ {
+ GE_ASSERT (NULL, md->items[i].data != NULL);
+ ret->data.ksk.keywords[i - havePreview]
+ = STRDUP (md->items[i].data);
+ }
+ }
}
- }
return ret;
}
@@ -829,24 +843,24 @@
* Convert a NULL-terminated array of keywords
* to an ECRS URI.
*/
-struct ECRS_URI * ECRS_keywordsToUri(const char * keyword[]) {
+struct ECRS_URI *
+ECRS_keywordsToUri (const char *keyword[])
+{
unsigned int count;
- URI * ret;
+ URI *ret;
unsigned int i;
count = 0;
while (keyword[count] != NULL)
count++;
- ret = MALLOC(sizeof(URI));
+ ret = MALLOC (sizeof (URI));
ret->type = ksk;
ret->data.ksk.keywordCount = 0;
ret->data.ksk.keywords = NULL;
- GROW(ret->data.ksk.keywords,
- ret->data.ksk.keywordCount,
- count);
- for (i=0;i<count;i++)
- ret->data.ksk.keywords[i] = STRDUP(keyword[i]);
+ GROW (ret->data.ksk.keywords, ret->data.ksk.keywordCount, count);
+ for (i = 0; i < count; i++)
+ ret->data.ksk.keywords[i] = STRDUP (keyword[i]);
return ret;
}
@@ -855,74 +869,75 @@
/**
* Are these two URIs equal?
*/
-int ECRS_equalsUri(const struct ECRS_URI * uri1,
- const struct ECRS_URI * uri2) {
+int
+ECRS_equalsUri (const struct ECRS_URI *uri1, const struct ECRS_URI *uri2)
+{
int ret;
int i;
int j;
- GE_ASSERT(NULL, uri1 != NULL);
- GE_ASSERT(NULL, uri2 != NULL);
+ GE_ASSERT (NULL, uri1 != NULL);
+ GE_ASSERT (NULL, uri2 != NULL);
if (uri1->type != uri2->type)
return NO;
- switch(uri1->type) {
- case chk:
- if (0 == memcmp(&uri1->data.fi,
- &uri2->data.fi,
- sizeof(FileIdentifier)))
- return YES;
- return NO;
- case sks:
- if (equalsHashCode512(&uri1->data.sks.namespace,
- &uri2->data.sks.namespace) &&
- equalsHashCode512(&uri1->data.sks.identifier,
- &uri2->data.sks.identifier) )
+ switch (uri1->type)
+ {
+ case chk:
+ if (0 == memcmp (&uri1->data.fi,
+ &uri2->data.fi, sizeof (FileIdentifier)))
+ return YES;
+ return NO;
+ case sks:
+ if (equalsHashCode512 (&uri1->data.sks.namespace,
+ &uri2->data.sks.namespace) &&
+ equalsHashCode512 (&uri1->data.sks.identifier,
+ &uri2->data.sks.identifier))
+ return YES;
+ return NO;
+ case ksk:
+ if (uri1->data.ksk.keywordCount != uri2->data.ksk.keywordCount)
+ return NO;
+ for (i = 0; i < uri1->data.ksk.keywordCount; i++)
+ {
+ ret = NO;
+ for (j = 0; j < uri2->data.ksk.keywordCount; j++)
+ {
+ if (0 == strcmp (uri1->data.ksk.keywords[i],
+ uri2->data.ksk.keywords[j]))
+ {
+ ret = YES;
+ break;
+ }
+ }
+ if (ret == NO)
+ return NO;
+ }
return YES;
- return NO;
- case ksk:
- if (uri1->data.ksk.keywordCount !=
- uri2->data.ksk.keywordCount)
+ case loc:
+ if (memcmp (&uri1->data.loc,
+ &uri2->data.loc,
+ sizeof (FileIdentifier) +
+ sizeof (PublicKey) +
+ sizeof (TIME_T) +
+ sizeof (unsigned short) + sizeof (unsigned short)) != 0)
+ return NO;
+ return YES;
+ default:
return NO;
- for (i=0;i<uri1->data.ksk.keywordCount;i++) {
- ret = NO;
- for (j=0;j<uri2->data.ksk.keywordCount;j++) {
- if (0 == strcmp(uri1->data.ksk.keywords[i],
- uri2->data.ksk.keywords[j])) {
- ret = YES;
- break;
- }
- }
- if (ret == NO)
- return NO;
}
- return YES;
- case loc:
- if (memcmp(&uri1->data.loc,
- &uri2->data.loc,
- sizeof(FileIdentifier) +
- sizeof(PublicKey) +
- sizeof(TIME_T) +
- sizeof(unsigned short) +
- sizeof(unsigned short)) != 0)
- return NO;
- return YES;
- default:
- return NO;
- }
}
/**
* Obtain the identity of the peer offering the data
* @return -1 if this is not a location URI, otherwise OK
*/
-int ECRS_getPeerFromUri(const struct ECRS_URI * uri,
- PeerIdentity * peer) {
+int
+ECRS_getPeerFromUri (const struct ECRS_URI *uri, PeerIdentity * peer)
+{
if (uri->type != loc)
return -1;
- hash(&uri->data.loc.peer,
- sizeof(PublicKey),
- &peer->hashPubKey);
+ hash (&uri->data.loc.peer, sizeof (PublicKey), &peer->hashPubKey);
return OK;
}
@@ -932,12 +947,13 @@
* @return NULL if argument is not a location URI
*/
struct ECRS_URI *
-ECRS_getContentUri(const struct ECRS_URI * uri) {
- struct ECRS_URI * ret;
+ECRS_getContentUri (const struct ECRS_URI *uri)
+{
+ struct ECRS_URI *ret;
if (uri->type != loc)
return NULL;
- ret = MALLOC(sizeof(struct ECRS_URI));
+ ret = MALLOC (sizeof (struct ECRS_URI));
ret->type = chk;
ret->data.fi = uri->data.loc.fi;
return ret;
@@ -957,27 +973,26 @@
* @return the location URI
*/
struct ECRS_URI *
-ECRS_uriFromLocation(const struct ECRS_URI * baseUri,
- const PublicKey * sender,
- TIME_T expirationTime,
- ECRS_SignFunction signer,
- void * signer_cls) {
- struct ECRS_URI * uri;
+ECRS_uriFromLocation (const struct ECRS_URI *baseUri,
+ const PublicKey * sender,
+ TIME_T expirationTime,
+ ECRS_SignFunction signer, void *signer_cls)
+{
+ struct ECRS_URI *uri;
if (baseUri->type != chk)
return NULL;
- uri = MALLOC(sizeof(struct ECRS_URI));
+ uri = MALLOC (sizeof (struct ECRS_URI));
uri->type = loc;
uri->data.loc.fi = baseUri->data.fi;
uri->data.loc.peer = *sender;
uri->data.loc.expirationTime = expirationTime;
- signer(signer_cls,
- sizeof(FileIdentifier) +
- sizeof(PeerIdentity) +
- sizeof(TIME_T),
- &uri->data.loc.fi,
- &uri->data.loc.contentSignature);
+ signer (signer_cls,
+ sizeof (FileIdentifier) +
+ sizeof (PeerIdentity) +
+ sizeof (TIME_T),
+ &uri->data.loc.fi, &uri->data.loc.contentSignature);
return uri;
}
Modified: GNUnet/src/applications/fs/ecrs/uri.h
===================================================================
--- GNUnet/src/applications/fs/ecrs/uri.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/uri.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -26,6 +26,6 @@
/**
* Generate a file URI.
*/
-char * createFileURI(const FileIdentifier * fi);
+char *createFileURI (const FileIdentifier * fi);
#endif
Modified: GNUnet/src/applications/fs/ecrs/uritest.c
===================================================================
--- GNUnet/src/applications/fs/ecrs/uritest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs/uritest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -32,184 +32,219 @@
#define ABORT() { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__);
return 1; }
-static int testKeyword() {
- char * uri;
- struct ECRS_URI * ret;
+static int
+testKeyword ()
+{
+ char *uri;
+ struct ECRS_URI *ret;
- if (NULL != ECRS_stringToUri(NULL, "gnunet://ecrs/ksk/++"))
- ABORT();
- ret = ECRS_stringToUri(NULL, "gnunet://ecrs/ksk/foo+bar");
+ if (NULL != ECRS_stringToUri (NULL, "gnunet://ecrs/ksk/++"))
+ ABORT ();
+ ret = ECRS_stringToUri (NULL, "gnunet://ecrs/ksk/foo+bar");
if (ret == NULL)
- ABORT();
- if (! ECRS_isKeywordUri(ret)) {
- ECRS_freeUri(ret);
- ABORT();
- }
- if ( (2 != ret->data.ksk.keywordCount) ||
- (0 != strcmp("foo", ret->data.ksk.keywords[0])) ||
- (0 != strcmp("bar", ret->data.ksk.keywords[1])) ) {
- ECRS_freeUri(ret);
- ABORT();
- }
+ ABORT ();
+ if (!ECRS_isKeywordUri (ret))
+ {
+ ECRS_freeUri (ret);
+ ABORT ();
+ }
+ if ((2 != ret->data.ksk.keywordCount) ||
+ (0 != strcmp ("foo", ret->data.ksk.keywords[0])) ||
+ (0 != strcmp ("bar", ret->data.ksk.keywords[1])))
+ {
+ ECRS_freeUri (ret);
+ ABORT ();
+ }
- uri = ECRS_uriToString(ret);
- if (0 != strcmp(uri,
- "gnunet://ecrs/ksk/foo+bar")) {
- FREE(uri);
- ECRS_freeUri(ret);
- ABORT();
- }
- FREE(uri);
- ECRS_freeUri(ret);
+ uri = ECRS_uriToString (ret);
+ if (0 != strcmp (uri, "gnunet://ecrs/ksk/foo+bar"))
+ {
+ FREE (uri);
+ ECRS_freeUri (ret);
+ ABORT ();
+ }
+ FREE (uri);
+ ECRS_freeUri (ret);
return 0;
}
-static int testLocation() {
- struct ECRS_URI * uri;
- char * uric;
- struct ECRS_URI * uri2;
+static int
+testLocation ()
+{
+ struct ECRS_URI *uri;
+ char *uric;
+ struct ECRS_URI *uri2;
PublicKey pk;
- struct PrivateKey * hk;
- struct ECRS_URI * baseURI;
+ struct PrivateKey *hk;
+ struct ECRS_URI *baseURI;
- baseURI = ECRS_stringToUri(NULL,
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.42");
- hk = makePrivateKey();
- getPublicKey(hk,
- &pk);
- uri = ECRS_uriFromLocation(baseURI,
- &pk,
- 43,
- (ECRS_SignFunction) &sign,
- hk);
- freePrivateKey(hk);
- if (uri == NULL) {
- GE_BREAK(NULL, 0);
- ECRS_freeUri(baseURI);
- return 1;
- }
- if (! ECRS_isLocationUri(uri)) {
- GE_BREAK(NULL, 0);
- ECRS_freeUri(uri);
- ECRS_freeUri(baseURI);
- return 1;
- }
- uri2 = ECRS_getContentUri(uri);
- if (! ECRS_equalsUri(baseURI,
- uri2)) {
- GE_BREAK(NULL, 0);
- ECRS_freeUri(uri);
- ECRS_freeUri(uri2);
- ECRS_freeUri(baseURI);
- return 1;
- }
- ECRS_freeUri(uri2);
- ECRS_freeUri(baseURI);
- uric = ECRS_uriToString(uri);
+ baseURI =
+ ECRS_stringToUri (NULL,
+
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.42");
+ hk = makePrivateKey ();
+ getPublicKey (hk, &pk);
+ uri = ECRS_uriFromLocation (baseURI,
+ &pk, 43, (ECRS_SignFunction) & sign, hk);
+ freePrivateKey (hk);
+ if (uri == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ ECRS_freeUri (baseURI);
+ return 1;
+ }
+ if (!ECRS_isLocationUri (uri))
+ {
+ GE_BREAK (NULL, 0);
+ ECRS_freeUri (uri);
+ ECRS_freeUri (baseURI);
+ return 1;
+ }
+ uri2 = ECRS_getContentUri (uri);
+ if (!ECRS_equalsUri (baseURI, uri2))
+ {
+ GE_BREAK (NULL, 0);
+ ECRS_freeUri (uri);
+ ECRS_freeUri (uri2);
+ ECRS_freeUri (baseURI);
+ return 1;
+ }
+ ECRS_freeUri (uri2);
+ ECRS_freeUri (baseURI);
+ uric = ECRS_uriToString (uri);
#if 0
/* not for the faint of heart: */
- printf("URI: `%s'\n", uric);
+ printf ("URI: `%s'\n", uric);
#endif
- uri2 = ECRS_stringToUri(NULL, uric);
- FREE(uric);
- if (uri2 == NULL) {
- GE_BREAK(NULL, 0);
- ECRS_freeUri(uri);
- return 1;
- }
- if (YES != ECRS_equalsUri(uri,
- uri2)) {
- GE_BREAK(NULL, 0);
- ECRS_freeUri(uri);
- ECRS_freeUri(uri2);
- return 1;
- }
- ECRS_freeUri(uri2);
- ECRS_freeUri(uri);
+ uri2 = ECRS_stringToUri (NULL, uric);
+ FREE (uric);
+ if (uri2 == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ ECRS_freeUri (uri);
+ return 1;
+ }
+ if (YES != ECRS_equalsUri (uri, uri2))
+ {
+ GE_BREAK (NULL, 0);
+ ECRS_freeUri (uri);
+ ECRS_freeUri (uri2);
+ return 1;
+ }
+ ECRS_freeUri (uri2);
+ ECRS_freeUri (uri);
return 0;
}
-static int testNamespace(int i) {
- char * uri;
- struct ECRS_URI * ret;
+static int
+testNamespace (int i)
+{
+ char *uri;
+ struct ECRS_URI *ret;
- if (NULL != ECRS_stringToUri(NULL,
"gnunet://ecrs/sks/D1KJS9H2A82Q65VKQ0ML3RFU6U1D3VUK"))
- ABORT();
- if (NULL != ECRS_stringToUri(NULL,
"gnunet://ecrs/sks/D1KJS9H2A82Q65VKQ0ML3RFU6U1D3V/test"))
- ABORT();
- if (NULL != ECRS_stringToUri(NULL, "gnunet://ecrs/sks/test"))
- ABORT();
- ret = ECRS_stringToUri(NULL,
"gnunet://ecrs/sks/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820/test");
+ if (NULL !=
+ ECRS_stringToUri (NULL,
+ "gnunet://ecrs/sks/D1KJS9H2A82Q65VKQ0ML3RFU6U1D3VUK"))
+ ABORT ();
+ if (NULL !=
+ ECRS_stringToUri (NULL,
+
"gnunet://ecrs/sks/D1KJS9H2A82Q65VKQ0ML3RFU6U1D3V/test"))
+ ABORT ();
+ if (NULL != ECRS_stringToUri (NULL, "gnunet://ecrs/sks/test"))
+ ABORT ();
+ ret =
+ ECRS_stringToUri (NULL,
+
"gnunet://ecrs/sks/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820/test");
if (ret == NULL)
- ABORT();
- if (ECRS_isKeywordUri(ret)) {
- ECRS_freeUri(ret);
- ABORT();
- }
- if (! ECRS_isNamespaceUri(ret)) {
- ECRS_freeUri(ret);
- ABORT();
- }
+ ABORT ();
+ if (ECRS_isKeywordUri (ret))
+ {
+ ECRS_freeUri (ret);
+ ABORT ();
+ }
+ if (!ECRS_isNamespaceUri (ret))
+ {
+ ECRS_freeUri (ret);
+ ABORT ();
+ }
- uri = ECRS_uriToString(ret);
- if (0 != strcmp(uri,
-
"gnunet://ecrs/sks/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820/TOJB1NAAUVJKJAGQHRHS22N9I8VM32C0ESN4EFS836IT950E1MP7LGC5V2GE3LFO9U4BP23VQPTH8DPIOC2CONT9LM76ULVL00KAHVO"))
{
- ECRS_freeUri(ret);
- FREE(uri);
- ABORT();
- }
- FREE(uri);
- ECRS_freeUri(ret);
+ uri = ECRS_uriToString (ret);
+ if (0 != strcmp (uri,
+
"gnunet://ecrs/sks/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820/TOJB1NAAUVJKJAGQHRHS22N9I8VM32C0ESN4EFS836IT950E1MP7LGC5V2GE3LFO9U4BP23VQPTH8DPIOC2CONT9LM76ULVL00KAHVO"))
+ {
+ ECRS_freeUri (ret);
+ FREE (uri);
+ ABORT ();
+ }
+ FREE (uri);
+ ECRS_freeUri (ret);
return 0;
}
-static int testFile(int i) {
- char * uri;
- struct ECRS_URI * ret;
+static int
+testFile (int i)
+{
+ char *uri;
+ struct ECRS_URI *ret;
- if (NULL != ECRS_stringToUri(NULL,
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H00000440000.42"))
- ABORT();
- if (NULL != ECRS_stringToUri(NULL,
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000"))
- ABORT();
- if (NULL != ECRS_stringToUri(NULL,
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.FGH"))
- ABORT();
- ret = ECRS_stringToUri(NULL,
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.42");
+ if (NULL !=
+ ECRS_stringToUri (NULL,
+
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H00000440000.42"))
+ ABORT ();
+ if (NULL !=
+ ECRS_stringToUri (NULL,
+
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000"))
+ ABORT ();
+ if (NULL !=
+ ECRS_stringToUri (NULL,
+
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.FGH"))
+ ABORT ();
+ ret =
+ ECRS_stringToUri (NULL,
+
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.42");
if (ret == NULL)
- ABORT();
- if (ECRS_isKeywordUri(ret)) {
- ECRS_freeUri(ret);
- ABORT();
- }
- if (ECRS_isNamespaceUri(ret)) {
- ECRS_freeUri(ret);
- ABORT();
- }
- if (ntohll(ret->data.fi.file_length) != 42) {
- ECRS_freeUri(ret);
- ABORT();
- }
+ ABORT ();
+ if (ECRS_isKeywordUri (ret))
+ {
+ ECRS_freeUri (ret);
+ ABORT ();
+ }
+ if (ECRS_isNamespaceUri (ret))
+ {
+ ECRS_freeUri (ret);
+ ABORT ();
+ }
+ if (ntohll (ret->data.fi.file_length) != 42)
+ {
+ ECRS_freeUri (ret);
+ ABORT ();
+ }
- uri = ECRS_uriToString(ret);
- if (0 != strcmp(uri,
-
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.42"))
{
- FREE(uri);
- ECRS_freeUri(ret);
- ABORT();
- }
- FREE(uri);
- ECRS_freeUri(ret);
+ uri = ECRS_uriToString (ret);
+ if (0 != strcmp (uri,
+
"gnunet://ecrs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.42"))
+ {
+ FREE (uri);
+ ECRS_freeUri (ret);
+ ABORT ();
+ }
+ FREE (uri);
+ ECRS_freeUri (ret);
return 0;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
int i;
- failureCount += testKeyword();
- failureCount += testLocation();
- for (i=0;i<255;i++) {
- failureCount += testNamespace(i);
- failureCount += testFile(i);
- }
+ failureCount += testKeyword ();
+ failureCount += testLocation ();
+ for (i = 0; i < 255; i++)
+ {
+ failureCount += testNamespace (i);
+ failureCount += testFile (i);
+ }
if (failureCount != 0)
return 1;
return 0;
Modified: GNUnet/src/applications/fs/ecrs_core.c
===================================================================
--- GNUnet/src/applications/fs/ecrs_core.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs_core.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -43,50 +43,41 @@
* @return OK on success, SYSERR if data does not
* match the query
*/
-int fileBlockEncode(const DBlock * data,
- unsigned int len,
- const HashCode512 * query,
- Datastore_Value ** value) {
+int
+fileBlockEncode (const DBlock * data,
+ unsigned int len,
+ const HashCode512 * query, Datastore_Value ** value)
+{
HashCode512 hc;
SESSIONKEY skey;
- INITVECTOR iv; /* initial value */
- Datastore_Value * val;
- DBlock * db;
+ INITVECTOR iv; /* initial value */
+ Datastore_Value *val;
+ DBlock *db;
- GE_ASSERT(NULL, len >= sizeof(DBlock));
- GE_ASSERT(NULL, (data!=NULL) && (query != NULL));
- hash(&data[1],
- len - sizeof(DBlock),
- &hc);
- hashToKey(&hc,
- &skey,
- &iv);
- val = MALLOC(sizeof(Datastore_Value) + len);
- val->size = htonl(sizeof(Datastore_Value) + len);
- val->type = htonl(D_BLOCK);
- val->prio = htonl(0);
- val->anonymityLevel = htonl(0);
- val->expirationTime = htonll(0);
- db = (DBlock*) &val[1];
- db->type = htonl(D_BLOCK);
- GE_ASSERT(NULL,
- len - sizeof(DBlock) < MAX_BUFFER_SIZE);
- GE_ASSERT(NULL,
- len - sizeof(DBlock)
- == encryptBlock(&data[1],
- len - sizeof(DBlock),
- &skey,
- &iv,
- &db[1]));
- hash(&db[1],
- len - sizeof(DBlock),
- &hc);
- if (! equalsHashCode512(query,
- &hc)) {
- FREE(val);
- *value = NULL;
- return SYSERR;
- }
+ GE_ASSERT (NULL, len >= sizeof (DBlock));
+ GE_ASSERT (NULL, (data != NULL) && (query != NULL));
+ hash (&data[1], len - sizeof (DBlock), &hc);
+ hashToKey (&hc, &skey, &iv);
+ val = MALLOC (sizeof (Datastore_Value) + len);
+ val->size = htonl (sizeof (Datastore_Value) + len);
+ val->type = htonl (D_BLOCK);
+ val->prio = htonl (0);
+ val->anonymityLevel = htonl (0);
+ val->expirationTime = htonll (0);
+ db = (DBlock *) & val[1];
+ db->type = htonl (D_BLOCK);
+ GE_ASSERT (NULL, len - sizeof (DBlock) < MAX_BUFFER_SIZE);
+ GE_ASSERT (NULL,
+ len - sizeof (DBlock)
+ == encryptBlock (&data[1],
+ len - sizeof (DBlock), &skey, &iv, &db[1]));
+ hash (&db[1], len - sizeof (DBlock), &hc);
+ if (!equalsHashCode512 (query, &hc))
+ {
+ FREE (val);
+ *value = NULL;
+ return SYSERR;
+ }
*value = val;
return OK;
}
@@ -95,13 +86,11 @@
* Get the key that will be used to decrypt
* a certain block of data.
*/
-void fileBlockGetKey(const DBlock * data,
- unsigned int len,
- HashCode512 * key) {
- GE_ASSERT(NULL, len >= sizeof(DBlock));
- hash(&data[1],
- len - sizeof(DBlock),
- key);
+void
+fileBlockGetKey (const DBlock * data, unsigned int len, HashCode512 * key)
+{
+ GE_ASSERT (NULL, len >= sizeof (DBlock));
+ hash (&data[1], len - sizeof (DBlock), key);
}
/**
@@ -110,40 +99,36 @@
*
* @param db the block in plaintext
*/
-void fileBlockGetQuery(const DBlock * db,
- unsigned int len,
- HashCode512 * query) {
- char * tmp;
- const char * data;
+void
+fileBlockGetQuery (const DBlock * db, unsigned int len, HashCode512 * query)
+{
+ char *tmp;
+ const char *data;
HashCode512 hc;
SESSIONKEY skey;
INITVECTOR iv;
- GE_ASSERT(NULL, len >= sizeof(DBlock));
- data = (const char*) &db[1];
- len -= sizeof(DBlock);
- GE_ASSERT(NULL, len < MAX_BUFFER_SIZE);
- hash(data, len, &hc);
- hashToKey(&hc,
- &skey,
- &iv);
- tmp = MALLOC(len);
- GE_ASSERT(NULL, len == encryptBlock(data,
- len,
- &skey,
- &iv,
- tmp));
- hash(tmp, len, query);
- FREE(tmp);
+ GE_ASSERT (NULL, len >= sizeof (DBlock));
+ data = (const char *) &db[1];
+ len -= sizeof (DBlock);
+ GE_ASSERT (NULL, len < MAX_BUFFER_SIZE);
+ hash (data, len, &hc);
+ hashToKey (&hc, &skey, &iv);
+ tmp = MALLOC (len);
+ GE_ASSERT (NULL, len == encryptBlock (data, len, &skey, &iv, tmp));
+ hash (tmp, len, query);
+ FREE (tmp);
}
-unsigned int getTypeOfBlock(unsigned int size,
- const DBlock * data) {
- if (size <= 4) {
- GE_BREAK(NULL, 0);
- return ANY_BLOCK; /* signal error */
- }
- return ntohl(*((const unsigned int*)data));
+unsigned int
+getTypeOfBlock (unsigned int size, const DBlock * data)
+{
+ if (size <= 4)
+ {
+ GE_BREAK (NULL, 0);
+ return ANY_BLOCK; /* signal error */
+ }
+ return ntohl (*((const unsigned int *) data));
}
/**
@@ -155,117 +140,123 @@
* @return SYSERR if the content is invalid or
* the content type is not known
*/
-int getQueryFor(unsigned int size,
- const DBlock * data,
- int verify,
- HashCode512 * query) {
+int
+getQueryFor (unsigned int size,
+ const DBlock * data, int verify, HashCode512 * query)
+{
unsigned int type;
- type = getTypeOfBlock(size, data);
- if (type == ANY_BLOCK) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- switch (type) {
- case D_BLOCK:
- /* CHK: hash of content == query */
- hash(&data[1],
- size - sizeof(DBlock),
- query);
- return OK;
- case S_BLOCK: {
- const SBlock * sb;
- if (size < sizeof(SBlock)) {
- GE_BREAK(NULL, 0);
+ type = getTypeOfBlock (size, data);
+ if (type == ANY_BLOCK)
+ {
+ GE_BREAK (NULL, 0);
return SYSERR;
}
- sb = (const SBlock*) data;
- if ( (verify == YES) &&
- (OK != verifySig(&sb->identifier,
- size
- - sizeof(Signature)
- - sizeof(PublicKey)
- - sizeof(unsigned int),
- &sb->signature,
- &sb->subspace)) ) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- *query = sb->identifier;
- return OK;
- }
- case K_BLOCK: {
- const KBlock * kb;
- if (size < sizeof(KBlock)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- kb = (const KBlock*) data;
- if ( (verify == YES) &&
- ( (OK != verifySig(&kb[1],
- size - sizeof(KBlock),
- &kb->signature,
- &kb->keyspace)) ) ) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- hash(&kb->keyspace,
- sizeof(PublicKey),
- query);
- return OK;
- }
- case N_BLOCK: {
- const NBlock * nb;
- if (size < sizeof(NBlock)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- nb = (const NBlock*) data;
- if ( (verify == YES) &&
- (OK != verifySig(&nb->identifier,
- size
- - sizeof(Signature)
- - sizeof(PublicKey)
- - sizeof(unsigned int),
- &nb->signature,
- &nb->subspace)) ) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- *query = nb->namespace; /* XOR with all zeros makes no difference... */
- return OK;
- }
- case KN_BLOCK: {
- const KNBlock * kb;
- if (size < sizeof(KNBlock)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- kb = (const KNBlock*) data;
- if ( (verify == YES) &&
- ( (OK != verifySig(&kb->nblock,
- size
- - sizeof(KBlock)
- - sizeof(unsigned int),
- &kb->kblock.signature,
- &kb->kblock.keyspace)) ) ) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- hash(&kb->kblock.keyspace,
- sizeof(PublicKey),
- query);
- return OK;
- }
- case ONDEMAND_BLOCK: {
- GE_BREAK(NULL, 0); /* should never be used here! */
- return SYSERR;
- }
- default: {
- GE_BREAK(NULL, 0); /* unknown block type */
- return SYSERR;
- }
- } /* end switch */
+ switch (type)
+ {
+ case D_BLOCK:
+ /* CHK: hash of content == query */
+ hash (&data[1], size - sizeof (DBlock), query);
+ return OK;
+ case S_BLOCK:
+ {
+ const SBlock *sb;
+ if (size < sizeof (SBlock))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ sb = (const SBlock *) data;
+ if ((verify == YES) &&
+ (OK != verifySig (&sb->identifier,
+ size
+ - sizeof (Signature)
+ - sizeof (PublicKey)
+ - sizeof (unsigned int),
+ &sb->signature, &sb->subspace)))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ *query = sb->identifier;
+ return OK;
+ }
+ case K_BLOCK:
+ {
+ const KBlock *kb;
+ if (size < sizeof (KBlock))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ kb = (const KBlock *) data;
+ if ((verify == YES) &&
+ ((OK != verifySig (&kb[1],
+ size - sizeof (KBlock),
+ &kb->signature, &kb->keyspace))))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ hash (&kb->keyspace, sizeof (PublicKey), query);
+ return OK;
+ }
+ case N_BLOCK:
+ {
+ const NBlock *nb;
+ if (size < sizeof (NBlock))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ nb = (const NBlock *) data;
+ if ((verify == YES) &&
+ (OK != verifySig (&nb->identifier,
+ size
+ - sizeof (Signature)
+ - sizeof (PublicKey)
+ - sizeof (unsigned int),
+ &nb->signature, &nb->subspace)))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ *query = nb->namespace; /* XOR with all zeros makes no difference... */
+ return OK;
+ }
+ case KN_BLOCK:
+ {
+ const KNBlock *kb;
+ if (size < sizeof (KNBlock))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ kb = (const KNBlock *) data;
+ if ((verify == YES) &&
+ ((OK != verifySig (&kb->nblock,
+ size
+ - sizeof (KBlock)
+ - sizeof (unsigned int),
+ &kb->kblock.signature, &kb->kblock.keyspace))))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ hash (&kb->kblock.keyspace, sizeof (PublicKey), query);
+ return OK;
+ }
+ case ONDEMAND_BLOCK:
+ {
+ GE_BREAK (NULL, 0); /* should never be used here! */
+ return SYSERR;
+ }
+ default:
+ {
+ GE_BREAK (NULL, 0); /* unknown block type */
+ return SYSERR;
+ }
+ } /* end switch */
}
@@ -284,59 +275,57 @@
* NO; SYSERR if the keyCount does not match the
* query type
*/
-int isDatumApplicable(unsigned int type,
- unsigned int size,
- const DBlock * data,
- const HashCode512 * hc,
- unsigned int keyCount,
- const HashCode512 * keys) {
+int
+isDatumApplicable (unsigned int type,
+ unsigned int size,
+ const DBlock * data,
+ const HashCode512 * hc,
+ unsigned int keyCount, const HashCode512 * keys)
+{
HashCode512 h;
- if (type != getTypeOfBlock(size, data)) {
- GE_BREAK(NULL, 0);
- return SYSERR; /* type mismatch */
- }
- if (! equalsHashCode512(hc, &keys[0])) {
- GE_BREAK(NULL, 0); /* mismatch between primary queries,
- we should not even see those here. */
- return SYSERR;
- }
+ if (type != getTypeOfBlock (size, data))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR; /* type mismatch */
+ }
+ if (!equalsHashCode512 (hc, &keys[0]))
+ {
+ GE_BREAK (NULL, 0); /* mismatch between primary queries,
+ we should not even see those here. */
+ return SYSERR;
+ }
if (keyCount == 0)
- return YES; /* request was to match only primary key */
- switch (type) {
- case S_BLOCK:
- if (keyCount != 2)
- return SYSERR; /* no match */
- hash(&((const SBlock*)data)->subspace,
- sizeof(PublicKey),
- &h);
- if (equalsHashCode512(&keys[1],
- &h))
+ return YES; /* request was to match only primary key */
+ switch (type)
+ {
+ case S_BLOCK:
+ if (keyCount != 2)
+ return SYSERR; /* no match */
+ hash (&((const SBlock *) data)->subspace, sizeof (PublicKey), &h);
+ if (equalsHashCode512 (&keys[1], &h))
+ return OK;
+ return SYSERR;
+ case N_BLOCK:
+ if (keyCount != 2)
+ return SYSERR; /* no match */
+ hash (&((const NBlock *) data)->subspace, sizeof (PublicKey), &h);
+ if (!equalsHashCode512 (&keys[1], &h))
+ return SYSERR;
return OK;
- return SYSERR;
- case N_BLOCK:
- if (keyCount != 2)
- return SYSERR; /* no match */
- hash(&((const NBlock*)data)->subspace,
- sizeof(PublicKey),
- &h);
- if (! equalsHashCode512(&keys[1],
- &h))
+ case D_BLOCK:
+ case K_BLOCK:
+ case KN_BLOCK:
+ if (keyCount != 1)
+ GE_BREAK (NULL, 0); /* keyCount should be 1 */
+ return OK; /* if query matches, everything matches! */
+ case ANY_BLOCK:
+ GE_BREAK (NULL, 0); /* block type should be known */
return SYSERR;
- return OK;
- case D_BLOCK:
- case K_BLOCK:
- case KN_BLOCK:
- if (keyCount != 1)
- GE_BREAK(NULL, 0); /* keyCount should be 1 */
- return OK; /* if query matches, everything matches! */
- case ANY_BLOCK:
- GE_BREAK(NULL, 0); /* block type should be known */
- return SYSERR;
- default:
- GE_BREAK(NULL, 0); /* unknown block type */
- return SYSERR;
- }
+ default:
+ GE_BREAK (NULL, 0); /* unknown block type */
+ return SYSERR;
+ }
}
/* end of ecrs_core.c */
Modified: GNUnet/src/applications/fs/ecrs_core_test.c
===================================================================
--- GNUnet/src/applications/fs/ecrs_core_test.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/ecrs_core_test.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,48 +30,38 @@
#define CHECK(a,b) { if (! (a)) { fprintf(stderr, "Error at %s:%d\n",
__FILE__, __LINE__); FREENONNULL(b); return 1; } }
-static int testEC() {
- DBlock * data;
- Datastore_Value * value;
+static int
+testEC ()
+{
+ DBlock *data;
+ Datastore_Value *value;
HashCode512 query;
HashCode512 key;
unsigned int len;
- len = sizeof(DBlock) + 42;
- data = MALLOC(len);
- memset(&data[1], rand(), len - sizeof(DBlock));
- data->type = htonl(D_BLOCK);
- CHECK(D_BLOCK == getTypeOfBlock(len,
- data),
- data);
- fileBlockGetKey(data, len, &key);
- fileBlockGetQuery(data, len, &query);
- CHECK(OK == fileBlockEncode(data,
- len,
- &query,
- &value),
- data);
- memcpy(data,
- &value[1],
- len);
- FREE(value);
- CHECK(YES == isDatumApplicable(D_BLOCK,
- len,
- data,
- &query,
- 1,
- &query),
- data);
- FREE(data);
+ len = sizeof (DBlock) + 42;
+ data = MALLOC (len);
+ memset (&data[1], rand (), len - sizeof (DBlock));
+ data->type = htonl (D_BLOCK);
+ CHECK (D_BLOCK == getTypeOfBlock (len, data), data);
+ fileBlockGetKey (data, len, &key);
+ fileBlockGetQuery (data, len, &query);
+ CHECK (OK == fileBlockEncode (data, len, &query, &value), data);
+ memcpy (data, &value[1], len);
+ FREE (value);
+ CHECK (YES == isDatumApplicable (D_BLOCK,
+ len, data, &query, 1, &query), data);
+ FREE (data);
return 0;
}
-int main(int argc,
- char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
- failureCount += testEC();
- fprintf(stderr, "\n");
+ failureCount += testEC ();
+ fprintf (stderr, "\n");
if (failureCount != 0)
return 1;
return 0;
Modified: GNUnet/src/applications/fs/fsui/deserialize.c
===================================================================
--- GNUnet/src/applications/fs/fsui/deserialize.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/fsui/deserialize.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -32,97 +32,104 @@
#include "fsui.h"
-static int read_int(int fd,
- int * val) {
+static int
+read_int (int fd, int *val)
+{
int big;
- if (sizeof(int) != READ(fd, &big, sizeof(int))) \
- return SYSERR; \
- *val = ntohl(big);
+ if (sizeof (int) != READ (fd, &big, sizeof (int)))
+ return SYSERR;
+ *val = ntohl (big);
return OK;
}
#define READINT(a) if (OK != read_int(fd, (int*) &a)) return SYSERR;
-static int read_long(int fd,
- long long * val) {
+static int
+read_long (int fd, long long *val)
+{
long long big;
- if (sizeof(long long) != READ(fd, &big, sizeof(long long))) \
- return SYSERR; \
- *val = ntohll(big);
+ if (sizeof (long long) != READ (fd, &big, sizeof (long long)))
+ return SYSERR;
+ *val = ntohll (big);
return OK;
}
#define READLONG(a) if (OK != read_long(fd, (long long*) &a)) return SYSERR;
-static struct ECRS_URI * read_uri(struct GE_Context * ectx,
- int fd) {
- char * buf;
- struct ECRS_URI * ret;
+static struct ECRS_URI *
+read_uri (struct GE_Context *ectx, int fd)
+{
+ char *buf;
+ struct ECRS_URI *ret;
unsigned int size;
- if (OK != read_int(fd, (int*) &size))
+ if (OK != read_int (fd, (int *) &size))
return NULL;
- buf = MALLOC(size+1);
+ buf = MALLOC (size + 1);
buf[size] = '\0';
- if (size != READ(fd,
- buf,
- size)) {
- FREE(buf);
- return NULL;
- }
- ret = ECRS_stringToUri(ectx, buf);
- GE_BREAK(ectx, ret != NULL);
- FREE(buf);
+ if (size != READ (fd, buf, size))
+ {
+ FREE (buf);
+ return NULL;
+ }
+ ret = ECRS_stringToUri (ectx, buf);
+ GE_BREAK (ectx, ret != NULL);
+ FREE (buf);
return ret;
}
#define READURI(u) if (NULL == (u = read_uri(ectx, fd))) return SYSERR;
-static char * read_string(int fd,
- unsigned int maxLen) {
- char * buf;
+static char *
+read_string (int fd, unsigned int maxLen)
+{
+ char *buf;
unsigned int big;
- if (OK != read_int(fd, (int*) &big))
+ if (OK != read_int (fd, (int *) &big))
return NULL;
if (big > maxLen)
return NULL;
- buf = MALLOC(big + 1);
+ buf = MALLOC (big + 1);
buf[big] = '\0';
- if (big != READ(fd, buf, big)) {
- FREE(buf);
- return NULL;
- }
+ if (big != READ (fd, buf, big))
+ {
+ FREE (buf);
+ return NULL;
+ }
return buf;
}
#define READSTRING(c, max) if (NULL == (c = read_string(fd, max))) return
SYSERR;
-static void fixState(FSUI_State * state) {
- switch (*state) { /* try to correct errors */
- case FSUI_ACTIVE:
- *state = FSUI_PENDING;
- break;
- case FSUI_PENDING:
- case FSUI_COMPLETED_JOINED:
- case FSUI_ABORTED_JOINED:
- case FSUI_ERROR_JOINED:
- break;
- case FSUI_ERROR:
- *state = FSUI_ERROR_JOINED;
- break;
- case FSUI_ABORTED:
- *state = FSUI_ABORTED_JOINED;
- break;
- case FSUI_COMPLETED:
- *state = FSUI_COMPLETED_JOINED;
- break;
- default:
- *state = FSUI_ERROR_JOINED;
- break;
- }
+static void
+fixState (FSUI_State * state)
+{
+ switch (*state)
+ { /* try to correct errors */
+ case FSUI_ACTIVE:
+ *state = FSUI_PENDING;
+ break;
+ case FSUI_PENDING:
+ case FSUI_COMPLETED_JOINED:
+ case FSUI_ABORTED_JOINED:
+ case FSUI_ERROR_JOINED:
+ break;
+ case FSUI_ERROR:
+ *state = FSUI_ERROR_JOINED;
+ break;
+ case FSUI_ABORTED:
+ *state = FSUI_ABORTED_JOINED;
+ break;
+ case FSUI_COMPLETED:
+ *state = FSUI_COMPLETED_JOINED;
+ break;
+ default:
+ *state = FSUI_ERROR_JOINED;
+ break;
+ }
}
@@ -132,37 +139,37 @@
* @return OK on success, SYSERR on error
*/
static struct ECRS_MetaData *
-read_meta(struct GE_Context * ectx,
- int fd) {
+read_meta (struct GE_Context *ectx, int fd)
+{
unsigned int size;
- char * buf;
- struct ECRS_MetaData * meta;
+ char *buf;
+ struct ECRS_MetaData *meta;
- if (read_int(fd, (int*)&size) != OK) {
- GE_BREAK(ectx, 0);
- return NULL;
- }
- if (size > 1024 * 1024) {
- GE_BREAK(ectx, 0);
- return NULL;
- }
- buf = MALLOC(size);
- if (size != READ(fd,
- buf,
- size)) {
- FREE(buf);
- GE_BREAK(ectx, 0);
- return NULL;
- }
- meta = ECRS_deserializeMetaData(ectx,
- buf,
- size);
- if (meta == NULL) {
- FREE(buf);
- GE_BREAK(ectx, 0);
- return NULL;
- }
- FREE(buf);
+ if (read_int (fd, (int *) &size) != OK)
+ {
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
+ if (size > 1024 * 1024)
+ {
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
+ buf = MALLOC (size);
+ if (size != READ (fd, buf, size))
+ {
+ FREE (buf);
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
+ meta = ECRS_deserializeMetaData (ectx, buf, size);
+ if (meta == NULL)
+ {
+ FREE (buf);
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
+ FREE (buf);
return meta;
}
@@ -171,24 +178,25 @@
*
* @return OK on success, SYSERR on error
*/
-static int readFileInfo(struct GE_Context * ectx,
- int fd,
- ECRS_FileInfo * fi) {
- fi->meta = read_meta(ectx, fd);
- if (fi->meta == NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+static int
+readFileInfo (struct GE_Context *ectx, int fd, ECRS_FileInfo * fi)
+{
+ fi->meta = read_meta (ectx, fd);
+ if (fi->meta == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
fi->uri = NULL;
- fi->uri
- = read_uri(ectx, fd);
- if (fi->uri == NULL) {
- ECRS_freeMetaData(fi->meta);
- fi->meta = NULL;
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ fi->uri = read_uri (ectx, fd);
+ if (fi->uri == NULL)
+ {
+ ECRS_freeMetaData (fi->meta);
+ fi->meta = NULL;
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
return OK;
}
@@ -202,559 +210,553 @@
* list (these two cannot be distinguished)
*/
static FSUI_DownloadList *
-readDownloadList(struct GE_Context * ectx,
- int fd,
- FSUI_Context * ctx,
- FSUI_DownloadList * parent) {
- FSUI_DownloadList * ret;
- FSUI_SearchList * pos;
+readDownloadList (struct GE_Context *ectx,
+ int fd, FSUI_Context * ctx, FSUI_DownloadList * parent)
+{
+ FSUI_DownloadList *ret;
+ FSUI_SearchList *pos;
unsigned int big;
int i;
int ok;
int soff;
- GE_ASSERT(ectx, ctx != NULL);
- if ( (OK != read_int(fd, (int*) &big)) ||
- (big == 0) )
+ GE_ASSERT (ectx, ctx != NULL);
+ if ((OK != read_int (fd, (int *) &big)) || (big == 0))
return NULL;
- ret = MALLOC(sizeof(FSUI_DownloadList));
- memset(ret,
- 0,
- sizeof(FSUI_DownloadList));
+ ret = MALLOC (sizeof (FSUI_DownloadList));
+ memset (ret, 0, sizeof (FSUI_DownloadList));
ret->ctx = ctx;
- if ( (OK != read_int(fd, (int*) &soff)) ||
- (OK != read_int(fd, (int*) &ret->state)) ||
- (OK != read_int(fd, (int*) &ret->is_recursive)) ||
- (OK != read_int(fd, (int*) &ret->is_directory)) ||
- (OK != read_int(fd, (int*) &ret->anonymityLevel)) ||
- (OK != read_int(fd, (int*) &ret->completedDownloadsCount)) ||
- (OK != read_long(fd, (long long*) &ret->total)) ||
- (OK != read_long(fd, (long long*) &ret->completed)) ||
- (OK != read_long(fd, (long long*) &ret->runTime)) ||
- (OK != read_int(fd, (int*) &big)) ||
- (big > 1024 * 1024) ) {
- GE_BREAK(NULL, 0);
- FREE(ret);
- return NULL;
- }
- fixState(&ret->state);
- ret->filename = MALLOC(big+1);
+ if ((OK != read_int (fd, (int *) &soff)) ||
+ (OK != read_int (fd, (int *) &ret->state)) ||
+ (OK != read_int (fd, (int *) &ret->is_recursive)) ||
+ (OK != read_int (fd, (int *) &ret->is_directory)) ||
+ (OK != read_int (fd, (int *) &ret->anonymityLevel)) ||
+ (OK != read_int (fd, (int *) &ret->completedDownloadsCount)) ||
+ (OK != read_long (fd, (long long *) &ret->total)) ||
+ (OK != read_long (fd, (long long *) &ret->completed)) ||
+ (OK != read_long (fd, (long long *) &ret->runTime)) ||
+ (OK != read_int (fd, (int *) &big)) || (big > 1024 * 1024))
+ {
+ GE_BREAK (NULL, 0);
+ FREE (ret);
+ return NULL;
+ }
+ fixState (&ret->state);
+ ret->filename = MALLOC (big + 1);
ret->filename[big] = '\0';
- if (big != READ(fd, ret->filename, big)) {
- GE_BREAK(ectx, 0);
- FREE(ret->filename);
- FREE(ret);
- return NULL;
- }
- if (OK != readFileInfo(ectx,
- fd,
- &ret->fi)) {
- GE_BREAK(NULL, 0);
- FREE(ret->filename);
- FREE(ret);
- return NULL;
- }
+ if (big != READ (fd, ret->filename, big))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (ret->filename);
+ FREE (ret);
+ return NULL;
+ }
+ if (OK != readFileInfo (ectx, fd, &ret->fi))
+ {
+ GE_BREAK (NULL, 0);
+ FREE (ret->filename);
+ FREE (ret);
+ return NULL;
+ }
if (ret->completedDownloadsCount > 0)
ret->completedDownloads
- = MALLOC(sizeof(struct ECRS_URI *) *
- ret->completedDownloadsCount);
+ = MALLOC (sizeof (struct ECRS_URI *) * ret->completedDownloadsCount);
ok = YES;
- for (i=0;i<ret->completedDownloadsCount;i++) {
- ret->completedDownloads[i] = read_uri(ectx, fd);
- if (ret->completedDownloads[i] == NULL) {
- GE_BREAK(NULL, 0);
- ok = NO;
+ for (i = 0; i < ret->completedDownloadsCount; i++)
+ {
+ ret->completedDownloads[i] = read_uri (ectx, fd);
+ if (ret->completedDownloads[i] == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ ok = NO;
+ }
}
- }
- if (NO == ok) {
- FREE(ret->filename);
- ECRS_freeUri(ret->fi.uri);
- ECRS_freeMetaData(ret->fi.meta);
- for (i=0;i<ret->completedDownloadsCount;i++) {
- if (ret->completedDownloads[i] != NULL)
- ECRS_freeUri(ret->completedDownloads[i]);
+ if (NO == ok)
+ {
+ FREE (ret->filename);
+ ECRS_freeUri (ret->fi.uri);
+ ECRS_freeMetaData (ret->fi.meta);
+ for (i = 0; i < ret->completedDownloadsCount; i++)
+ {
+ if (ret->completedDownloads[i] != NULL)
+ ECRS_freeUri (ret->completedDownloads[i]);
+ }
+ FREE (ret->completedDownloads);
+ FREE (ret);
+ GE_BREAK (NULL, 0);
+ return NULL;
}
- FREE(ret->completedDownloads);
- FREE(ret);
- GE_BREAK(NULL, 0);
- return NULL;
- }
ret->parent = parent;
- if (soff == 0) {
- ret->search = NULL;
- } else {
- pos = ctx->activeSearches;
- while (--soff > 0) {
- if (pos == NULL) {
- GE_BREAK(NULL, 0);
- break;
- }
- pos = pos->next;
+ if (soff == 0)
+ {
+ ret->search = NULL;
}
- ret->search = pos;
- if (pos != NULL) {
- GROW(pos->my_downloads,
- pos->my_downloads_size,
- pos->my_downloads_size + 1);
- pos->my_downloads[pos->my_downloads_size -1] = ret;
+ else
+ {
+ pos = ctx->activeSearches;
+ while (--soff > 0)
+ {
+ if (pos == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ break;
+ }
+ pos = pos->next;
+ }
+ ret->search = pos;
+ if (pos != NULL)
+ {
+ GROW (pos->my_downloads,
+ pos->my_downloads_size, pos->my_downloads_size + 1);
+ pos->my_downloads[pos->my_downloads_size - 1] = ret;
+ }
}
- }
- ret->next = readDownloadList(ectx,
- fd,
- ctx,
- parent);
- ret->child = readDownloadList(ectx,
- fd,
- ctx,
- ret);
+ ret->next = readDownloadList (ectx, fd, ctx, parent);
+ ret->child = readDownloadList (ectx, fd, ctx, ret);
#if DEBUG_PERSISTENCE
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSUI persistence: restoring download `%s': (%llu, %llu)\n",
- ret->filename,
- ret->completed,
- ret->total);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FSUI persistence: restoring download `%s': (%llu, %llu)\n",
+ ret->filename, ret->completed, ret->total);
#endif
return ret;
}
-static int checkMagic(int fd) {
+static int
+checkMagic (int fd)
+{
char magic[8];
- if (8 != READ(fd, magic, 8)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- if (0 != memcmp(magic,
- "FSUI01\n\0",
- 8)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
+ if (8 != READ (fd, magic, 8))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ if (0 != memcmp (magic, "FSUI01\n\0", 8))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
return OK;
}
-static int readCollection(int fd,
- struct FSUI_Context * ctx) {
+static int
+readCollection (int fd, struct FSUI_Context *ctx)
+{
int big;
/* deserialize collection data */
- READINT(big);
- if (big == 0) {
- ctx->collectionData = NULL;
- return OK;
- }
- if ( (big > 16 * 1024 * 1024) ||
- (big < sizeof(unsigned int) ) ) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- ctx->collectionData
- = MALLOC(big);
- if (big - sizeof(unsigned int) !=
- READ(fd,
- &ctx->collectionData[1],
- big - sizeof(unsigned int))) {
- FREE(ctx->collectionData);
- ctx->collectionData = NULL;
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
+ READINT (big);
+ if (big == 0)
+ {
+ ctx->collectionData = NULL;
+ return OK;
+ }
+ if ((big > 16 * 1024 * 1024) || (big < sizeof (unsigned int)))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ ctx->collectionData = MALLOC (big);
+ if (big - sizeof (unsigned int) !=
+ READ (fd, &ctx->collectionData[1], big - sizeof (unsigned int)))
+ {
+ FREE (ctx->collectionData);
+ ctx->collectionData = NULL;
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
return OK;
}
-static int readSearches(int fd,
- struct FSUI_Context * ctx) {
+static int
+readSearches (int fd, struct FSUI_Context *ctx)
+{
int big;
- FSUI_SearchList * list;
- FSUI_SearchList * last;
+ FSUI_SearchList *list;
+ FSUI_SearchList *last;
int i;
- ResultPending * rp;
- char * buf;
+ ResultPending *rp;
+ char *buf;
cron_t stime;
- while (1) {
- READINT(big);
- if (big == 0)
- return OK;
- list
- = MALLOC(sizeof(FSUI_SearchList));
- memset(list,
- 0,
- sizeof(FSUI_SearchList));
- if ( (OK != read_int(fd, (int*) &list->state)) ||
- (OK != read_int(fd, (int*) &list->maxResults)) ||
- (OK != read_long(fd, (long long*) &list->timeout)) ||
- (OK != read_long(fd, (long long*) &list->start_time)) ||
- (OK != read_long(fd, (long long*) &stime)) ||
- (OK != read_int(fd, (int*) &list->anonymityLevel)) ||
- (OK != read_int(fd, (int*) &list->sizeResultsReceived)) ||
- (OK != read_int(fd, (int*) &list->sizeUnmatchedResultsReceived)) ||
- (list->sizeResultsReceived > 1024*1024) ||
- (list->sizeUnmatchedResultsReceived > 1024*1024) ) {
- GE_BREAK(NULL, 0);
- break;
- }
- fixState(&list->state);
- if (stime > get_time())
- stime = get_time();
- list->start_time += get_time() - stime;
- buf = read_string(fd, 1024 * 1024);
- if (buf == NULL) {
- GE_BREAK(NULL, 0);
- break;
- }
- list->uri
- = ECRS_stringToUri(NULL, buf);
- FREE(buf);
- if (list->uri == NULL) {
- GE_BREAK(NULL, 0);
- break;
- }
- if (! ( ECRS_isKeywordUri(list->uri) ||
- ECRS_isNamespaceUri(list->uri)) ) {
- GE_BREAK(NULL, 0);
- break;
- }
- list->numberOfURIKeys
- = ECRS_countKeywordsOfUri(list->uri);
- if (list->sizeResultsReceived > 0) {
- list->resultsReceived
- = MALLOC(list->sizeResultsReceived *
- sizeof(ECRS_FileInfo));
- memset(list->resultsReceived,
- 0,
- list->sizeResultsReceived *
- sizeof(ECRS_FileInfo));
- }
- if (list->sizeUnmatchedResultsReceived > 0) {
- list->unmatchedResultsReceived
- = MALLOC(list->sizeUnmatchedResultsReceived *
- sizeof(ResultPending));
- memset(list->unmatchedResultsReceived,
- 0,
- list->sizeUnmatchedResultsReceived *
- sizeof(ResultPending));
- }
- for (i=0;i<list->sizeResultsReceived;i++)
- if (OK != readFileInfo(ctx->ectx,
- fd,
- &list->resultsReceived[i])) {
- GE_BREAK(NULL, 0);
- goto ERR;
- }
- for (i=0;i<list->sizeUnmatchedResultsReceived;i++) {
- rp = &list->unmatchedResultsReceived[i];
- if (OK != readFileInfo(ctx->ectx,
- fd,
- &rp->fi)) {
- GE_BREAK(NULL, 0);
- goto ERR;
- }
- if (OK != read_int(fd, (int*) &rp->matchingKeyCount)) {
- GE_BREAK(NULL, 0);
- goto ERR;
- }
- if ( (rp->matchingKeyCount > 1024) ||
- (rp->matchingKeyCount >= list->numberOfURIKeys) ) {
- GE_BREAK(NULL, 0);
- goto ERR;
- }
- if (rp->matchingKeyCount > 0) {
- rp->matchingKeys
- = MALLOC(sizeof(HashCode512) *
- rp->matchingKeyCount);
- if (sizeof(HashCode512) *
- rp->matchingKeyCount !=
- READ(fd,
- rp->matchingKeys,
- sizeof(HashCode512) *
- rp->matchingKeyCount)) {
- GE_BREAK(NULL, 0);
- goto ERR;
- }
- }
- }
- list->ctx
- = ctx;
- list->next
- = NULL;
- /* finally: append (!) to list */
+ while (1)
+ {
+ READINT (big);
+ if (big == 0)
+ return OK;
+ list = MALLOC (sizeof (FSUI_SearchList));
+ memset (list, 0, sizeof (FSUI_SearchList));
+ if ((OK != read_int (fd, (int *) &list->state)) ||
+ (OK != read_int (fd, (int *) &list->maxResults)) ||
+ (OK != read_long (fd, (long long *) &list->timeout)) ||
+ (OK != read_long (fd, (long long *) &list->start_time)) ||
+ (OK != read_long (fd, (long long *) &stime)) ||
+ (OK != read_int (fd, (int *) &list->anonymityLevel)) ||
+ (OK != read_int (fd, (int *) &list->sizeResultsReceived)) ||
+ (OK != read_int (fd, (int *) &list->sizeUnmatchedResultsReceived))
+ || (list->sizeResultsReceived > 1024 * 1024)
+ || (list->sizeUnmatchedResultsReceived > 1024 * 1024))
+ {
+ GE_BREAK (NULL, 0);
+ break;
+ }
+ fixState (&list->state);
+ if (stime > get_time ())
+ stime = get_time ();
+ list->start_time += get_time () - stime;
+ buf = read_string (fd, 1024 * 1024);
+ if (buf == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ break;
+ }
+ list->uri = ECRS_stringToUri (NULL, buf);
+ FREE (buf);
+ if (list->uri == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ break;
+ }
+ if (!(ECRS_isKeywordUri (list->uri) || ECRS_isNamespaceUri (list->uri)))
+ {
+ GE_BREAK (NULL, 0);
+ break;
+ }
+ list->numberOfURIKeys = ECRS_countKeywordsOfUri (list->uri);
+ if (list->sizeResultsReceived > 0)
+ {
+ list->resultsReceived
+ = MALLOC (list->sizeResultsReceived * sizeof (ECRS_FileInfo));
+ memset (list->resultsReceived,
+ 0, list->sizeResultsReceived * sizeof (ECRS_FileInfo));
+ }
+ if (list->sizeUnmatchedResultsReceived > 0)
+ {
+ list->unmatchedResultsReceived
+ = MALLOC (list->sizeUnmatchedResultsReceived *
+ sizeof (ResultPending));
+ memset (list->unmatchedResultsReceived,
+ 0,
+ list->sizeUnmatchedResultsReceived *
+ sizeof (ResultPending));
+ }
+ for (i = 0; i < list->sizeResultsReceived; i++)
+ if (OK != readFileInfo (ctx->ectx, fd, &list->resultsReceived[i]))
+ {
+ GE_BREAK (NULL, 0);
+ goto ERR;
+ }
+ for (i = 0; i < list->sizeUnmatchedResultsReceived; i++)
+ {
+ rp = &list->unmatchedResultsReceived[i];
+ if (OK != readFileInfo (ctx->ectx, fd, &rp->fi))
+ {
+ GE_BREAK (NULL, 0);
+ goto ERR;
+ }
+ if (OK != read_int (fd, (int *) &rp->matchingKeyCount))
+ {
+ GE_BREAK (NULL, 0);
+ goto ERR;
+ }
+ if ((rp->matchingKeyCount > 1024) ||
+ (rp->matchingKeyCount >= list->numberOfURIKeys))
+ {
+ GE_BREAK (NULL, 0);
+ goto ERR;
+ }
+ if (rp->matchingKeyCount > 0)
+ {
+ rp->matchingKeys
+ = MALLOC (sizeof (HashCode512) * rp->matchingKeyCount);
+ if (sizeof (HashCode512) *
+ rp->matchingKeyCount !=
+ READ (fd,
+ rp->matchingKeys,
+ sizeof (HashCode512) * rp->matchingKeyCount))
+ {
+ GE_BREAK (NULL, 0);
+ goto ERR;
+ }
+ }
+ }
+ list->ctx = ctx;
+ list->next = NULL;
+ /* finally: append (!) to list */
- if (ctx->activeSearches == NULL) {
- ctx->activeSearches = list;
- } else {
- last = ctx->activeSearches;
- while (last->next != NULL)
- last = last->next;
- last->next = list;
- }
- } /* end OUTER: 'while(1)' */
- ERR:
+ if (ctx->activeSearches == NULL)
+ {
+ ctx->activeSearches = list;
+ }
+ else
+ {
+ last = ctx->activeSearches;
+ while (last->next != NULL)
+ last = last->next;
+ last->next = list;
+ }
+ } /* end OUTER: 'while(1)' */
+ERR:
/* error - deallocate 'list' */
- if (list->resultsReceived != NULL) {
- for (i=0;i<list->sizeResultsReceived;i++) {
- if (list->resultsReceived[i].uri != NULL)
- ECRS_freeUri(list->resultsReceived[i].uri);
- if (list->resultsReceived[i].meta != NULL)
- ECRS_freeMetaData(list->resultsReceived[i].meta);
+ if (list->resultsReceived != NULL)
+ {
+ for (i = 0; i < list->sizeResultsReceived; i++)
+ {
+ if (list->resultsReceived[i].uri != NULL)
+ ECRS_freeUri (list->resultsReceived[i].uri);
+ if (list->resultsReceived[i].meta != NULL)
+ ECRS_freeMetaData (list->resultsReceived[i].meta);
+ }
+ GROW (list->resultsReceived, list->sizeResultsReceived, 0);
}
- GROW(list->resultsReceived,
- list->sizeResultsReceived,
- 0);
- }
- if (list->unmatchedResultsReceived != NULL) {
- for (i=0;i<list->sizeUnmatchedResultsReceived;i++) {
- rp = &list->unmatchedResultsReceived[i];
+ if (list->unmatchedResultsReceived != NULL)
+ {
+ for (i = 0; i < list->sizeUnmatchedResultsReceived; i++)
+ {
+ rp = &list->unmatchedResultsReceived[i];
- if (rp->fi.uri != NULL)
- ECRS_freeUri(rp->fi.uri);
- if (rp->fi.meta != NULL)
- ECRS_freeMetaData(rp->fi.meta);
- FREENONNULL(rp->matchingKeys);
+ if (rp->fi.uri != NULL)
+ ECRS_freeUri (rp->fi.uri);
+ if (rp->fi.meta != NULL)
+ ECRS_freeMetaData (rp->fi.meta);
+ FREENONNULL (rp->matchingKeys);
+ }
+ GROW (list->resultsReceived, list->sizeResultsReceived, 0);
}
- GROW(list->resultsReceived,
- list->sizeResultsReceived,
- 0);
- }
if (list->uri != NULL)
- ECRS_freeUri(list->uri);
- FREE(list);
+ ECRS_freeUri (list->uri);
+ FREE (list);
return SYSERR;
}
-static int readDownloads(int fd,
- struct FSUI_Context * ctx) {
- memset(&ctx->activeDownloads,
- 0,
- sizeof(FSUI_DownloadList));
+static int
+readDownloads (int fd, struct FSUI_Context *ctx)
+{
+ memset (&ctx->activeDownloads, 0, sizeof (FSUI_DownloadList));
ctx->activeDownloads.child
- = readDownloadList(ctx->ectx,
- fd,
- ctx,
- &ctx->activeDownloads);
+ = readDownloadList (ctx->ectx, fd, ctx, &ctx->activeDownloads);
return OK;
}
-static int readUploadList(struct FSUI_Context * ctx,
- struct FSUI_UploadList * parent,
- int fd,
- struct FSUI_UploadShared * shared,
- int top) {
- struct FSUI_UploadList * list;
+static int
+readUploadList (struct FSUI_Context *ctx,
+ struct FSUI_UploadList *parent,
+ int fd, struct FSUI_UploadShared *shared, int top)
+{
+ struct FSUI_UploadList *list;
struct FSUI_UploadList l;
unsigned long long stime;
int big;
int bag;
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
ectx = ctx->ectx;
- GE_ASSERT(ectx, shared != NULL);
- while (1) {
- READINT(big);
- if (big == 0)
- return OK;
- if ( (big < 1) || (big > 15) ) {
- GE_BREAK(NULL, 0);
- return SYSERR;
+ GE_ASSERT (ectx, shared != NULL);
+ while (1)
+ {
+ READINT (big);
+ if (big == 0)
+ return OK;
+ if ((big < 1) || (big > 15))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ READINT (bag);
+ if (bag != 0x34D1F023)
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ memset (&l, 0, sizeof (FSUI_UploadList));
+ READINT (l.state);
+ fixState (&l.state);
+ if (l.state == FSUI_PENDING)
+ l.state = FSUI_ACTIVE;
+ READLONG (l.completed);
+ READLONG (l.total);
+ READLONG (stime);
+ if (stime < get_time ())
+ stime = get_time ();
+ READLONG (l.start_time);
+ if (l.start_time != 0)
+ l.start_time = (get_time () - stime) + l.start_time;
+ l.uri = NULL;
+ if ((big & 2) == 2)
+ READURI (l.uri);
+ if ((big & 4) == 4)
+ {
+ l.keywords = read_uri (ctx->ectx, fd);
+ if (l.keywords == NULL)
+ {
+ if (l.uri != NULL)
+ ECRS_freeUri (l.uri);
+ GE_BREAK (NULL, 0);
+ break;
+ }
+ }
+ if ((big & 8) == 8)
+ {
+ l.meta = read_meta (ctx->ectx, fd);
+ if (l.meta == NULL)
+ {
+ if (l.uri != NULL)
+ ECRS_freeUri (l.uri);
+ if (l.keywords != NULL)
+ ECRS_freeUri (l.keywords);
+ GE_BREAK (NULL, 0);
+ break;
+ }
+ }
+ l.filename = read_string (fd, 1024 * 1024);
+ if (l.filename == NULL)
+ {
+ if (l.uri != NULL)
+ ECRS_freeUri (l.uri);
+ if (l.meta != NULL)
+ ECRS_freeMetaData (l.meta);
+ if (l.keywords != NULL)
+ ECRS_freeUri (l.keywords);
+ GE_BREAK (NULL, 0);
+ break;
+ }
+ list = MALLOC (sizeof (struct FSUI_UploadList));
+ memcpy (list, &l, sizeof (struct FSUI_UploadList));
+ list->shared = shared;
+ list->parent = parent;
+ if (OK != readUploadList (ctx, list, fd, shared, NO))
+ {
+ if (l.uri != NULL)
+ ECRS_freeUri (l.uri);
+ FREE (l.filename);
+ FREE (list);
+ GE_BREAK (NULL, 0);
+ break;
+ }
+ list->next = parent->child;
+ parent->child = list;
+ if (top == YES)
+ return OK;
}
- READINT(bag);
- if (bag != 0x34D1F023) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- memset(&l,
- 0,
- sizeof(FSUI_UploadList));
- READINT(l.state);
- fixState(&l.state);
- if (l.state == FSUI_PENDING)
- l.state = FSUI_ACTIVE;
- READLONG(l.completed);
- READLONG(l.total);
- READLONG(stime);
- if (stime < get_time())
- stime = get_time();
- READLONG(l.start_time);
- if (l.start_time != 0)
- l.start_time = (get_time() - stime) + l.start_time;
- l.uri = NULL;
- if ( (big & 2) == 2)
- READURI(l.uri);
- if ( (big & 4) == 4) {
- l.keywords = read_uri(ctx->ectx, fd);
- if (l.keywords == NULL) {
- if (l.uri != NULL)
- ECRS_freeUri(l.uri);
- GE_BREAK(NULL, 0);
- break;
- }
- }
- if ( (big & 8) == 8) {
- l.meta = read_meta(ctx->ectx, fd);
- if (l.meta == NULL) {
- if (l.uri != NULL)
- ECRS_freeUri(l.uri);
- if (l.keywords != NULL)
- ECRS_freeUri(l.keywords);
- GE_BREAK(NULL, 0);
- break;
- }
- }
- l.filename = read_string(fd, 1024*1024);
- if (l.filename == NULL) {
- if (l.uri != NULL)
- ECRS_freeUri(l.uri);
- if (l.meta != NULL)
- ECRS_freeMetaData(l.meta);
- if (l.keywords != NULL)
- ECRS_freeUri(l.keywords);
- GE_BREAK(NULL, 0);
- break;
- }
- list = MALLOC(sizeof(struct FSUI_UploadList));
- memcpy(list,
- &l,
- sizeof(struct FSUI_UploadList));
- list->shared = shared;
- list->parent = parent;
- if (OK != readUploadList(ctx,
- list,
- fd,
- shared,
- NO)) {
- if (l.uri != NULL)
- ECRS_freeUri(l.uri);
- FREE(l.filename);
- FREE(list);
- GE_BREAK(NULL, 0);
- break;
- }
- list->next = parent->child;
- parent->child = list;
- if (top == YES)
- return OK;
- }
return SYSERR;
}
-static int readUploads(int fd,
- struct FSUI_Context * ctx) {
+static int
+readUploads (int fd, struct FSUI_Context *ctx)
+{
int big;
int bag;
- struct FSUI_UploadShared * shared;
+ struct FSUI_UploadShared *shared;
struct FSUI_UploadShared sshared;
- memset(&ctx->activeUploads,
- 0,
- sizeof(FSUI_UploadList));
- while (1) {
- READINT(big);
- if (big == 0)
- return OK;
- if ( (big < 1) && (big > 7) ) {
- GE_BREAK(NULL, 0);
- break;
- }
- READINT(bag);
- if (bag != 0x44D1F024) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- memset(&sshared,
- 0,
- sizeof(FSUI_UploadShared));
- READINT(sshared.doIndex);
- READINT(sshared.anonymityLevel);
- READINT(sshared.priority);
- READINT(sshared.individualKeywords);
- READLONG(sshared.expiration);
- if ((big & 2) == 2)
- READSTRING(sshared.extractor_config, 1024*1024);
- if ((big & 4) == 4) {
- sshared.global_keywords = read_uri(ctx->ectx, fd);
- if (sshared.global_keywords == NULL) {
- FREENONNULL(sshared.extractor_config);
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- }
- shared = MALLOC(sizeof(FSUI_UploadShared));
- memcpy(shared,
- &sshared,
- sizeof(FSUI_UploadShared));
- shared->ctx = ctx;
- if (OK != readUploadList(ctx,
- &ctx->activeUploads,
- fd,
- shared,
- YES)) {
- GE_BREAK(NULL, 0);
+ memset (&ctx->activeUploads, 0, sizeof (FSUI_UploadList));
+ while (1)
+ {
+ READINT (big);
+ if (big == 0)
+ return OK;
+ if ((big < 1) && (big > 7))
+ {
+ GE_BREAK (NULL, 0);
+ break;
+ }
+ READINT (bag);
+ if (bag != 0x44D1F024)
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ memset (&sshared, 0, sizeof (FSUI_UploadShared));
+ READINT (sshared.doIndex);
+ READINT (sshared.anonymityLevel);
+ READINT (sshared.priority);
+ READINT (sshared.individualKeywords);
+ READLONG (sshared.expiration);
+ if ((big & 2) == 2)
+ READSTRING (sshared.extractor_config, 1024 * 1024);
+ if ((big & 4) == 4)
+ {
+ sshared.global_keywords = read_uri (ctx->ectx, fd);
+ if (sshared.global_keywords == NULL)
+ {
+ FREENONNULL (sshared.extractor_config);
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ }
+ shared = MALLOC (sizeof (FSUI_UploadShared));
+ memcpy (shared, &sshared, sizeof (FSUI_UploadShared));
+ shared->ctx = ctx;
+ if (OK != readUploadList (ctx, &ctx->activeUploads, fd, shared, YES))
+ {
+ GE_BREAK (NULL, 0);
#if 0
- /* cannot do this, readUploadList
- may have added *some* uploads that
- still reference shared -- need to
- find and cleanup those first,
- or at least detect their presence
- and not free */
- FREE(shared->extractor_config);
- FREE(shared);
+ /* cannot do this, readUploadList
+ may have added *some* uploads that
+ still reference shared -- need to
+ find and cleanup those first,
+ or at least detect their presence
+ and not free */
+ FREE (shared->extractor_config);
+ FREE (shared);
#endif
- break;
+ break;
+ }
}
- }
return SYSERR;
}
-static int readUnindex(int fd,
- struct FSUI_Context * ctx) {
+static int
+readUnindex (int fd, struct FSUI_Context *ctx)
+{
int big;
- char * name;
- struct FSUI_UnindexList * ul;
+ char *name;
+ struct FSUI_UnindexList *ul;
- while (1) {
- READINT(big);
- if (big != 1)
- return OK;
- READINT(big); /* state */
- READSTRING(name, 1024 * 1024);
- ul = MALLOC(sizeof(struct FSUI_UnindexList));
- ul->state = big;
- ul->filename = name;
- ul->next = ctx->unindexOperations;
- ul->ctx = ctx;
- ctx->unindexOperations = ul;
- }
+ while (1)
+ {
+ READINT (big);
+ if (big != 1)
+ return OK;
+ READINT (big); /* state */
+ READSTRING (name, 1024 * 1024);
+ ul = MALLOC (sizeof (struct FSUI_UnindexList));
+ ul->state = big;
+ ul->filename = name;
+ ul->next = ctx->unindexOperations;
+ ul->ctx = ctx;
+ ctx->unindexOperations = ul;
+ }
return SYSERR;
}
-void FSUI_deserialize(struct FSUI_Context * ctx) {
+void
+FSUI_deserialize (struct FSUI_Context *ctx)
+{
int fd;
fd = -1;
- if (0 != ACCESS(ctx->name, R_OK))
+ if (0 != ACCESS (ctx->name, R_OK))
return;
- fd = disk_file_open(ctx->ectx,
- ctx->name,
- O_RDONLY);
+ fd = disk_file_open (ctx->ectx, ctx->name, O_RDONLY);
if (fd == -1)
return;
- if ( (OK != checkMagic(fd)) ||
- (OK != readCollection(fd, ctx) ) ||
- (OK != readSearches(fd, ctx) ) ||
- (OK != readDownloads(fd, ctx) ) ||
- (OK != readUnindex(fd, ctx) ) ||
- (OK != readUploads(fd, ctx) ) ) {
- GE_BREAK(ctx->ectx, 0);
- GE_LOG(ctx->ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("FSUI state file `%s' had syntax error at offset %u.\n"),
- ctx->name,
- lseek(fd, 0, SEEK_CUR));
- }
- CLOSE(fd);
- UNLINK(ctx->name);
+ if ((OK != checkMagic (fd)) ||
+ (OK != readCollection (fd, ctx)) ||
+ (OK != readSearches (fd, ctx)) ||
+ (OK != readDownloads (fd, ctx)) ||
+ (OK != readUnindex (fd, ctx)) || (OK != readUploads (fd, ctx)))
+ {
+ GE_BREAK (ctx->ectx, 0);
+ GE_LOG (ctx->ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("FSUI state file `%s' had syntax error at offset %u.\n"),
+ ctx->name, lseek (fd, 0, SEEK_CUR));
+ }
+ CLOSE (fd);
+ UNLINK (ctx->name);
}
Modified: GNUnet/src/applications/fs/fsui/download.c
===================================================================
--- GNUnet/src/applications/fs/fsui/download.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/fsui/download.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -38,18 +38,16 @@
* Mark the given URI as found in a directory
* in URITRACK.
*/
-static int listURIfoundDirectory(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * prnt) {
- FSUI_DownloadList * dl = prnt;
+static int
+listURIfoundDirectory (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *prnt)
+{
+ FSUI_DownloadList *dl = prnt;
if (isRoot == YES)
- return OK; /* namespace ad, ignore */
- URITRACK_addState(dl->ctx->ectx,
- dl->ctx->cfg,
- fi->uri,
- URITRACK_DIRECTORY_FOUND);
+ return OK; /* namespace ad, ignore */
+ URITRACK_addState (dl->ctx->ectx,
+ dl->ctx->cfg, fi->uri, URITRACK_DIRECTORY_FOUND);
return OK;
}
@@ -59,83 +57,72 @@
/**
* Start to download a file.
*/
-static FSUI_DownloadList *
-startDownload(struct FSUI_Context * ctx,
- unsigned int anonymityLevel,
- int is_recursive,
- const struct ECRS_URI * uri,
- const struct ECRS_MetaData * meta,
- const char * filename,
- struct FSUI_SearchList * psearch,
- FSUI_DownloadList * parent);
+static FSUI_DownloadList *startDownload (struct FSUI_Context *ctx,
+ unsigned int anonymityLevel,
+ int is_recursive,
+ const struct ECRS_URI *uri,
+ const struct ECRS_MetaData *meta,
+ const char *filename,
+ struct FSUI_SearchList *psearch,
+ FSUI_DownloadList * parent);
/**
* Initiate a (recursive) download of the given
* directory entry.
*/
-static int triggerRecursiveDownload(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * prnt) {
- FSUI_DownloadList * parent = prnt;
- struct GE_Context * ectx;
+static int
+triggerRecursiveDownload (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *prnt)
+{
+ FSUI_DownloadList *parent = prnt;
+ struct GE_Context *ectx;
int i;
- FSUI_DownloadList * pos;
- char * filename;
- char * fullName;
- char * dotdot;
+ FSUI_DownloadList *pos;
+ char *filename;
+ char *fullName;
+ char *dotdot;
ectx = parent->ctx->ectx;
if (isRoot == YES)
- return OK; /* namespace ad, ignore */
+ return OK; /* namespace ad, ignore */
- URITRACK_trackURI(ectx,
- parent->ctx->cfg,
- fi);
- for (i=0;i<parent->completedDownloadsCount;i++)
- if (ECRS_equalsUri(parent->completedDownloads[i],
- fi->uri))
- return OK; /* already complete! */
+ URITRACK_trackURI (ectx, parent->ctx->cfg, fi);
+ for (i = 0; i < parent->completedDownloadsCount; i++)
+ if (ECRS_equalsUri (parent->completedDownloads[i], fi->uri))
+ return OK; /* already complete! */
pos = parent->child;
- while (pos != NULL) {
- if (ECRS_equalsUri(pos->fi.uri,
- fi->uri))
- return OK; /* already downloading */
- pos = pos->next;
- }
- filename = ECRS_getFromMetaData(fi->meta,
- EXTRACTOR_FILENAME);
- if (filename == NULL) {
- char * tmp = ECRS_uriToString(fi->uri);
- GE_ASSERT(ectx,
- strlen(tmp) >= strlen(ECRS_URI_PREFIX) + strlen(ECRS_FILE_INFIX));
- filename = STRDUP(&tmp[strlen(ECRS_URI_PREFIX) + strlen(ECRS_FILE_INFIX)]);
- FREE(tmp);
- }
- fullName = MALLOC(strlen(parent->filename) + 2
- + strlen(filename));
- strcpy(fullName,
- parent->filename);
- strcat(fullName,
- filename);
- while (NULL != (dotdot = strstr(fullName, "..")))
+ while (pos != NULL)
+ {
+ if (ECRS_equalsUri (pos->fi.uri, fi->uri))
+ return OK; /* already downloading */
+ pos = pos->next;
+ }
+ filename = ECRS_getFromMetaData (fi->meta, EXTRACTOR_FILENAME);
+ if (filename == NULL)
+ {
+ char *tmp = ECRS_uriToString (fi->uri);
+ GE_ASSERT (ectx,
+ strlen (tmp) >=
+ strlen (ECRS_URI_PREFIX) + strlen (ECRS_FILE_INFIX));
+ filename =
+ STRDUP (&tmp[strlen (ECRS_URI_PREFIX) + strlen (ECRS_FILE_INFIX)]);
+ FREE (tmp);
+ }
+ fullName = MALLOC (strlen (parent->filename) + 2 + strlen (filename));
+ strcpy (fullName, parent->filename);
+ strcat (fullName, filename);
+ while (NULL != (dotdot = strstr (fullName, "..")))
dotdot[0] = dotdot[1] = '_';
- FREE(filename);
+ FREE (filename);
#if DEBUG_DTM
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Starting recursive download of `%s'\n",
- fullName);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Starting recursive download of `%s'\n", fullName);
#endif
- startDownload(parent->ctx,
- parent->anonymityLevel,
- YES,
- fi->uri,
- fi->meta,
- fullName,
- parent->search,
- parent);
- FREE(fullName);
+ startDownload (parent->ctx,
+ parent->anonymityLevel,
+ YES, fi->uri, fi->meta, fullName, parent->search, parent);
+ FREE (fullName);
return OK;
}
@@ -143,268 +130,260 @@
* Progress notification from ECRS. Tell FSUI client.
*/
static void
-downloadProgressCallback(unsigned long long totalBytes,
- unsigned long long completedBytes,
- cron_t eta,
- unsigned long long lastBlockOffset,
- const char * lastBlock,
- unsigned int lastBlockSize,
- void * cls) {
- FSUI_DownloadList * dl = cls;
+downloadProgressCallback (unsigned long long totalBytes,
+ unsigned long long completedBytes,
+ cron_t eta,
+ unsigned long long lastBlockOffset,
+ const char *lastBlock,
+ unsigned int lastBlockSize, void *cls)
+{
+ FSUI_DownloadList *dl = cls;
FSUI_Event event;
- struct ECRS_MetaData * md;
+ struct ECRS_MetaData *md;
cron_t now;
cron_t run_time;
- GE_ASSERT(dl->ctx->ectx,
- dl->total == totalBytes);
+ GE_ASSERT (dl->ctx->ectx, dl->total == totalBytes);
dl->completed = completedBytes;
event.type = FSUI_download_progress;
event.data.DownloadProgress.dc.pos = dl;
event.data.DownloadProgress.dc.cctx = dl->cctx;
- event.data.DownloadProgress.dc.ppos = dl->parent ==
&dl->ctx->activeDownloads ? NULL : dl->parent;
+ event.data.DownloadProgress.dc.ppos =
+ dl->parent == &dl->ctx->activeDownloads ? NULL : dl->parent;
event.data.DownloadProgress.dc.pcctx = dl->parent->cctx;
event.data.DownloadProgress.dc.spos = dl->search;
- event.data.DownloadProgress.dc.sctx = dl->search == NULL ? NULL :
dl->search->cctx;
+ event.data.DownloadProgress.dc.sctx =
+ dl->search == NULL ? NULL : dl->search->cctx;
event.data.DownloadProgress.completed = dl->completed;
event.data.DownloadProgress.total = dl->total;
event.data.DownloadProgress.last_offset = lastBlockOffset;
- now = get_time();
+ now = get_time ();
run_time = now - dl->startTime;
- if ( (dl->total == 0) || (dl->completed == 0) ) {
- eta = now;
- } else {
- eta = (cron_t) (dl->startTime +
- (((double)(run_time)/(double)dl->completed))
- * (double)dl->total);
- if (eta < now)
+ if ((dl->total == 0) || (dl->completed == 0))
+ {
eta = now;
- }
+ }
+ else
+ {
+ eta = (cron_t) (dl->startTime +
+ (((double) (run_time) / (double) dl->completed))
+ * (double) dl->total);
+ if (eta < now)
+ eta = now;
+ }
event.data.DownloadProgress.eta = eta;
event.data.DownloadProgress.filename = dl->filename;
event.data.DownloadProgress.uri = dl->fi.uri;
event.data.DownloadProgress.last_block = lastBlock;
event.data.DownloadProgress.last_size = lastBlockSize;
- dl->ctx->ecb(dl->ctx->ecbClosure,
- &event);
- if ( (lastBlockOffset == 0) &&
- (dl->is_directory == SYSERR) ) {
- /* check if this is a directory */
- if ( (lastBlockSize > strlen(GNUNET_DIRECTORY_MAGIC)) &&
- (0 == strncmp(GNUNET_DIRECTORY_MAGIC,
- lastBlock,
- strlen(GNUNET_DIRECTORY_MAGIC)) ) )
- dl->is_directory = YES;
- else
- dl->is_directory = NO;
- }
- if (dl->is_directory == YES) {
- md = NULL;
- ECRS_listDirectory(dl->ctx->ectx,
- lastBlock,
- lastBlockSize,
- &md,
- &listURIfoundDirectory,
- dl);
- if (md != NULL)
- ECRS_freeMetaData(md);
- }
- if ( (dl->is_recursive == YES) &&
- (dl->is_directory == YES) ) {
- md = NULL;
- MUTEX_LOCK(dl->ctx->lock);
- ECRS_listDirectory(dl->ctx->ectx,
- lastBlock,
- lastBlockSize,
- &md,
- &triggerRecursiveDownload,
- dl);
- MUTEX_UNLOCK(dl->ctx->lock);
- if (md != NULL)
- ECRS_freeMetaData(md);
- }
+ dl->ctx->ecb (dl->ctx->ecbClosure, &event);
+ if ((lastBlockOffset == 0) && (dl->is_directory == SYSERR))
+ {
+ /* check if this is a directory */
+ if ((lastBlockSize > strlen (GNUNET_DIRECTORY_MAGIC)) &&
+ (0 == strncmp (GNUNET_DIRECTORY_MAGIC,
+ lastBlock, strlen (GNUNET_DIRECTORY_MAGIC))))
+ dl->is_directory = YES;
+ else
+ dl->is_directory = NO;
+ }
+ if (dl->is_directory == YES)
+ {
+ md = NULL;
+ ECRS_listDirectory (dl->ctx->ectx,
+ lastBlock,
+ lastBlockSize, &md, &listURIfoundDirectory, dl);
+ if (md != NULL)
+ ECRS_freeMetaData (md);
+ }
+ if ((dl->is_recursive == YES) && (dl->is_directory == YES))
+ {
+ md = NULL;
+ MUTEX_LOCK (dl->ctx->lock);
+ ECRS_listDirectory (dl->ctx->ectx,
+ lastBlock,
+ lastBlockSize, &md, &triggerRecursiveDownload, dl);
+ MUTEX_UNLOCK (dl->ctx->lock);
+ if (md != NULL)
+ ECRS_freeMetaData (md);
+ }
}
/**
* Check if termination of this download is desired.
*/
static int
-testTerminate(void * cls) {
- FSUI_DownloadList * dl = cls;
+testTerminate (void *cls)
+{
+ FSUI_DownloadList *dl = cls;
- if ( (dl->state == FSUI_ERROR) ||
- (dl->state == FSUI_ABORTED) )
- return SYSERR; /* aborted - delete! */
+ if ((dl->state == FSUI_ERROR) || (dl->state == FSUI_ABORTED))
+ return SYSERR; /* aborted - delete! */
if (dl->state != FSUI_ACTIVE)
- return NO; /* suspended */
+ return NO; /* suspended */
return OK;
}
/**
* Thread that downloads a file.
*/
-void * downloadThread(void * cls) {
- FSUI_DownloadList * dl = cls;
+void *
+downloadThread (void *cls)
+{
+ FSUI_DownloadList *dl = cls;
int ret;
FSUI_Event event;
- struct GE_Context * ectx;
- struct GE_Memory * mem;
- struct GE_Context * ee;
+ struct GE_Context *ectx;
+ struct GE_Memory *mem;
+ struct GE_Context *ee;
- dl->startTime = get_time() - dl->runTime;
+ dl->startTime = get_time () - dl->runTime;
ectx = dl->ctx->ectx;
#if DEBUG_DTM
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Download thread for `%s' started...\n",
- dl->filename);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Download thread for `%s' started...\n", dl->filename);
#endif
- GE_ASSERT(ectx, dl->ctx != NULL);
- GE_ASSERT(ectx, dl->filename != NULL);
- mem = GE_memory_create(2);
- ee = GE_create_context_memory(GE_USER | GE_ADMIN | GE_ERROR | GE_WARNING |
GE_FATAL | GE_BULK | GE_IMMEDIATE,
- mem);
- ret = ECRS_downloadFile(ee,
- dl->ctx->cfg,
- dl->fi.uri,
- dl->filename,
- dl->anonymityLevel,
- &downloadProgressCallback,
- dl,
- &testTerminate,
- dl);
- if (ret == OK) {
- dl->state = FSUI_COMPLETED;
- event.type = FSUI_download_completed;
- event.data.DownloadCompleted.dc.pos = dl;
- event.data.DownloadCompleted.dc.cctx = dl->cctx;
- event.data.DownloadCompleted.dc.ppos = dl->parent ==
&dl->ctx->activeDownloads ? NULL : dl->parent;
- event.data.DownloadCompleted.dc.pcctx = dl->parent->cctx;
- event.data.DownloadCompleted.dc.spos = dl->search;
- event.data.DownloadCompleted.dc.sctx = dl->search == NULL ? NULL :
dl->search->cctx;
- event.data.DownloadCompleted.total = dl->total;
- event.data.DownloadCompleted.filename = dl->filename;
- event.data.DownloadCompleted.uri = dl->fi.uri;
- URITRACK_addState(dl->ctx->ectx,
- dl->ctx->cfg,
- dl->fi.uri,
- URITRACK_DOWNLOAD_COMPLETED);
- dl->ctx->ecb(dl->ctx->ecbClosure,
- &event);
- } else if (dl->state == FSUI_ACTIVE) {
- const char * error;
+ GE_ASSERT (ectx, dl->ctx != NULL);
+ GE_ASSERT (ectx, dl->filename != NULL);
+ mem = GE_memory_create (2);
+ ee =
+ GE_create_context_memory (GE_USER | GE_ADMIN | GE_ERROR | GE_WARNING |
+ GE_FATAL | GE_BULK | GE_IMMEDIATE, mem);
+ ret =
+ ECRS_downloadFile (ee, dl->ctx->cfg, dl->fi.uri, dl->filename,
+ dl->anonymityLevel, &downloadProgressCallback, dl,
+ &testTerminate, dl);
+ if (ret == OK)
+ {
+ dl->state = FSUI_COMPLETED;
+ event.type = FSUI_download_completed;
+ event.data.DownloadCompleted.dc.pos = dl;
+ event.data.DownloadCompleted.dc.cctx = dl->cctx;
+ event.data.DownloadCompleted.dc.ppos =
+ dl->parent == &dl->ctx->activeDownloads ? NULL : dl->parent;
+ event.data.DownloadCompleted.dc.pcctx = dl->parent->cctx;
+ event.data.DownloadCompleted.dc.spos = dl->search;
+ event.data.DownloadCompleted.dc.sctx =
+ dl->search == NULL ? NULL : dl->search->cctx;
+ event.data.DownloadCompleted.total = dl->total;
+ event.data.DownloadCompleted.filename = dl->filename;
+ event.data.DownloadCompleted.uri = dl->fi.uri;
+ URITRACK_addState (dl->ctx->ectx,
+ dl->ctx->cfg,
+ dl->fi.uri, URITRACK_DOWNLOAD_COMPLETED);
+ dl->ctx->ecb (dl->ctx->ecbClosure, &event);
+ }
+ else if (dl->state == FSUI_ACTIVE)
+ {
+ const char *error;
- /* ECRS error */
- dl->state = FSUI_ERROR;
- event.type = FSUI_download_error;
- event.data.DownloadError.dc.pos = dl;
- event.data.DownloadError.dc.cctx = dl->cctx;
- event.data.DownloadError.dc.ppos = dl->parent == &dl->ctx->activeDownloads
? NULL : dl->parent;
- event.data.DownloadError.dc.pcctx = dl->parent->cctx;
- event.data.DownloadError.dc.spos = dl->search;
- event.data.DownloadError.dc.sctx = dl->search == NULL ? NULL :
dl->search->cctx;
- error = GE_memory_get(mem, 0);
- if (error == NULL)
- error = _("Download failed (no reason given)");
- event.data.DownloadError.message = error;
- URITRACK_addState(dl->ctx->ectx,
- dl->ctx->cfg,
- dl->fi.uri,
- URITRACK_DOWNLOAD_ABORTED);
- dl->ctx->ecb(dl->ctx->ecbClosure,
- &event);
- } else if (dl->state == FSUI_ABORTED) { /* aborted */
- event.type = FSUI_download_aborted;
- event.data.DownloadAborted.dc.pos = dl;
- event.data.DownloadAborted.dc.cctx = dl->cctx;
- event.data.DownloadAborted.dc.ppos = dl->parent ==
&dl->ctx->activeDownloads ? NULL : dl->parent;
- event.data.DownloadAborted.dc.pcctx = dl->parent->cctx;
- event.data.DownloadAborted.dc.spos = dl->search;
- event.data.DownloadAborted.dc.sctx = dl->search == NULL ? NULL :
dl->search->cctx;
- URITRACK_addState(dl->ctx->ectx,
- dl->ctx->cfg,
- dl->fi.uri,
- URITRACK_DOWNLOAD_ABORTED);
- dl->ctx->ecb(dl->ctx->ecbClosure,
- &event);
- } else {
- /* else: suspended */
- GE_BREAK(NULL, dl->state == FSUI_SUSPENDING);
- }
+ /* ECRS error */
+ dl->state = FSUI_ERROR;
+ event.type = FSUI_download_error;
+ event.data.DownloadError.dc.pos = dl;
+ event.data.DownloadError.dc.cctx = dl->cctx;
+ event.data.DownloadError.dc.ppos =
+ dl->parent == &dl->ctx->activeDownloads ? NULL : dl->parent;
+ event.data.DownloadError.dc.pcctx = dl->parent->cctx;
+ event.data.DownloadError.dc.spos = dl->search;
+ event.data.DownloadError.dc.sctx =
+ dl->search == NULL ? NULL : dl->search->cctx;
+ error = GE_memory_get (mem, 0);
+ if (error == NULL)
+ error = _("Download failed (no reason given)");
+ event.data.DownloadError.message = error;
+ URITRACK_addState (dl->ctx->ectx,
+ dl->ctx->cfg, dl->fi.uri, URITRACK_DOWNLOAD_ABORTED);
+ dl->ctx->ecb (dl->ctx->ecbClosure, &event);
+ }
+ else if (dl->state == FSUI_ABORTED)
+ { /* aborted */
+ event.type = FSUI_download_aborted;
+ event.data.DownloadAborted.dc.pos = dl;
+ event.data.DownloadAborted.dc.cctx = dl->cctx;
+ event.data.DownloadAborted.dc.ppos =
+ dl->parent == &dl->ctx->activeDownloads ? NULL : dl->parent;
+ event.data.DownloadAborted.dc.pcctx = dl->parent->cctx;
+ event.data.DownloadAborted.dc.spos = dl->search;
+ event.data.DownloadAborted.dc.sctx =
+ dl->search == NULL ? NULL : dl->search->cctx;
+ URITRACK_addState (dl->ctx->ectx, dl->ctx->cfg, dl->fi.uri,
+ URITRACK_DOWNLOAD_ABORTED);
+ dl->ctx->ecb (dl->ctx->ecbClosure, &event);
+ }
+ else
+ {
+ /* else: suspended */
+ GE_BREAK (NULL, dl->state == FSUI_SUSPENDING);
+ }
- if ( (ret == OK) &&
- (dl->is_directory == YES) &&
- (ECRS_fileSize(dl->fi.uri) > 0) ) {
- char * dirBlock;
- int fd;
- char * fn;
- size_t totalBytes;
- struct ECRS_MetaData * md;
+ if ((ret == OK) &&
+ (dl->is_directory == YES) && (ECRS_fileSize (dl->fi.uri) > 0))
+ {
+ char *dirBlock;
+ int fd;
+ char *fn;
+ size_t totalBytes;
+ struct ECRS_MetaData *md;
- totalBytes = ECRS_fileSize(dl->fi.uri);
- fn = MALLOC(strlen(dl->filename) + strlen(GNUNET_DIRECTORY_EXT) + 1);
- strcpy(fn, dl->filename);
- fd = strlen(fn)-1;
- if (fn[fd] == '/' || fn[fd] == '\\') {
- fn[fd] = '\0';
- strcat(fn, GNUNET_DIRECTORY_EXT);
- }
- fd = disk_file_open(ectx,
- fn,
- O_LARGEFILE | O_RDONLY);
- if (fd != -1) {
- dirBlock = MMAP(NULL,
- totalBytes,
- PROT_READ,
- MAP_SHARED,
- fd,
- 0);
- if (MAP_FAILED == dirBlock) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_BULK | GE_ADMIN | GE_USER,
- "mmap",
- fn);
- } else {
- md = NULL;
- ECRS_listDirectory(dl->ctx->ectx,
- dirBlock,
- totalBytes,
- &md,
- &listURIfoundDirectory,
- dl);
- if (md != NULL)
- ECRS_freeMetaData(md);
+ totalBytes = ECRS_fileSize (dl->fi.uri);
+ fn = MALLOC (strlen (dl->filename) + strlen (GNUNET_DIRECTORY_EXT) + 1);
+ strcpy (fn, dl->filename);
+ fd = strlen (fn) - 1;
+ if (fn[fd] == '/' || fn[fd] == '\\')
+ {
+ fn[fd] = '\0';
+ strcat (fn, GNUNET_DIRECTORY_EXT);
+ }
+ fd = disk_file_open (ectx, fn, O_LARGEFILE | O_RDONLY);
+ if (fd != -1)
+ {
+ dirBlock = MMAP (NULL, totalBytes, PROT_READ, MAP_SHARED, fd, 0);
+ if (MAP_FAILED == dirBlock)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_BULK | GE_ADMIN | GE_USER,
+ "mmap", fn);
+ }
+ else
+ {
+ md = NULL;
+ ECRS_listDirectory (dl->ctx->ectx,
+ dirBlock,
+ totalBytes,
+ &md, &listURIfoundDirectory, dl);
+ if (md != NULL)
+ ECRS_freeMetaData (md);
- if (dl->is_recursive) {
- /* load directory, start downloads */
- md = NULL;
- MUTEX_LOCK(dl->ctx->lock);
- ECRS_listDirectory(dl->ctx->ectx,
- dirBlock,
- totalBytes,
- &md,
- &triggerRecursiveDownload,
- dl);
- MUTEX_UNLOCK(dl->ctx->lock);
- ECRS_freeMetaData(md);
- MUNMAP(dirBlock, totalBytes);
- }
- }
- CLOSE(fd);
+ if (dl->is_recursive)
+ {
+ /* load directory, start downloads */
+ md = NULL;
+ MUTEX_LOCK (dl->ctx->lock);
+ ECRS_listDirectory (dl->ctx->ectx,
+ dirBlock,
+ totalBytes,
+ &md, &triggerRecursiveDownload, dl);
+ MUTEX_UNLOCK (dl->ctx->lock);
+ ECRS_freeMetaData (md);
+ MUNMAP (dirBlock, totalBytes);
+ }
+ }
+ CLOSE (fd);
+ }
+ FREE (fn);
}
- FREE(fn);
- }
#if DEBUG_DTM
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Download thread for `%s' terminated (%s)...\n",
- dl->filename,
- ret == OK ? "COMPLETED" : "ABORTED");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Download thread for `%s' terminated (%s)...\n",
+ dl->filename, ret == OK ? "COMPLETED" : "ABORTED");
#endif
- dl->runTime = get_time() - dl->startTime;
- GE_free_context(ee);
- GE_memory_free(mem);
+ dl->runTime = get_time () - dl->startTime;
+ GE_free_context (ee);
+ GE_memory_free (mem);
return NULL;
}
@@ -412,70 +391,66 @@
* Start to download a file.
*/
static FSUI_DownloadList *
-startDownload(struct FSUI_Context * ctx,
- unsigned int anonymityLevel,
- int is_recursive,
- const struct ECRS_URI * uri,
- const struct ECRS_MetaData * meta,
- const char * filename,
- struct FSUI_SearchList * psearch,
- FSUI_DownloadList * parent) {
- FSUI_DownloadList * dl;
+startDownload (struct FSUI_Context *ctx,
+ unsigned int anonymityLevel,
+ int is_recursive,
+ const struct ECRS_URI *uri,
+ const struct ECRS_MetaData *meta,
+ const char *filename,
+ struct FSUI_SearchList *psearch, FSUI_DownloadList * parent)
+{
+ FSUI_DownloadList *dl;
FSUI_Event event;
- GE_ASSERT(NULL, ctx != NULL);
- GE_ASSERT(NULL, parent != NULL);
- if (! (ECRS_isFileUri(uri) ||
- ECRS_isLocationUri(uri)) ) {
- GE_BREAK(NULL, 0); /* wrong type of URI! */
- return NULL;
- }
- dl = MALLOC(sizeof(FSUI_DownloadList));
- memset(dl,
- 0,
- sizeof(FSUI_DownloadList));
- dl->startTime = 0; /* not run at all so far! */
- dl->runTime = 0; /* not run at all so far! */
+ GE_ASSERT (NULL, ctx != NULL);
+ GE_ASSERT (NULL, parent != NULL);
+ if (!(ECRS_isFileUri (uri) || ECRS_isLocationUri (uri)))
+ {
+ GE_BREAK (NULL, 0); /* wrong type of URI! */
+ return NULL;
+ }
+ dl = MALLOC (sizeof (FSUI_DownloadList));
+ memset (dl, 0, sizeof (FSUI_DownloadList));
+ dl->startTime = 0; /* not run at all so far! */
+ dl->runTime = 0; /* not run at all so far! */
dl->state = FSUI_PENDING;
dl->is_recursive = is_recursive;
dl->parent = parent;
dl->search = psearch;
- dl->is_directory = SYSERR; /* don't know */
+ dl->is_directory = SYSERR; /* don't know */
dl->anonymityLevel = anonymityLevel;
dl->ctx = ctx;
- dl->filename = STRDUP(filename);
- dl->fi.uri = ECRS_dupUri(uri);
- dl->fi.meta = ECRS_dupMetaData(meta);
- dl->total = ECRS_fileSize(uri);
+ dl->filename = STRDUP (filename);
+ dl->fi.uri = ECRS_dupUri (uri);
+ dl->fi.meta = ECRS_dupMetaData (meta);
+ dl->total = ECRS_fileSize (uri);
dl->child = NULL;
dl->cctx = NULL;
/* signal start! */
event.type = FSUI_download_started;
event.data.DownloadStarted.dc.pos = dl;
event.data.DownloadStarted.dc.cctx = NULL;
- event.data.DownloadStarted.dc.ppos = dl->parent == &ctx->activeDownloads ?
NULL : dl->parent;
+ event.data.DownloadStarted.dc.ppos =
+ dl->parent == &ctx->activeDownloads ? NULL : dl->parent;
event.data.DownloadStarted.dc.pcctx = dl->parent->cctx;
event.data.DownloadStarted.dc.spos = dl->search;
- event.data.DownloadStarted.dc.sctx = dl->search == NULL ? NULL :
dl->search->cctx;
- event.data.DownloadStarted.total = ECRS_fileSize(dl->fi.uri);
+ event.data.DownloadStarted.dc.sctx =
+ dl->search == NULL ? NULL : dl->search->cctx;
+ event.data.DownloadStarted.total = ECRS_fileSize (dl->fi.uri);
event.data.DownloadStarted.filename = dl->filename;
event.data.DownloadStarted.fi.uri = dl->fi.uri;
event.data.DownloadStarted.fi.meta = dl->fi.meta;
event.data.DownloadStarted.anonymityLevel = dl->anonymityLevel;
- URITRACK_addState(ctx->ectx,
- ctx->cfg,
- uri,
- URITRACK_DOWNLOAD_STARTED);
- dl->cctx = dl->ctx->ecb(dl->ctx->ecbClosure,
- &event);
+ URITRACK_addState (ctx->ectx, ctx->cfg, uri, URITRACK_DOWNLOAD_STARTED);
+ dl->cctx = dl->ctx->ecb (dl->ctx->ecbClosure, &event);
dl->next = parent->child;
parent->child = dl;
- if (psearch != NULL) {
- GROW(psearch->my_downloads,
- psearch->my_downloads_size,
- psearch->my_downloads_size + 1);
- psearch->my_downloads[psearch->my_downloads_size -1] = dl;
- }
+ if (psearch != NULL)
+ {
+ GROW (psearch->my_downloads,
+ psearch->my_downloads_size, psearch->my_downloads_size + 1);
+ psearch->my_downloads[psearch->my_downloads_size - 1] = dl;
+ }
return dl;
}
@@ -487,28 +462,24 @@
* if the disk does not have enough space).
*/
struct FSUI_DownloadList *
-FSUI_startDownload(struct FSUI_Context * ctx,
- unsigned int anonymityLevel,
- int doRecursive,
- const struct ECRS_URI * uri,
- const struct ECRS_MetaData * meta,
- const char * filename,
- struct FSUI_SearchList * psearch,
- struct FSUI_DownloadList * pdownload) {
- struct FSUI_DownloadList * ret;
+FSUI_startDownload (struct FSUI_Context *ctx,
+ unsigned int anonymityLevel,
+ int doRecursive,
+ const struct ECRS_URI *uri,
+ const struct ECRS_MetaData *meta,
+ const char *filename,
+ struct FSUI_SearchList *psearch,
+ struct FSUI_DownloadList *pdownload)
+{
+ struct FSUI_DownloadList *ret;
- MUTEX_LOCK(ctx->lock);
+ MUTEX_LOCK (ctx->lock);
if (pdownload == NULL)
pdownload = &ctx->activeDownloads;
- ret = startDownload(ctx,
- anonymityLevel,
- doRecursive,
- uri,
- meta,
- filename,
- psearch,
- pdownload);
- MUTEX_UNLOCK(ctx->lock);
+ ret = startDownload (ctx,
+ anonymityLevel,
+ doRecursive, uri, meta, filename, psearch, pdownload);
+ MUTEX_UNLOCK (ctx->lock);
return ret;
}
@@ -519,10 +490,12 @@
*
* @return YES if change done that may require re-trying
*/
-int FSUI_updateDownloadThread(FSUI_DownloadList * list) {
- struct GE_Context * ectx;
- FSUI_DownloadList * dpos;
- void * unused;
+int
+FSUI_updateDownloadThread (FSUI_DownloadList * list)
+{
+ struct GE_Context *ectx;
+ FSUI_DownloadList *dpos;
+ void *unused;
int ret;
if (list == NULL)
@@ -530,87 +503,85 @@
ectx = list->ctx->ectx;
#if DEBUG_DTM
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Download thread manager investigates pending download of file `%s' (%u/%u
downloads)\n",
- list->filename,
- list->ctx->activeDownloadThreads,
- list->ctx->threadPoolSize);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Download thread manager investigates pending download of file `%s'
(%u/%u downloads)\n",
+ list->filename,
+ list->ctx->activeDownloadThreads, list->ctx->threadPoolSize);
#endif
ret = NO;
/* should this one be started? */
- if ( (list->ctx->threadPoolSize
- > list->ctx->activeDownloadThreads) &&
- (list->state == FSUI_PENDING) &&
- ( (list->total > list->completed) ||
- (list->total == 0) ) ) {
+ if ((list->ctx->threadPoolSize
+ > list->ctx->activeDownloadThreads) &&
+ (list->state == FSUI_PENDING) &&
+ ((list->total > list->completed) || (list->total == 0)))
+ {
#if DEBUG_DTM
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Download thread manager starts download of file `%s'\n",
- list->filename);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Download thread manager starts download of file `%s'\n",
+ list->filename);
#endif
- list->state = FSUI_ACTIVE;
- list->handle = PTHREAD_CREATE(&downloadThread,
- list,
- 128 * 1024);
- if (list->handle != NULL) {
- list->ctx->activeDownloadThreads++;
- } else {
- GE_LOG_STRERROR(ectx,
- GE_ADMIN | GE_USER | GE_BULK | GE_ERROR,
- "pthread_create");
- list->state = FSUI_ERROR_JOINED;
+ list->state = FSUI_ACTIVE;
+ list->handle = PTHREAD_CREATE (&downloadThread, list, 128 * 1024);
+ if (list->handle != NULL)
+ {
+ list->ctx->activeDownloadThreads++;
+ }
+ else
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_ADMIN | GE_USER | GE_BULK | GE_ERROR,
+ "pthread_create");
+ list->state = FSUI_ERROR_JOINED;
+ }
}
- }
/* should this one be stopped? */
- if ( (list->ctx->threadPoolSize
- < list->ctx->activeDownloadThreads) &&
- (list->state == FSUI_ACTIVE) ) {
+ if ((list->ctx->threadPoolSize
+ < list->ctx->activeDownloadThreads) && (list->state == FSUI_ACTIVE))
+ {
#if DEBUG_DTM
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Download thread manager aborts active download of file `%s' (%u/%u
downloads)\n",
- list->filename,
- list->ctx->activeDownloadThreads,
- list->ctx->threadPoolSize);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Download thread manager aborts active download of file `%s'
(%u/%u downloads)\n",
+ list->filename,
+ list->ctx->activeDownloadThreads, list->ctx->threadPoolSize);
#endif
- list->state = FSUI_SUSPENDING;
- GE_ASSERT(ectx, list->handle != NULL);
- PTHREAD_STOP_SLEEP(list->handle);
- PTHREAD_JOIN(list->handle,
- &unused);
- list->handle = NULL;
- list->ctx->activeDownloadThreads--;
- list->state = FSUI_PENDING;
- ret = YES;
- }
+ list->state = FSUI_SUSPENDING;
+ GE_ASSERT (ectx, list->handle != NULL);
+ PTHREAD_STOP_SLEEP (list->handle);
+ PTHREAD_JOIN (list->handle, &unused);
+ list->handle = NULL;
+ list->ctx->activeDownloadThreads--;
+ list->state = FSUI_PENDING;
+ ret = YES;
+ }
/* has this one "died naturally"? */
- if ( (list->state == FSUI_COMPLETED) ||
- (list->state == FSUI_ABORTED) ||
- (list->state == FSUI_ERROR) ) {
+ if ((list->state == FSUI_COMPLETED) ||
+ (list->state == FSUI_ABORTED) || (list->state == FSUI_ERROR))
+ {
#if DEBUG_DTM
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Download thread manager collects inactive download of file `%s'\n",
- list->filename);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Download thread manager collects inactive download of file
`%s'\n",
+ list->filename);
#endif
- PTHREAD_JOIN(list->handle,
- &unused);
- list->handle = NULL;
- list->ctx->activeDownloadThreads--;
- list->state++; /* adds _JOINED */
- ret = YES;
- }
+ PTHREAD_JOIN (list->handle, &unused);
+ list->handle = NULL;
+ list->ctx->activeDownloadThreads--;
+ list->state++; /* adds _JOINED */
+ ret = YES;
+ }
dpos = list->child;
- while (dpos != NULL) {
- if (YES == FSUI_updateDownloadThread(dpos))
- ret = YES;
- dpos = dpos->next;
- }
+ while (dpos != NULL)
+ {
+ if (YES == FSUI_updateDownloadThread (dpos))
+ ret = YES;
+ dpos = dpos->next;
+ }
return ret;
}
@@ -621,25 +592,29 @@
* @return SYSERR if no such download is pending,
* NO if the download has already finished
*/
-int FSUI_abortDownload(struct FSUI_Context * ctx,
- struct FSUI_DownloadList * dl) {
- struct FSUI_DownloadList * c;
+int
+FSUI_abortDownload (struct FSUI_Context *ctx, struct FSUI_DownloadList *dl)
+{
+ struct FSUI_DownloadList *c;
- GE_ASSERT(ctx->ectx, dl != NULL);
+ GE_ASSERT (ctx->ectx, dl != NULL);
c = dl->child;
- while (c != NULL) {
- FSUI_abortDownload(ctx, c);
- c = c->next;
- }
- if ( (dl->state != FSUI_ACTIVE) &&
- (dl->state != FSUI_PENDING) )
+ while (c != NULL)
+ {
+ FSUI_abortDownload (ctx, c);
+ c = c->next;
+ }
+ if ((dl->state != FSUI_ACTIVE) && (dl->state != FSUI_PENDING))
return NO;
- if (dl->state == FSUI_ACTIVE) {
- dl->state = FSUI_ABORTED;
- PTHREAD_STOP_SLEEP(dl->handle);
- } else {
- dl->state = FSUI_ABORTED_JOINED;
- }
+ if (dl->state == FSUI_ACTIVE)
+ {
+ dl->state = FSUI_ABORTED;
+ PTHREAD_STOP_SLEEP (dl->handle);
+ }
+ else
+ {
+ dl->state = FSUI_ABORTED_JOINED;
+ }
return OK;
}
@@ -649,82 +624,85 @@
*
* @return SYSERR if no such download is pending
*/
-int FSUI_stopDownload(struct FSUI_Context * ctx,
- struct FSUI_DownloadList * dl) {
- void * unused;
- struct FSUI_DownloadList * prev;
+int
+FSUI_stopDownload (struct FSUI_Context *ctx, struct FSUI_DownloadList *dl)
+{
+ void *unused;
+ struct FSUI_DownloadList *prev;
FSUI_Event event;
int i;
- GE_ASSERT(ctx->ectx, dl != NULL);
+ GE_ASSERT (ctx->ectx, dl != NULL);
while (dl->child != NULL)
- FSUI_stopDownload(ctx,
- dl->child);
- MUTEX_LOCK(ctx->lock);
- prev = (dl->parent != NULL) ? dl->parent->child : ctx->activeDownloads.child;
- while ( (prev != dl) &&
- (prev != NULL) &&
- (prev->next != dl) )
+ FSUI_stopDownload (ctx, dl->child);
+ MUTEX_LOCK (ctx->lock);
+ prev =
+ (dl->parent != NULL) ? dl->parent->child : ctx->activeDownloads.child;
+ while ((prev != dl) && (prev != NULL) && (prev->next != dl))
prev = prev->next;
- if (prev == NULL) {
- MUTEX_UNLOCK(ctx->lock);
- GE_LOG(ctx->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSUI_stopDownload failed to locate download.\n");
- return SYSERR;
- }
+ if (prev == NULL)
+ {
+ MUTEX_UNLOCK (ctx->lock);
+ GE_LOG (ctx->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FSUI_stopDownload failed to locate download.\n");
+ return SYSERR;
+ }
if (prev == dl)
- dl->parent->child = dl->next; /* first child of parent */
+ dl->parent->child = dl->next; /* first child of parent */
else
- prev->next = dl->next; /* not first child */
- MUTEX_UNLOCK(ctx->lock);
- if ( (dl->state == FSUI_ACTIVE) ||
- (dl->state == FSUI_COMPLETED) ||
- (dl->state == FSUI_ABORTED) ||
- (dl->state == FSUI_ERROR) ) {
- GE_ASSERT(ctx->ectx, dl->handle != NULL);
- PTHREAD_JOIN(dl->handle,
- &unused);
- MUTEX_LOCK(ctx->lock);
- dl->ctx->activeDownloadThreads--;
- MUTEX_UNLOCK(ctx->lock);
- dl->handle = NULL;
- if (dl->state == FSUI_ACTIVE)
- dl->state = FSUI_PENDING;
- else
- dl->state++; /* add _JOINED */
- } else {
- GE_ASSERT(ctx->ectx, dl->handle == NULL);
- }
+ prev->next = dl->next; /* not first child */
+ MUTEX_UNLOCK (ctx->lock);
+ if ((dl->state == FSUI_ACTIVE) ||
+ (dl->state == FSUI_COMPLETED) ||
+ (dl->state == FSUI_ABORTED) || (dl->state == FSUI_ERROR))
+ {
+ GE_ASSERT (ctx->ectx, dl->handle != NULL);
+ PTHREAD_JOIN (dl->handle, &unused);
+ MUTEX_LOCK (ctx->lock);
+ dl->ctx->activeDownloadThreads--;
+ MUTEX_UNLOCK (ctx->lock);
+ dl->handle = NULL;
+ if (dl->state == FSUI_ACTIVE)
+ dl->state = FSUI_PENDING;
+ else
+ dl->state++; /* add _JOINED */
+ }
+ else
+ {
+ GE_ASSERT (ctx->ectx, dl->handle == NULL);
+ }
event.type = FSUI_download_stopped;
event.data.DownloadStopped.dc.pos = dl;
event.data.DownloadStopped.dc.cctx = dl->cctx;
- event.data.DownloadStopped.dc.ppos = dl->parent == &ctx->activeDownloads ?
NULL : dl->parent;
+ event.data.DownloadStopped.dc.ppos =
+ dl->parent == &ctx->activeDownloads ? NULL : dl->parent;
event.data.DownloadStopped.dc.pcctx = dl->parent->cctx;
event.data.DownloadStopped.dc.spos = dl->search;
- event.data.DownloadStopped.dc.sctx = dl->search == NULL ? NULL :
dl->search->cctx;
- ctx->ecb(ctx->ecbClosure,
- &event);
- if (dl->search != NULL) {
- for (i=0;i<dl->search->my_downloads_size;i++) {
- if (dl->search->my_downloads[i] == dl) {
- dl->search->my_downloads[i] =
- dl->search->my_downloads[dl->search->my_downloads_size -1];
- GROW(dl->search->my_downloads,
- dl->search->my_downloads_size,
- dl->search->my_downloads_size - 1);
- }
+ event.data.DownloadStopped.dc.sctx =
+ dl->search == NULL ? NULL : dl->search->cctx;
+ ctx->ecb (ctx->ecbClosure, &event);
+ if (dl->search != NULL)
+ {
+ for (i = 0; i < dl->search->my_downloads_size; i++)
+ {
+ if (dl->search->my_downloads[i] == dl)
+ {
+ dl->search->my_downloads[i] =
+ dl->search->my_downloads[dl->search->my_downloads_size - 1];
+ GROW (dl->search->my_downloads,
+ dl->search->my_downloads_size,
+ dl->search->my_downloads_size - 1);
+ }
+ }
}
- }
- for (i=dl->completedDownloadsCount-1;i>=0;i--)
- ECRS_freeUri(dl->completedDownloads[i]);
- GROW(dl->completedDownloads,
- dl->completedDownloadsCount,
- 0);
- ECRS_freeUri(dl->fi.uri);
- ECRS_freeMetaData(dl->fi.meta);
- FREE(dl->filename);
- FREE(dl);
+ for (i = dl->completedDownloadsCount - 1; i >= 0; i--)
+ ECRS_freeUri (dl->completedDownloads[i]);
+ GROW (dl->completedDownloads, dl->completedDownloadsCount, 0);
+ ECRS_freeUri (dl->fi.uri);
+ ECRS_freeMetaData (dl->fi.meta);
+ FREE (dl->filename);
+ FREE (dl);
return OK;
}
Modified: GNUnet/src/applications/fs/fsui/downloadtest.c
===================================================================
--- GNUnet/src/applications/fs/fsui/downloadtest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/fsui/downloadtest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -37,176 +37,174 @@
static volatile int suspendRestart = 0;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static char * makeName(unsigned int i) {
- char * fn;
+static char *
+makeName (unsigned int i)
+{
+ char *fn;
- fn = MALLOC(strlen("/tmp/gnunet-fsui-downloadtest/FSUITEST") + 14);
- SNPRINTF(fn,
- strlen("/tmp/gnunet-fsui-downloadtest/FSUITEST") + 14,
- "/tmp/gnunet-fsui-downloadtest/FSUITEST%u",
- i);
- disk_directory_create_for_file(NULL, fn);
+ fn = MALLOC (strlen ("/tmp/gnunet-fsui-downloadtest/FSUITEST") + 14);
+ SNPRINTF (fn,
+ strlen ("/tmp/gnunet-fsui-downloadtest/FSUITEST") + 14,
+ "/tmp/gnunet-fsui-downloadtest/FSUITEST%u", i);
+ disk_directory_create_for_file (NULL, fn);
return fn;
}
static volatile enum FSUI_EventType lastEvent;
static volatile enum FSUI_EventType waitForEvent;
-static struct FSUI_Context * ctx;
-static struct ECRS_URI * upURI;
-static struct FSUI_SearchList * search;
-static struct FSUI_DownloadList * download;
+static struct FSUI_Context *ctx;
+static struct ECRS_URI *upURI;
+static struct FSUI_SearchList *search;
+static struct FSUI_DownloadList *download;
-static void * eventCallback(void * cls,
- const FSUI_Event * event) {
- char * fn;
+static void *
+eventCallback (void *cls, const FSUI_Event * event)
+{
+ char *fn;
- switch(event->type) {
- case FSUI_search_suspended:
- search = NULL;
- break;
- case FSUI_download_suspended:
- download = NULL;
- break;
- case FSUI_search_resumed:
+ switch (event->type)
+ {
+ case FSUI_search_suspended:
+ search = NULL;
+ break;
+ case FSUI_download_suspended:
+ download = NULL;
+ break;
+ case FSUI_search_resumed:
#if DEBUG_VERBOSE
- printf("Search resuming\n");
+ printf ("Search resuming\n");
#endif
- search = event->data.SearchResumed.sc.pos;
- break;
- case FSUI_download_resumed:
+ search = event->data.SearchResumed.sc.pos;
+ break;
+ case FSUI_download_resumed:
#if DEBUG_VERBOSE
- printf("Download resuming\n");
+ printf ("Download resuming\n");
#endif
- download = event->data.DownloadResumed.dc.pos;
- break;
- case FSUI_search_completed:
+ download = event->data.DownloadResumed.dc.pos;
+ break;
+ case FSUI_search_completed:
#if DEBUG_VERBOSE
- printf("Search completed\n");
+ printf ("Search completed\n");
#endif
- if (download == NULL) {
- fprintf(stderr,
- "ERROR: Search completed but download not started!\n");
- }
- break;
- case FSUI_search_result:
+ if (download == NULL)
+ {
+ fprintf (stderr,
+ "ERROR: Search completed but download not started!\n");
+ }
+ break;
+ case FSUI_search_result:
#if DEBUG_VERBOSE
- printf("Received search result\n");
+ printf ("Received search result\n");
#endif
- if (download == NULL) {
- char * u;
+ if (download == NULL)
+ {
+ char *u;
- if (! ECRS_equalsUri(upURI,
- event->data.SearchResult.fi.uri)) {
+ if (!ECRS_equalsUri (upURI, event->data.SearchResult.fi.uri))
+ {
#if DEBUG_VERBOSE
- printf("Received search result for different file (download not
started).\n");
+ printf
+ ("Received search result for different file (download not
started).\n");
#endif
- return NULL; /* ignore */
- }
- fn = makeName(43);
- u = ECRS_uriToString(event->data.SearchResult.fi.uri);
+ return NULL; /* ignore */
+ }
+ fn = makeName (43);
+ u = ECRS_uriToString (event->data.SearchResult.fi.uri);
#if DEBUG_VERBOSE
- printf("Download started: %s.\n", u);
+ printf ("Download started: %s.\n", u);
#endif
- FREE(u);
- download = FSUI_startDownload(ctx,
- 0,
- NO,
- event->data.SearchResult.fi.uri,
- event->data.SearchResult.fi.meta,
- fn,
- NULL,
- NULL);
- if (download == NULL) {
- GE_BREAK(ectx, 0);
- return NULL;
- }
- FREE(fn);
- suspendRestart = 4;
- }
- break;
- case FSUI_upload_progress:
+ FREE (u);
+ download = FSUI_startDownload (ctx,
+ 0,
+ NO,
+ event->data.SearchResult.fi.uri,
+ event->data.SearchResult.fi.meta,
+ fn, NULL, NULL);
+ if (download == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
+ FREE (fn);
+ suspendRestart = 4;
+ }
+ break;
+ case FSUI_upload_progress:
#if DEBUG_VERBOSE
- printf("Upload is progressing (%llu/%llu)...\n",
- event->data.UploadProgress.completed,
- event->data.UploadProgress.total);
+ printf ("Upload is progressing (%llu/%llu)...\n",
+ event->data.UploadProgress.completed,
+ event->data.UploadProgress.total);
#endif
- break;
- case FSUI_upload_completed:
- upURI = ECRS_dupUri(event->data.UploadCompleted.uri);
+ break;
+ case FSUI_upload_completed:
+ upURI = ECRS_dupUri (event->data.UploadCompleted.uri);
#if DEBUG_VERBOSE
- printf("Upload complete.\n");
+ printf ("Upload complete.\n");
#endif
- break;
- case FSUI_download_completed:
+ break;
+ case FSUI_download_completed:
#if DEBUG_VERBOSE
- printf("Download complete.\n");
+ printf ("Download complete.\n");
#endif
- FSUI_abortSearch(ctx,
- search);
- FSUI_stopSearch(ctx,
- search);
- search = NULL;
- break;
- case FSUI_download_progress:
+ FSUI_abortSearch (ctx, search);
+ FSUI_stopSearch (ctx, search);
+ search = NULL;
+ break;
+ case FSUI_download_progress:
#if DEBUG_VERBOSE
- printf("Download is progressing (%llu/%llu)...\n",
- event->data.DownloadProgress.completed,
- event->data.DownloadProgress.total);
+ printf ("Download is progressing (%llu/%llu)...\n",
+ event->data.DownloadProgress.completed,
+ event->data.DownloadProgress.total);
#endif
- break;
- case FSUI_unindex_progress:
+ break;
+ case FSUI_unindex_progress:
#if DEBUG_VERBOSE
- printf("Unindex is progressing (%llu/%llu)...\n",
- event->data.UnindexProgress.completed,
- event->data.UnindexProgress.total);
+ printf ("Unindex is progressing (%llu/%llu)...\n",
+ event->data.UnindexProgress.completed,
+ event->data.UnindexProgress.total);
#endif
- break;
- case FSUI_unindex_completed:
+ break;
+ case FSUI_unindex_completed:
#if DEBUG_VERBOSE
- printf("Unindex complete.\n");
+ printf ("Unindex complete.\n");
#endif
- break;
- case FSUI_unindex_error:
- case FSUI_upload_error:
- case FSUI_download_error:
- case FSUI_search_error:
- fprintf(stderr,
- "Received ERROR: %d\n",
- event->type);
- GE_BREAK(ectx, 0);
- break;
- case FSUI_download_aborted:
+ break;
+ case FSUI_unindex_error:
+ case FSUI_upload_error:
+ case FSUI_download_error:
+ case FSUI_search_error:
+ fprintf (stderr, "Received ERROR: %d\n", event->type);
+ GE_BREAK (ectx, 0);
+ break;
+ case FSUI_download_aborted:
#if DEBUG_VERBOSE
- printf("Received download aborted event.\n");
+ printf ("Received download aborted event.\n");
#endif
- break;
- case FSUI_unindex_suspended:
- case FSUI_upload_suspended:
+ break;
+ case FSUI_unindex_suspended:
+ case FSUI_upload_suspended:
#if DEBUG_VERBOSE
- fprintf(stderr,
- "Received SUSPENDING: %d\n",
- event->type);
+ fprintf (stderr, "Received SUSPENDING: %d\n", event->type);
#endif
- break;
- case FSUI_upload_started:
- case FSUI_upload_stopped:
- case FSUI_download_started:
- case FSUI_download_stopped:
- case FSUI_search_started:
- case FSUI_search_aborted:
- case FSUI_search_stopped:
- case FSUI_unindex_started:
- case FSUI_unindex_stopped:
- break;
- default:
- printf("Unexpected event: %d\n",
- event->type);
- break;
- }
+ break;
+ case FSUI_upload_started:
+ case FSUI_upload_stopped:
+ case FSUI_download_started:
+ case FSUI_download_stopped:
+ case FSUI_search_started:
+ case FSUI_search_aborted:
+ case FSUI_search_stopped:
+ case FSUI_unindex_started:
+ case FSUI_unindex_stopped:
+ break;
+ default:
+ printf ("Unexpected event: %d\n", event->type);
+ break;
+ }
if (lastEvent == waitForEvent)
- return NULL; /* ignore all other events */
+ return NULL; /* ignore all other events */
lastEvent = event->type;
return NULL;
}
@@ -215,187 +213,160 @@
#define START_DAEMON 1
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
#if START_DAEMON
pid_t daemon;
#endif
int ok;
int i;
- struct ECRS_URI * uri = NULL;
- char * fn = NULL;
- char * keywords[] = {
+ struct ECRS_URI *uri = NULL;
+ char *fn = NULL;
+ char *keywords[] = {
"down_foo",
"down_bar",
NULL,
};
char keyword[40];
int prog;
- char * buf;
- struct ECRS_MetaData * meta;
- struct ECRS_URI * kuri = NULL;
- struct GC_Configuration * cfg;
- struct FSUI_UnindexList * unindex = NULL;
- struct FSUI_UploadList * upload = NULL;
+ char *buf;
+ struct ECRS_MetaData *meta;
+ struct ECRS_URI *kuri = NULL;
+ struct GC_Configuration *cfg;
+ struct FSUI_UnindexList *unindex = NULL;
+ struct FSUI_UploadList *upload = NULL;
ok = YES;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_DAEMON
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
- CHECK(OK == connection_wait_for_running(NULL,
- cfg,
- 30 * cronSECONDS));
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
+ CHECK (OK == connection_wait_for_running (NULL, cfg, 30 * cronSECONDS));
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
/* ACTUAL TEST CODE */
#endif
- ctx = FSUI_start(NULL,
- cfg,
- "fsuidownloadtest",
- 32,
- YES,
- &eventCallback,
- NULL);
- CHECK(ctx != NULL);
- fn = makeName(42);
- buf = MALLOC(FILESIZE);
- for (i=0;i<FILESIZE;i++)
- buf[i] = weak_randomi(256);
- disk_file_write(ectx,
- fn,
- buf,
- FILESIZE,
- "600");
- FREE(buf);
- meta = ECRS_createMetaData();
- kuri = ECRS_parseListKeywordURI(ectx,
- 2,
- (const char**)keywords);
+ ctx = FSUI_start (NULL,
+ cfg, "fsuidownloadtest", 32, YES, &eventCallback, NULL);
+ CHECK (ctx != NULL);
+ fn = makeName (42);
+ buf = MALLOC (FILESIZE);
+ for (i = 0; i < FILESIZE; i++)
+ buf[i] = weak_randomi (256);
+ disk_file_write (ectx, fn, buf, FILESIZE, "600");
+ FREE (buf);
+ meta = ECRS_createMetaData ();
+ kuri = ECRS_parseListKeywordURI (ectx, 2, (const char **) keywords);
waitForEvent = FSUI_upload_completed;
- upload = FSUI_startUpload(ctx,
- fn,
- (DirectoryScanCallback) &disk_directory_scan,
- NULL,
- 0,
- 0,
- YES,
- NO,
- NO,
- get_time() + 5 * cronHOURS,
- meta,
- kuri,
- kuri);
- CHECK(upload != NULL);
- ECRS_freeUri(kuri);
+ upload = FSUI_startUpload (ctx,
+ fn,
+ (DirectoryScanCallback) & disk_directory_scan,
+ NULL,
+ 0,
+ 0,
+ YES,
+ NO,
+ NO,
+ get_time () + 5 * cronHOURS, meta, kuri, kuri);
+ CHECK (upload != NULL);
+ ECRS_freeUri (kuri);
kuri = NULL;
- ECRS_freeMetaData(meta);
+ ECRS_freeMetaData (meta);
prog = 0;
- while (lastEvent != FSUI_upload_completed) {
- prog++;
- CHECK(prog < 5000);
- PTHREAD_SLEEP(50 * cronMILLIS);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- FSUI_stopUpload(ctx, upload);
- SNPRINTF(keyword,
- 40,
- "%s %s %s",
- keywords[0],
- _("AND"),
- keywords[1]);
- uri = ECRS_parseCharKeywordURI(ectx,
- keyword);
+ while (lastEvent != FSUI_upload_completed)
+ {
+ prog++;
+ CHECK (prog < 5000);
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
+ FSUI_stopUpload (ctx, upload);
+ SNPRINTF (keyword, 40, "%s %s %s", keywords[0], _("AND"), keywords[1]);
+ uri = ECRS_parseCharKeywordURI (ectx, keyword);
waitForEvent = FSUI_download_completed;
- search = FSUI_startSearch(ctx,
- 0,
- 10000,
- 240 * cronSECONDS,
- uri);
- CHECK(search != NULL);
+ search = FSUI_startSearch (ctx, 0, 10000, 240 * cronSECONDS, uri);
+ CHECK (search != NULL);
prog = 0;
- while (search != NULL) {
- prog++;
- CHECK(prog < 10000);
- PTHREAD_SLEEP(50 * cronMILLIS);
- if ( (suspendRestart > 0) &&
- (weak_randomi(4) == 0) ) {
+ while (search != NULL)
+ {
+ prog++;
+ CHECK (prog < 10000);
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ if ((suspendRestart > 0) && (weak_randomi (4) == 0))
+ {
#if 1
#if DEBUG_VERBOSE
- printf("Testing FSUI suspend-resume\n");
+ printf ("Testing FSUI suspend-resume\n");
#endif
- FSUI_stop(ctx); /* download possibly incomplete
- at this point, thus testing resume */
- CHECK(search == NULL);
- CHECK(download == NULL);
- ctx = FSUI_start(NULL,
- cfg,
- "fsuidownloadtest",
- 32,
- YES,
- &eventCallback,
- NULL);
+ FSUI_stop (ctx); /* download possibly incomplete
+ at this point, thus testing resume */
+ CHECK (search == NULL);
+ CHECK (download == NULL);
+ ctx = FSUI_start (NULL,
+ cfg,
+ "fsuidownloadtest",
+ 32, YES, &eventCallback, NULL);
#if DEBUG_VERBOSE
- printf("Resumed...\n");
+ printf ("Resumed...\n");
#endif
#endif
- suspendRestart--;
+ suspendRestart--;
+ }
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
}
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- CHECK(search == NULL);
- CHECK(download != NULL);
+ CHECK (search == NULL);
+ CHECK (download != NULL);
waitForEvent = FSUI_unindex_completed;
- unindex = FSUI_startUnindex(ctx, fn);
- CHECK(unindex != NULL);
+ unindex = FSUI_startUnindex (ctx, fn);
+ CHECK (unindex != NULL);
prog = 0;
- while (lastEvent != FSUI_unindex_completed) {
- prog++;
- CHECK(prog < 5000);
- PTHREAD_SLEEP(50 * cronMILLIS);
- CHECK(lastEvent != FSUI_unindex_error);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- CHECK(lastEvent == FSUI_unindex_completed);
+ while (lastEvent != FSUI_unindex_completed)
+ {
+ prog++;
+ CHECK (prog < 5000);
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ CHECK (lastEvent != FSUI_unindex_error);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
+ CHECK (lastEvent == FSUI_unindex_completed);
/* END OF TEST CODE */
- FAILURE:
- if (ctx != NULL) {
- if (unindex != NULL)
- FSUI_stopUnindex(ctx,
- unindex);
- if (download != NULL)
- FSUI_stopDownload(ctx,
- download);
- FSUI_stop(ctx);
- }
- if (fn != NULL) {
- UNLINK(fn);
- FREE(fn);
- }
+FAILURE:
+ if (ctx != NULL)
+ {
+ if (unindex != NULL)
+ FSUI_stopUnindex (ctx, unindex);
+ if (download != NULL)
+ FSUI_stopDownload (ctx, download);
+ FSUI_stop (ctx);
+ }
+ if (fn != NULL)
+ {
+ UNLINK (fn);
+ FREE (fn);
+ }
if (uri != NULL)
- ECRS_freeUri(uri);
+ ECRS_freeUri (uri);
if (kuri != NULL)
- ECRS_freeUri(kuri);
- fn = makeName(43);
+ ECRS_freeUri (kuri);
+ fn = makeName (43);
/* TODO: verify file 'fn(42)' == file 'fn(43)' */
- UNLINK(fn);
- FREE(fn);
+ UNLINK (fn);
+ FREE (fn);
if (upURI != NULL)
- ECRS_freeUri(upURI);
+ ECRS_freeUri (upURI);
#if START_DAEMON
- GE_BREAK(NULL, OK == os_daemon_stop(NULL, daemon));
+ GE_BREAK (NULL, OK == os_daemon_stop (NULL, daemon));
#endif
- GC_free(cfg);
+ GC_free (cfg);
return (ok == YES) ? 0 : 1;
}
Modified: GNUnet/src/applications/fs/fsui/fsui-loader.c
===================================================================
--- GNUnet/src/applications/fs/fsui/fsui-loader.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/fsui/fsui-loader.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -28,54 +28,50 @@
#include "gnunet_fsui_lib.h"
#include "gnunet_util_config_impl.h"
-static void * eventCallback(void * cls,
- const FSUI_Event * event) {
+static void *
+eventCallback (void *cls, const FSUI_Event * event)
+{
#if 0
- switch(event->type) {
- case FSUI_search_result:
- printf("Received search result\n");
- break;
- case FSUI_upload_complete:
- printf("Upload complete.\n");
- break;
- case FSUI_download_complete:
- printf("Download complete.\n");
- break;
- case FSUI_unindex_complete:
- printf("Unindex complete.\n");
- break;
- default:
- printf("Other event.\n");
- break;
- }
+ switch (event->type)
+ {
+ case FSUI_search_result:
+ printf ("Received search result\n");
+ break;
+ case FSUI_upload_complete:
+ printf ("Upload complete.\n");
+ break;
+ case FSUI_download_complete:
+ printf ("Download complete.\n");
+ break;
+ case FSUI_unindex_complete:
+ printf ("Unindex complete.\n");
+ break;
+ default:
+ printf ("Other event.\n");
+ break;
+ }
#endif
return NULL;
}
-int main(int argc,
- char * argv[]) {
- struct FSUI_Context * ctx;
- struct GC_Configuration * cfg;
+int
+main (int argc, char *argv[])
+{
+ struct FSUI_Context *ctx;
+ struct GC_Configuration *cfg;
- os_init(NULL);
- cfg = GC_create_C_impl();
- if (argc != 2) {
- fprintf(stderr,
- "Call with name of FSUI resource file!\n");
- return -1;
- }
- ctx = FSUI_start(NULL,
- cfg,
- argv[1],
- 16,
- YES,
- &eventCallback,
- NULL);
+ os_init (NULL);
+ cfg = GC_create_C_impl ();
+ if (argc != 2)
+ {
+ fprintf (stderr, "Call with name of FSUI resource file!\n");
+ return -1;
+ }
+ ctx = FSUI_start (NULL, cfg, argv[1], 16, YES, &eventCallback, NULL);
if (ctx != NULL)
- FSUI_stop(ctx);
+ FSUI_stop (ctx);
else
- fprintf(stderr,
- "FSUI_start failed!\n");
- GC_free(cfg);
+ fprintf (stderr, "FSUI_start failed!\n");
+ GC_free (cfg);
return (ctx == NULL);
}
Modified: GNUnet/src/applications/fs/fsui/fsui.c
===================================================================
--- GNUnet/src/applications/fs/fsui/fsui.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/fsui/fsui.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -38,102 +38,115 @@
/**
* Cron job for download load management.
*/
-static void updateDownloadThreads(void * c) {
- FSUI_Context * ctx = c;
- FSUI_DownloadList * dpos;
+static void
+updateDownloadThreads (void *c)
+{
+ FSUI_Context *ctx = c;
+ FSUI_DownloadList *dpos;
- MUTEX_LOCK(ctx->lock);
+ MUTEX_LOCK (ctx->lock);
dpos = ctx->activeDownloads.child;
#if DEBUG_PERSISTENCE
if (dpos != NULL)
- GE_LOG(ctx->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Download thread manager schedules pending downloads...\n");
+ GE_LOG (ctx->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Download thread manager schedules pending downloads...\n");
#endif
- while (dpos != NULL) {
- FSUI_updateDownloadThread(dpos);
- dpos = dpos->next;
- }
- MUTEX_UNLOCK(ctx->lock);
+ while (dpos != NULL)
+ {
+ FSUI_updateDownloadThread (dpos);
+ dpos = dpos->next;
+ }
+ MUTEX_UNLOCK (ctx->lock);
}
/* ******************* START code *********************** */
-static void signalDownloadResume(struct FSUI_DownloadList * ret,
- FSUI_Context * ctx) {
+static void
+signalDownloadResume (struct FSUI_DownloadList *ret, FSUI_Context * ctx)
+{
FSUI_Event event;
cron_t now;
cron_t eta;
- while (ret != NULL) {
- event.type = FSUI_download_resumed;
- event.data.DownloadResumed.dc.pos = ret;
- event.data.DownloadResumed.dc.cctx = ret->cctx;
- event.data.DownloadResumed.dc.ppos = ret->parent == &ctx->activeDownloads
? NULL : ret->parent;
- event.data.DownloadResumed.dc.pcctx = ret->parent->cctx;
- event.data.DownloadResumed.dc.spos = ret->search;
- event.data.DownloadResumed.dc.sctx = ret->search == NULL ? NULL :
ret->search->cctx;
- event.data.DownloadResumed.completed = ret->completed;
- event.data.DownloadResumed.total = ret->total;
- event.data.DownloadResumed.state = ret->state;
- now = get_time();
- if ( (ret->total == 0) || (ret->completed == 0) ) {
- eta = now;
- } else {
- eta = (cron_t) (now - ret->runTime +
- (((double)(ret->runTime)/(double)ret->completed))
- * (double)ret->total);
- if (eta < now)
- eta = now;
+ while (ret != NULL)
+ {
+ event.type = FSUI_download_resumed;
+ event.data.DownloadResumed.dc.pos = ret;
+ event.data.DownloadResumed.dc.cctx = ret->cctx;
+ event.data.DownloadResumed.dc.ppos =
+ ret->parent == &ctx->activeDownloads ? NULL : ret->parent;
+ event.data.DownloadResumed.dc.pcctx = ret->parent->cctx;
+ event.data.DownloadResumed.dc.spos = ret->search;
+ event.data.DownloadResumed.dc.sctx =
+ ret->search == NULL ? NULL : ret->search->cctx;
+ event.data.DownloadResumed.completed = ret->completed;
+ event.data.DownloadResumed.total = ret->total;
+ event.data.DownloadResumed.state = ret->state;
+ now = get_time ();
+ if ((ret->total == 0) || (ret->completed == 0))
+ {
+ eta = now;
+ }
+ else
+ {
+ eta = (cron_t) (now - ret->runTime +
+ (((double) (ret->runTime) /
+ (double) ret->completed)) * (double) ret->total);
+ if (eta < now)
+ eta = now;
+ }
+ event.data.DownloadResumed.eta = eta;
+ event.data.DownloadResumed.filename = ret->filename;
+ event.data.DownloadResumed.fi.uri = ret->fi.uri;
+ event.data.DownloadResumed.fi.meta = ret->fi.meta;
+ event.data.DownloadResumed.anonymityLevel = ret->anonymityLevel;
+ ret->cctx = ctx->ecb (ctx->ecbClosure, &event);
+ if (ret->child != NULL)
+ signalDownloadResume (ret->child, ctx);
+ ret = ret->next;
}
- event.data.DownloadResumed.eta = eta;
- event.data.DownloadResumed.filename = ret->filename;
- event.data.DownloadResumed.fi.uri = ret->fi.uri;
- event.data.DownloadResumed.fi.meta = ret->fi.meta;
- event.data.DownloadResumed.anonymityLevel = ret->anonymityLevel;
- ret->cctx = ctx->ecb(ctx->ecbClosure, &event);
- if (ret->child != NULL)
- signalDownloadResume(ret->child,
- ctx);
- ret = ret->next;
- }
}
-static void signalUploadResume(struct FSUI_UploadList * ret,
- FSUI_Context * ctx) {
+static void
+signalUploadResume (struct FSUI_UploadList *ret, FSUI_Context * ctx)
+{
FSUI_Event event;
cron_t now;
cron_t eta;
- while (ret != NULL) {
- event.type = FSUI_upload_resumed;
- event.data.UploadResumed.uc.pos = ret;
- event.data.UploadResumed.uc.cctx = NULL;
- event.data.UploadResumed.uc.ppos = ret->parent;
- event.data.UploadResumed.uc.pcctx = ret->parent->cctx;
- event.data.UploadResumed.completed = ret->completed;
- event.data.UploadResumed.total = ret->total;
- event.data.UploadResumed.uri = ret->uri;
- event.data.UploadResumed.state = ret->state;
- now = get_time();
- if ( (ret->total == 0) || (ret->completed == 0) ) {
- eta = now;
- } else {
- eta = (cron_t) (ret->start_time +
- (((double)(now - ret->start_time)/(double)ret->completed))
- * (double)ret->total);
- if (eta < now)
- eta = now;
+ while (ret != NULL)
+ {
+ event.type = FSUI_upload_resumed;
+ event.data.UploadResumed.uc.pos = ret;
+ event.data.UploadResumed.uc.cctx = NULL;
+ event.data.UploadResumed.uc.ppos = ret->parent;
+ event.data.UploadResumed.uc.pcctx = ret->parent->cctx;
+ event.data.UploadResumed.completed = ret->completed;
+ event.data.UploadResumed.total = ret->total;
+ event.data.UploadResumed.uri = ret->uri;
+ event.data.UploadResumed.state = ret->state;
+ now = get_time ();
+ if ((ret->total == 0) || (ret->completed == 0))
+ {
+ eta = now;
+ }
+ else
+ {
+ eta = (cron_t) (ret->start_time +
+ (((double) (now - ret->start_time) /
+ (double) ret->completed)) * (double) ret->total);
+ if (eta < now)
+ eta = now;
+ }
+ event.data.UploadResumed.eta = eta;
+ event.data.UploadResumed.anonymityLevel = ret->shared->anonymityLevel;
+ event.data.UploadResumed.filename = ret->filename;
+ ret->cctx = ctx->ecb (ctx->ecbClosure, &event);
+ if (ret->child != NULL)
+ signalUploadResume (ret->child, ctx);
+ ret = ret->next;
}
- event.data.UploadResumed.eta = eta;
- event.data.UploadResumed.anonymityLevel = ret->shared->anonymityLevel;
- event.data.UploadResumed.filename = ret->filename;
- ret->cctx = ctx->ecb(ctx->ecbClosure, &event);
- if (ret->child != NULL)
- signalUploadResume(ret->child,
- ctx);
- ret = ret->next;
- }
}
/**
@@ -141,20 +154,22 @@
* Only re-starts top-level upload threads;
* threads below are controlled by the parent.
*/
-static void doResumeUploads(struct FSUI_UploadList * ret,
- FSUI_Context * ctx) {
- while (ret != NULL) {
- if (ret->state == FSUI_ACTIVE) {
- ret->shared->handle = PTHREAD_CREATE(&FSUI_uploadThread,
- ret,
- 128 * 1024);
- if (ret->shared->handle == NULL)
- GE_DIE_STRERROR(ctx->ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "pthread_create");
+static void
+doResumeUploads (struct FSUI_UploadList *ret, FSUI_Context * ctx)
+{
+ while (ret != NULL)
+ {
+ if (ret->state == FSUI_ACTIVE)
+ {
+ ret->shared->handle = PTHREAD_CREATE (&FSUI_uploadThread,
+ ret, 128 * 1024);
+ if (ret->shared->handle == NULL)
+ GE_DIE_STRERROR (ctx->ectx,
+ GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
+ "pthread_create");
+ }
+ ret = ret->next;
}
- ret = ret->next;
- }
}
/**
@@ -165,28 +180,25 @@
* @param name name of the context, must not be NULL
* @return NULL on error
*/
-struct FSUI_Context * FSUI_start(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name,
- unsigned int threadPoolSize,
- int doResume,
- FSUI_EventCallback cb,
- void * closure) {
+struct FSUI_Context *
+FSUI_start (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *name,
+ unsigned int threadPoolSize,
+ int doResume, FSUI_EventCallback cb, void *closure)
+{
FSUI_Event event;
- FSUI_Context * ret;
- FSUI_SearchList * list;
- FSUI_UnindexList * xlist;
- char * fn;
- char * gh;
+ FSUI_Context *ret;
+ FSUI_SearchList *list;
+ FSUI_UnindexList *xlist;
+ char *fn;
+ char *gh;
unsigned long long size;
- GE_ASSERT(ectx, cfg != NULL);
- ret = MALLOC(sizeof(FSUI_Context));
- memset(ret,
- 0,
- sizeof(FSUI_Context));
- ret->activeDownloads.state
- = FSUI_PENDING; /* !? */
+ GE_ASSERT (ectx, cfg != NULL);
+ ret = MALLOC (sizeof (FSUI_Context));
+ memset (ret, 0, sizeof (FSUI_Context));
+ ret->activeDownloads.state = FSUI_PENDING; /* !? */
ret->activeDownloads.ctx = ret;
ret->cfg = cfg;
ret->ecb = cb;
@@ -196,126 +208,118 @@
ret->threadPoolSize = 32;
ret->activeDownloadThreads = 0;
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &gh);
- disk_directory_create(ectx, gh);
- fn = MALLOC(strlen(gh) + strlen(name) + 2 + 5);
- strcpy(fn, gh);
- FREE(gh);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, name);
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &gh);
+ disk_directory_create (ectx, gh);
+ fn = MALLOC (strlen (gh) + strlen (name) + 2 + 5);
+ strcpy (fn, gh);
+ FREE (gh);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, name);
ret->name = fn;
/* 1) read state in */
- if (doResume) {
- ret->ipc = IPC_SEMAPHORE_CREATE(ectx,
- fn,
- 1);
+ if (doResume)
+ {
+ ret->ipc = IPC_SEMAPHORE_CREATE (ectx, fn, 1);
#if DEBUG_PERSISTENCE
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- "Getting IPC lock for FSUI (%s).\n",
- fn);
+ GE_LOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ "Getting IPC lock for FSUI (%s).\n", fn);
#endif
- IPC_SEMAPHORE_DOWN(ret->ipc, YES);
+ IPC_SEMAPHORE_DOWN (ret->ipc, YES);
#if DEBUG_PERSISTENCE
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- "Aquired IPC lock.\n");
+ GE_LOG (ectx, GE_INFO | GE_REQUEST | GE_USER, "Aquired IPC lock.\n");
#endif
- strcat(fn, ".res");
- FSUI_deserialize(ret);
- } else {
- ret->ipc = NULL;
- }
- ret->lock = MUTEX_CREATE(YES);
+ strcat (fn, ".res");
+ FSUI_deserialize (ret);
+ }
+ else
+ {
+ ret->ipc = NULL;
+ }
+ ret->lock = MUTEX_CREATE (YES);
/* 2) do resume events */
/* 2a) signal download restarts */
- signalDownloadResume(ret->activeDownloads.child,
- ret);
+ signalDownloadResume (ret->activeDownloads.child, ret);
/* 2b) signal search restarts */
list = ret->activeSearches;
- while (list != NULL) {
- event.type = FSUI_search_resumed;
- event.data.SearchResumed.sc.pos = list;
- event.data.SearchResumed.sc.cctx = NULL;
- event.data.SearchResumed.fis = list->resultsReceived;
- event.data.SearchResumed.fisSize = list->sizeResultsReceived;
- event.data.SearchResumed.anonymityLevel = list->anonymityLevel;
- event.data.SearchResumed.searchURI = list->uri;
- event.data.SearchResumed.state = list->state;
- list->cctx = cb(closure, &event);
- list = list->next;
- }
+ while (list != NULL)
+ {
+ event.type = FSUI_search_resumed;
+ event.data.SearchResumed.sc.pos = list;
+ event.data.SearchResumed.sc.cctx = NULL;
+ event.data.SearchResumed.fis = list->resultsReceived;
+ event.data.SearchResumed.fisSize = list->sizeResultsReceived;
+ event.data.SearchResumed.anonymityLevel = list->anonymityLevel;
+ event.data.SearchResumed.searchURI = list->uri;
+ event.data.SearchResumed.state = list->state;
+ list->cctx = cb (closure, &event);
+ list = list->next;
+ }
/* 2c) signal upload restarts */
- signalUploadResume(ret->activeUploads.child,
- ret);
+ signalUploadResume (ret->activeUploads.child, ret);
/* 2d) signal unindex restarts */
xlist = ret->unindexOperations;
- while (xlist != NULL) {
- if (OK != disk_file_size(ectx,
- xlist->filename,
- &size,
- YES))
- size = 0;
- event.type = FSUI_unindex_resumed;
- event.data.UnindexResumed.uc.pos = xlist;
- event.data.UnindexResumed.uc.cctx = NULL;
- event.data.UnindexResumed.completed = (xlist->state ==
FSUI_COMPLETED_JOINED) ? size : 0;
- event.data.UnindexResumed.total = size;
- event.data.UnindexResumed.eta = get_time();
- event.data.UnindexResumed.filename = xlist->filename;
- event.data.UnindexResumed.state = xlist->state;
- xlist->cctx = cb(closure, &event);
- xlist = xlist->next;
- }
+ while (xlist != NULL)
+ {
+ if (OK != disk_file_size (ectx, xlist->filename, &size, YES))
+ size = 0;
+ event.type = FSUI_unindex_resumed;
+ event.data.UnindexResumed.uc.pos = xlist;
+ event.data.UnindexResumed.uc.cctx = NULL;
+ event.data.UnindexResumed.completed =
+ (xlist->state == FSUI_COMPLETED_JOINED) ? size : 0;
+ event.data.UnindexResumed.total = size;
+ event.data.UnindexResumed.eta = get_time ();
+ event.data.UnindexResumed.filename = xlist->filename;
+ event.data.UnindexResumed.state = xlist->state;
+ xlist->cctx = cb (closure, &event);
+ xlist = xlist->next;
+ }
/* 3) restart processing */
- ret->cron = cron_create(ectx);
+ ret->cron = cron_create (ectx);
/* 3a) resume downloads */
- cron_add_job(ret->cron,
- &updateDownloadThreads,
- 0,
- FSUI_UDT_FREQUENCY,
- ret);
- cron_start(ret->cron);
+ cron_add_job (ret->cron,
+ &updateDownloadThreads, 0, FSUI_UDT_FREQUENCY, ret);
+ cron_start (ret->cron);
/* 3b) resume uploads */
- doResumeUploads(ret->activeUploads.child,
- ret);
+ doResumeUploads (ret->activeUploads.child, ret);
/* 3c) resume unindexing */
xlist = ret->unindexOperations;
- while (xlist != NULL) {
- if (xlist->state == FSUI_PENDING) {
- xlist->state = FSUI_ACTIVE;
- xlist->handle = PTHREAD_CREATE(&FSUI_unindexThread,
- xlist,
- 32 * 1024);
- if (xlist->handle == NULL)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "pthread_create");
+ while (xlist != NULL)
+ {
+ if (xlist->state == FSUI_PENDING)
+ {
+ xlist->state = FSUI_ACTIVE;
+ xlist->handle = PTHREAD_CREATE (&FSUI_unindexThread,
+ xlist, 32 * 1024);
+ if (xlist->handle == NULL)
+ GE_DIE_STRERROR (ectx,
+ GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
+ "pthread_create");
+ }
+ xlist = xlist->next;
}
- xlist = xlist->next;
- }
/* 3d) resume searching */
list = ret->activeSearches;
- while (list != NULL) {
- if (list->state == FSUI_PENDING) {
- list->state = FSUI_ACTIVE;
- list->handle = PTHREAD_CREATE(&FSUI_searchThread,
- list,
- 32 * 1024);
- if (list->handle == NULL)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "pthread_create");
+ while (list != NULL)
+ {
+ if (list->state == FSUI_PENDING)
+ {
+ list->state = FSUI_ACTIVE;
+ list->handle = PTHREAD_CREATE (&FSUI_searchThread, list, 32 * 1024);
+ if (list->handle == NULL)
+ GE_DIE_STRERROR (ectx,
+ GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
+ "pthread_create");
+ }
+ list = list->next;
}
- list = list->next;
- }
return ret;
}
@@ -325,274 +329,279 @@
/**
* (recursively) signal download suspension.
*/
-static void signalDownloadSuspend(struct GE_Context * ectx,
- FSUI_Context * ctx,
- FSUI_DownloadList * list) {
+static void
+signalDownloadSuspend (struct GE_Context *ectx,
+ FSUI_Context * ctx, FSUI_DownloadList * list)
+{
FSUI_Event event;
- while (list != NULL) {
- signalDownloadSuspend(ectx,
- ctx,
- list->child);
- event.type = FSUI_download_suspended;
- event.data.DownloadSuspended.dc.pos = list;
- event.data.DownloadSuspended.dc.cctx = list->cctx;
- event.data.DownloadSuspended.dc.ppos = list->parent ==
&ctx->activeDownloads ? NULL : list->parent;
- event.data.DownloadSuspended.dc.pcctx = list->parent->cctx;
- event.data.DownloadSuspended.dc.spos = list->search;
- event.data.DownloadSuspended.dc.sctx = list->search == NULL ? NULL :
list->search->cctx;
- ctx->ecb(ctx->ecbClosure, &event);
- list = list->next;
- }
+ while (list != NULL)
+ {
+ signalDownloadSuspend (ectx, ctx, list->child);
+ event.type = FSUI_download_suspended;
+ event.data.DownloadSuspended.dc.pos = list;
+ event.data.DownloadSuspended.dc.cctx = list->cctx;
+ event.data.DownloadSuspended.dc.ppos =
+ list->parent == &ctx->activeDownloads ? NULL : list->parent;
+ event.data.DownloadSuspended.dc.pcctx = list->parent->cctx;
+ event.data.DownloadSuspended.dc.spos = list->search;
+ event.data.DownloadSuspended.dc.sctx =
+ list->search == NULL ? NULL : list->search->cctx;
+ ctx->ecb (ctx->ecbClosure, &event);
+ list = list->next;
+ }
}
/**
* (recursively) signal upload suspension.
*/
-static void signalUploadSuspend(struct GE_Context * ectx,
- FSUI_Context * ctx,
- FSUI_UploadList * upos) {
+static void
+signalUploadSuspend (struct GE_Context *ectx,
+ FSUI_Context * ctx, FSUI_UploadList * upos)
+{
FSUI_Event event;
- while (upos != NULL) {
- signalUploadSuspend(ectx,
- ctx,
- upos->child);
- event.type = FSUI_upload_suspended;
- event.data.UploadSuspended.uc.pos = upos;
- event.data.UploadSuspended.uc.cctx = upos->cctx;
- event.data.UploadSuspended.uc.ppos = upos->parent;
- event.data.UploadSuspended.uc.pcctx = upos->parent->cctx;
- ctx->ecb(ctx->ecbClosure, &event);
- upos = upos->next;
- }
+ while (upos != NULL)
+ {
+ signalUploadSuspend (ectx, ctx, upos->child);
+ event.type = FSUI_upload_suspended;
+ event.data.UploadSuspended.uc.pos = upos;
+ event.data.UploadSuspended.uc.cctx = upos->cctx;
+ event.data.UploadSuspended.uc.ppos = upos->parent;
+ event.data.UploadSuspended.uc.pcctx = upos->parent->cctx;
+ ctx->ecb (ctx->ecbClosure, &event);
+ upos = upos->next;
+ }
}
/**
* (recursively) free download list
*/
-static void freeDownloadList(FSUI_DownloadList * list) {
- FSUI_DownloadList * next;
+static void
+freeDownloadList (FSUI_DownloadList * list)
+{
+ FSUI_DownloadList *next;
int i;
- while (list != NULL) {
- freeDownloadList(list->child);
- ECRS_freeUri(list->fi.uri);
- ECRS_freeMetaData(list->fi.meta);
- FREE(list->filename);
- for (i=0;i<list->completedDownloadsCount;i++)
- ECRS_freeUri(list->completedDownloads[i]);
- GROW(list->completedDownloads,
- list->completedDownloadsCount,
- 0);
- next = list->next;
- FREE(list);
- list = next;
- }
+ while (list != NULL)
+ {
+ freeDownloadList (list->child);
+ ECRS_freeUri (list->fi.uri);
+ ECRS_freeMetaData (list->fi.meta);
+ FREE (list->filename);
+ for (i = 0; i < list->completedDownloadsCount; i++)
+ ECRS_freeUri (list->completedDownloads[i]);
+ GROW (list->completedDownloads, list->completedDownloadsCount, 0);
+ next = list->next;
+ FREE (list);
+ list = next;
+ }
}
/**
* (recursively) free upload list
*/
-static void freeUploadList(struct FSUI_Context * ctx,
- FSUI_UploadList * list) {
- FSUI_UploadList * next;
- FSUI_UploadShared * shared;
+static void
+freeUploadList (struct FSUI_Context *ctx, FSUI_UploadList * list)
+{
+ FSUI_UploadList *next;
+ FSUI_UploadShared *shared;
- while (list != NULL) {
- freeUploadList(ctx, list->child);
- next = list->next;
- FREE(list->filename);
- if (list->meta != NULL)
- ECRS_freeMetaData(list->meta);
- if (list->keywords != NULL)
- ECRS_freeUri(list->keywords);
- if (list->uri != NULL)
- ECRS_freeUri(list->uri);
- if (list->parent == &ctx->activeUploads) {
- shared = list->shared;
- EXTRACTOR_removeAll(shared->extractors);
- if (shared->global_keywords != NULL)
- ECRS_freeUri(shared->global_keywords);
- FREENONNULL(shared->extractor_config);
- FREE(shared);
+ while (list != NULL)
+ {
+ freeUploadList (ctx, list->child);
+ next = list->next;
+ FREE (list->filename);
+ if (list->meta != NULL)
+ ECRS_freeMetaData (list->meta);
+ if (list->keywords != NULL)
+ ECRS_freeUri (list->keywords);
+ if (list->uri != NULL)
+ ECRS_freeUri (list->uri);
+ if (list->parent == &ctx->activeUploads)
+ {
+ shared = list->shared;
+ EXTRACTOR_removeAll (shared->extractors);
+ if (shared->global_keywords != NULL)
+ ECRS_freeUri (shared->global_keywords);
+ FREENONNULL (shared->extractor_config);
+ FREE (shared);
+ }
+ FREE (list);
+ list = next;
}
- FREE(list);
- list = next;
- }
}
/**
* Stop all processes under FSUI control (serialize state, continue
* later if possible).
*/
-void FSUI_stop(struct FSUI_Context * ctx) {
- struct GE_Context * ectx;
- FSUI_SearchList * spos;
- FSUI_DownloadList * dpos;
- FSUI_UnindexList * xpos;
- FSUI_UploadList * upos;
+void
+FSUI_stop (struct FSUI_Context *ctx)
+{
+ struct GE_Context *ectx;
+ FSUI_SearchList *spos;
+ FSUI_DownloadList *dpos;
+ FSUI_UnindexList *xpos;
+ FSUI_UploadList *upos;
FSUI_Event event;
- void * unused;
+ void *unused;
int i;
ectx = ctx->ectx;
if (ctx->ipc != NULL)
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSUI shutdown. This may take a while.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FSUI shutdown. This may take a while.\n");
/* 1) stop everything */
- cron_stop(ctx->cron);
- cron_del_job(ctx->cron,
- &updateDownloadThreads,
- FSUI_UDT_FREQUENCY,
- ctx);
- cron_destroy(ctx->cron);
+ cron_stop (ctx->cron);
+ cron_del_job (ctx->cron, &updateDownloadThreads, FSUI_UDT_FREQUENCY, ctx);
+ cron_destroy (ctx->cron);
/* 1a) stop downloading */
ctx->threadPoolSize = 0;
dpos = ctx->activeDownloads.child;
- while (dpos != NULL) {
- FSUI_updateDownloadThread(dpos);
- dpos = dpos->next;
- }
+ while (dpos != NULL)
+ {
+ FSUI_updateDownloadThread (dpos);
+ dpos = dpos->next;
+ }
/* 1b) stop searching */
spos = ctx->activeSearches;
- while (spos != NULL) {
- if ( (spos->state == FSUI_ACTIVE) ||
- (spos->state == FSUI_ABORTED) ||
- (spos->state == FSUI_ERROR) ||
- (spos->state == FSUI_COMPLETED) ) {
- if (spos->state == FSUI_ACTIVE)
- spos->state = FSUI_PENDING;
- PTHREAD_STOP_SLEEP(spos->handle);
- PTHREAD_JOIN(spos->handle, &unused);
- if (spos->state != FSUI_PENDING)
- spos->state++; /* _JOINED */
+ while (spos != NULL)
+ {
+ if ((spos->state == FSUI_ACTIVE) ||
+ (spos->state == FSUI_ABORTED) ||
+ (spos->state == FSUI_ERROR) || (spos->state == FSUI_COMPLETED))
+ {
+ if (spos->state == FSUI_ACTIVE)
+ spos->state = FSUI_PENDING;
+ PTHREAD_STOP_SLEEP (spos->handle);
+ PTHREAD_JOIN (spos->handle, &unused);
+ if (spos->state != FSUI_PENDING)
+ spos->state++; /* _JOINED */
+ }
+ spos = spos->next;
}
- spos = spos->next;
- }
/* 1c) stop unindexing */
xpos = ctx->unindexOperations;
- while (xpos != NULL) {
- if ( (xpos->state == FSUI_ACTIVE) ||
- (xpos->state == FSUI_ABORTED) ||
- (xpos->state == FSUI_ERROR) ||
- (xpos->state == FSUI_COMPLETED) ) {
- if (xpos->state == FSUI_ACTIVE)
- xpos->state = FSUI_PENDING;
- PTHREAD_STOP_SLEEP(xpos->handle);
- PTHREAD_JOIN(xpos->handle, &unused);
- if (xpos->state != FSUI_PENDING)
- xpos->state++; /* _JOINED */
+ while (xpos != NULL)
+ {
+ if ((xpos->state == FSUI_ACTIVE) ||
+ (xpos->state == FSUI_ABORTED) ||
+ (xpos->state == FSUI_ERROR) || (xpos->state == FSUI_COMPLETED))
+ {
+ if (xpos->state == FSUI_ACTIVE)
+ xpos->state = FSUI_PENDING;
+ PTHREAD_STOP_SLEEP (xpos->handle);
+ PTHREAD_JOIN (xpos->handle, &unused);
+ if (xpos->state != FSUI_PENDING)
+ xpos->state++; /* _JOINED */
+ }
+ xpos = xpos->next;
}
- xpos = xpos->next;
- }
/* 1d) stop uploading */
upos = ctx->activeUploads.child;
- while (upos != NULL) {
- if ( (upos->state == FSUI_ACTIVE) ||
- (upos->state == FSUI_ABORTED) ||
- (upos->state == FSUI_ERROR) ||
- (upos->state == FSUI_COMPLETED) ) {
- /* NOTE: will force transitive termination
- of rest of tree! */
- if (upos->state == FSUI_ACTIVE)
- upos->state = FSUI_PENDING;
- PTHREAD_STOP_SLEEP(upos->shared->handle);
- PTHREAD_JOIN(upos->shared->handle, &unused);
- if (upos->state != FSUI_PENDING)
- upos->state++; /* _JOINED */
+ while (upos != NULL)
+ {
+ if ((upos->state == FSUI_ACTIVE) ||
+ (upos->state == FSUI_ABORTED) ||
+ (upos->state == FSUI_ERROR) || (upos->state == FSUI_COMPLETED))
+ {
+ /* NOTE: will force transitive termination
+ of rest of tree! */
+ if (upos->state == FSUI_ACTIVE)
+ upos->state = FSUI_PENDING;
+ PTHREAD_STOP_SLEEP (upos->shared->handle);
+ PTHREAD_JOIN (upos->shared->handle, &unused);
+ if (upos->state != FSUI_PENDING)
+ upos->state++; /* _JOINED */
+ }
+ upos = upos->next;
}
- upos = upos->next;
- }
/* 2) signal suspension events */
/* 2a) signal search suspension */
spos = ctx->activeSearches;
- while (spos != NULL) {
- event.type = FSUI_search_suspended;
- event.data.SearchSuspended.sc.pos = spos;
- event.data.SearchSuspended.sc.cctx = spos->cctx;
- ctx->ecb(ctx->ecbClosure, &event);
- spos = spos->next;
- }
+ while (spos != NULL)
+ {
+ event.type = FSUI_search_suspended;
+ event.data.SearchSuspended.sc.pos = spos;
+ event.data.SearchSuspended.sc.cctx = spos->cctx;
+ ctx->ecb (ctx->ecbClosure, &event);
+ spos = spos->next;
+ }
/* 2b) signal uploads suspension */
- signalUploadSuspend(ectx,
- ctx,
- ctx->activeUploads.child);
+ signalUploadSuspend (ectx, ctx, ctx->activeUploads.child);
/* 2c) signal downloads suspension */
- signalDownloadSuspend(ectx,
- ctx,
- ctx->activeDownloads.child);
+ signalDownloadSuspend (ectx, ctx, ctx->activeDownloads.child);
/* 2d) signal unindex suspension */
xpos = ctx->unindexOperations;
- while (xpos != NULL) {
- event.type = FSUI_unindex_suspended;
- event.data.UnindexSuspended.uc.pos = xpos;
- event.data.UnindexSuspended.uc.cctx = xpos->cctx;
- ctx->ecb(ctx->ecbClosure, &event);
- xpos = xpos->next;
- }
+ while (xpos != NULL)
+ {
+ event.type = FSUI_unindex_suspended;
+ event.data.UnindexSuspended.uc.pos = xpos;
+ event.data.UnindexSuspended.uc.cctx = xpos->cctx;
+ ctx->ecb (ctx->ecbClosure, &event);
+ xpos = xpos->next;
+ }
/* 3) serialize all of the FSUI state */
if (ctx->ipc != NULL)
- FSUI_serialize(ctx);
+ FSUI_serialize (ctx);
/* 4) finally, free memory */
/* 4a) free search memory */
- while (ctx->activeSearches != NULL) {
- spos = ctx->activeSearches;
- ctx->activeSearches = spos->next;
- ECRS_freeUri(spos->uri);
- for (i=spos->sizeResultsReceived-1;i>=0;i--) {
- ECRS_FileInfo * fi;
- fi = &spos->resultsReceived[i];
- ECRS_freeMetaData(fi->meta);
- ECRS_freeUri(fi->uri);
- }
- GROW(spos->resultsReceived,
- spos->sizeResultsReceived,
- 0);
- for (i=spos->sizeUnmatchedResultsReceived-1;i>=0;i--) {
- ResultPending * rp;
+ while (ctx->activeSearches != NULL)
+ {
+ spos = ctx->activeSearches;
+ ctx->activeSearches = spos->next;
+ ECRS_freeUri (spos->uri);
+ for (i = spos->sizeResultsReceived - 1; i >= 0; i--)
+ {
+ ECRS_FileInfo *fi;
+ fi = &spos->resultsReceived[i];
+ ECRS_freeMetaData (fi->meta);
+ ECRS_freeUri (fi->uri);
+ }
+ GROW (spos->resultsReceived, spos->sizeResultsReceived, 0);
+ for (i = spos->sizeUnmatchedResultsReceived - 1; i >= 0; i--)
+ {
+ ResultPending *rp;
- rp = &spos->unmatchedResultsReceived[i];
- GROW(rp->matchingKeys,
- rp->matchingKeyCount,
- 0);
- ECRS_freeMetaData(rp->fi.meta);
- ECRS_freeUri(rp->fi.uri);
+ rp = &spos->unmatchedResultsReceived[i];
+ GROW (rp->matchingKeys, rp->matchingKeyCount, 0);
+ ECRS_freeMetaData (rp->fi.meta);
+ ECRS_freeUri (rp->fi.uri);
+ }
+ GROW (spos->unmatchedResultsReceived,
+ spos->sizeUnmatchedResultsReceived, 0);
+ FREE (spos);
}
- GROW(spos->unmatchedResultsReceived,
- spos->sizeUnmatchedResultsReceived,
- 0);
- FREE(spos);
- }
/* 4b) free unindex memory */
- while (ctx->unindexOperations != NULL) {
- xpos = ctx->unindexOperations;
- ctx->unindexOperations = xpos->next;
- FREE(xpos->filename);
- FREE(xpos);
- }
+ while (ctx->unindexOperations != NULL)
+ {
+ xpos = ctx->unindexOperations;
+ ctx->unindexOperations = xpos->next;
+ FREE (xpos->filename);
+ FREE (xpos);
+ }
/* 4c) free upload memory */
- freeUploadList(ctx,
- ctx->activeUploads.child);
+ freeUploadList (ctx, ctx->activeUploads.child);
/* 4d) free download memory */
- freeDownloadList(ctx->activeDownloads.child);
+ freeDownloadList (ctx->activeDownloads.child);
/* 5) finish FSUI Context */
- if (ctx->ipc != NULL) {
- IPC_SEMAPHORE_UP(ctx->ipc);
- IPC_SEMAPHORE_DESTROY(ctx->ipc);
- }
- MUTEX_DESTROY(ctx->lock);
- FREE(ctx->name);
if (ctx->ipc != NULL)
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSUI shutdown complete.\n");
- FREE(ctx);
+ {
+ IPC_SEMAPHORE_UP (ctx->ipc);
+ IPC_SEMAPHORE_DESTROY (ctx->ipc);
+ }
+ MUTEX_DESTROY (ctx->lock);
+ FREE (ctx->name);
+ if (ctx->ipc != NULL)
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "FSUI shutdown complete.\n");
+ FREE (ctx);
}
Modified: GNUnet/src/applications/fs/fsui/fsui.h
===================================================================
--- GNUnet/src/applications/fs/fsui/fsui.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/fsui/fsui.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -34,12 +34,13 @@
/**
* Track record for a given result.
*/
-typedef struct {
+typedef struct
+{
/**
* What are these keys?
*/
- HashCode512 * matchingKeys;
+ HashCode512 *matchingKeys;
/**
* What info do we have about this result?
@@ -57,7 +58,8 @@
/**
* @brief list of active searches
*/
-typedef struct FSUI_SearchList {
+typedef struct FSUI_SearchList
+{
/**
* Desired timeout (relative) for this search
@@ -72,36 +74,36 @@
/**
* Searches are kept in a simple linked list.
*/
- struct FSUI_SearchList * next;
+ struct FSUI_SearchList *next;
/**
* Context for this search
*/
- struct FSUI_Context * ctx;
+ struct FSUI_Context *ctx;
/**
* Handle to the thread which performs the search.
*/
- struct PTHREAD * handle;
+ struct PTHREAD *handle;
/**
* Which URI are we searching?
*/
- struct ECRS_URI * uri;
+ struct ECRS_URI *uri;
/**
* What downloads belong to this search?
*/
- struct FSUI_DownloadList ** my_downloads;
+ struct FSUI_DownloadList **my_downloads;
/**
* List of all results found so far.
*/
- ECRS_FileInfo * resultsReceived;
+ ECRS_FileInfo *resultsReceived;
- ResultPending * unmatchedResultsReceived;
+ ResultPending *unmatchedResultsReceived;
- void * cctx;
+ void *cctx;
/**
* Desired anonymity level for this search
@@ -143,7 +145,8 @@
/**
* @brief list of active downloads
*/
-typedef struct FSUI_DownloadList {
+typedef struct FSUI_DownloadList
+{
/**
* How many bytes is this download in total
@@ -164,51 +167,51 @@
/**
* Filename for this download.
*/
- char * filename;
+ char *filename;
/**
* Next in the linked list of all downloads
* kept in FSUI context.
*/
- struct FSUI_DownloadList * next;
+ struct FSUI_DownloadList *next;
/**
* For recursive downloads, download entry for
* the parent.
*/
- struct FSUI_DownloadList * parent;
+ struct FSUI_DownloadList *parent;
/**
* If this is a recursive download, this is the
* list of sub-downloads that are currently
* going on in parallel.
*/
- struct FSUI_DownloadList * child;
+ struct FSUI_DownloadList *child;
/**
* Search that this download belongs to (maybe NULL)
*/
- struct FSUI_SearchList * search;
+ struct FSUI_SearchList *search;
/**
* FSUI context for this download.
*/
- struct FSUI_Context * ctx;
+ struct FSUI_Context *ctx;
/**
* Client context for the downloadx
*/
- void * cctx;
+ void *cctx;
/**
* Currently assigned thread (if any).
*/
- struct PTHREAD * handle;
+ struct PTHREAD *handle;
/**
* FIs of completed sub-downloads.
*/
- struct ECRS_URI ** completedDownloads;
+ struct ECRS_URI **completedDownloads;
/**
* When did the download start? Note that if a download is resumed,
@@ -269,19 +272,20 @@
/**
* Context for the unindex thread.
*/
-typedef struct FSUI_UnindexList {
+typedef struct FSUI_UnindexList
+{
cron_t start_time;
- struct FSUI_UnindexList * next;
+ struct FSUI_UnindexList *next;
- struct PTHREAD * handle;
+ struct PTHREAD *handle;
- char * filename;
+ char *filename;
- struct FSUI_Context * ctx;
+ struct FSUI_Context *ctx;
- void * cctx;
+ void *cctx;
FSUI_State state;
@@ -291,26 +295,27 @@
/**
* Shared context for upload of entire structure.
*/
-typedef struct FSUI_UploadShared {
+typedef struct FSUI_UploadShared
+{
cron_t expiration;
DirectoryScanCallback dsc;
- void * dscClosure;
-
- EXTRACTOR_ExtractorList * extractors;
+ void *dscClosure;
- struct FSUI_Context * ctx;
+ EXTRACTOR_ExtractorList *extractors;
- struct PTHREAD * handle;
+ struct FSUI_Context *ctx;
+ struct PTHREAD *handle;
+
/**
* Keywords to be used for all uploads.
*/
- struct ECRS_URI * global_keywords;
+ struct ECRS_URI *global_keywords;
- char * extractor_config;
+ char *extractor_config;
int doIndex;
@@ -325,7 +330,8 @@
/**
* Context for each file upload.
*/
-typedef struct FSUI_UploadList {
+typedef struct FSUI_UploadList
+{
unsigned long long completed;
@@ -333,35 +339,35 @@
cron_t start_time;
- struct FSUI_UploadShared * shared;
+ struct FSUI_UploadShared *shared;
- struct FSUI_UploadList * next;
+ struct FSUI_UploadList *next;
- struct FSUI_UploadList * child;
+ struct FSUI_UploadList *child;
- struct FSUI_UploadList * parent;
+ struct FSUI_UploadList *parent;
/**
* Metadata for this file.
*/
- struct ECRS_MetaData * meta;
+ struct ECRS_MetaData *meta;
/**
* Keywords to be used for this upload.
*/
- struct ECRS_URI * keywords;
+ struct ECRS_URI *keywords;
/**
* URI for this file (set upon completion).
*/
- struct ECRS_URI * uri;
+ struct ECRS_URI *uri;
- char * filename;
+ char *filename;
/**
* FSUI-client context.
*/
- void * cctx;
+ void *cctx;
/**
* State of this sub-process.
@@ -373,30 +379,31 @@
/**
* @brief global state of the FSUI library
*/
-typedef struct FSUI_Context {
+typedef struct FSUI_Context
+{
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
/**
* IPC semaphore used to ensure mutual exclusion
* between different processes of the same name
* that all use resume.
*/
- struct IPC_SEMAPHORE * ipc;
+ struct IPC_SEMAPHORE *ipc;
/**
* Name of the tool using FSUI (used for resume).
*/
- char * name;
+ char *name;
/**
* Lock to synchronize access to the FSUI Context.
*/
- struct MUTEX * lock;
+ struct MUTEX *lock;
- struct CronManager * cron;
+ struct CronManager *cron;
/**
* Callback for notifying the client about events.
@@ -406,22 +413,22 @@
/**
* Extra argument to ecb.
*/
- void * ecbClosure;
+ void *ecbClosure;
/**
* Collection related data.
*/
- DataContainer * collectionData;
+ DataContainer *collectionData;
/**
* List of active searches.
*/
- FSUI_SearchList * activeSearches;
+ FSUI_SearchList *activeSearches;
/**
* List of active unindex operations.
*/
- FSUI_UnindexList * unindexOperations;
+ FSUI_UnindexList *unindexOperations;
FSUI_UploadList activeUploads;
@@ -454,16 +461,16 @@
*
* @return YES if change done that may require re-trying
*/
-int FSUI_updateDownloadThread(FSUI_DownloadList * list);
+int FSUI_updateDownloadThread (FSUI_DownloadList * list);
-void * FSUI_uploadThread(void * dl);
+void *FSUI_uploadThread (void *dl);
-void * FSUI_searchThread(void * pos);
+void *FSUI_searchThread (void *pos);
-void * FSUI_unindexThread(void * cls);
+void *FSUI_unindexThread (void *cls);
-void FSUI_serialize(struct FSUI_Context * ctx);
+void FSUI_serialize (struct FSUI_Context *ctx);
-void FSUI_deserialize(struct FSUI_Context * ctx);
+void FSUI_deserialize (struct FSUI_Context *ctx);
#endif
Modified: GNUnet/src/applications/fs/fsui/fsuitest.c
===================================================================
--- GNUnet/src/applications/fs/fsui/fsuitest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/fsui/fsuitest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -34,216 +34,189 @@
#define CHECK(a) if (!(a)) { ok = NO; GE_BREAK(NULL, 0); goto FAILURE; }
-static char * makeName(unsigned int i) {
- char * fn;
+static char *
+makeName (unsigned int i)
+{
+ char *fn;
- fn = MALLOC(strlen("/tmp/gnunet-fsui-serializetest/FSUITEST") + 14);
- SNPRINTF(fn,
- strlen("/tmp/gnunet-fsui-test/FSUITEST") + 14,
- "/tmp/gnunet-fsui-test/FSUITEST%u",
- i);
- disk_directory_create_for_file(NULL, fn);
+ fn = MALLOC (strlen ("/tmp/gnunet-fsui-serializetest/FSUITEST") + 14);
+ SNPRINTF (fn,
+ strlen ("/tmp/gnunet-fsui-test/FSUITEST") + 14,
+ "/tmp/gnunet-fsui-test/FSUITEST%u", i);
+ disk_directory_create_for_file (NULL, fn);
return fn;
}
static volatile enum FSUI_EventType lastEvent;
-static struct FSUI_Context * ctx;
+static struct FSUI_Context *ctx;
-static struct FSUI_DownloadList * download;
+static struct FSUI_DownloadList *download;
-static void * eventCallback(void * cls,
- const FSUI_Event * event) {
+static void *
+eventCallback (void *cls, const FSUI_Event * event)
+{
static char unused;
- char * fn;
+ char *fn;
- switch(event->type) {
- case FSUI_search_resumed:
- case FSUI_download_resumed:
- case FSUI_upload_resumed:
- case FSUI_unindex_resumed:
- return &unused;
- case FSUI_search_result:
+ switch (event->type)
+ {
+ case FSUI_search_resumed:
+ case FSUI_download_resumed:
+ case FSUI_upload_resumed:
+ case FSUI_unindex_resumed:
+ return &unused;
+ case FSUI_search_result:
#if DEBUG_VERBOSE
- printf("Received search result\n");
+ printf ("Received search result\n");
#endif
- fn = makeName(43);
- download = FSUI_startDownload(ctx,
- 0,
- NO,
- event->data.SearchResult.fi.uri,
- event->data.SearchResult.fi.meta,
- fn,
- NULL,
- NULL);
- FREE(fn);
- break;
- case FSUI_upload_completed:
+ fn = makeName (43);
+ download = FSUI_startDownload (ctx,
+ 0,
+ NO,
+ event->data.SearchResult.fi.uri,
+ event->data.SearchResult.fi.meta,
+ fn, NULL, NULL);
+ FREE (fn);
+ break;
+ case FSUI_upload_completed:
#if DEBUG_VERBOSE
- printf("Upload complete.\n");
+ printf ("Upload complete.\n");
#endif
- break;
- case FSUI_download_completed:
+ break;
+ case FSUI_download_completed:
#if DEBUG_VERBOSE
- printf("Download complete.\n");
+ printf ("Download complete.\n");
#endif
- break;
- case FSUI_unindex_completed:
+ break;
+ case FSUI_unindex_completed:
#if DEBUG_VERBOSE
- printf("Unindex complete.\n");
+ printf ("Unindex complete.\n");
#endif
- break;
- default:
- break;
- }
+ break;
+ default:
+ break;
+ }
lastEvent = event->type;
return NULL;
}
#define START_DAEMON 1
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
#if START_DAEMON
pid_t daemon;
#endif
int ok;
- struct ECRS_URI * uri;
- char * filename = NULL;
- char * keywords[] = {
+ struct ECRS_URI *uri;
+ char *filename = NULL;
+ char *keywords[] = {
"fsui_foo",
"fsui_bar",
NULL,
};
char keyword[40];
int prog;
- struct ECRS_MetaData * meta;
- struct ECRS_URI * kuri;
- struct GC_Configuration * cfg;
- struct FSUI_UploadList * upload;
- struct FSUI_SearchList * search;
- struct FSUI_UnindexList * unindex;
+ struct ECRS_MetaData *meta;
+ struct ECRS_URI *kuri;
+ struct GC_Configuration *cfg;
+ struct FSUI_UploadList *upload;
+ struct FSUI_SearchList *search;
+ struct FSUI_UnindexList *unindex;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_DAEMON
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
- CHECK(OK == connection_wait_for_running(NULL,
- cfg,
- 60 * cronSECONDS));
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
+ CHECK (OK == connection_wait_for_running (NULL, cfg, 60 * cronSECONDS));
#endif
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
ok = YES;
/* ACTUAL TEST CODE */
- ctx = FSUI_start(NULL,
- cfg,
- "fsuitest",
- 32, /* thread pool size */
- NO, /* no resume */
- &eventCallback,
- NULL);
- CHECK(ctx != NULL);
- filename = makeName(42);
- disk_file_write(NULL,
- filename,
- "foo bar test!",
- strlen("foo bar test!"),
- "600");
- meta = ECRS_createMetaData();
- kuri = ECRS_parseListKeywordURI(NULL,
- 2,
- (const char**)keywords);
- upload = FSUI_startUpload(ctx,
- filename,
- (DirectoryScanCallback) &disk_directory_scan,
- NULL,
- 0, /* anonymity */
- 0, /* priority */
- YES,
- NO,
- NO,
- get_time() + 5 * cronHOURS,
- meta,
- kuri,
- kuri);
- CHECK(upload != NULL);
- ECRS_freeUri(kuri);
- ECRS_freeMetaData(meta);
+ ctx = FSUI_start (NULL, cfg, "fsuitest", 32, /* thread pool size */
+ NO, /* no resume */
+ &eventCallback, NULL);
+ CHECK (ctx != NULL);
+ filename = makeName (42);
+ disk_file_write (NULL,
+ filename,
+ "foo bar test!", strlen ("foo bar test!"), "600");
+ meta = ECRS_createMetaData ();
+ kuri = ECRS_parseListKeywordURI (NULL, 2, (const char **) keywords);
+ upload = FSUI_startUpload (ctx, filename, (DirectoryScanCallback) &
disk_directory_scan, NULL, 0, /* anonymity */
+ 0, /* priority */
+ YES,
+ NO,
+ NO,
+ get_time () + 5 * cronHOURS, meta, kuri, kuri);
+ CHECK (upload != NULL);
+ ECRS_freeUri (kuri);
+ ECRS_freeMetaData (meta);
prog = 0;
- while (lastEvent != FSUI_upload_completed) {
- prog++;
- CHECK(prog < 10000)
-
- PTHREAD_SLEEP(50 * cronMILLIS);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- SNPRINTF(keyword,
- 40,
- "%s %s %s",
- keywords[0],
- _("AND"),
- keywords[1]);
- uri = ECRS_parseCharKeywordURI(NULL,
- keyword);
- search = FSUI_startSearch(ctx,
- 0,
- 100,
- 240 * cronSECONDS,
- uri);
- ECRS_freeUri(uri);
- CHECK(search != NULL);
+ while (lastEvent != FSUI_upload_completed)
+ {
+ prog++;
+ CHECK (prog < 10000) PTHREAD_SLEEP (50 * cronMILLIS);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
+ SNPRINTF (keyword, 40, "%s %s %s", keywords[0], _("AND"), keywords[1]);
+ uri = ECRS_parseCharKeywordURI (NULL, keyword);
+ search = FSUI_startSearch (ctx, 0, 100, 240 * cronSECONDS, uri);
+ ECRS_freeUri (uri);
+ CHECK (search != NULL);
prog = 0;
- while (lastEvent != FSUI_download_completed) {
- prog++;
- CHECK(prog < 10000);
- PTHREAD_SLEEP(50 * cronMILLIS);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- FSUI_abortSearch(ctx,
- search);
- FSUI_stopSearch(ctx,
- search);
- unindex = FSUI_startUnindex(ctx, filename);
+ while (lastEvent != FSUI_download_completed)
+ {
+ prog++;
+ CHECK (prog < 10000);
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
+ FSUI_abortSearch (ctx, search);
+ FSUI_stopSearch (ctx, search);
+ unindex = FSUI_startUnindex (ctx, filename);
prog = 0;
- while (lastEvent != FSUI_unindex_completed) {
- prog++;
- CHECK(prog < 10000);
- PTHREAD_SLEEP(50 * cronMILLIS);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
+ while (lastEvent != FSUI_unindex_completed)
+ {
+ prog++;
+ CHECK (prog < 10000);
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
if (lastEvent != FSUI_unindex_completed)
- FSUI_abortUnindex(ctx, unindex);
- FSUI_stopUnindex(ctx, unindex);
+ FSUI_abortUnindex (ctx, unindex);
+ FSUI_stopUnindex (ctx, unindex);
/* END OF TEST CODE */
- FAILURE:
+FAILURE:
if (ctx != NULL)
- FSUI_stop(ctx);
- if (filename != NULL) {
- UNLINK(filename);
- FREE(filename);
- }
- filename = makeName(43);
+ FSUI_stop (ctx);
+ if (filename != NULL)
+ {
+ UNLINK (filename);
+ FREE (filename);
+ }
+ filename = makeName (43);
/* TODO: verify file 'filename(42)' == file 'filename(43)' */
- UNLINK(filename);
- FREE(filename);
+ UNLINK (filename);
+ FREE (filename);
#if START_DAEMON
- GE_ASSERT(NULL, OK == os_daemon_stop(NULL, daemon));
+ GE_ASSERT (NULL, OK == os_daemon_stop (NULL, daemon));
#endif
- GC_free(cfg);
+ GC_free (cfg);
return (ok == YES) ? 0 : 1;
}
Modified: GNUnet/src/applications/fs/fsui/fsuitest2.c
===================================================================
--- GNUnet/src/applications/fs/fsui/fsuitest2.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/fsui/fsuitest2.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -33,66 +33,53 @@
#define CHECK(a) if (!(a)) { ok = NO; GE_BREAK(NULL, 0); goto FAILURE; }
-static struct FSUI_Context * ctx;
+static struct FSUI_Context *ctx;
-static void * eventCallback(void * cls,
- const FSUI_Event * event) {
+static void *
+eventCallback (void *cls, const FSUI_Event * event)
+{
return NULL;
}
#define START_DAEMON 1
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
#if START_DAEMON
pid_t daemon;
#endif
int ok;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_DAEMON
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
- CHECK(OK == connection_wait_for_running(NULL,
- cfg,
- 60 * cronSECONDS));
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
+ CHECK (OK == connection_wait_for_running (NULL, cfg, 60 * cronSECONDS));
#endif
ok = YES;
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
/* ACTUAL TEST CODE */
- ctx = FSUI_start(NULL,
- cfg,
- "fsuitest2",
- 32,
- YES, /* do resume! */
- &eventCallback,
- NULL);
- CHECK(ctx != NULL);
- FSUI_stop(ctx);
- ctx = FSUI_start(NULL,
- cfg,
- "fsuitest2",
- 32,
- YES,
- &eventCallback,
- NULL);
- CHECK(ctx != NULL);
- FAILURE:
+ ctx = FSUI_start (NULL, cfg, "fsuitest2", 32, YES, /* do resume! */
+ &eventCallback, NULL);
+ CHECK (ctx != NULL);
+ FSUI_stop (ctx);
+ ctx = FSUI_start (NULL, cfg, "fsuitest2", 32, YES, &eventCallback, NULL);
+ CHECK (ctx != NULL);
+FAILURE:
if (ctx != NULL)
- FSUI_stop(ctx);
+ FSUI_stop (ctx);
#if START_DAEMON
- GE_ASSERT(NULL, OK == os_daemon_stop(NULL, daemon));
+ GE_ASSERT (NULL, OK == os_daemon_stop (NULL, daemon));
#endif
- GC_free(cfg);
+ GC_free (cfg);
return (ok == YES) ? 0 : 1;
}
Modified: GNUnet/src/applications/fs/fsui/search.c
===================================================================
--- GNUnet/src/applications/fs/fsui/search.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/fsui/search.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -40,164 +40,162 @@
/**
* Pass the result to the client and note it as shown.
*/
-static void processResult(const ECRS_FileInfo * fi,
- FSUI_SearchList * pos) {
+static void
+processResult (const ECRS_FileInfo * fi, FSUI_SearchList * pos)
+{
FSUI_Event event;
- GROW(pos->resultsReceived,
- pos->sizeResultsReceived,
- pos->sizeResultsReceived+1);
- pos->resultsReceived[pos->sizeResultsReceived-1].uri
- = ECRS_dupUri(fi->uri);
- pos->resultsReceived[pos->sizeResultsReceived-1].meta
- = ECRS_dupMetaData(fi->meta);
+ GROW (pos->resultsReceived,
+ pos->sizeResultsReceived, pos->sizeResultsReceived + 1);
+ pos->resultsReceived[pos->sizeResultsReceived - 1].uri
+ = ECRS_dupUri (fi->uri);
+ pos->resultsReceived[pos->sizeResultsReceived - 1].meta
+ = ECRS_dupMetaData (fi->meta);
event.type = FSUI_search_result;
event.data.SearchResult.sc.pos = pos;
event.data.SearchResult.sc.cctx = pos->cctx;
event.data.SearchResult.fi = *fi;
event.data.SearchResult.searchURI = pos->uri;
- pos->ctx->ecb(pos->ctx->ecbClosure,
- &event);
- URITRACK_addState(pos->ctx->ectx,
- pos->ctx->cfg,
- pos->uri,
- URITRACK_SEARCH_RESULT);
+ pos->ctx->ecb (pos->ctx->ecbClosure, &event);
+ URITRACK_addState (pos->ctx->ectx,
+ pos->ctx->cfg, pos->uri, URITRACK_SEARCH_RESULT);
}
/**
* Process results found by ECRS.
*/
-static int spcb(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * cls) {
- FSUI_SearchList * pos = cls;
+static int
+spcb (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *cls)
+{
+ FSUI_SearchList *pos = cls;
unsigned int i;
unsigned int j;
- ResultPending * rp;
- struct GE_Context * ectx;
+ ResultPending *rp;
+ struct GE_Context *ectx;
ectx = pos->ctx->ectx;
- URITRACK_trackURI(ectx,
- pos->ctx->cfg,
- fi);
- if (isRoot) {
- NS_setNamespaceRoot(ectx,
- pos->ctx->cfg,
- fi->uri);
- NS_addNamespaceInfo(ectx,
- pos->ctx->cfg,
- fi->uri,
- fi->meta);
- return OK;
- }
- for (i=0;i<pos->sizeResultsReceived;i++)
- if (ECRS_equalsUri(fi->uri,
- pos->resultsReceived[i].uri)) {
+ URITRACK_trackURI (ectx, pos->ctx->cfg, fi);
+ if (isRoot)
+ {
+ NS_setNamespaceRoot (ectx, pos->ctx->cfg, fi->uri);
+ NS_addNamespaceInfo (ectx, pos->ctx->cfg, fi->uri, fi->meta);
+ return OK;
+ }
+ for (i = 0; i < pos->sizeResultsReceived; i++)
+ if (ECRS_equalsUri (fi->uri, pos->resultsReceived[i].uri))
+ {
#if DEBUG_SEARCH
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received search result that I have seen before.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received search result that I have seen before.\n");
#endif
- return OK; /* seen before */
- }
- if (pos->numberOfURIKeys > 1) {
- if (key == NULL) {
- GE_BREAK(ectx, 0);
+ return OK; /* seen before */
+ }
+ if (pos->numberOfURIKeys > 1)
+ {
+ if (key == NULL)
+ {
+ GE_BREAK (ectx, 0);
#if DEBUG_SEARCH
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received search result without key to decrypt.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received search result without key to decrypt.\n");
#endif
- return SYSERR;
- }
- for (i=0;i<pos->sizeUnmatchedResultsReceived;i++) {
- rp = &pos->unmatchedResultsReceived[i];
- if (ECRS_equalsUri(fi->uri,
- rp->fi.uri)) {
- for (j=0;j<rp->matchingKeyCount;j++)
- if (0 == memcmp(key,
- &rp->matchingKeys[j],
- sizeof(HashCode512))) {
+ return SYSERR;
+ }
+ for (i = 0; i < pos->sizeUnmatchedResultsReceived; i++)
+ {
+ rp = &pos->unmatchedResultsReceived[i];
+ if (ECRS_equalsUri (fi->uri, rp->fi.uri))
+ {
+ for (j = 0; j < rp->matchingKeyCount; j++)
+ if (0 == memcmp (key,
+ &rp->matchingKeys[j], sizeof (HashCode512)))
+ {
#if DEBUG_SEARCH
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received search result that I have seen before (missing keyword to
show client).\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received search result that I have seen before
(missing keyword to show client).\n");
#endif
- return OK;
- }
- if (rp->matchingKeyCount + 1 == pos->numberOfURIKeys) {
+ return OK;
+ }
+ if (rp->matchingKeyCount + 1 == pos->numberOfURIKeys)
+ {
#if DEBUG_SEARCH
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received search result (showing client)!\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received search result (showing client)!\n");
#endif
- GROW(rp->matchingKeys,
- rp->matchingKeyCount,
- 0);
- processResult(&rp->fi,
- pos);
- ECRS_freeUri(rp->fi.uri);
- ECRS_freeMetaData(rp->fi.meta);
- pos->unmatchedResultsReceived[i]
- = pos->unmatchedResultsReceived[pos->sizeUnmatchedResultsReceived-1];
- GROW(pos->unmatchedResultsReceived,
- pos->sizeUnmatchedResultsReceived,
- pos->sizeUnmatchedResultsReceived-1);
- return OK;
- } else {
- GROW(rp->matchingKeys,
- rp->matchingKeyCount,
- rp->matchingKeyCount+1);
- rp->matchingKeys[rp->matchingKeyCount-1] = *key;
+ GROW (rp->matchingKeys, rp->matchingKeyCount, 0);
+ processResult (&rp->fi, pos);
+ ECRS_freeUri (rp->fi.uri);
+ ECRS_freeMetaData (rp->fi.meta);
+ pos->unmatchedResultsReceived[i]
+ =
+ pos->unmatchedResultsReceived[pos->
+ sizeUnmatchedResultsReceived
+ - 1];
+ GROW (pos->unmatchedResultsReceived,
+ pos->sizeUnmatchedResultsReceived,
+ pos->sizeUnmatchedResultsReceived - 1);
+ return OK;
+ }
+ else
+ {
+ GROW (rp->matchingKeys,
+ rp->matchingKeyCount, rp->matchingKeyCount + 1);
+ rp->matchingKeys[rp->matchingKeyCount - 1] = *key;
#if DEBUG_SEARCH
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received search result (waiting for more %u keys before showing
client).\n",
- pos->numberOfURIKeys - rp->matchingKeyCount);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received search result (waiting for more %u keys
before showing client).\n",
+ pos->numberOfURIKeys - rp->matchingKeyCount);
#endif
- return OK;
- }
- }
- }
- GROW(pos->unmatchedResultsReceived,
- pos->sizeUnmatchedResultsReceived,
- pos->sizeUnmatchedResultsReceived+1);
- rp = &pos->unmatchedResultsReceived[pos->sizeUnmatchedResultsReceived-1];
- rp->fi.meta = ECRS_dupMetaData(fi->meta);
- rp->fi.uri = ECRS_dupUri(fi->uri);
- rp->matchingKeys = NULL;
- rp->matchingKeyCount = 0;
- GROW(rp->matchingKeys,
- rp->matchingKeyCount,
- 1);
- rp->matchingKeys[0] = *key;
+ return OK;
+ }
+ }
+ }
+ GROW (pos->unmatchedResultsReceived,
+ pos->sizeUnmatchedResultsReceived,
+ pos->sizeUnmatchedResultsReceived + 1);
+ rp =
+ &pos->unmatchedResultsReceived[pos->sizeUnmatchedResultsReceived - 1];
+ rp->fi.meta = ECRS_dupMetaData (fi->meta);
+ rp->fi.uri = ECRS_dupUri (fi->uri);
+ rp->matchingKeys = NULL;
+ rp->matchingKeyCount = 0;
+ GROW (rp->matchingKeys, rp->matchingKeyCount, 1);
+ rp->matchingKeys[0] = *key;
#if DEBUG_SEARCH
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received search result (waiting for %u more keys before showing
client).\n",
- pos->numberOfURIKeys - rp->matchingKeyCount);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received search result (waiting for %u more keys before showing
client).\n",
+ pos->numberOfURIKeys - rp->matchingKeyCount);
#endif
- return OK;
- } else {
+ return OK;
+ }
+ else
+ {
#if DEBUG_SEARCH
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received search result (showing client)!\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received search result (showing client)!\n");
#endif
- processResult(fi,
- pos);
- }
+ processResult (fi, pos);
+ }
return OK;
}
-static int testTerminate(void * cls) {
- FSUI_SearchList * pos = cls;
- if ( (pos->state == FSUI_ACTIVE) &&
- (pos->maxResults > pos->sizeResultsReceived) )
+static int
+testTerminate (void *cls)
+{
+ FSUI_SearchList *pos = cls;
+ if ((pos->state == FSUI_ACTIVE) &&
+ (pos->maxResults > pos->sizeResultsReceived))
return OK;
return SYSERR;
}
@@ -205,59 +203,60 @@
/**
* Thread that searches for data.
*/
-void * FSUI_searchThread(void * cls) {
- FSUI_SearchList * pos = cls;
+void *
+FSUI_searchThread (void *cls)
+{
+ FSUI_SearchList *pos = cls;
FSUI_Event event;
int ret;
- struct GE_Memory * mem;
- struct GE_Context * ee;
+ struct GE_Memory *mem;
+ struct GE_Context *ee;
- mem = GE_memory_create(2);
- ee = GE_create_context_memory(GE_USER | GE_ADMIN |
- GE_ERROR | GE_WARNING | GE_FATAL |
- GE_BULK | GE_IMMEDIATE,
- mem);
- ret = ECRS_search(ee,
- pos->ctx->cfg,
- pos->uri,
- pos->anonymityLevel,
- pos->timeout,
- &spcb,
- pos,
- &testTerminate,
- pos);
- if (ret != OK) {
- const char * error;
+ mem = GE_memory_create (2);
+ ee = GE_create_context_memory (GE_USER | GE_ADMIN |
+ GE_ERROR | GE_WARNING | GE_FATAL |
+ GE_BULK | GE_IMMEDIATE, mem);
+ ret = ECRS_search (ee,
+ pos->ctx->cfg,
+ pos->uri,
+ pos->anonymityLevel,
+ pos->timeout, &spcb, pos, &testTerminate, pos);
+ if (ret != OK)
+ {
+ const char *error;
- pos->state = FSUI_ERROR;
- event.type = FSUI_search_error;
- event.data.SearchError.sc.pos = pos;
- event.data.SearchError.sc.cctx = pos->cctx;
- error = GE_memory_get(mem, 0);
- if (error == NULL)
- error = _("Error running search (no reason given).");
- event.data.SearchError.message = error;
- pos->ctx->ecb(pos->ctx->ecbClosure,
- &event);
- } else if (pos->state == FSUI_ABORTED) {
- event.type = FSUI_search_aborted;
- event.data.SearchAborted.sc.pos = pos;
- event.data.SearchAborted.sc.cctx = pos->cctx;
- pos->ctx->ecb(pos->ctx->ecbClosure,
- &event);
- } else if (pos->state == FSUI_ACTIVE) {
- pos->state = FSUI_COMPLETED;
- event.type = FSUI_search_completed;
- event.data.SearchCompleted.sc.pos = pos;
- event.data.SearchCompleted.sc.cctx = pos->cctx;
- pos->ctx->ecb(pos->ctx->ecbClosure,
- &event);
- } else {
- GE_ASSERT(NULL, pos->state == FSUI_PENDING);
- /* must be suspending */
- }
- GE_free_context(ee);
- GE_memory_free(mem);
+ pos->state = FSUI_ERROR;
+ event.type = FSUI_search_error;
+ event.data.SearchError.sc.pos = pos;
+ event.data.SearchError.sc.cctx = pos->cctx;
+ error = GE_memory_get (mem, 0);
+ if (error == NULL)
+ error = _("Error running search (no reason given).");
+ event.data.SearchError.message = error;
+ pos->ctx->ecb (pos->ctx->ecbClosure, &event);
+ }
+ else if (pos->state == FSUI_ABORTED)
+ {
+ event.type = FSUI_search_aborted;
+ event.data.SearchAborted.sc.pos = pos;
+ event.data.SearchAborted.sc.cctx = pos->cctx;
+ pos->ctx->ecb (pos->ctx->ecbClosure, &event);
+ }
+ else if (pos->state == FSUI_ACTIVE)
+ {
+ pos->state = FSUI_COMPLETED;
+ event.type = FSUI_search_completed;
+ event.data.SearchCompleted.sc.pos = pos;
+ event.data.SearchCompleted.sc.cctx = pos->cctx;
+ pos->ctx->ecb (pos->ctx->ecbClosure, &event);
+ }
+ else
+ {
+ GE_ASSERT (NULL, pos->state == FSUI_PENDING);
+ /* must be suspending */
+ }
+ GE_free_context (ee);
+ GE_memory_free (mem);
return NULL;
}
@@ -265,8 +264,10 @@
/**
* Thread that searches for data (and signals startup).
*/
-void * FSUI_searchThreadSignal(void * cls) {
- FSUI_SearchList * pos = cls;
+void *
+FSUI_searchThreadSignal (void *cls)
+{
+ FSUI_SearchList *pos = cls;
FSUI_Event event;
event.type = FSUI_search_started;
@@ -274,147 +275,144 @@
event.data.SearchStarted.sc.cctx = NULL;
event.data.SearchStarted.searchURI = pos->uri;
event.data.SearchStarted.anonymityLevel = pos->anonymityLevel;
- pos->cctx = pos->ctx->ecb(pos->ctx->ecbClosure,
- &event);
- return FSUI_searchThread(pos);
+ pos->cctx = pos->ctx->ecb (pos->ctx->ecbClosure, &event);
+ return FSUI_searchThread (pos);
}
/**
* Start a search.
*/
struct FSUI_SearchList *
-FSUI_startSearch(struct FSUI_Context * ctx,
- unsigned int anonymityLevel,
- unsigned int maxResults,
- cron_t timeout,
- const struct ECRS_URI * uri) {
- FSUI_SearchList * pos;
- struct GE_Context * ectx;
+FSUI_startSearch (struct FSUI_Context *ctx,
+ unsigned int anonymityLevel,
+ unsigned int maxResults,
+ cron_t timeout, const struct ECRS_URI *uri)
+{
+ FSUI_SearchList *pos;
+ struct GE_Context *ectx;
ectx = ctx->ectx;
- MUTEX_LOCK(ctx->lock);
- pos = MALLOC(sizeof(FSUI_SearchList));
+ MUTEX_LOCK (ctx->lock);
+ pos = MALLOC (sizeof (FSUI_SearchList));
pos->maxResults = maxResults;
pos->state = FSUI_ACTIVE;
- pos->uri = ECRS_dupUri(uri);
- pos->numberOfURIKeys = ECRS_countKeywordsOfUri(uri);
+ pos->uri = ECRS_dupUri (uri);
+ pos->numberOfURIKeys = ECRS_countKeywordsOfUri (uri);
pos->sizeResultsReceived = 0;
pos->resultsReceived = NULL;
pos->sizeUnmatchedResultsReceived = 0;
pos->unmatchedResultsReceived = 0;
pos->anonymityLevel = anonymityLevel;
pos->ctx = ctx;
- pos->start_time = get_time();
+ pos->start_time = get_time ();
pos->timeout = timeout;
- pos->handle = PTHREAD_CREATE(&FSUI_searchThreadSignal,
- pos,
- 32 * 1024);
- if (pos->handle == NULL) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_IMMEDIATE | GE_USER | GE_ADMIN,
- "PTHREAD_CREATE");
- ECRS_freeUri(pos->uri);
- FREE(pos);
- MUTEX_UNLOCK(ctx->lock);
- return NULL;
- }
+ pos->handle = PTHREAD_CREATE (&FSUI_searchThreadSignal, pos, 32 * 1024);
+ if (pos->handle == NULL)
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_ERROR | GE_IMMEDIATE | GE_USER | GE_ADMIN,
+ "PTHREAD_CREATE");
+ ECRS_freeUri (pos->uri);
+ FREE (pos);
+ MUTEX_UNLOCK (ctx->lock);
+ return NULL;
+ }
pos->next = ctx->activeSearches;
ctx->activeSearches = pos;
- MUTEX_UNLOCK(ctx->lock);
+ MUTEX_UNLOCK (ctx->lock);
return pos;
}
/**
* Abort a search.
*/
-int FSUI_abortSearch(struct FSUI_Context * ctx,
- struct FSUI_SearchList * sl) {
- if (sl->state == FSUI_PENDING) {
- sl->state = FSUI_ABORTED_JOINED;
- return OK;
- }
+int
+FSUI_abortSearch (struct FSUI_Context *ctx, struct FSUI_SearchList *sl)
+{
+ if (sl->state == FSUI_PENDING)
+ {
+ sl->state = FSUI_ABORTED_JOINED;
+ return OK;
+ }
if (sl->state != FSUI_ACTIVE)
return SYSERR;
sl->state = FSUI_ABORTED;
- PTHREAD_STOP_SLEEP(sl->handle);
+ PTHREAD_STOP_SLEEP (sl->handle);
return OK;
}
/**
* Stop a search.
*/
-int FSUI_stopSearch(struct FSUI_Context * ctx,
- struct FSUI_SearchList * sl) {
+int
+FSUI_stopSearch (struct FSUI_Context *ctx, struct FSUI_SearchList *sl)
+{
FSUI_Event event;
- FSUI_SearchList * pos;
- FSUI_SearchList * prev;
- void * unused;
+ FSUI_SearchList *pos;
+ FSUI_SearchList *prev;
+ void *unused;
int i;
- MUTEX_LOCK(ctx->lock);
+ MUTEX_LOCK (ctx->lock);
prev = NULL;
pos = ctx->activeSearches;
- while ( (pos != sl) &&
- (pos != NULL) ) {
- prev = pos;
- pos = pos->next;
- }
- if (pos == NULL) {
- MUTEX_UNLOCK(ctx->lock);
- return SYSERR;
- }
+ while ((pos != sl) && (pos != NULL))
+ {
+ prev = pos;
+ pos = pos->next;
+ }
+ if (pos == NULL)
+ {
+ MUTEX_UNLOCK (ctx->lock);
+ return SYSERR;
+ }
if (prev == NULL)
ctx->activeSearches = pos->next;
else
prev->next = pos->next;
- for (i=0;i<sl->my_downloads_size;i++)
+ for (i = 0; i < sl->my_downloads_size; i++)
sl->my_downloads[i]->search = NULL;
- GROW(sl->my_downloads,
- sl->my_downloads_size,
- 0);
- MUTEX_UNLOCK(ctx->lock);
+ GROW (sl->my_downloads, sl->my_downloads_size, 0);
+ MUTEX_UNLOCK (ctx->lock);
pos->next = NULL;
- if ( (pos->state == FSUI_ACTIVE) ||
- (pos->state == FSUI_COMPLETED) ||
- (pos->state == FSUI_ABORTED) ||
- (pos->state == FSUI_ERROR) ) {
- GE_ASSERT(ctx->ectx, pos->handle != NULL);
- PTHREAD_JOIN(pos->handle,
- &unused);
- pos->handle = NULL;
- if (pos->state == FSUI_ACTIVE)
- pos->state = FSUI_PENDING;
- else
- pos->state++; /* add _JOINED */
- } else {
- GE_ASSERT(ctx->ectx, pos->handle == NULL);
- }
+ if ((pos->state == FSUI_ACTIVE) ||
+ (pos->state == FSUI_COMPLETED) ||
+ (pos->state == FSUI_ABORTED) || (pos->state == FSUI_ERROR))
+ {
+ GE_ASSERT (ctx->ectx, pos->handle != NULL);
+ PTHREAD_JOIN (pos->handle, &unused);
+ pos->handle = NULL;
+ if (pos->state == FSUI_ACTIVE)
+ pos->state = FSUI_PENDING;
+ else
+ pos->state++; /* add _JOINED */
+ }
+ else
+ {
+ GE_ASSERT (ctx->ectx, pos->handle == NULL);
+ }
event.type = FSUI_search_stopped;
event.data.SearchStopped.sc.pos = pos;
event.data.SearchStopped.sc.cctx = pos->cctx;
- pos->ctx->ecb(pos->ctx->ecbClosure,
- &event);
+ pos->ctx->ecb (pos->ctx->ecbClosure, &event);
- ECRS_freeUri(pos->uri);
- for (i=0;i<pos->sizeResultsReceived;i++) {
- ECRS_freeUri(pos->resultsReceived[i].uri);
- ECRS_freeMetaData(pos->resultsReceived[i].meta);
- }
- GROW(pos->resultsReceived,
- pos->sizeResultsReceived,
- 0);
- for (i=0;i<pos->sizeUnmatchedResultsReceived;i++) {
- ECRS_freeUri(pos->unmatchedResultsReceived[i].fi.uri);
- ECRS_freeMetaData(pos->unmatchedResultsReceived[i].fi.meta);
- GROW(pos->unmatchedResultsReceived[i].matchingKeys,
- pos->unmatchedResultsReceived[i].matchingKeyCount,
- 0);
- }
- GROW(pos->unmatchedResultsReceived,
- pos->sizeUnmatchedResultsReceived,
- 0);
- FREE(pos);
+ ECRS_freeUri (pos->uri);
+ for (i = 0; i < pos->sizeResultsReceived; i++)
+ {
+ ECRS_freeUri (pos->resultsReceived[i].uri);
+ ECRS_freeMetaData (pos->resultsReceived[i].meta);
+ }
+ GROW (pos->resultsReceived, pos->sizeResultsReceived, 0);
+ for (i = 0; i < pos->sizeUnmatchedResultsReceived; i++)
+ {
+ ECRS_freeUri (pos->unmatchedResultsReceived[i].fi.uri);
+ ECRS_freeMetaData (pos->unmatchedResultsReceived[i].fi.meta);
+ GROW (pos->unmatchedResultsReceived[i].matchingKeys,
+ pos->unmatchedResultsReceived[i].matchingKeyCount, 0);
+ }
+ GROW (pos->unmatchedResultsReceived, pos->sizeUnmatchedResultsReceived, 0);
+ FREE (pos);
return OK;
}
Modified: GNUnet/src/applications/fs/fsui/searchtest.c
===================================================================
--- GNUnet/src/applications/fs/fsui/searchtest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/fsui/searchtest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -32,268 +32,233 @@
#define CHECK(a) if (!(a)) { ok = NO; GE_BREAK(NULL, 0); goto FAILURE; }
-static char * makeName(unsigned int i) {
- char * fn;
+static char *
+makeName (unsigned int i)
+{
+ char *fn;
- fn = MALLOC(strlen("/tmp/gnunet-fsui-searchtest/FSUITEST") + 14);
- SNPRINTF(fn,
- strlen("/tmp/gnunet-fsui-searchtest/FSUITEST") + 14,
- "/tmp/gnunet-fsui-searchtest/FSUITEST%u",
- i);
- disk_directory_create_for_file(NULL, fn);
+ fn = MALLOC (strlen ("/tmp/gnunet-fsui-searchtest/FSUITEST") + 14);
+ SNPRINTF (fn,
+ strlen ("/tmp/gnunet-fsui-searchtest/FSUITEST") + 14,
+ "/tmp/gnunet-fsui-searchtest/FSUITEST%u", i);
+ disk_directory_create_for_file (NULL, fn);
return fn;
}
static volatile enum FSUI_EventType lastEvent;
-static struct FSUI_SearchList * search;
+static struct FSUI_SearchList *search;
-static struct ECRS_URI * uri;
+static struct ECRS_URI *uri;
-static struct FSUI_Context * ctx;
+static struct FSUI_Context *ctx;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
static volatile enum FSUI_EventType waitForEvent;
-static void * eventCallback(void * cls,
- const FSUI_Event * event) {
+static void *
+eventCallback (void *cls, const FSUI_Event * event)
+{
static char unused;
- MUTEX_LOCK(lock);
- switch(event->type) {
- case FSUI_search_resumed:
- search = event->data.SearchResumed.sc.pos;
- break;
- case FSUI_search_suspended:
- search = NULL;
- break;
- case FSUI_download_resumed:
- case FSUI_upload_resumed:
- case FSUI_unindex_resumed:
- MUTEX_UNLOCK(lock);
- return &unused;
- case FSUI_search_result:
- printf("Received search result\n");
- uri = ECRS_dupUri(event->data.SearchResult.fi.uri);
- break;
- case FSUI_upload_completed:
- printf("Upload complete.\n");
- break;
- case FSUI_download_completed:
- printf("Download complete.\n");
- break;
- case FSUI_unindex_completed:
- printf("Unindex complete.\n");
- break;
- case FSUI_upload_error:
- printf("Upload error.\n");
- break;
- case FSUI_download_error:
- printf("Download error.\n");
- break;
- case FSUI_unindex_error:
- printf("Unindex error.\n");
- break;
- default:
- break;
- }
+ MUTEX_LOCK (lock);
+ switch (event->type)
+ {
+ case FSUI_search_resumed:
+ search = event->data.SearchResumed.sc.pos;
+ break;
+ case FSUI_search_suspended:
+ search = NULL;
+ break;
+ case FSUI_download_resumed:
+ case FSUI_upload_resumed:
+ case FSUI_unindex_resumed:
+ MUTEX_UNLOCK (lock);
+ return &unused;
+ case FSUI_search_result:
+ printf ("Received search result\n");
+ uri = ECRS_dupUri (event->data.SearchResult.fi.uri);
+ break;
+ case FSUI_upload_completed:
+ printf ("Upload complete.\n");
+ break;
+ case FSUI_download_completed:
+ printf ("Download complete.\n");
+ break;
+ case FSUI_unindex_completed:
+ printf ("Unindex complete.\n");
+ break;
+ case FSUI_upload_error:
+ printf ("Upload error.\n");
+ break;
+ case FSUI_download_error:
+ printf ("Download error.\n");
+ break;
+ case FSUI_unindex_error:
+ printf ("Unindex error.\n");
+ break;
+ default:
+ break;
+ }
if (lastEvent != waitForEvent)
lastEvent = event->type;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return NULL;
}
#define START_DAEMON 1
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
#if START_DAEMON
pid_t daemon;
#endif
int ok;
- char * fn = NULL;
- char * keywords[] = {
+ char *fn = NULL;
+ char *keywords[] = {
"search_foo",
"search_bar",
NULL,
};
char keyword[40];
int prog;
- struct ECRS_MetaData * meta;
- struct ECRS_URI * kuri;
- struct GC_Configuration * cfg;
- struct FSUI_UploadList * upload;
- struct FSUI_UnindexList * unindex;
- struct FSUI_DownloadList * download;
- struct ECRS_URI * luri;
+ struct ECRS_MetaData *meta;
+ struct ECRS_URI *kuri;
+ struct GC_Configuration *cfg;
+ struct FSUI_UploadList *upload;
+ struct FSUI_UnindexList *unindex;
+ struct FSUI_DownloadList *download;
+ struct ECRS_URI *luri;
ok = YES;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_DAEMON
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
- CHECK(OK == connection_wait_for_running(NULL,
- cfg,
- 30 * cronSECONDS));
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
+ CHECK (OK == connection_wait_for_running (NULL, cfg, 30 * cronSECONDS));
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
/* ACTUAL TEST CODE */
#endif
- lock = MUTEX_CREATE(NO);
- ctx = FSUI_start(NULL,
- cfg,
- "fsuisearchtest",
- 32,
- YES,
- &eventCallback,
- NULL);
- CHECK(ctx != NULL);
- SNPRINTF(keyword,
- 40,
- "%s %s %s",
- keywords[0],
- _("AND"),
- keywords[1]);
- luri = ECRS_parseCharKeywordURI(NULL, keyword);
- search = FSUI_startSearch(ctx,
- 0,
- 100,
- 240 * cronSECONDS,
- luri);
- ECRS_freeUri(luri);
+ lock = MUTEX_CREATE (NO);
+ ctx = FSUI_start (NULL,
+ cfg, "fsuisearchtest", 32, YES, &eventCallback, NULL);
+ CHECK (ctx != NULL);
+ SNPRINTF (keyword, 40, "%s %s %s", keywords[0], _("AND"), keywords[1]);
+ luri = ECRS_parseCharKeywordURI (NULL, keyword);
+ search = FSUI_startSearch (ctx, 0, 100, 240 * cronSECONDS, luri);
+ ECRS_freeUri (luri);
uri = NULL;
- CHECK(NULL != search);
- FSUI_stop(ctx);
+ CHECK (NULL != search);
+ FSUI_stop (ctx);
/* resume search! */
- ctx = FSUI_start(NULL,
- cfg,
- "fsuisearchtest",
- 32,
- YES,
- &eventCallback,
- NULL);
- fn = makeName(42);
- disk_file_write(NULL,
- fn,
- "foo bar test!",
- strlen("foo bar test!"),
- "600");
- meta = ECRS_createMetaData();
- kuri = ECRS_parseListKeywordURI(NULL,
- 2,
- (const char**)keywords);
+ ctx = FSUI_start (NULL,
+ cfg, "fsuisearchtest", 32, YES, &eventCallback, NULL);
+ fn = makeName (42);
+ disk_file_write (NULL,
+ fn, "foo bar test!", strlen ("foo bar test!"), "600");
+ meta = ECRS_createMetaData ();
+ kuri = ECRS_parseListKeywordURI (NULL, 2, (const char **) keywords);
waitForEvent = FSUI_upload_completed;
upload =
- FSUI_startUpload(ctx,
- fn,
- (DirectoryScanCallback) &disk_directory_scan,
- NULL,
- 0,
- 0,
- YES,
- NO,
- NO,
- get_time() + 5 * cronHOURS,
- meta,
- kuri,
- kuri);
- CHECK(NULL != upload);
- FREE(fn);
+ FSUI_startUpload (ctx,
+ fn,
+ (DirectoryScanCallback) & disk_directory_scan,
+ NULL,
+ 0,
+ 0,
+ YES,
+ NO, NO, get_time () + 5 * cronHOURS, meta, kuri, kuri);
+ CHECK (NULL != upload);
+ FREE (fn);
fn = NULL;
- ECRS_freeUri(kuri);
- ECRS_freeMetaData(meta);
+ ECRS_freeUri (kuri);
+ ECRS_freeMetaData (meta);
prog = 0;
- while (lastEvent != FSUI_upload_completed) {
- prog++;
- if (prog == 10000) {
- fprintf(stderr,
- "Upload failed to complete -- last event: %u\n",
- lastEvent);
+ while (lastEvent != FSUI_upload_completed)
+ {
+ prog++;
+ if (prog == 10000)
+ {
+ fprintf (stderr,
+ "Upload failed to complete -- last event: %u\n",
+ lastEvent);
+ }
+ CHECK (prog < 10000) PTHREAD_SLEEP (50 * cronMILLIS);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
}
- CHECK(prog < 10000)
- PTHREAD_SLEEP(50 * cronMILLIS);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- FSUI_stopUpload(ctx, upload);
+ FSUI_stopUpload (ctx, upload);
- while (uri == NULL) {
- prog++;
- CHECK(prog < 10000)
- PTHREAD_SLEEP(50 * cronMILLIS);
- }
- FSUI_abortSearch(ctx,
- search);
- FSUI_stopSearch(ctx,
- search);
- CHECK(uri != NULL);
- fn = makeName(43);
- meta = ECRS_createMetaData();
+ while (uri == NULL)
+ {
+ prog++;
+ CHECK (prog < 10000) PTHREAD_SLEEP (50 * cronMILLIS);
+ }
+ FSUI_abortSearch (ctx, search);
+ FSUI_stopSearch (ctx, search);
+ CHECK (uri != NULL);
+ fn = makeName (43);
+ meta = ECRS_createMetaData ();
waitForEvent = FSUI_download_completed;
- download = FSUI_startDownload(ctx,
- 0,
- NO,
- uri,
- meta,
- fn,
- NULL,
- NULL);
- ECRS_freeMetaData(meta);
- FREE(fn);
+ download = FSUI_startDownload (ctx, 0, NO, uri, meta, fn, NULL, NULL);
+ ECRS_freeMetaData (meta);
+ FREE (fn);
fn = NULL;
- ECRS_freeUri(uri);
+ ECRS_freeUri (uri);
prog = 0;
- while (lastEvent != FSUI_download_completed) {
- prog++;
- CHECK(prog < 10000);
- PTHREAD_SLEEP(50 * cronMILLIS);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- FSUI_stopDownload(ctx, download);
- fn = makeName(42);
+ while (lastEvent != FSUI_download_completed)
+ {
+ prog++;
+ CHECK (prog < 10000);
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
+ FSUI_stopDownload (ctx, download);
+ fn = makeName (42);
waitForEvent = FSUI_unindex_completed;
- unindex = FSUI_startUnindex(ctx, fn);
- FREE(fn);
+ unindex = FSUI_startUnindex (ctx, fn);
+ FREE (fn);
fn = NULL;
- CHECK(NULL != unindex);
+ CHECK (NULL != unindex);
prog = 0;
- while (lastEvent != FSUI_unindex_completed) {
- prog++;
- CHECK(prog < 10000);
- PTHREAD_SLEEP(50 * cronMILLIS);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- FSUI_stopUnindex(ctx, unindex);
+ while (lastEvent != FSUI_unindex_completed)
+ {
+ prog++;
+ CHECK (prog < 10000);
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
+ FSUI_stopUnindex (ctx, unindex);
/* END OF TEST CODE */
- FAILURE:
+FAILURE:
if (ctx != NULL)
- FSUI_stop(ctx);
+ FSUI_stop (ctx);
if (lock != NULL)
- MUTEX_DESTROY(lock);
- FREENONNULL(fn);
+ MUTEX_DESTROY (lock);
+ FREENONNULL (fn);
/* TODO: verify file 'fn(42)' == file 'fn(43)' */
- fn = makeName(42);
- UNLINK(fn);
- FREE(fn);
- fn = makeName(43);
- UNLINK(fn);
- FREE(fn);
+ fn = makeName (42);
+ UNLINK (fn);
+ FREE (fn);
+ fn = makeName (43);
+ UNLINK (fn);
+ FREE (fn);
#if START_DAEMON
- GE_ASSERT(NULL, OK == os_daemon_stop(NULL, daemon));
+ GE_ASSERT (NULL, OK == os_daemon_stop (NULL, daemon));
#endif
- GC_free(cfg);
+ GC_free (cfg);
return (ok == YES) ? 0 : 1;
}
Modified: GNUnet/src/applications/fs/fsui/serialize.c
===================================================================
--- GNUnet/src/applications/fs/fsui/serialize.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/fsui/serialize.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -31,321 +31,311 @@
#include "gnunet_directories.h"
#include "fsui.h"
-static void WRITEINT(int fd,
- int val) {
+static void
+WRITEINT (int fd, int val)
+{
int big;
- big = htonl(val);
- WRITE(fd, &big, sizeof(int));
+ big = htonl (val);
+ WRITE (fd, &big, sizeof (int));
}
-static void WRITELONG(int fd,
- long long val) {
+static void
+WRITELONG (int fd, long long val)
+{
long long big;
- big = htonll(val);
- WRITE(fd, &big, sizeof(long long));
+ big = htonll (val);
+ WRITE (fd, &big, sizeof (long long));
}
-static void writeURI(int fd,
- const struct ECRS_URI * uri) {
- char * buf;
+static void
+writeURI (int fd, const struct ECRS_URI *uri)
+{
+ char *buf;
unsigned int size;
- buf = ECRS_uriToString(uri);
- size = strlen(buf);
- WRITEINT(fd, size);
- WRITE(fd,
- buf,
- size);
- FREE(buf);
+ buf = ECRS_uriToString (uri);
+ size = strlen (buf);
+ WRITEINT (fd, size);
+ WRITE (fd, buf, size);
+ FREE (buf);
}
-static void WRITESTRING(int fd,
- const char * name) {
- GE_BREAK(NULL, name != NULL);
- WRITEINT(fd,
- strlen(name));
- WRITE(fd,
- name,
- strlen(name));
+static void
+WRITESTRING (int fd, const char *name)
+{
+ GE_BREAK (NULL, name != NULL);
+ WRITEINT (fd, strlen (name));
+ WRITE (fd, name, strlen (name));
}
-static void writeMetaData(struct GE_Context * ectx,
- int fd,
- const struct ECRS_MetaData * meta) {
+static void
+writeMetaData (struct GE_Context *ectx,
+ int fd, const struct ECRS_MetaData *meta)
+{
unsigned int size;
- char * buf;
+ char *buf;
- size = ECRS_sizeofMetaData(meta,
- ECRS_SERIALIZE_FULL | ECRS_SERIALIZE_NO_COMPRESS);
+ size = ECRS_sizeofMetaData (meta,
+ ECRS_SERIALIZE_FULL |
+ ECRS_SERIALIZE_NO_COMPRESS);
if (size > 1024 * 1024)
size = 1024 * 1024;
- buf = MALLOC(size);
- ECRS_serializeMetaData(ectx,
- meta,
- buf,
- size,
- ECRS_SERIALIZE_PART | ECRS_SERIALIZE_NO_COMPRESS);
- WRITEINT(fd, size);
- WRITE(fd,
- buf,
- size);
- FREE(buf);
+ buf = MALLOC (size);
+ ECRS_serializeMetaData (ectx,
+ meta,
+ buf,
+ size,
+ ECRS_SERIALIZE_PART | ECRS_SERIALIZE_NO_COMPRESS);
+ WRITEINT (fd, size);
+ WRITE (fd, buf, size);
+ FREE (buf);
}
-static void writeFileInfo(struct GE_Context * ectx,
- int fd,
- const ECRS_FileInfo * fi) {
- writeMetaData(ectx, fd, fi->meta);
- writeURI(fd, fi->uri);
+static void
+writeFileInfo (struct GE_Context *ectx, int fd, const ECRS_FileInfo * fi)
+{
+ writeMetaData (ectx, fd, fi->meta);
+ writeURI (fd, fi->uri);
}
/**
* (recursively) write a download list.
*/
-static void writeDownloadList(struct GE_Context * ectx,
- int fd,
- FSUI_Context * ctx,
- FSUI_DownloadList * list) {
+static void
+writeDownloadList (struct GE_Context *ectx,
+ int fd, FSUI_Context * ctx, FSUI_DownloadList * list)
+{
int i;
- FSUI_SearchList * pos;
+ FSUI_SearchList *pos;
- if (list == NULL) {
- WRITEINT(fd, 0);
- return;
- }
+ if (list == NULL)
+ {
+ WRITEINT (fd, 0);
+ return;
+ }
#if DEBUG_PERSISTENCE
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Serializing download state of download `%s': (%llu, %llu)\n",
- list->filename,
- list->completed,
- list->total);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Serializing download state of download `%s': (%llu, %llu)\n",
+ list->filename, list->completed, list->total);
#endif
- WRITEINT(fd, 1);
- if (list->search == NULL) {
- WRITEINT(fd, 0);
- } else {
- i = 1;
- pos = ctx->activeSearches;
- while (pos != list->search) {
- if ( (pos->sizeResultsReceived <= 1024 * 1024) &&
- (pos->sizeUnmatchedResultsReceived <= 1024 * 1024) )
- i++;
- pos = pos->next;
- if (pos == NULL) {
- GE_BREAK(ectx, 0);
- i = 0;
- break;
- }
+ WRITEINT (fd, 1);
+ if (list->search == NULL)
+ {
+ WRITEINT (fd, 0);
}
- if ( (pos != NULL) &&
- ( (pos->sizeResultsReceived < 1024 * 1024) ||
- (pos->sizeUnmatchedResultsReceived < 1024 * 1024) ) )
- i = 0;
- WRITEINT(fd, i);
- }
- WRITEINT(fd, list->state);
- WRITEINT(fd, list->is_recursive);
- WRITEINT(fd, list->is_directory);
- WRITEINT(fd, list->anonymityLevel);
- WRITEINT(fd, list->completedDownloadsCount);
- WRITELONG(fd, list->total);
- WRITELONG(fd, list->completed);
- WRITELONG(fd, get_time() - list->startTime);
+ else
+ {
+ i = 1;
+ pos = ctx->activeSearches;
+ while (pos != list->search)
+ {
+ if ((pos->sizeResultsReceived <= 1024 * 1024) &&
+ (pos->sizeUnmatchedResultsReceived <= 1024 * 1024))
+ i++;
+ pos = pos->next;
+ if (pos == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ i = 0;
+ break;
+ }
+ }
+ if ((pos != NULL) &&
+ ((pos->sizeResultsReceived < 1024 * 1024) ||
+ (pos->sizeUnmatchedResultsReceived < 1024 * 1024)))
+ i = 0;
+ WRITEINT (fd, i);
+ }
+ WRITEINT (fd, list->state);
+ WRITEINT (fd, list->is_recursive);
+ WRITEINT (fd, list->is_directory);
+ WRITEINT (fd, list->anonymityLevel);
+ WRITEINT (fd, list->completedDownloadsCount);
+ WRITELONG (fd, list->total);
+ WRITELONG (fd, list->completed);
+ WRITELONG (fd, get_time () - list->startTime);
- WRITESTRING(fd, list->filename);
- writeFileInfo(ectx,
- fd,
- &list->fi);
- for (i=0;i<list->completedDownloadsCount;i++)
- writeURI(fd, list->completedDownloads[i]);
- writeDownloadList(ectx,
- fd,
- ctx,
- list->next);
- writeDownloadList(ectx,
- fd,
- ctx,
- list->child);
+ WRITESTRING (fd, list->filename);
+ writeFileInfo (ectx, fd, &list->fi);
+ for (i = 0; i < list->completedDownloadsCount; i++)
+ writeURI (fd, list->completedDownloads[i]);
+ writeDownloadList (ectx, fd, ctx, list->next);
+ writeDownloadList (ectx, fd, ctx, list->child);
}
-static void writeCollection(int fd,
- struct FSUI_Context * ctx) {
- if ( (ctx->collectionData == NULL) ||
- (ctx->collectionData->size > 16 * 1024 * 1024) ) {
- WRITEINT(fd, 0);
- return;
- }
+static void
+writeCollection (int fd, struct FSUI_Context *ctx)
+{
+ if ((ctx->collectionData == NULL) ||
+ (ctx->collectionData->size > 16 * 1024 * 1024))
+ {
+ WRITEINT (fd, 0);
+ return;
+ }
/* serialize collection data */
- WRITE(fd,
- ctx->collectionData,
- ntohl(ctx->collectionData->size));
+ WRITE (fd, ctx->collectionData, ntohl (ctx->collectionData->size));
}
-static void writeSearches(int fd,
- struct FSUI_Context * ctx) {
- FSUI_SearchList * spos;
+static void
+writeSearches (int fd, struct FSUI_Context *ctx)
+{
+ FSUI_SearchList *spos;
int i;
spos = ctx->activeSearches;
- while (spos != NULL) {
- if ( (spos->sizeResultsReceived > 1024 * 1024) ||
- (spos->sizeUnmatchedResultsReceived > 1024 * 1024) ) {
- /* too large to serialize - skip! */
+ while (spos != NULL)
+ {
+ if ((spos->sizeResultsReceived > 1024 * 1024) ||
+ (spos->sizeUnmatchedResultsReceived > 1024 * 1024))
+ {
+ /* too large to serialize - skip! */
+ spos = spos->next;
+ continue;
+ }
+ GE_ASSERT (ctx->ectx,
+ ECRS_isKeywordUri (spos->uri) ||
+ ECRS_isNamespaceUri (spos->uri));
+ WRITEINT (fd, 1);
+ WRITEINT (fd, spos->state);
+ WRITEINT (fd, spos->maxResults);
+ WRITELONG (fd, spos->timeout);
+ WRITELONG (fd, spos->start_time);
+ WRITELONG (fd, get_time ());
+ WRITEINT (fd, spos->anonymityLevel);
+ WRITEINT (fd, spos->sizeResultsReceived);
+ WRITEINT (fd, spos->sizeUnmatchedResultsReceived);
+ writeURI (fd, spos->uri);
+ for (i = 0; i < spos->sizeResultsReceived; i++)
+ writeFileInfo (ctx->ectx, fd, &spos->resultsReceived[i]);
+ for (i = 0; i < spos->sizeUnmatchedResultsReceived; i++)
+ {
+ ResultPending *rp;
+
+ rp = &spos->unmatchedResultsReceived[i];
+ writeFileInfo (ctx->ectx, fd, &rp->fi);
+ GE_ASSERT (ctx->ectx, rp->matchingKeyCount < spos->numberOfURIKeys);
+ if (rp->matchingKeyCount > 1024)
+ {
+ WRITEINT (fd, 0); /* too large to serialize */
+ continue;
+ }
+ WRITEINT (fd, rp->matchingKeyCount);
+ WRITE (fd,
+ rp->matchingKeys,
+ sizeof (HashCode512) * rp->matchingKeyCount);
+ }
spos = spos->next;
- continue;
}
- GE_ASSERT(ctx->ectx,
- ECRS_isKeywordUri(spos->uri) ||
- ECRS_isNamespaceUri(spos->uri));
- WRITEINT(fd, 1);
- WRITEINT(fd, spos->state);
- WRITEINT(fd, spos->maxResults);
- WRITELONG(fd, spos->timeout);
- WRITELONG(fd, spos->start_time);
- WRITELONG(fd, get_time());
- WRITEINT(fd, spos->anonymityLevel);
- WRITEINT(fd, spos->sizeResultsReceived);
- WRITEINT(fd, spos->sizeUnmatchedResultsReceived);
- writeURI(fd, spos->uri);
- for (i=0;i<spos->sizeResultsReceived;i++)
- writeFileInfo(ctx->ectx,
- fd,
- &spos->resultsReceived[i]);
- for (i=0;i<spos->sizeUnmatchedResultsReceived;i++) {
- ResultPending * rp;
-
- rp = &spos->unmatchedResultsReceived[i];
- writeFileInfo(ctx->ectx,
- fd,
- &rp->fi);
- GE_ASSERT(ctx->ectx,
- rp->matchingKeyCount < spos->numberOfURIKeys);
- if (rp->matchingKeyCount > 1024) {
- WRITEINT(fd, 0); /* too large to serialize */
- continue;
- }
- WRITEINT(fd, rp->matchingKeyCount);
- WRITE(fd,
- rp->matchingKeys,
- sizeof(HashCode512) * rp->matchingKeyCount);
- }
- spos = spos->next;
- }
- WRITEINT(fd, 0);
+ WRITEINT (fd, 0);
}
-static void writeUnindexing(int fd,
- struct FSUI_Context * ctx) {
- FSUI_UnindexList * xpos;
+static void
+writeUnindexing (int fd, struct FSUI_Context *ctx)
+{
+ FSUI_UnindexList *xpos;
xpos = ctx->unindexOperations;
- while (xpos != NULL) {
- WRITEINT(fd, 1);
- WRITEINT(fd, xpos->state);
- WRITESTRING(fd, xpos->filename);
- xpos = xpos->next;
- }
+ while (xpos != NULL)
+ {
+ WRITEINT (fd, 1);
+ WRITEINT (fd, xpos->state);
+ WRITESTRING (fd, xpos->filename);
+ xpos = xpos->next;
+ }
/* unindex list terminator */
- WRITEINT(fd, 0);
+ WRITEINT (fd, 0);
}
-static void writeUploadList(int fd,
- struct FSUI_Context * ctx,
- struct FSUI_UploadList * upos,
- int top) {
+static void
+writeUploadList (int fd,
+ struct FSUI_Context *ctx,
+ struct FSUI_UploadList *upos, int top)
+{
int bits;
- while (upos != NULL) {
- bits = 1;
- if (upos->uri != NULL)
- bits |= 2;
- if (upos->keywords != NULL)
- bits |= 4;
- if (upos->meta != NULL)
- bits |= 8;
- WRITEINT(fd, bits);
- WRITEINT(fd, 0x34D1F023);
- WRITEINT(fd, upos->state);
- WRITELONG(fd, upos->completed);
- WRITELONG(fd, upos->total);
- WRITELONG(fd, get_time());
- WRITELONG(fd, upos->start_time);
- if (upos->uri != NULL)
- writeURI(fd, upos->uri);
- if (upos->keywords != NULL)
- writeURI(fd, upos->keywords);
- if (upos->meta != NULL)
- writeMetaData(ctx->ectx, fd, upos->meta);
- WRITESTRING(fd, upos->filename);
- writeUploadList(fd, ctx, upos->child, NO);
- if (top == YES)
- break;
- upos = upos->next;
- }
- WRITEINT(fd, 0);
+ while (upos != NULL)
+ {
+ bits = 1;
+ if (upos->uri != NULL)
+ bits |= 2;
+ if (upos->keywords != NULL)
+ bits |= 4;
+ if (upos->meta != NULL)
+ bits |= 8;
+ WRITEINT (fd, bits);
+ WRITEINT (fd, 0x34D1F023);
+ WRITEINT (fd, upos->state);
+ WRITELONG (fd, upos->completed);
+ WRITELONG (fd, upos->total);
+ WRITELONG (fd, get_time ());
+ WRITELONG (fd, upos->start_time);
+ if (upos->uri != NULL)
+ writeURI (fd, upos->uri);
+ if (upos->keywords != NULL)
+ writeURI (fd, upos->keywords);
+ if (upos->meta != NULL)
+ writeMetaData (ctx->ectx, fd, upos->meta);
+ WRITESTRING (fd, upos->filename);
+ writeUploadList (fd, ctx, upos->child, NO);
+ if (top == YES)
+ break;
+ upos = upos->next;
+ }
+ WRITEINT (fd, 0);
}
-static void writeUploads(int fd,
- struct FSUI_Context * ctx,
- struct FSUI_UploadList * upos) {
- struct FSUI_UploadShared * shared;
+static void
+writeUploads (int fd, struct FSUI_Context *ctx, struct FSUI_UploadList *upos)
+{
+ struct FSUI_UploadShared *shared;
int bits;
- while (upos != NULL) {
- shared = upos->shared;
- bits = 1;
- if (shared->extractor_config != NULL)
- bits |= 2;
- if (shared->global_keywords != NULL)
- bits |= 4;
- WRITEINT(fd, bits);
- WRITEINT(fd, 0x44D1F024);
- WRITEINT(fd, shared->doIndex);
- WRITEINT(fd, shared->anonymityLevel);
- WRITEINT(fd, shared->priority);
- WRITEINT(fd, shared->individualKeywords);
- WRITELONG(fd, shared->expiration);
- if (shared->extractor_config != NULL)
- WRITESTRING(fd,
- shared->extractor_config);
- if (shared->global_keywords != NULL)
- writeURI(fd, shared->global_keywords);
- writeUploadList(fd,
- ctx,
- upos,
- YES);
- upos = upos->next;
- }
- WRITEINT(fd, 0);
+ while (upos != NULL)
+ {
+ shared = upos->shared;
+ bits = 1;
+ if (shared->extractor_config != NULL)
+ bits |= 2;
+ if (shared->global_keywords != NULL)
+ bits |= 4;
+ WRITEINT (fd, bits);
+ WRITEINT (fd, 0x44D1F024);
+ WRITEINT (fd, shared->doIndex);
+ WRITEINT (fd, shared->anonymityLevel);
+ WRITEINT (fd, shared->priority);
+ WRITEINT (fd, shared->individualKeywords);
+ WRITELONG (fd, shared->expiration);
+ if (shared->extractor_config != NULL)
+ WRITESTRING (fd, shared->extractor_config);
+ if (shared->global_keywords != NULL)
+ writeURI (fd, shared->global_keywords);
+ writeUploadList (fd, ctx, upos, YES);
+ upos = upos->next;
+ }
+ WRITEINT (fd, 0);
}
-void FSUI_serialize(struct FSUI_Context * ctx) {
+void
+FSUI_serialize (struct FSUI_Context *ctx)
+{
int fd;
- fd = disk_file_open(ctx->ectx,
- ctx->name,
- O_CREAT|O_TRUNC|O_WRONLY,
- S_IRUSR|S_IWUSR);
+ fd = disk_file_open (ctx->ectx,
+ ctx->name,
+ O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
if (fd == -1)
return;
- WRITE(fd,
- "FSUI01\n\0",
- 8); /* magic */
- writeCollection(fd, ctx);
- writeSearches(fd, ctx);
- writeDownloadList(ctx->ectx,
- fd,
- ctx,
- ctx->activeDownloads.child);
- writeUnindexing(fd, ctx);
- writeUploads(fd,
- ctx,
- ctx->activeUploads.child);
- CLOSE(fd);
+ WRITE (fd, "FSUI01\n\0", 8); /* magic */
+ writeCollection (fd, ctx);
+ writeSearches (fd, ctx);
+ writeDownloadList (ctx->ectx, fd, ctx, ctx->activeDownloads.child);
+ writeUnindexing (fd, ctx);
+ writeUploads (fd, ctx, ctx->activeUploads.child);
+ CLOSE (fd);
}
/* end of serializer */
Modified: GNUnet/src/applications/fs/fsui/serializetest.c
===================================================================
--- GNUnet/src/applications/fs/fsui/serializetest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/fsui/serializetest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -37,115 +37,107 @@
static volatile int suspendRestart = 0;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static char * makeName(unsigned int i) {
- char * fn;
+static char *
+makeName (unsigned int i)
+{
+ char *fn;
- fn = MALLOC(strlen("/tmp/gnunet-fsui-serializetest/FSUITEST") + 14);
- SNPRINTF(fn,
- strlen("/tmp/gnunet-fsui-serializetest/FSUITEST") + 14,
- "/tmp/gnunet-fsui-serializetest/FSUITEST%u",
- i);
- disk_directory_create_for_file(NULL, fn);
+ fn = MALLOC (strlen ("/tmp/gnunet-fsui-serializetest/FSUITEST") + 14);
+ SNPRINTF (fn,
+ strlen ("/tmp/gnunet-fsui-serializetest/FSUITEST") + 14,
+ "/tmp/gnunet-fsui-serializetest/FSUITEST%u", i);
+ disk_directory_create_for_file (NULL, fn);
return fn;
}
static volatile enum FSUI_EventType lastEvent;
static volatile enum FSUI_EventType waitForEvent;
-static struct FSUI_Context * ctx;
-static struct ECRS_URI * upURI;
-static struct FSUI_UnindexList * unindex;
-static struct FSUI_UploadList * upload;
+static struct FSUI_Context *ctx;
+static struct ECRS_URI *upURI;
+static struct FSUI_UnindexList *unindex;
+static struct FSUI_UploadList *upload;
-static void * eventCallback(void * cls,
- const FSUI_Event * event) {
- switch(event->type) {
- case FSUI_upload_progress:
+static void *
+eventCallback (void *cls, const FSUI_Event * event)
+{
+ switch (event->type)
+ {
+ case FSUI_upload_progress:
#if DEBUG_VERBOSE
- printf("Upload is progressing (%llu/%llu)...\n",
- event->data.UploadProgress.completed,
- event->data.UploadProgress.total);
+ printf ("Upload is progressing (%llu/%llu)...\n",
+ event->data.UploadProgress.completed,
+ event->data.UploadProgress.total);
#endif
- break;
- case FSUI_upload_completed:
- upURI = ECRS_dupUri(event->data.UploadCompleted.uri);
+ break;
+ case FSUI_upload_completed:
+ upURI = ECRS_dupUri (event->data.UploadCompleted.uri);
#if DEBUG_VERBOSE
- printf("Upload complete.\n");
+ printf ("Upload complete.\n");
#endif
- break;
- case FSUI_unindex_progress:
+ break;
+ case FSUI_unindex_progress:
#if DEBUG_VERBOSE
- printf("Unindex is progressing (%llu/%llu)...\n",
- event->data.UnindexProgress.completed,
- event->data.UnindexProgress.total);
+ printf ("Unindex is progressing (%llu/%llu)...\n",
+ event->data.UnindexProgress.completed,
+ event->data.UnindexProgress.total);
#endif
- break;
- case FSUI_unindex_completed:
+ break;
+ case FSUI_unindex_completed:
#if DEBUG_VERBOSE
- printf("Unindex complete.\n");
+ printf ("Unindex complete.\n");
#endif
- break;
- case FSUI_unindex_error:
- case FSUI_upload_error:
- case FSUI_download_error:
- case FSUI_search_error:
- fprintf(stderr,
- "Received ERROR: %d\n",
- event->type);
- GE_BREAK(ectx, 0);
- break;
- case FSUI_download_aborted:
+ break;
+ case FSUI_unindex_error:
+ case FSUI_upload_error:
+ case FSUI_download_error:
+ case FSUI_search_error:
+ fprintf (stderr, "Received ERROR: %d\n", event->type);
+ GE_BREAK (ectx, 0);
+ break;
+ case FSUI_download_aborted:
#if DEBUG_VERBOSE
- printf("Received download aborted event.\n");
+ printf ("Received download aborted event.\n");
#endif
- break;
- case FSUI_unindex_resumed:
+ break;
+ case FSUI_unindex_resumed:
#if DEBUG_VERBOSE
- fprintf(stderr,
- "Received RESUMING: %d\n",
- event->type);
+ fprintf (stderr, "Received RESUMING: %d\n", event->type);
#endif
- unindex = event->data.UnindexResumed.uc.pos;
- break;
- case FSUI_upload_resumed:
+ unindex = event->data.UnindexResumed.uc.pos;
+ break;
+ case FSUI_upload_resumed:
#if DEBUG_VERBOSE
- fprintf(stderr,
- "Received RESUMING: %d\n",
- event->type);
+ fprintf (stderr, "Received RESUMING: %d\n", event->type);
#endif
- upload = event->data.UploadResumed.uc.pos;
- break;
- break;
- case FSUI_unindex_suspended:
- unindex = NULL;
+ upload = event->data.UploadResumed.uc.pos;
+ break;
+ break;
+ case FSUI_unindex_suspended:
+ unindex = NULL;
#if DEBUG_VERBOSE
- fprintf(stderr,
- "Received SUSPENDING: %d\n",
- event->type);
+ fprintf (stderr, "Received SUSPENDING: %d\n", event->type);
#endif
- break;
- case FSUI_upload_suspended:
- upload = NULL;
+ break;
+ case FSUI_upload_suspended:
+ upload = NULL;
#if DEBUG_VERBOSE
- fprintf(stderr,
- "Received SUSPENDING: %d\n",
- event->type);
+ fprintf (stderr, "Received SUSPENDING: %d\n", event->type);
#endif
- break;
- case FSUI_upload_started:
- case FSUI_upload_stopped:
- case FSUI_unindex_started:
- case FSUI_unindex_stopped:
- break;
- default:
- printf("Unexpected event: %d\n",
- event->type);
- break;
- }
+ break;
+ case FSUI_upload_started:
+ case FSUI_upload_stopped:
+ case FSUI_unindex_started:
+ case FSUI_unindex_stopped:
+ break;
+ default:
+ printf ("Unexpected event: %d\n", event->type);
+ break;
+ }
if (lastEvent == waitForEvent)
- return NULL; /* ignore all other events */
+ return NULL; /* ignore all other events */
lastEvent = event->type;
return NULL;
}
@@ -154,174 +146,154 @@
#define START_DAEMON 1
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
#if START_DAEMON
pid_t daemon;
#endif
int ok;
int i;
- char * fn = NULL;
- char * keywords[] = {
+ char *fn = NULL;
+ char *keywords[] = {
"down_foo",
"down_bar",
NULL,
};
int prog;
- char * buf;
- struct ECRS_MetaData * meta;
- struct ECRS_URI * kuri = NULL;
- struct GC_Configuration * cfg;
+ char *buf;
+ struct ECRS_MetaData *meta;
+ struct ECRS_URI *kuri = NULL;
+ struct GC_Configuration *cfg;
ok = YES;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_DAEMON
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
- CHECK(OK == connection_wait_for_running(NULL,
- cfg,
- 30 * cronSECONDS));
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
+ CHECK (OK == connection_wait_for_running (NULL, cfg, 30 * cronSECONDS));
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
/* ACTUAL TEST CODE */
#endif
- ctx = FSUI_start(NULL,
- cfg,
- "fsuiserializetest",
- 32,
- YES,
- &eventCallback,
- NULL);
- CHECK(ctx != NULL);
- fn = makeName(42);
- buf = MALLOC(FILESIZE);
- for (i=0;i<FILESIZE;i++)
- buf[i] = weak_randomi(256);
- disk_file_write(ectx,
- fn,
- buf,
- FILESIZE,
- "600");
- FREE(buf);
- meta = ECRS_createMetaData();
- kuri = ECRS_parseListKeywordURI(ectx,
- 2,
- (const char**)keywords);
+ ctx = FSUI_start (NULL,
+ cfg, "fsuiserializetest", 32, YES, &eventCallback, NULL);
+ CHECK (ctx != NULL);
+ fn = makeName (42);
+ buf = MALLOC (FILESIZE);
+ for (i = 0; i < FILESIZE; i++)
+ buf[i] = weak_randomi (256);
+ disk_file_write (ectx, fn, buf, FILESIZE, "600");
+ FREE (buf);
+ meta = ECRS_createMetaData ();
+ kuri = ECRS_parseListKeywordURI (ectx, 2, (const char **) keywords);
waitForEvent = FSUI_upload_completed;
- upload = FSUI_startUpload(ctx,
- fn,
- (DirectoryScanCallback) &disk_directory_scan,
- NULL,
- 0,
- 0,
- YES,
- NO,
- NO,
- get_time() + 5 * cronHOURS,
- meta,
- kuri,
- kuri);
- CHECK(upload != NULL);
- ECRS_freeUri(kuri);
+ upload = FSUI_startUpload (ctx,
+ fn,
+ (DirectoryScanCallback) & disk_directory_scan,
+ NULL,
+ 0,
+ 0,
+ YES,
+ NO,
+ NO,
+ get_time () + 5 * cronHOURS, meta, kuri, kuri);
+ CHECK (upload != NULL);
+ ECRS_freeUri (kuri);
kuri = NULL;
- ECRS_freeMetaData(meta);
+ ECRS_freeMetaData (meta);
prog = 0;
suspendRestart = 4;
- while (lastEvent != FSUI_upload_completed) {
- if ( (suspendRestart > 0) &&
- (weak_randomi(4) == 0) ) {
+ while (lastEvent != FSUI_upload_completed)
+ {
+ if ((suspendRestart > 0) && (weak_randomi (4) == 0))
+ {
#if 1
#if DEBUG_VERBOSE
- printf("Testing FSUI suspend-resume\n");
+ printf ("Testing FSUI suspend-resume\n");
#endif
- FSUI_stop(ctx); /* download possibly incomplete
- at this point, thus testing resume */
- ctx = FSUI_start(NULL,
- cfg,
- "fsuiserializetest",
- 32,
- YES,
- &eventCallback,
- NULL);
+ FSUI_stop (ctx); /* download possibly incomplete
+ at this point, thus testing resume */
+ ctx = FSUI_start (NULL,
+ cfg,
+ "fsuiserializetest",
+ 32, YES, &eventCallback, NULL);
#if DEBUG_VERBOSE
- printf("Resumed...\n");
+ printf ("Resumed...\n");
#endif
#endif
- suspendRestart--;
+ suspendRestart--;
+ }
+ prog++;
+ CHECK (prog < 5000);
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
}
- prog++;
- CHECK(prog < 5000);
- PTHREAD_SLEEP(50 * cronMILLIS);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- FSUI_stopUpload(ctx, upload);
+ FSUI_stopUpload (ctx, upload);
waitForEvent = FSUI_unindex_completed;
- unindex = FSUI_startUnindex(ctx, fn);
- CHECK(unindex != NULL);
+ unindex = FSUI_startUnindex (ctx, fn);
+ CHECK (unindex != NULL);
prog = 0;
suspendRestart = 4;
- while (lastEvent != FSUI_unindex_completed) {
- if ( (suspendRestart > 0) &&
- (weak_randomi(4) == 0) ) {
+ while (lastEvent != FSUI_unindex_completed)
+ {
+ if ((suspendRestart > 0) && (weak_randomi (4) == 0))
+ {
#if 1
#if DEBUG_VERBOSE
- printf("Testing FSUI suspend-resume\n");
+ printf ("Testing FSUI suspend-resume\n");
#endif
- FSUI_stop(ctx); /* download possibly incomplete
- at this point, thus testing resume */
- ctx = FSUI_start(NULL,
- cfg,
- "fsuiserializetest",
- 32,
- YES,
- &eventCallback,
- NULL);
+ FSUI_stop (ctx); /* download possibly incomplete
+ at this point, thus testing resume */
+ ctx = FSUI_start (NULL,
+ cfg,
+ "fsuiserializetest",
+ 32, YES, &eventCallback, NULL);
#if DEBUG_VERBOSE
- printf("Resumed...\n");
+ printf ("Resumed...\n");
#endif
#endif
- suspendRestart--;
+ suspendRestart--;
+ }
+ prog++;
+ CHECK (prog < 5000);
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ CHECK (lastEvent != FSUI_unindex_error);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
}
- prog++;
- CHECK(prog < 5000);
- PTHREAD_SLEEP(50 * cronMILLIS);
- CHECK(lastEvent != FSUI_unindex_error);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- CHECK(lastEvent == FSUI_unindex_completed);
+ CHECK (lastEvent == FSUI_unindex_completed);
/* END OF TEST CODE */
- FAILURE:
- if (ctx != NULL) {
- if (unindex != NULL)
- FSUI_stopUnindex(ctx,
- unindex);
- FSUI_stop(ctx);
- }
- if (fn != NULL) {
- UNLINK(fn);
- FREE(fn);
- }
+FAILURE:
+ if (ctx != NULL)
+ {
+ if (unindex != NULL)
+ FSUI_stopUnindex (ctx, unindex);
+ FSUI_stop (ctx);
+ }
+ if (fn != NULL)
+ {
+ UNLINK (fn);
+ FREE (fn);
+ }
if (kuri != NULL)
- ECRS_freeUri(kuri);
- fn = makeName(43);
+ ECRS_freeUri (kuri);
+ fn = makeName (43);
/* TODO: verify file 'fn(42)' == file 'fn(43)' */
- UNLINK(fn);
- FREE(fn);
+ UNLINK (fn);
+ FREE (fn);
if (upURI != NULL)
- ECRS_freeUri(upURI);
+ ECRS_freeUri (upURI);
#if START_DAEMON
- GE_ASSERT(NULL, OK == os_daemon_stop(NULL, daemon));
+ GE_ASSERT (NULL, OK == os_daemon_stop (NULL, daemon));
#endif
- GC_free(cfg);
+ GC_free (cfg);
return (ok == YES) ? 0 : 1;
}
Modified: GNUnet/src/applications/fs/fsui/serializetest2.c
===================================================================
--- GNUnet/src/applications/fs/fsui/serializetest2.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/fsui/serializetest2.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -38,24 +38,25 @@
#define CHECK(a) if (!(a)) { ok = NO; GE_BREAK(ectx, 0); goto FAILURE; }
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static char * makeName(unsigned int i) {
- char * fn;
+static char *
+makeName (unsigned int i)
+{
+ char *fn;
- fn = MALLOC(strlen(UPLOAD_PREFIX "/FSUITEST") + 14);
- SNPRINTF(fn,
- strlen(UPLOAD_PREFIX "/FSUITEST") + 14,
- UPLOAD_PREFIX "/FSUITEST%u",
- i);
- disk_directory_create_for_file(NULL, fn);
+ fn = MALLOC (strlen (UPLOAD_PREFIX "/FSUITEST") + 14);
+ SNPRINTF (fn,
+ strlen (UPLOAD_PREFIX "/FSUITEST") + 14,
+ UPLOAD_PREFIX "/FSUITEST%u", i);
+ disk_directory_create_for_file (NULL, fn);
return fn;
}
-static struct FSUI_Context * ctx;
-static struct ECRS_URI * upURI;
-static struct FSUI_SearchList * search;
-static struct FSUI_DownloadList * download;
+static struct FSUI_Context *ctx;
+static struct ECRS_URI *upURI;
+static struct FSUI_SearchList *search;
+static struct FSUI_DownloadList *download;
static int have_error;
/**
@@ -65,239 +66,251 @@
*/
static int no_check;
-static void * eventCallback(void * cls,
- const FSUI_Event * event) {
+static void *
+eventCallback (void *cls, const FSUI_Event * event)
+{
if (no_check)
return NULL;
- switch(event->type) {
- case FSUI_search_suspended:
- search = NULL;
- break;
- case FSUI_download_suspended:
- if (event->data.DownloadSuspended.dc.spos != search) {
- fprintf(stderr,
- "Download suspended but search reference not set correctly.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadSuspended.dc.pos == download) &&
- (event->data.DownloadSuspended.dc.ppos != NULL) ) {
- fprintf(stderr,
- "Download suspended but parent reference not set to NULL.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadSuspended.dc.pos != download) &&
- (event->data.DownloadSuspended.dc.ppos != download) ) {
- fprintf(stderr,
- "Download suspended but parent reference not set correctly (%p instead
of %p).\n",
- event->data.DownloadSuspended.dc.ppos,
- download);
- have_error = 1;
- }
- if (event->data.DownloadSuspended.dc.pos == download)
- download = NULL;
- break;
- case FSUI_search_resumed:
+ switch (event->type)
+ {
+ case FSUI_search_suspended:
+ search = NULL;
+ break;
+ case FSUI_download_suspended:
+ if (event->data.DownloadSuspended.dc.spos != search)
+ {
+ fprintf (stderr,
+ "Download suspended but search reference not set
correctly.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadSuspended.dc.pos == download) &&
+ (event->data.DownloadSuspended.dc.ppos != NULL))
+ {
+ fprintf (stderr,
+ "Download suspended but parent reference not set to
NULL.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadSuspended.dc.pos != download) &&
+ (event->data.DownloadSuspended.dc.ppos != download))
+ {
+ fprintf (stderr,
+ "Download suspended but parent reference not set correctly
(%p instead of %p).\n",
+ event->data.DownloadSuspended.dc.ppos, download);
+ have_error = 1;
+ }
+ if (event->data.DownloadSuspended.dc.pos == download)
+ download = NULL;
+ break;
+ case FSUI_search_resumed:
#if DEBUG_VERBOSE
- printf("Search resuming\n");
+ printf ("Search resuming\n");
#endif
- search = event->data.SearchResumed.sc.pos;
- break;
- case FSUI_download_resumed:
- if (download == NULL)
- download = event->data.DownloadResumed.dc.pos;
- if (event->data.DownloadResumed.dc.spos != search) {
- fprintf(stderr,
- "Download resuming but search reference not set correctly.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadResumed.dc.pos == download) &&
- (event->data.DownloadResumed.dc.ppos != NULL) ) {
- fprintf(stderr,
- "Download resuming but parent reference not set to NULL.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadResumed.dc.pos != download) &&
- (event->data.DownloadResumed.dc.ppos != download) ) {
- fprintf(stderr,
- "Download resuming but parent reference not set correctly.\n");
- have_error = 1;
- }
+ search = event->data.SearchResumed.sc.pos;
+ break;
+ case FSUI_download_resumed:
+ if (download == NULL)
+ download = event->data.DownloadResumed.dc.pos;
+ if (event->data.DownloadResumed.dc.spos != search)
+ {
+ fprintf (stderr,
+ "Download resuming but search reference not set
correctly.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadResumed.dc.pos == download) &&
+ (event->data.DownloadResumed.dc.ppos != NULL))
+ {
+ fprintf (stderr,
+ "Download resuming but parent reference not set to
NULL.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadResumed.dc.pos != download) &&
+ (event->data.DownloadResumed.dc.ppos != download))
+ {
+ fprintf (stderr,
+ "Download resuming but parent reference not set
correctly.\n");
+ have_error = 1;
+ }
#if DEBUG_VERBOSE
- printf("Download resuming\n");
+ printf ("Download resuming\n");
#endif
- break;
- case FSUI_search_result:
+ break;
+ case FSUI_search_result:
#if DEBUG_VERBOSE
- printf("Received search result\n");
+ printf ("Received search result\n");
#endif
- break;
- case FSUI_upload_progress:
+ break;
+ case FSUI_upload_progress:
#if DEBUG_VERBOSE
- printf("Upload is progressing (%llu/%llu)...\n",
- event->data.UploadProgress.completed,
- event->data.UploadProgress.total);
+ printf ("Upload is progressing (%llu/%llu)...\n",
+ event->data.UploadProgress.completed,
+ event->data.UploadProgress.total);
#endif
- break;
- case FSUI_upload_completed:
- if (upURI != NULL)
- ECRS_freeUri(upURI);
- upURI = ECRS_dupUri(event->data.UploadCompleted.uri);
+ break;
+ case FSUI_upload_completed:
+ if (upURI != NULL)
+ ECRS_freeUri (upURI);
+ upURI = ECRS_dupUri (event->data.UploadCompleted.uri);
#if DEBUG_VERBOSE
- printf("Upload complete.\n");
+ printf ("Upload complete.\n");
#endif
- break;
- case FSUI_download_completed:
- if (event->data.DownloadCompleted.dc.spos != search) {
- fprintf(stderr,
- "Download completed but search reference not set correctly.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadCompleted.dc.pos == download) &&
- (event->data.DownloadCompleted.dc.ppos != NULL) ) {
- fprintf(stderr,
- "Download completed but parent reference not set to NULL.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadCompleted.dc.pos != download) &&
- (event->data.DownloadCompleted.dc.ppos != download) ) {
- fprintf(stderr,
- "Download completed but parent reference not set correctly.\n");
- have_error = 1;
- }
+ break;
+ case FSUI_download_completed:
+ if (event->data.DownloadCompleted.dc.spos != search)
+ {
+ fprintf (stderr,
+ "Download completed but search reference not set
correctly.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadCompleted.dc.pos == download) &&
+ (event->data.DownloadCompleted.dc.ppos != NULL))
+ {
+ fprintf (stderr,
+ "Download completed but parent reference not set to
NULL.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadCompleted.dc.pos != download) &&
+ (event->data.DownloadCompleted.dc.ppos != download))
+ {
+ fprintf (stderr,
+ "Download completed but parent reference not set
correctly.\n");
+ have_error = 1;
+ }
#if DEBUG_VERBOSE
- printf("Download complete.\n");
+ printf ("Download complete.\n");
#endif
- break;
- case FSUI_download_progress:
- if (event->data.DownloadResumed.dc.spos != search) {
- fprintf(stderr,
- "Download progressing but search reference not set correctly.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadResumed.dc.pos == download) &&
- (event->data.DownloadResumed.dc.ppos != NULL) ) {
- fprintf(stderr,
- "Download progressing but parent reference not set to NULL.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadResumed.dc.pos != download) &&
- (event->data.DownloadResumed.dc.ppos != download) ) {
- fprintf(stderr,
- "Download progressing but parent reference not set correctly.\n");
- have_error = 1;
- }
+ break;
+ case FSUI_download_progress:
+ if (event->data.DownloadResumed.dc.spos != search)
+ {
+ fprintf (stderr,
+ "Download progressing but search reference not set
correctly.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadResumed.dc.pos == download) &&
+ (event->data.DownloadResumed.dc.ppos != NULL))
+ {
+ fprintf (stderr,
+ "Download progressing but parent reference not set to
NULL.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadResumed.dc.pos != download) &&
+ (event->data.DownloadResumed.dc.ppos != download))
+ {
+ fprintf (stderr,
+ "Download progressing but parent reference not set
correctly.\n");
+ have_error = 1;
+ }
#if DEBUG_VERBOSE
- printf("Download is progressing (%llu/%llu)...\n",
- event->data.DownloadProgress.completed,
- event->data.DownloadProgress.total);
+ printf ("Download is progressing (%llu/%llu)...\n",
+ event->data.DownloadProgress.completed,
+ event->data.DownloadProgress.total);
#endif
- break;
- case FSUI_unindex_progress:
+ break;
+ case FSUI_unindex_progress:
#if DEBUG_VERBOSE
- printf("Unindex is progressing (%llu/%llu)...\n",
- event->data.UnindexProgress.completed,
- event->data.UnindexProgress.total);
+ printf ("Unindex is progressing (%llu/%llu)...\n",
+ event->data.UnindexProgress.completed,
+ event->data.UnindexProgress.total);
#endif
- break;
- case FSUI_unindex_completed:
+ break;
+ case FSUI_unindex_completed:
#if DEBUG_VERBOSE
- printf("Unindex complete.\n");
+ printf ("Unindex complete.\n");
#endif
- break;
- case FSUI_unindex_error:
- fprintf(stderr,
- "Received ERROR: %d %s\n",
- event->type,
- event->data.UnindexError.message);
- GE_BREAK(ectx, 0);
- break;
- case FSUI_upload_error:
- fprintf(stderr,
- "Received ERROR: %d %s\n",
- event->type,
- event->data.UploadError.message);
- GE_BREAK(ectx, 0);
- break;
- case FSUI_download_error:
- fprintf(stderr,
- "Received ERROR: %d %s\n",
- event->type,
- event->data.DownloadError.message);
- GE_BREAK(ectx, 0);
- break;
- case FSUI_search_error:
- fprintf(stderr,
- "Received ERROR: %d %s\n",
- event->type,
- event->data.SearchError.message);
- GE_BREAK(ectx, 0);
- break;
- case FSUI_download_aborted:
+ break;
+ case FSUI_unindex_error:
+ fprintf (stderr,
+ "Received ERROR: %d %s\n",
+ event->type, event->data.UnindexError.message);
+ GE_BREAK (ectx, 0);
+ break;
+ case FSUI_upload_error:
+ fprintf (stderr,
+ "Received ERROR: %d %s\n",
+ event->type, event->data.UploadError.message);
+ GE_BREAK (ectx, 0);
+ break;
+ case FSUI_download_error:
+ fprintf (stderr,
+ "Received ERROR: %d %s\n",
+ event->type, event->data.DownloadError.message);
+ GE_BREAK (ectx, 0);
+ break;
+ case FSUI_search_error:
+ fprintf (stderr,
+ "Received ERROR: %d %s\n",
+ event->type, event->data.SearchError.message);
+ GE_BREAK (ectx, 0);
+ break;
+ case FSUI_download_aborted:
#if DEBUG_VERBOSE
- printf("Received download aborted event.\n");
+ printf ("Received download aborted event.\n");
#endif
- break;
- case FSUI_unindex_suspended:
- case FSUI_upload_suspended:
+ break;
+ case FSUI_unindex_suspended:
+ case FSUI_upload_suspended:
#if DEBUG_VERBOSE
- fprintf(stderr,
- "Received SUSPENDING: %d\n",
- event->type);
+ fprintf (stderr, "Received SUSPENDING: %d\n", event->type);
#endif
- break;
- case FSUI_download_started:
- if (download == NULL)
- download = event->data.DownloadStarted.dc.pos;
- if (event->data.DownloadStarted.dc.spos != search) {
- fprintf(stderr,
- "Download started but search reference not set correctly.\n");
- have_error = 1;
+ break;
+ case FSUI_download_started:
+ if (download == NULL)
+ download = event->data.DownloadStarted.dc.pos;
+ if (event->data.DownloadStarted.dc.spos != search)
+ {
+ fprintf (stderr,
+ "Download started but search reference not set
correctly.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadStarted.dc.pos == download) &&
+ (event->data.DownloadStarted.dc.ppos != NULL))
+ {
+ fprintf (stderr,
+ "Download started but parent reference not set to NULL.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadStarted.dc.pos != download) &&
+ (event->data.DownloadStarted.dc.ppos != download))
+ {
+ fprintf (stderr,
+ "Download started but parent reference not set
correctly.\n");
+ have_error = 1;
+ }
+ break;
+ case FSUI_download_stopped:
+ if (event->data.DownloadStopped.dc.spos != search)
+ {
+ fprintf (stderr,
+ "Download stopped but search reference not set
correctly.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadStopped.dc.pos == download) &&
+ (event->data.DownloadStopped.dc.ppos != NULL))
+ {
+ fprintf (stderr,
+ "Download stopped but parent reference not set to NULL.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadStopped.dc.pos != download) &&
+ (event->data.DownloadStopped.dc.ppos != download))
+ {
+ fprintf (stderr,
+ "Download stopped but parent reference not set
correctly.\n");
+ have_error = 1;
+ }
+ break;
+ case FSUI_upload_started:
+ case FSUI_upload_stopped:
+ case FSUI_search_started:
+ case FSUI_search_aborted:
+ case FSUI_search_stopped:
+ case FSUI_unindex_started:
+ case FSUI_unindex_stopped:
+ break;
+ default:
+ printf ("Unexpected event: %d\n", event->type);
+ break;
}
- if ( (event->data.DownloadStarted.dc.pos == download) &&
- (event->data.DownloadStarted.dc.ppos != NULL) ) {
- fprintf(stderr,
- "Download started but parent reference not set to NULL.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadStarted.dc.pos != download) &&
- (event->data.DownloadStarted.dc.ppos != download) ) {
- fprintf(stderr,
- "Download started but parent reference not set correctly.\n");
- have_error = 1;
- }
- break;
- case FSUI_download_stopped:
- if (event->data.DownloadStopped.dc.spos != search) {
- fprintf(stderr,
- "Download stopped but search reference not set correctly.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadStopped.dc.pos == download) &&
- (event->data.DownloadStopped.dc.ppos != NULL) ) {
- fprintf(stderr,
- "Download stopped but parent reference not set to NULL.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadStopped.dc.pos != download) &&
- (event->data.DownloadStopped.dc.ppos != download) ) {
- fprintf(stderr,
- "Download stopped but parent reference not set correctly.\n");
- have_error = 1;
- }
- break;
- case FSUI_upload_started:
- case FSUI_upload_stopped:
- case FSUI_search_started:
- case FSUI_search_aborted:
- case FSUI_search_stopped:
- case FSUI_unindex_started:
- case FSUI_unindex_stopped:
- break;
- default:
- printf("Unexpected event: %d\n",
- event->type);
- break;
- }
return NULL;
}
@@ -305,186 +318,150 @@
#define START_DAEMON 1
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
#if START_DAEMON
pid_t daemon;
#endif
int ok;
int i;
int j;
- struct ECRS_URI * uri = NULL;
- char * fn = NULL;
- char * keywords[] = {
+ struct ECRS_URI *uri = NULL;
+ char *fn = NULL;
+ char *keywords[] = {
"down_foo",
"down_bar",
NULL,
};
char keyword[40];
int prog;
- char * buf;
- struct ECRS_MetaData * meta;
- struct ECRS_URI * kuri = NULL;
- struct GC_Configuration * cfg;
- struct FSUI_UnindexList * unindex = NULL;
- struct FSUI_UploadList * upload = NULL;
+ char *buf;
+ struct ECRS_MetaData *meta;
+ struct ECRS_URI *kuri = NULL;
+ struct GC_Configuration *cfg;
+ struct FSUI_UnindexList *unindex = NULL;
+ struct FSUI_UploadList *upload = NULL;
int suspendRestart = 0;
ok = YES;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_DAEMON
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
- CHECK(OK == connection_wait_for_running(NULL,
- cfg,
- 30 * cronSECONDS));
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
+ CHECK (OK == connection_wait_for_running (NULL, cfg, 30 * cronSECONDS));
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
/* ACTUAL TEST CODE */
#endif
- ctx = FSUI_start(NULL,
- cfg,
- "serializetest2",
- 32,
- YES,
- &eventCallback,
- NULL);
- CHECK(ctx != NULL);
- for (j=4;j<256;j+=4) {
- fn = makeName(j);
- buf = MALLOC(FILESIZE * j);
- for (i=0;i<FILESIZE;i++)
- buf[i] = weak_randomi(256);
- disk_file_write(ectx,
- fn,
- buf,
- FILESIZE,
- "600");
- FREE(buf);
- FREE(fn);
- }
- meta = ECRS_createMetaData();
- kuri = ECRS_parseListKeywordURI(ectx,
- 2,
- (const char**)keywords);
- ECRS_addToMetaData(meta,
- EXTRACTOR_MIMETYPE,
- GNUNET_DIRECTORY_MIME);
- upload = FSUI_startUpload(ctx,
- UPLOAD_PREFIX,
- (DirectoryScanCallback) &disk_directory_scan,
- NULL,
- 0,
- 0,
- YES,
- NO,
- NO,
- get_time() + 5 * cronHOURS,
- meta,
- kuri,
- kuri);
- CHECK(upload != NULL);
- ECRS_freeUri(kuri);
+ ctx = FSUI_start (NULL,
+ cfg, "serializetest2", 32, YES, &eventCallback, NULL);
+ CHECK (ctx != NULL);
+ for (j = 4; j < 256; j += 4)
+ {
+ fn = makeName (j);
+ buf = MALLOC (FILESIZE * j);
+ for (i = 0; i < FILESIZE; i++)
+ buf[i] = weak_randomi (256);
+ disk_file_write (ectx, fn, buf, FILESIZE, "600");
+ FREE (buf);
+ FREE (fn);
+ }
+ meta = ECRS_createMetaData ();
+ kuri = ECRS_parseListKeywordURI (ectx, 2, (const char **) keywords);
+ ECRS_addToMetaData (meta, EXTRACTOR_MIMETYPE, GNUNET_DIRECTORY_MIME);
+ upload = FSUI_startUpload (ctx,
+ UPLOAD_PREFIX,
+ (DirectoryScanCallback) & disk_directory_scan,
+ NULL,
+ 0,
+ 0,
+ YES,
+ NO,
+ NO,
+ get_time () + 5 * cronHOURS, meta, kuri, kuri);
+ CHECK (upload != NULL);
+ ECRS_freeUri (kuri);
kuri = NULL;
- FSUI_stopUpload(ctx, upload);
- CHECK(upURI != NULL);
- SNPRINTF(keyword,
- 40,
- "%s %s %s",
- keywords[0],
- _("AND"),
- keywords[1]);
- uri = ECRS_parseCharKeywordURI(ectx,
- keyword);
- search = FSUI_startSearch(ctx,
- 0,
- 100,
- 240 * cronSECONDS,
- uri);
- CHECK(search != NULL);
- download = FSUI_startDownload(ctx,
- 0,
- YES,
- upURI,
- meta,
- UPLOAD_PREFIX "-download",
- search,
- NULL);
- ECRS_freeMetaData(meta);
+ FSUI_stopUpload (ctx, upload);
+ CHECK (upURI != NULL);
+ SNPRINTF (keyword, 40, "%s %s %s", keywords[0], _("AND"), keywords[1]);
+ uri = ECRS_parseCharKeywordURI (ectx, keyword);
+ search = FSUI_startSearch (ctx, 0, 100, 240 * cronSECONDS, uri);
+ CHECK (search != NULL);
+ download = FSUI_startDownload (ctx,
+ 0,
+ YES,
+ upURI,
+ meta,
+ UPLOAD_PREFIX "-download", search, NULL);
+ ECRS_freeMetaData (meta);
prog = 0;
suspendRestart = 10;
- while (prog < 1000) {
- prog++;
- PTHREAD_SLEEP(50 * cronMILLIS);
- if ( (suspendRestart > 0) &&
- (weak_randomi(100) == 0) ) {
+ while (prog < 1000)
+ {
+ prog++;
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ if ((suspendRestart > 0) && (weak_randomi (100) == 0))
+ {
#if 1
#if DEBUG_VERBOSE
- printf("Testing FSUI suspend-resume\n");
+ printf ("Testing FSUI suspend-resume\n");
#endif
- FSUI_stop(ctx); /* download possibly incomplete
- at this point, thus testing resume */
- CHECK(search == NULL);
- CHECK(download == NULL);
- ctx = FSUI_start(NULL,
- cfg,
- "serializetest2",
- 32,
- YES,
- &eventCallback,
- NULL);
+ FSUI_stop (ctx); /* download possibly incomplete
+ at this point, thus testing resume */
+ CHECK (search == NULL);
+ CHECK (download == NULL);
+ ctx = FSUI_start (NULL,
+ cfg,
+ "serializetest2", 32, YES, &eventCallback, NULL);
#if DEBUG_VERBOSE
- printf("Resumed...\n");
+ printf ("Resumed...\n");
#endif
#endif
- suspendRestart--;
+ suspendRestart--;
+ }
+ if ((search != NULL) && (suspendRestart >= 5))
+ {
+ no_check = 1;
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ FSUI_abortSearch (ctx, search);
+ FSUI_stopSearch (ctx, search);
+ search = NULL;
+ no_check = 0;
+ }
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
}
- if ( (search != NULL) &&
- (suspendRestart >= 5) ) {
- no_check = 1;
- PTHREAD_SLEEP(50 * cronMILLIS);
- FSUI_abortSearch(ctx,
- search);
- FSUI_stopSearch(ctx,
- search);
- search = NULL;
- no_check = 0;
+ FSUI_stopDownload (ctx, download);
+ for (j = 4; j < 256; j += 4)
+ {
+ fn = makeName (j);
+ unindex = FSUI_startUnindex (ctx, fn);
+ FSUI_stopUnindex (ctx, unindex);
+ UNLINK (fn);
+ FREE (fn);
}
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- FSUI_stopDownload(ctx,
- download);
- for (j=4;j<256;j+=4) {
- fn = makeName(j);
- unindex = FSUI_startUnindex(ctx, fn);
- FSUI_stopUnindex(ctx,
- unindex);
- UNLINK(fn);
- FREE(fn);
- }
/* END OF TEST CODE */
- FAILURE:
+FAILURE:
if (ctx != NULL)
- FSUI_stop(ctx);
+ FSUI_stop (ctx);
if (uri != NULL)
- ECRS_freeUri(uri);
+ ECRS_freeUri (uri);
if (kuri != NULL)
- ECRS_freeUri(kuri);
+ ECRS_freeUri (kuri);
if (upURI != NULL)
- ECRS_freeUri(upURI);
+ ECRS_freeUri (upURI);
#if START_DAEMON
- GE_BREAK(NULL, OK == os_daemon_stop(NULL, daemon));
+ GE_BREAK (NULL, OK == os_daemon_stop (NULL, daemon));
#endif
- GC_free(cfg);
+ GC_free (cfg);
if (have_error)
ok = NO;
return (ok == YES) ? 0 : 1;
Modified: GNUnet/src/applications/fs/fsui/serializetest3.c
===================================================================
--- GNUnet/src/applications/fs/fsui/serializetest3.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/fsui/serializetest3.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -37,89 +37,86 @@
#define CHECK(a) if (!(a)) { ok = NO; GE_BREAK(ectx, 0); goto FAILURE; }
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct FSUI_Context * ctx;
-static struct FSUI_SearchList * search;
+static struct FSUI_Context *ctx;
+static struct FSUI_SearchList *search;
static int have_error;
-static void * eventCallback(void * cls,
- const FSUI_Event * event) {
- switch(event->type) {
- case FSUI_search_suspended:
- search = NULL;
- break;
- case FSUI_search_resumed:
+static void *
+eventCallback (void *cls, const FSUI_Event * event)
+{
+ switch (event->type)
+ {
+ case FSUI_search_suspended:
+ search = NULL;
+ break;
+ case FSUI_search_resumed:
#if DEBUG_VERBOSE
- printf("Search resuming\n");
+ printf ("Search resuming\n");
#endif
- search = event->data.SearchResumed.sc.pos;
- break;
- case FSUI_search_result:
+ search = event->data.SearchResumed.sc.pos;
+ break;
+ case FSUI_search_result:
#if DEBUG_VERBOSE
- printf("Received search result\n");
+ printf ("Received search result\n");
#endif
- break;
- case FSUI_upload_progress:
+ break;
+ case FSUI_upload_progress:
#if DEBUG_VERBOSE
- printf("Upload is progressing (%llu/%llu)...\n",
- event->data.UploadProgress.completed,
- event->data.UploadProgress.total);
+ printf ("Upload is progressing (%llu/%llu)...\n",
+ event->data.UploadProgress.completed,
+ event->data.UploadProgress.total);
#endif
- break;
- case FSUI_upload_completed:
+ break;
+ case FSUI_upload_completed:
#if DEBUG_VERBOSE
- printf("Upload complete.\n");
+ printf ("Upload complete.\n");
#endif
- break;
- case FSUI_unindex_progress:
+ break;
+ case FSUI_unindex_progress:
#if DEBUG_VERBOSE
- printf("Unindex is progressing (%llu/%llu)...\n",
- event->data.UnindexProgress.completed,
- event->data.UnindexProgress.total);
+ printf ("Unindex is progressing (%llu/%llu)...\n",
+ event->data.UnindexProgress.completed,
+ event->data.UnindexProgress.total);
#endif
- break;
- case FSUI_unindex_completed:
+ break;
+ case FSUI_unindex_completed:
#if DEBUG_VERBOSE
- printf("Unindex complete.\n");
+ printf ("Unindex complete.\n");
#endif
- break;
- case FSUI_unindex_error:
- case FSUI_upload_error:
- case FSUI_download_error:
- case FSUI_search_error:
- fprintf(stderr,
- "Received ERROR: %d\n",
- event->type);
- GE_BREAK(ectx, 0);
- break;
- case FSUI_download_aborted:
+ break;
+ case FSUI_unindex_error:
+ case FSUI_upload_error:
+ case FSUI_download_error:
+ case FSUI_search_error:
+ fprintf (stderr, "Received ERROR: %d\n", event->type);
+ GE_BREAK (ectx, 0);
+ break;
+ case FSUI_download_aborted:
#if DEBUG_VERBOSE
- printf("Received download aborted event.\n");
+ printf ("Received download aborted event.\n");
#endif
- break;
- case FSUI_unindex_suspended:
- case FSUI_upload_suspended:
+ break;
+ case FSUI_unindex_suspended:
+ case FSUI_upload_suspended:
#if DEBUG_VERBOSE
- fprintf(stderr,
- "Received SUSPENDING: %d\n",
- event->type);
+ fprintf (stderr, "Received SUSPENDING: %d\n", event->type);
#endif
- break;
- case FSUI_upload_started:
- case FSUI_upload_stopped:
- case FSUI_search_started:
- case FSUI_search_aborted:
- case FSUI_search_stopped:
- case FSUI_search_completed:
- case FSUI_unindex_started:
- case FSUI_unindex_stopped:
- break;
- default:
- printf("Unexpected event: %d\n",
- event->type);
- break;
- }
+ break;
+ case FSUI_upload_started:
+ case FSUI_upload_stopped:
+ case FSUI_search_started:
+ case FSUI_search_aborted:
+ case FSUI_search_stopped:
+ case FSUI_search_completed:
+ case FSUI_unindex_started:
+ case FSUI_unindex_stopped:
+ break;
+ default:
+ printf ("Unexpected event: %d\n", event->type);
+ break;
+ }
return NULL;
}
@@ -127,111 +124,87 @@
#define START_DAEMON 1
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
#if START_DAEMON
pid_t daemon;
#endif
int ok;
- struct ECRS_URI * uri = NULL;
- char * keywords[] = {
+ struct ECRS_URI *uri = NULL;
+ char *keywords[] = {
"down_foo",
"down_bar",
NULL,
};
char keyword[40];
int prog;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
int suspendRestart = 0;
ok = YES;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_DAEMON
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
- CHECK(OK == connection_wait_for_running(NULL,
- cfg,
- 30 * cronSECONDS));
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
+ CHECK (OK == connection_wait_for_running (NULL, cfg, 30 * cronSECONDS));
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
/* ACTUAL TEST CODE */
#endif
- ctx = FSUI_start(NULL,
- cfg,
- "serializetest3",
- 32,
- YES,
- &eventCallback,
- NULL);
- CHECK(ctx != NULL);
- SNPRINTF(keyword,
- 40,
- "%s %s %s",
- keywords[0],
- _("AND"),
- keywords[1]);
- uri = ECRS_parseCharKeywordURI(ectx,
- keyword);
- search = FSUI_startSearch(ctx,
- 0,
- 100,
- 240 * cronSECONDS,
- uri);
- CHECK(search != NULL);
+ ctx = FSUI_start (NULL,
+ cfg, "serializetest3", 32, YES, &eventCallback, NULL);
+ CHECK (ctx != NULL);
+ SNPRINTF (keyword, 40, "%s %s %s", keywords[0], _("AND"), keywords[1]);
+ uri = ECRS_parseCharKeywordURI (ectx, keyword);
+ search = FSUI_startSearch (ctx, 0, 100, 240 * cronSECONDS, uri);
+ CHECK (search != NULL);
prog = 0;
suspendRestart = 10;
- while (prog < 1000) {
- prog++;
- PTHREAD_SLEEP(50 * cronMILLIS);
- if ( (suspendRestart > 0) &&
- (weak_randomi(100) == 0) ) {
+ while (prog < 1000)
+ {
+ prog++;
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ if ((suspendRestart > 0) && (weak_randomi (100) == 0))
+ {
#if 1
#if DEBUG_VERBOSE
- printf("Testing FSUI suspend-resume\n");
+ printf ("Testing FSUI suspend-resume\n");
#endif
- FSUI_stop(ctx); /* download possibly incomplete
- at this point, thus testing resume */
- CHECK(search == NULL);
- ctx = FSUI_start(NULL,
- cfg,
- "serializetest3",
- 32,
- YES,
- &eventCallback,
- NULL);
+ FSUI_stop (ctx); /* download possibly incomplete
+ at this point, thus testing resume */
+ CHECK (search == NULL);
+ ctx = FSUI_start (NULL,
+ cfg,
+ "serializetest3", 32, YES, &eventCallback, NULL);
#if DEBUG_VERBOSE
- printf("Resumed...\n");
+ printf ("Resumed...\n");
#endif
#endif
- suspendRestart--;
+ suspendRestart--;
+ }
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
}
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- FSUI_abortSearch(ctx,
- search);
- FSUI_stopSearch(ctx,
- search);
+ FSUI_abortSearch (ctx, search);
+ FSUI_stopSearch (ctx, search);
search = NULL;
/* END OF TEST CODE */
- FAILURE:
+FAILURE:
if (ctx != NULL)
- FSUI_stop(ctx);
+ FSUI_stop (ctx);
if (uri != NULL)
- ECRS_freeUri(uri);
+ ECRS_freeUri (uri);
#if START_DAEMON
- GE_BREAK(NULL,
- OK == os_daemon_stop(NULL, daemon));
+ GE_BREAK (NULL, OK == os_daemon_stop (NULL, daemon));
#endif
- GC_free(cfg);
+ GC_free (cfg);
if (have_error)
ok = NO;
return (ok == YES) ? 0 : 1;
Modified: GNUnet/src/applications/fs/fsui/serializetest4.c
===================================================================
--- GNUnet/src/applications/fs/fsui/serializetest4.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/fsui/serializetest4.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -38,23 +38,24 @@
#define CHECK(a) if (!(a)) { ok = NO; GE_BREAK(ectx, 0); goto FAILURE; }
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static char * makeName(unsigned int i) {
- char * fn;
+static char *
+makeName (unsigned int i)
+{
+ char *fn;
- fn = MALLOC(strlen(UPLOAD_PREFIX "/FSUITEST") + 14);
- SNPRINTF(fn,
- strlen(UPLOAD_PREFIX "/FSUITEST") + 14,
- UPLOAD_PREFIX "/FSUITEST%u",
- i);
- disk_directory_create_for_file(NULL, fn);
+ fn = MALLOC (strlen (UPLOAD_PREFIX "/FSUITEST") + 14);
+ SNPRINTF (fn,
+ strlen (UPLOAD_PREFIX "/FSUITEST") + 14,
+ UPLOAD_PREFIX "/FSUITEST%u", i);
+ disk_directory_create_for_file (NULL, fn);
return fn;
}
-static struct FSUI_Context * ctx;
-static struct ECRS_URI * upURI;
-static struct FSUI_DownloadList * download;
+static struct FSUI_Context *ctx;
+static struct ECRS_URI *upURI;
+static struct FSUI_DownloadList *download;
static int have_error;
/**
@@ -64,206 +65,220 @@
*/
static int no_check;
-static void * eventCallback(void * cls,
- const FSUI_Event * event) {
+static void *
+eventCallback (void *cls, const FSUI_Event * event)
+{
if (no_check)
return NULL;
- switch(event->type) {
- case FSUI_download_suspended:
- if (event->data.DownloadSuspended.dc.spos != NULL) {
- fprintf(stderr,
- "Download suspended but search reference not set correctly.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadSuspended.dc.pos == download) &&
- (event->data.DownloadSuspended.dc.ppos != NULL) ) {
- fprintf(stderr,
- "Download suspended but parent reference not set to NULL.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadSuspended.dc.pos != download) &&
- (event->data.DownloadSuspended.dc.ppos != download) ) {
- fprintf(stderr,
- "Download suspended but parent reference not set correctly (%p instead
of %p).\n",
- event->data.DownloadSuspended.dc.ppos,
- download);
- have_error = 1;
- }
- if (event->data.DownloadSuspended.dc.pos == download)
- download = NULL;
- break;
- case FSUI_download_resumed:
- if (download == NULL)
- download = event->data.DownloadResumed.dc.pos;
- if (event->data.DownloadResumed.dc.spos != NULL) {
- fprintf(stderr,
- "Download resuming but search reference not set correctly.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadResumed.dc.pos == download) &&
- (event->data.DownloadResumed.dc.ppos != NULL) ) {
- fprintf(stderr,
- "Download resuming but parent reference not set to NULL.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadResumed.dc.pos != download) &&
- (event->data.DownloadResumed.dc.ppos != download) ) {
- fprintf(stderr,
- "Download resuming but parent reference not set correctly.\n");
- have_error = 1;
- }
+ switch (event->type)
+ {
+ case FSUI_download_suspended:
+ if (event->data.DownloadSuspended.dc.spos != NULL)
+ {
+ fprintf (stderr,
+ "Download suspended but search reference not set
correctly.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadSuspended.dc.pos == download) &&
+ (event->data.DownloadSuspended.dc.ppos != NULL))
+ {
+ fprintf (stderr,
+ "Download suspended but parent reference not set to
NULL.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadSuspended.dc.pos != download) &&
+ (event->data.DownloadSuspended.dc.ppos != download))
+ {
+ fprintf (stderr,
+ "Download suspended but parent reference not set correctly
(%p instead of %p).\n",
+ event->data.DownloadSuspended.dc.ppos, download);
+ have_error = 1;
+ }
+ if (event->data.DownloadSuspended.dc.pos == download)
+ download = NULL;
+ break;
+ case FSUI_download_resumed:
+ if (download == NULL)
+ download = event->data.DownloadResumed.dc.pos;
+ if (event->data.DownloadResumed.dc.spos != NULL)
+ {
+ fprintf (stderr,
+ "Download resuming but search reference not set
correctly.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadResumed.dc.pos == download) &&
+ (event->data.DownloadResumed.dc.ppos != NULL))
+ {
+ fprintf (stderr,
+ "Download resuming but parent reference not set to
NULL.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadResumed.dc.pos != download) &&
+ (event->data.DownloadResumed.dc.ppos != download))
+ {
+ fprintf (stderr,
+ "Download resuming but parent reference not set
correctly.\n");
+ have_error = 1;
+ }
#if DEBUG_VERBOSE
- printf("Download resuming\n");
+ printf ("Download resuming\n");
#endif
- break;
- case FSUI_upload_progress:
+ break;
+ case FSUI_upload_progress:
#if DEBUG_VERBOSE
- printf("Upload is progressing (%llu/%llu)...\n",
- event->data.UploadProgress.completed,
- event->data.UploadProgress.total);
+ printf ("Upload is progressing (%llu/%llu)...\n",
+ event->data.UploadProgress.completed,
+ event->data.UploadProgress.total);
#endif
- break;
- case FSUI_upload_completed:
- if (upURI != NULL)
- ECRS_freeUri(upURI);
- upURI = ECRS_dupUri(event->data.UploadCompleted.uri);
+ break;
+ case FSUI_upload_completed:
+ if (upURI != NULL)
+ ECRS_freeUri (upURI);
+ upURI = ECRS_dupUri (event->data.UploadCompleted.uri);
#if DEBUG_VERBOSE
- printf("Upload complete.\n");
+ printf ("Upload complete.\n");
#endif
- break;
- case FSUI_download_completed:
- if (event->data.DownloadCompleted.dc.spos != NULL) {
- fprintf(stderr,
- "Download completed but search reference not set correctly.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadCompleted.dc.pos == download) &&
- (event->data.DownloadCompleted.dc.ppos != NULL) ) {
- fprintf(stderr,
- "Download completed but parent reference not set to NULL.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadCompleted.dc.pos != download) &&
- (event->data.DownloadCompleted.dc.ppos != download) ) {
- fprintf(stderr,
- "Download completed but parent reference not set correctly.\n");
- have_error = 1;
- }
+ break;
+ case FSUI_download_completed:
+ if (event->data.DownloadCompleted.dc.spos != NULL)
+ {
+ fprintf (stderr,
+ "Download completed but search reference not set
correctly.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadCompleted.dc.pos == download) &&
+ (event->data.DownloadCompleted.dc.ppos != NULL))
+ {
+ fprintf (stderr,
+ "Download completed but parent reference not set to
NULL.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadCompleted.dc.pos != download) &&
+ (event->data.DownloadCompleted.dc.ppos != download))
+ {
+ fprintf (stderr,
+ "Download completed but parent reference not set
correctly.\n");
+ have_error = 1;
+ }
#if DEBUG_VERBOSE
- printf("Download complete.\n");
+ printf ("Download complete.\n");
#endif
- break;
- case FSUI_download_progress:
- if (event->data.DownloadResumed.dc.spos != NULL) {
- fprintf(stderr,
- "Download progressing but search reference not set correctly.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadResumed.dc.pos == download) &&
- (event->data.DownloadResumed.dc.ppos != NULL) ) {
- fprintf(stderr,
- "Download progressing but parent reference not set to NULL.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadResumed.dc.pos != download) &&
- (event->data.DownloadResumed.dc.ppos != download) ) {
- fprintf(stderr,
- "Download progressing but parent reference not set correctly.\n");
- have_error = 1;
- }
+ break;
+ case FSUI_download_progress:
+ if (event->data.DownloadResumed.dc.spos != NULL)
+ {
+ fprintf (stderr,
+ "Download progressing but search reference not set
correctly.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadResumed.dc.pos == download) &&
+ (event->data.DownloadResumed.dc.ppos != NULL))
+ {
+ fprintf (stderr,
+ "Download progressing but parent reference not set to
NULL.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadResumed.dc.pos != download) &&
+ (event->data.DownloadResumed.dc.ppos != download))
+ {
+ fprintf (stderr,
+ "Download progressing but parent reference not set
correctly.\n");
+ have_error = 1;
+ }
#if DEBUG_VERBOSE
- printf("Download is progressing (%llu/%llu)...\n",
- event->data.DownloadProgress.completed,
- event->data.DownloadProgress.total);
+ printf ("Download is progressing (%llu/%llu)...\n",
+ event->data.DownloadProgress.completed,
+ event->data.DownloadProgress.total);
#endif
- break;
- case FSUI_unindex_progress:
+ break;
+ case FSUI_unindex_progress:
#if DEBUG_VERBOSE
- printf("Unindex is progressing (%llu/%llu)...\n",
- event->data.UnindexProgress.completed,
- event->data.UnindexProgress.total);
+ printf ("Unindex is progressing (%llu/%llu)...\n",
+ event->data.UnindexProgress.completed,
+ event->data.UnindexProgress.total);
#endif
- break;
- case FSUI_unindex_completed:
+ break;
+ case FSUI_unindex_completed:
#if DEBUG_VERBOSE
- printf("Unindex complete.\n");
+ printf ("Unindex complete.\n");
#endif
- break;
- case FSUI_unindex_error:
- case FSUI_upload_error:
- case FSUI_download_error:
- case FSUI_search_error:
- fprintf(stderr,
- "Received ERROR: %d\n",
- event->type);
- GE_BREAK(ectx, 0);
- break;
- case FSUI_download_aborted:
+ break;
+ case FSUI_unindex_error:
+ case FSUI_upload_error:
+ case FSUI_download_error:
+ case FSUI_search_error:
+ fprintf (stderr, "Received ERROR: %d\n", event->type);
+ GE_BREAK (ectx, 0);
+ break;
+ case FSUI_download_aborted:
#if DEBUG_VERBOSE
- printf("Received download aborted event.\n");
+ printf ("Received download aborted event.\n");
#endif
- break;
- case FSUI_unindex_suspended:
- case FSUI_upload_suspended:
+ break;
+ case FSUI_unindex_suspended:
+ case FSUI_upload_suspended:
#if DEBUG_VERBOSE
- fprintf(stderr,
- "Received SUSPENDING: %d\n",
- event->type);
+ fprintf (stderr, "Received SUSPENDING: %d\n", event->type);
#endif
- break;
- case FSUI_download_started:
- if (download == NULL)
- download = event->data.DownloadStarted.dc.pos;
- if (event->data.DownloadStarted.dc.spos != NULL) {
- fprintf(stderr,
- "Download started but search reference not set correctly.\n");
- have_error = 1;
+ break;
+ case FSUI_download_started:
+ if (download == NULL)
+ download = event->data.DownloadStarted.dc.pos;
+ if (event->data.DownloadStarted.dc.spos != NULL)
+ {
+ fprintf (stderr,
+ "Download started but search reference not set
correctly.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadStarted.dc.pos == download) &&
+ (event->data.DownloadStarted.dc.ppos != NULL))
+ {
+ fprintf (stderr,
+ "Download started but parent reference not set to NULL.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadStarted.dc.pos != download) &&
+ (event->data.DownloadStarted.dc.ppos != download))
+ {
+ fprintf (stderr,
+ "Download started but parent reference not set
correctly.\n");
+ have_error = 1;
+ }
+ break;
+ case FSUI_download_stopped:
+ if (event->data.DownloadStopped.dc.spos != NULL)
+ {
+ fprintf (stderr,
+ "Download stopped but search reference not set
correctly.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadStopped.dc.pos == download) &&
+ (event->data.DownloadStopped.dc.ppos != NULL))
+ {
+ fprintf (stderr,
+ "Download stopped but parent reference not set to NULL.\n");
+ have_error = 1;
+ }
+ if ((event->data.DownloadStopped.dc.pos != download) &&
+ (event->data.DownloadStopped.dc.ppos != download))
+ {
+ fprintf (stderr,
+ "Download stopped but parent reference not set
correctly.\n");
+ have_error = 1;
+ }
+ break;
+ case FSUI_upload_started:
+ case FSUI_upload_stopped:
+ case FSUI_search_started:
+ case FSUI_search_aborted:
+ case FSUI_search_stopped:
+ case FSUI_unindex_started:
+ case FSUI_unindex_stopped:
+ break;
+ default:
+ printf ("Unexpected event: %d\n", event->type);
+ break;
}
- if ( (event->data.DownloadStarted.dc.pos == download) &&
- (event->data.DownloadStarted.dc.ppos != NULL) ) {
- fprintf(stderr,
- "Download started but parent reference not set to NULL.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadStarted.dc.pos != download) &&
- (event->data.DownloadStarted.dc.ppos != download) ) {
- fprintf(stderr,
- "Download started but parent reference not set correctly.\n");
- have_error = 1;
- }
- break;
- case FSUI_download_stopped:
- if (event->data.DownloadStopped.dc.spos != NULL) {
- fprintf(stderr,
- "Download stopped but search reference not set correctly.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadStopped.dc.pos == download) &&
- (event->data.DownloadStopped.dc.ppos != NULL) ) {
- fprintf(stderr,
- "Download stopped but parent reference not set to NULL.\n");
- have_error = 1;
- }
- if ( (event->data.DownloadStopped.dc.pos != download) &&
- (event->data.DownloadStopped.dc.ppos != download) ) {
- fprintf(stderr,
- "Download stopped but parent reference not set correctly.\n");
- have_error = 1;
- }
- break;
- case FSUI_upload_started:
- case FSUI_upload_stopped:
- case FSUI_search_started:
- case FSUI_search_aborted:
- case FSUI_search_stopped:
- case FSUI_unindex_started:
- case FSUI_unindex_stopped:
- break;
- default:
- printf("Unexpected event: %d\n",
- event->type);
- break;
- }
return NULL;
}
@@ -271,167 +286,136 @@
#define START_DAEMON 1
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
#if START_DAEMON
pid_t daemon;
#endif
int ok;
int i;
int j;
- struct ECRS_URI * uri = NULL;
- char * fn = NULL;
- char * keywords[] = {
+ struct ECRS_URI *uri = NULL;
+ char *fn = NULL;
+ char *keywords[] = {
"down_foo",
"down_bar",
NULL,
};
char keyword[40];
int prog;
- char * buf;
- struct ECRS_MetaData * meta;
- struct ECRS_URI * kuri = NULL;
- struct GC_Configuration * cfg;
- struct FSUI_UnindexList * unindex = NULL;
- struct FSUI_UploadList * upload = NULL;
+ char *buf;
+ struct ECRS_MetaData *meta;
+ struct ECRS_URI *kuri = NULL;
+ struct GC_Configuration *cfg;
+ struct FSUI_UnindexList *unindex = NULL;
+ struct FSUI_UploadList *upload = NULL;
int suspendRestart = 0;
ok = YES;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_DAEMON
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
- CHECK(OK == connection_wait_for_running(NULL,
- cfg,
- 30 * cronSECONDS));
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
+ CHECK (OK == connection_wait_for_running (NULL, cfg, 30 * cronSECONDS));
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
/* ACTUAL TEST CODE */
#endif
- ctx = FSUI_start(NULL,
- cfg,
- "serializetest4",
- 32,
- YES,
- &eventCallback,
- NULL);
- CHECK(ctx != NULL);
- for (j=4;j<16;j+=4) {
- fn = makeName(j);
- buf = MALLOC(FILESIZE * j);
- for (i=0;i<FILESIZE;i++)
- buf[i] = weak_randomi(256);
- disk_file_write(ectx,
- fn,
- buf,
- FILESIZE,
- "600");
- FREE(buf);
- FREE(fn);
- }
- meta = ECRS_createMetaData();
- kuri = ECRS_parseListKeywordURI(ectx,
- 2,
- (const char**)keywords);
- ECRS_addToMetaData(meta,
- EXTRACTOR_MIMETYPE,
- GNUNET_DIRECTORY_MIME);
- upload = FSUI_startUpload(ctx,
- UPLOAD_PREFIX,
- (DirectoryScanCallback) &disk_directory_scan,
- NULL,
- 0,
- 0,
- YES,
- NO,
- NO,
- get_time() + 5 * cronHOURS,
- meta,
- kuri,
- kuri);
- CHECK(upload != NULL);
- ECRS_freeUri(kuri);
+ ctx = FSUI_start (NULL,
+ cfg, "serializetest4", 32, YES, &eventCallback, NULL);
+ CHECK (ctx != NULL);
+ for (j = 4; j < 16; j += 4)
+ {
+ fn = makeName (j);
+ buf = MALLOC (FILESIZE * j);
+ for (i = 0; i < FILESIZE; i++)
+ buf[i] = weak_randomi (256);
+ disk_file_write (ectx, fn, buf, FILESIZE, "600");
+ FREE (buf);
+ FREE (fn);
+ }
+ meta = ECRS_createMetaData ();
+ kuri = ECRS_parseListKeywordURI (ectx, 2, (const char **) keywords);
+ ECRS_addToMetaData (meta, EXTRACTOR_MIMETYPE, GNUNET_DIRECTORY_MIME);
+ upload = FSUI_startUpload (ctx,
+ UPLOAD_PREFIX,
+ (DirectoryScanCallback) & disk_directory_scan,
+ NULL,
+ 0,
+ 0,
+ YES,
+ NO,
+ NO,
+ get_time () + 5 * cronHOURS, meta, kuri, kuri);
+ CHECK (upload != NULL);
+ ECRS_freeUri (kuri);
kuri = NULL;
- FSUI_stopUpload(ctx, upload);
- SNPRINTF(keyword,
- 40,
- "%s %s %s",
- keywords[0],
- _("AND"),
- keywords[1]);
- uri = ECRS_parseCharKeywordURI(ectx,
- keyword);
- download = FSUI_startDownload(ctx,
- 0,
- YES,
- upURI,
- meta,
- UPLOAD_PREFIX "-download",
- NULL,
- NULL);
- ECRS_freeMetaData(meta);
+ FSUI_stopUpload (ctx, upload);
+ SNPRINTF (keyword, 40, "%s %s %s", keywords[0], _("AND"), keywords[1]);
+ uri = ECRS_parseCharKeywordURI (ectx, keyword);
+ download = FSUI_startDownload (ctx,
+ 0,
+ YES,
+ upURI,
+ meta, UPLOAD_PREFIX "-download", NULL, NULL);
+ ECRS_freeMetaData (meta);
prog = 0;
suspendRestart = 10;
- while (prog < 1000) {
- prog++;
- PTHREAD_SLEEP(50 * cronMILLIS);
- if ( (suspendRestart > 0) &&
- (weak_randomi(100) == 0) ) {
+ while (prog < 1000)
+ {
+ prog++;
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ if ((suspendRestart > 0) && (weak_randomi (100) == 0))
+ {
#if 1
#if DEBUG_VERBOSE
- printf("Testing FSUI suspend-resume\n");
+ printf ("Testing FSUI suspend-resume\n");
#endif
- FSUI_stop(ctx); /* download possibly incomplete
- at this point, thus testing resume */
- CHECK(download == NULL);
- ctx = FSUI_start(NULL,
- cfg,
- "serializetest4",
- 32,
- YES,
- &eventCallback,
- NULL);
+ FSUI_stop (ctx); /* download possibly incomplete
+ at this point, thus testing resume */
+ CHECK (download == NULL);
+ ctx = FSUI_start (NULL,
+ cfg,
+ "serializetest4", 32, YES, &eventCallback, NULL);
#if DEBUG_VERBOSE
- printf("Resumed...\n");
+ printf ("Resumed...\n");
#endif
#endif
- suspendRestart--;
+ suspendRestart--;
+ }
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
}
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- FSUI_stopDownload(ctx,
- download);
- for (j=4;j<16;j+=4) {
- fn = makeName(j);
- unindex = FSUI_startUnindex(ctx, fn);
- FSUI_stopUnindex(ctx,
- unindex);
- UNLINK(fn);
- FREE(fn);
- }
+ FSUI_stopDownload (ctx, download);
+ for (j = 4; j < 16; j += 4)
+ {
+ fn = makeName (j);
+ unindex = FSUI_startUnindex (ctx, fn);
+ FSUI_stopUnindex (ctx, unindex);
+ UNLINK (fn);
+ FREE (fn);
+ }
/* END OF TEST CODE */
- FAILURE:
+FAILURE:
if (ctx != NULL)
- FSUI_stop(ctx);
+ FSUI_stop (ctx);
if (uri != NULL)
- ECRS_freeUri(uri);
+ ECRS_freeUri (uri);
if (kuri != NULL)
- ECRS_freeUri(kuri);
+ ECRS_freeUri (kuri);
if (upURI != NULL)
- ECRS_freeUri(upURI);
+ ECRS_freeUri (upURI);
#if START_DAEMON
- GE_BREAK(NULL, OK == os_daemon_stop(NULL, daemon));
+ GE_BREAK (NULL, OK == os_daemon_stop (NULL, daemon));
#endif
- GC_free(cfg);
+ GC_free (cfg);
if (have_error)
ok = NO;
return (ok == YES) ? 0 : 1;
Modified: GNUnet/src/applications/fs/fsui/unindex.c
===================================================================
--- GNUnet/src/applications/fs/fsui/unindex.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/fsui/unindex.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,11 +35,11 @@
/**
* Transform an ECRS progress callback into an FSUI event.
*/
-static void progressCallback(unsigned long long totalBytes,
- unsigned long long completedBytes,
- cron_t eta,
- void * cls) {
- FSUI_UnindexList * utc = cls;
+static void
+progressCallback (unsigned long long totalBytes,
+ unsigned long long completedBytes, cron_t eta, void *cls)
+{
+ FSUI_UnindexList *utc = cls;
FSUI_Event event;
event.type = FSUI_unindex_progress;
@@ -49,12 +49,13 @@
event.data.UnindexProgress.completed = completedBytes;
event.data.UnindexProgress.eta = eta;
event.data.UnindexProgress.filename = utc->filename;
- utc->ctx->ecb(utc->ctx->ecbClosure,
- &event);
+ utc->ctx->ecb (utc->ctx->ecbClosure, &event);
}
-static int tt(void * cls) {
- FSUI_UnindexList * utc = cls;
+static int
+tt (void *cls)
+{
+ FSUI_UnindexList *utc = cls;
if (utc->state != FSUI_ACTIVE)
return SYSERR;
return OK;
@@ -63,98 +64,96 @@
/**
* Thread that does the unindex.
*/
-void * FSUI_unindexThread(void * cls) {
- FSUI_UnindexList * utc = cls;
+void *
+FSUI_unindexThread (void *cls)
+{
+ FSUI_UnindexList *utc = cls;
FSUI_Event event;
int ret;
unsigned long long size;
- struct GE_Memory * mem;
- struct GE_Context * ee;
+ struct GE_Memory *mem;
+ struct GE_Context *ee;
- if (OK != disk_file_size(utc->ctx->ectx,
- utc->filename,
- &size,
- YES)) {
- GE_BREAK(utc->ctx->ectx, 0);
- size = 0;
- }
- mem = GE_memory_create(2);
- ee = GE_create_context_memory(GE_USER | GE_ADMIN | GE_ERROR | GE_WARNING |
GE_FATAL | GE_BULK | GE_IMMEDIATE,
- mem);
- ret = ECRS_unindexFile(ee,
- utc->ctx->cfg,
- utc->filename,
- &progressCallback,
- utc,
- &tt,
- utc);
- if (ret == OK) {
- utc->state = FSUI_COMPLETED;
- event.type = FSUI_unindex_completed;
- event.data.UnindexCompleted.uc.pos = utc;
- event.data.UnindexCompleted.uc.cctx = utc->cctx;
- event.data.UnindexCompleted.total = size;
- event.data.UnindexCompleted.filename = utc->filename;
- utc->ctx->ecb(utc->ctx->ecbClosure,
- &event);
- } else if (utc->state == FSUI_ACTIVE) {
- const char * error;
+ if (OK != disk_file_size (utc->ctx->ectx, utc->filename, &size, YES))
+ {
+ GE_BREAK (utc->ctx->ectx, 0);
+ size = 0;
+ }
+ mem = GE_memory_create (2);
+ ee =
+ GE_create_context_memory (GE_USER | GE_ADMIN | GE_ERROR | GE_WARNING |
+ GE_FATAL | GE_BULK | GE_IMMEDIATE, mem);
+ ret =
+ ECRS_unindexFile (ee, utc->ctx->cfg, utc->filename, &progressCallback,
+ utc, &tt, utc);
+ if (ret == OK)
+ {
+ utc->state = FSUI_COMPLETED;
+ event.type = FSUI_unindex_completed;
+ event.data.UnindexCompleted.uc.pos = utc;
+ event.data.UnindexCompleted.uc.cctx = utc->cctx;
+ event.data.UnindexCompleted.total = size;
+ event.data.UnindexCompleted.filename = utc->filename;
+ utc->ctx->ecb (utc->ctx->ecbClosure, &event);
+ }
+ else if (utc->state == FSUI_ACTIVE)
+ {
+ const char *error;
- utc->state = FSUI_ERROR;
- event.type = FSUI_unindex_error;
- event.data.UnindexError.uc.pos = utc;
- event.data.UnindexError.uc.cctx = utc->cctx;
- error = GE_memory_get(mem, 0);
- if (error == NULL)
- error = _("Unindexing failed (no reason given)");
- event.data.UnindexError.message = error;
- utc->ctx->ecb(utc->ctx->ecbClosure,
- &event);
- } else if (utc->state == FSUI_ABORTED) {
- event.type = FSUI_unindex_aborted;
- event.data.UnindexAborted.uc.pos = utc;
- event.data.UnindexAborted.uc.cctx = utc->cctx;
- utc->ctx->ecb(utc->ctx->ecbClosure,
- &event);
- } else {
- /* must be suspending */
- GE_BREAK(NULL,
- utc->state == FSUI_PENDING);
- }
+ utc->state = FSUI_ERROR;
+ event.type = FSUI_unindex_error;
+ event.data.UnindexError.uc.pos = utc;
+ event.data.UnindexError.uc.cctx = utc->cctx;
+ error = GE_memory_get (mem, 0);
+ if (error == NULL)
+ error = _("Unindexing failed (no reason given)");
+ event.data.UnindexError.message = error;
+ utc->ctx->ecb (utc->ctx->ecbClosure, &event);
+ }
+ else if (utc->state == FSUI_ABORTED)
+ {
+ event.type = FSUI_unindex_aborted;
+ event.data.UnindexAborted.uc.pos = utc;
+ event.data.UnindexAborted.uc.cctx = utc->cctx;
+ utc->ctx->ecb (utc->ctx->ecbClosure, &event);
+ }
+ else
+ {
+ /* must be suspending */
+ GE_BREAK (NULL, utc->state == FSUI_PENDING);
+ }
#if 0
- GE_LOG(utc->ctx->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSUI unindexThread exits in state %u.\n",
- utc->state);
+ GE_LOG (utc->ctx->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FSUI unindexThread exits in state %u.\n", utc->state);
#endif
- GE_free_context(ee);
- GE_memory_free(mem);
+ GE_free_context (ee);
+ GE_memory_free (mem);
return NULL;
}
/**
* Thread that does the unindex.
*/
-static void * FSUI_unindexThreadEvent(void * cls) {
- FSUI_UnindexList * utc = cls;
+static void *
+FSUI_unindexThreadEvent (void *cls)
+{
+ FSUI_UnindexList *utc = cls;
FSUI_Event event;
unsigned long long size;
- if (OK != disk_file_size(utc->ctx->ectx,
- utc->filename,
- &size,
- YES)) {
- GE_BREAK(utc->ctx->ectx, 0);
- size = 0;
- }
+ if (OK != disk_file_size (utc->ctx->ectx, utc->filename, &size, YES))
+ {
+ GE_BREAK (utc->ctx->ectx, 0);
+ size = 0;
+ }
event.type = FSUI_unindex_started;
event.data.UnindexStarted.uc.pos = utc;
event.data.UnindexStarted.uc.cctx = NULL;
event.data.UnindexStarted.total = size;
event.data.UnindexStarted.filename = utc->filename;
- utc->cctx = utc->ctx->ecb(utc->ctx->ecbClosure,
- &event);
- return FSUI_unindexThread(utc);
+ utc->cctx = utc->ctx->ecb (utc->ctx->ecbClosure, &event);
+ return FSUI_unindexThread (utc);
}
/**
@@ -168,40 +167,39 @@
* running
*/
struct FSUI_UnindexList *
-FSUI_startUnindex(struct FSUI_Context * ctx,
- const char * filename) {
- FSUI_UnindexList * utc;
+FSUI_startUnindex (struct FSUI_Context *ctx, const char *filename)
+{
+ FSUI_UnindexList *utc;
- if (YES == disk_directory_test(ctx->ectx,
- filename)) {
- GE_BREAK(ctx->ectx, 0);
- return NULL;
- }
- if (YES != disk_file_test(ctx->ectx,
- filename)) {
- GE_BREAK(ctx->ectx, 0);
- return NULL;
- }
- utc = MALLOC(sizeof(FSUI_UnindexList));
+ if (YES == disk_directory_test (ctx->ectx, filename))
+ {
+ GE_BREAK (ctx->ectx, 0);
+ return NULL;
+ }
+ if (YES != disk_file_test (ctx->ectx, filename))
+ {
+ GE_BREAK (ctx->ectx, 0);
+ return NULL;
+ }
+ utc = MALLOC (sizeof (FSUI_UnindexList));
utc->ctx = ctx;
- utc->filename = STRDUP(filename);
- utc->start_time = get_time();
+ utc->filename = STRDUP (filename);
+ utc->start_time = get_time ();
utc->state = FSUI_ACTIVE;
- utc->handle = PTHREAD_CREATE(&FSUI_unindexThreadEvent,
- utc,
- 32 * 1024);
- if (utc->handle == NULL) {
- GE_LOG_STRERROR(ctx->ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_IMMEDIATE,
- "PTHREAD_CREATE");
- FREE(utc->filename);
- FREE(utc);
- return NULL;
- }
- MUTEX_LOCK(ctx->lock);
+ utc->handle = PTHREAD_CREATE (&FSUI_unindexThreadEvent, utc, 32 * 1024);
+ if (utc->handle == NULL)
+ {
+ GE_LOG_STRERROR (ctx->ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_IMMEDIATE,
+ "PTHREAD_CREATE");
+ FREE (utc->filename);
+ FREE (utc);
+ return NULL;
+ }
+ MUTEX_LOCK (ctx->lock);
utc->next = ctx->unindexOperations;
ctx->unindexOperations = utc;
- MUTEX_UNLOCK(ctx->lock);
+ MUTEX_UNLOCK (ctx->lock);
return utc;
}
@@ -211,17 +209,20 @@
*
* @return SYSERR if no such unindex is pending
*/
-int FSUI_abortUnindex(struct FSUI_Context * ctx,
- struct FSUI_UnindexList * ul) {
- if ( (ul->state != FSUI_ACTIVE) &&
- (ul->state != FSUI_PENDING) )
+int
+FSUI_abortUnindex (struct FSUI_Context *ctx, struct FSUI_UnindexList *ul)
+{
+ if ((ul->state != FSUI_ACTIVE) && (ul->state != FSUI_PENDING))
return NO;
- if (ul->state == FSUI_ACTIVE) {
- ul->state = FSUI_ABORTED;
- PTHREAD_STOP_SLEEP(ul->handle);
- } else {
- ul->state = FSUI_ABORTED_JOINED;
- }
+ if (ul->state == FSUI_ACTIVE)
+ {
+ ul->state = FSUI_ABORTED;
+ PTHREAD_STOP_SLEEP (ul->handle);
+ }
+ else
+ {
+ ul->state = FSUI_ABORTED_JOINED;
+ }
return OK;
}
@@ -231,64 +232,67 @@
*
* @return SYSERR if no such unindex is pending
*/
-int FSUI_stopUnindex(struct FSUI_Context * ctx,
- struct FSUI_UnindexList * dl) {
- FSUI_UnindexList * prev;
- struct GE_Context * ectx;
- void * unused;
+int
+FSUI_stopUnindex (struct FSUI_Context *ctx, struct FSUI_UnindexList *dl)
+{
+ FSUI_UnindexList *prev;
+ struct GE_Context *ectx;
+ void *unused;
FSUI_Event event;
ectx = ctx->ectx;
- if (dl == NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ if (dl == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
#if 0
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSUI_stopUnindex called.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "FSUI_stopUnindex called.\n");
#endif
- MUTEX_LOCK(ctx->lock);
+ MUTEX_LOCK (ctx->lock);
prev = ctx->unindexOperations;
- while ( (prev != dl) &&
- (prev != NULL) &&
- (prev->next != dl) )
+ while ((prev != dl) && (prev != NULL) && (prev->next != dl))
prev = prev->next;
- if (prev == NULL) {
- MUTEX_UNLOCK(ctx->lock);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSUI_stopUnindex failed to locate deletion operation.\n");
- return SYSERR;
- }
- if (prev == dl) {
- ctx->unindexOperations = dl->next;
- } else {
- prev->next = dl->next;
- }
- MUTEX_UNLOCK(ctx->lock);
- if ( (dl->state == FSUI_ACTIVE) ||
- (dl->state == FSUI_COMPLETED) ||
- (dl->state == FSUI_ABORTED) ||
- (dl->state == FSUI_ERROR) ) {
- GE_ASSERT(ctx->ectx, dl->handle != NULL);
- PTHREAD_JOIN(dl->handle,
- &unused);
- dl->handle = NULL;
- if (dl->state == FSUI_ACTIVE)
- dl->state = FSUI_PENDING;
- else
- dl->state++; /* add _JOINED */
- } else {
- GE_ASSERT(ctx->ectx, dl->handle == NULL);
- }
+ if (prev == NULL)
+ {
+ MUTEX_UNLOCK (ctx->lock);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FSUI_stopUnindex failed to locate deletion operation.\n");
+ return SYSERR;
+ }
+ if (prev == dl)
+ {
+ ctx->unindexOperations = dl->next;
+ }
+ else
+ {
+ prev->next = dl->next;
+ }
+ MUTEX_UNLOCK (ctx->lock);
+ if ((dl->state == FSUI_ACTIVE) ||
+ (dl->state == FSUI_COMPLETED) ||
+ (dl->state == FSUI_ABORTED) || (dl->state == FSUI_ERROR))
+ {
+ GE_ASSERT (ctx->ectx, dl->handle != NULL);
+ PTHREAD_JOIN (dl->handle, &unused);
+ dl->handle = NULL;
+ if (dl->state == FSUI_ACTIVE)
+ dl->state = FSUI_PENDING;
+ else
+ dl->state++; /* add _JOINED */
+ }
+ else
+ {
+ GE_ASSERT (ctx->ectx, dl->handle == NULL);
+ }
event.type = FSUI_unindex_stopped;
event.data.UnindexStopped.uc.pos = dl;
event.data.UnindexStopped.uc.cctx = dl->cctx;
- dl->ctx->ecb(dl->ctx->ecbClosure,
- &event);
- FREE(dl->filename);
- FREE(dl);
+ dl->ctx->ecb (dl->ctx->ecbClosure, &event);
+ FREE (dl->filename);
+ FREE (dl);
return OK;
}
Modified: GNUnet/src/applications/fs/fsui/upload.c
===================================================================
--- GNUnet/src/applications/fs/fsui/upload.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/fsui/upload.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -40,14 +40,14 @@
/**
* Transform an ECRS progress callback into an FSUI event.
*/
-static void progressCallback(unsigned long long totalBytes,
- unsigned long long completedBytes,
- cron_t eta,
- void * ptr) {
- FSUI_UploadList * utc = ptr;
+static void
+progressCallback (unsigned long long totalBytes,
+ unsigned long long completedBytes, cron_t eta, void *ptr)
+{
+ FSUI_UploadList *utc = ptr;
FSUI_Event event;
unsigned long long subtotal;
- FSUI_UploadList * pos;
+ FSUI_UploadList *pos;
cron_t xeta;
cron_t now;
@@ -61,31 +61,33 @@
event.data.UploadProgress.eta = eta;
event.data.UploadProgress.filename = utc->filename;
utc->completed = completedBytes;
- utc->shared->ctx->ecb(utc->shared->ctx->ecbClosure,
- &event);
- if (utc->parent != &utc->shared->ctx->activeUploads) {
- subtotal = 0;
- pos = utc->parent->child;
- while (pos != NULL) {
- subtotal += pos->completed;
- pos = pos->next;
+ utc->shared->ctx->ecb (utc->shared->ctx->ecbClosure, &event);
+ if (utc->parent != &utc->shared->ctx->activeUploads)
+ {
+ subtotal = 0;
+ pos = utc->parent->child;
+ while (pos != NULL)
+ {
+ subtotal += pos->completed;
+ pos = pos->next;
+ }
+ now = get_time ();
+ xeta = now;
+ if (subtotal > 0)
+ {
+ xeta = (cron_t) (utc->parent->start_time +
+ (((double) (now - utc->parent->start_time) /
+ (double) subtotal)) *
+ (double) utc->parent->total);
+ }
+ progressCallback (utc->parent->total, subtotal, xeta, utc->parent);
}
- now = get_time();
- xeta = now;
- if (subtotal > 0) {
- xeta = (cron_t) (utc->parent->start_time +
- (((double)(now - utc->parent->start_time)/(double)subtotal))
- * (double)utc->parent->total);
- }
- progressCallback(utc->parent->total,
- subtotal,
- xeta,
- utc->parent);
- }
}
-static int testTerminate(void * cls) {
- FSUI_UploadList * utc = cls;
+static int
+testTerminate (void *cls)
+{
+ FSUI_UploadList *utc = cls;
if (utc->state != FSUI_ACTIVE)
return SYSERR;
return OK;
@@ -96,113 +98,105 @@
* a directory, upload it and store the uri in *uri.
*/
static char *
-createDirectoryHelper(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct FSUI_UploadList * children,
- struct ECRS_MetaData * meta,
- char ** error) {
- ECRS_FileInfo * fis;
+createDirectoryHelper (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct FSUI_UploadList *children,
+ struct ECRS_MetaData *meta, char **error)
+{
+ ECRS_FileInfo *fis;
unsigned int count;
unsigned int size;
- char * data;
+ char *data;
unsigned long long len;
int ret;
- char * tempName;
- struct FSUI_UploadList * pos;
+ char *tempName;
+ struct FSUI_UploadList *pos;
int handle;
- struct GE_Memory * mem;
- struct GE_Context * ee;
+ struct GE_Memory *mem;
+ struct GE_Context *ee;
fis = NULL;
size = 0;
count = 0;
pos = children;
- while (pos != NULL) {
- if (pos->uri != NULL)
- count++;
- pos = pos->next;
- }
- GROW(fis,
- size,
- count);
+ while (pos != NULL)
+ {
+ if (pos->uri != NULL)
+ count++;
+ pos = pos->next;
+ }
+ GROW (fis, size, count);
count = 0;
pos = children;
- while (pos != NULL) {
- if (pos->uri != NULL) {
- fis[count].uri = pos->uri;
- fis[count].meta = pos->meta;
- count++;
+ while (pos != NULL)
+ {
+ if (pos->uri != NULL)
+ {
+ fis[count].uri = pos->uri;
+ fis[count].meta = pos->meta;
+ count++;
+ }
+ pos = pos->next;
}
- pos = pos->next;
- }
- GE_BREAK(ectx, count == size);
- mem = GE_memory_create(2);
- ee = GE_create_context_memory(GE_USER | GE_ADMIN | GE_ERROR | GE_WARNING |
GE_FATAL | GE_BULK | GE_IMMEDIATE,
- mem);
- ret = ECRS_createDirectory(ee,
- &data,
- &len,
- size,
- fis,
- meta);
- GROW(fis,
- size,
- 0);
- if (ret != OK) {
- *error = STRDUP(GE_memory_get(mem, 0));
- GE_free_context(ee);
- GE_memory_free(mem);
- return NULL;
- }
+ GE_BREAK (ectx, count == size);
+ mem = GE_memory_create (2);
+ ee =
+ GE_create_context_memory (GE_USER | GE_ADMIN | GE_ERROR | GE_WARNING |
+ GE_FATAL | GE_BULK | GE_IMMEDIATE, mem);
+ ret = ECRS_createDirectory (ee, &data, &len, size, fis, meta);
+ GROW (fis, size, 0);
+ if (ret != OK)
+ {
+ *error = STRDUP (GE_memory_get (mem, 0));
+ GE_free_context (ee);
+ GE_memory_free (mem);
+ return NULL;
+ }
pos = children;
- while (pos != NULL) {
- if (pos->uri != NULL)
- URITRACK_addState(ectx,
- cfg,
- pos->uri,
- URITRACK_DIRECTORY_ADDED);
- pos = pos->next;
- }
- GE_memory_reset(mem);
- tempName = STRDUP("/tmp/gnunet-upload-dir.XXXXXX");
- handle = mkstemp(tempName);
- if (handle == -1) {
- GE_LOG_STRERROR_FILE(ee,
- GE_ERROR | GE_USER | GE_BULK,
- "mkstemp",
- tempName);
- FREE(tempName);
- FREE(data);
- *error = STRDUP(GE_memory_get(mem, 0));
- GE_free_context(ee);
- GE_memory_free(mem);
- return NULL;
- }
- if (len != WRITE(handle,
- data,
- len)) {
- GE_LOG_STRERROR_FILE(ee,
- GE_ERROR | GE_USER | GE_BULK,
- "write",
- tempName);
- *error = STRDUP(GE_memory_get(mem, 0));
- GE_free_context(ee);
- GE_memory_free(mem);
- FREE(data);
- return NULL;
- }
- GE_free_context(ee);
- GE_memory_free(mem);
- CLOSE(handle);
- FREE(data);
+ while (pos != NULL)
+ {
+ if (pos->uri != NULL)
+ URITRACK_addState (ectx, cfg, pos->uri, URITRACK_DIRECTORY_ADDED);
+ pos = pos->next;
+ }
+ GE_memory_reset (mem);
+ tempName = STRDUP ("/tmp/gnunet-upload-dir.XXXXXX");
+ handle = mkstemp (tempName);
+ if (handle == -1)
+ {
+ GE_LOG_STRERROR_FILE (ee,
+ GE_ERROR | GE_USER | GE_BULK,
+ "mkstemp", tempName);
+ FREE (tempName);
+ FREE (data);
+ *error = STRDUP (GE_memory_get (mem, 0));
+ GE_free_context (ee);
+ GE_memory_free (mem);
+ return NULL;
+ }
+ if (len != WRITE (handle, data, len))
+ {
+ GE_LOG_STRERROR_FILE (ee,
+ GE_ERROR | GE_USER | GE_BULK, "write", tempName);
+ *error = STRDUP (GE_memory_get (mem, 0));
+ GE_free_context (ee);
+ GE_memory_free (mem);
+ FREE (data);
+ return NULL;
+ }
+ GE_free_context (ee);
+ GE_memory_free (mem);
+ CLOSE (handle);
+ FREE (data);
return tempName;
}
/**
* Signal upload error to client.
*/
-static void signalError(FSUI_UploadList * utc,
- const char * message) {
+static void
+signalError (FSUI_UploadList * utc, const char *message)
+{
FSUI_Event event;
utc->state = FSUI_ERROR;
@@ -212,224 +206,215 @@
event.data.UploadError.uc.ppos = utc->parent;
event.data.UploadError.uc.pcctx = utc->parent->cctx;
event.data.UploadError.message = message;
- utc->shared->ctx->ecb(utc->shared->ctx->ecbClosure,
- &event);
+ utc->shared->ctx->ecb (utc->shared->ctx->ecbClosure, &event);
}
-static void signalUploadStarted(struct FSUI_UploadList * utc,
- int first_only) {
+static void
+signalUploadStarted (struct FSUI_UploadList *utc, int first_only)
+{
FSUI_Event event;
- while (utc != NULL) {
- event.type = FSUI_upload_started;
- event.data.UploadStarted.uc.pos = utc;
- event.data.UploadStarted.uc.cctx = utc->cctx;
- event.data.UploadStarted.uc.ppos = utc->parent;
- event.data.UploadStarted.uc.pcctx = utc->parent->cctx;
- event.data.UploadStarted.total = utc->total;
- event.data.UploadStarted.anonymityLevel = utc->shared->anonymityLevel;
- event.data.UploadStarted.filename = utc->filename;
- utc->cctx = utc->shared->ctx->ecb(utc->shared->ctx->ecbClosure,
- &event);
- signalUploadStarted(utc->child, 0);
- if (first_only)
- break;
- utc = utc->next;
- }
+ while (utc != NULL)
+ {
+ event.type = FSUI_upload_started;
+ event.data.UploadStarted.uc.pos = utc;
+ event.data.UploadStarted.uc.cctx = utc->cctx;
+ event.data.UploadStarted.uc.ppos = utc->parent;
+ event.data.UploadStarted.uc.pcctx = utc->parent->cctx;
+ event.data.UploadStarted.total = utc->total;
+ event.data.UploadStarted.anonymityLevel = utc->shared->anonymityLevel;
+ event.data.UploadStarted.filename = utc->filename;
+ utc->cctx = utc->shared->ctx->ecb (utc->shared->ctx->ecbClosure,
+ &event);
+ signalUploadStarted (utc->child, 0);
+ if (first_only)
+ break;
+ utc = utc->next;
+ }
}
/**
* Thread that does the upload.
*/
-void * FSUI_uploadThread(void * cls) {
- FSUI_UploadList * utc = cls;
- FSUI_UploadList * cpos;
+void *
+FSUI_uploadThread (void *cls)
+{
+ FSUI_UploadList *utc = cls;
+ FSUI_UploadList *cpos;
FSUI_Event event;
ECRS_FileInfo fi;
int ret;
- struct GE_Context * ectx;
- char * filename;
- char * pfn;
- struct ECRS_URI * uri;
- struct ECRS_URI * loc;
+ struct GE_Context *ectx;
+ char *filename;
+ char *pfn;
+ struct ECRS_URI *uri;
+ struct ECRS_URI *loc;
size_t tpos;
- char * error;
- struct GE_Memory * mem;
- struct GE_Context * ee;
+ char *error;
+ struct GE_Memory *mem;
+ struct GE_Context *ee;
ectx = utc->shared->ctx->ectx;
- GE_ASSERT(ectx, utc->filename != NULL);
+ GE_ASSERT (ectx, utc->filename != NULL);
cpos = utc->child;
- while (cpos != NULL) {
- if (cpos->state == FSUI_ACTIVE)
- FSUI_uploadThread(cpos);
- cpos = cpos->next;
- }
+ while (cpos != NULL)
+ {
+ if (cpos->state == FSUI_ACTIVE)
+ FSUI_uploadThread (cpos);
+ cpos = cpos->next;
+ }
if (utc->state != FSUI_ACTIVE)
- return NULL; /* aborted or suspended */
- if (YES == disk_directory_test(ectx,
- utc->filename)) {
- error = NULL;
- filename = createDirectoryHelper(ectx,
- utc->shared->ctx->cfg,
- utc->child,
- utc->meta,
- &error);
- if (filename == NULL) {
- if (error == NULL)
- error = STRDUP(_("Failed to create temporary directory."));
- signalError(utc,
- error);
- FREE(error);
- return NULL;
+ return NULL; /* aborted or suspended */
+ if (YES == disk_directory_test (ectx, utc->filename))
+ {
+ error = NULL;
+ filename = createDirectoryHelper (ectx,
+ utc->shared->ctx->cfg,
+ utc->child, utc->meta, &error);
+ if (filename == NULL)
+ {
+ if (error == NULL)
+ error = STRDUP (_("Failed to create temporary directory."));
+ signalError (utc, error);
+ FREE (error);
+ return NULL;
+ }
}
- } else {
- filename = STRDUP(utc->filename);
- }
- utc->start_time = get_time();
- mem = GE_memory_create(2);
- ee = GE_create_context_memory(GE_USER | GE_ADMIN | GE_ERROR | GE_WARNING |
GE_FATAL | GE_BULK | GE_IMMEDIATE,
- mem);
- ret = ECRS_uploadFile(ee,
- utc->shared->ctx->cfg,
- filename,
- utc->shared->doIndex == YES ? (utc->child == NULL ? YES : NO) :
NO,
- utc->shared->anonymityLevel,
- utc->shared->priority,
- utc->shared->expiration,
- &progressCallback,
- utc,
- &testTerminate,
- utc,
- &utc->uri);
- if (ret != OK) {
- if (utc->state == FSUI_ACTIVE) {
- const char *err;
+ else
+ {
+ filename = STRDUP (utc->filename);
+ }
+ utc->start_time = get_time ();
+ mem = GE_memory_create (2);
+ ee =
+ GE_create_context_memory (GE_USER | GE_ADMIN | GE_ERROR | GE_WARNING |
+ GE_FATAL | GE_BULK | GE_IMMEDIATE, mem);
+ ret =
+ ECRS_uploadFile (ee, utc->shared->ctx->cfg, filename,
+ utc->shared->doIndex == YES ? (utc->child ==
+ NULL ? YES : NO) : NO,
+ utc->shared->anonymityLevel, utc->shared->priority,
+ utc->shared->expiration, &progressCallback, utc,
+ &testTerminate, utc, &utc->uri);
+ if (ret != OK)
+ {
+ if (utc->state == FSUI_ACTIVE)
+ {
+ const char *err;
- err = GE_memory_get(mem, 0);
- signalError(utc,
- err ? err : "");
- } else if (utc->state == FSUI_ABORTED) {
- event.type = FSUI_upload_aborted;
- event.data.UploadAborted.uc.pos = utc;
- event.data.UploadAborted.uc.cctx = utc->cctx;
- event.data.UploadAborted.uc.ppos = utc->parent;
- event.data.UploadAborted.uc.pcctx = utc->parent->cctx;
- utc->shared->ctx->ecb(utc->shared->ctx->ecbClosure,
- &event);
- } else {
- /* must be suspended */
- GE_BREAK(NULL, utc->state == FSUI_PENDING);
+ err = GE_memory_get (mem, 0);
+ signalError (utc, err ? err : "");
+ }
+ else if (utc->state == FSUI_ABORTED)
+ {
+ event.type = FSUI_upload_aborted;
+ event.data.UploadAborted.uc.pos = utc;
+ event.data.UploadAborted.uc.cctx = utc->cctx;
+ event.data.UploadAborted.uc.ppos = utc->parent;
+ event.data.UploadAborted.uc.pcctx = utc->parent->cctx;
+ utc->shared->ctx->ecb (utc->shared->ctx->ecbClosure, &event);
+ }
+ else
+ {
+ /* must be suspended */
+ GE_BREAK (NULL, utc->state == FSUI_PENDING);
+ }
+ if (utc->child != NULL)
+ UNLINK (filename);
+ FREE (filename);
+ GE_free_context (ee);
+ GE_memory_free (mem);
+ return NULL;
}
- if (utc->child != NULL)
- UNLINK(filename);
- FREE(filename);
- GE_free_context(ee);
- GE_memory_free(mem);
- return NULL;
- }
utc->state = FSUI_COMPLETED;
if (utc->child == NULL)
- ECRS_extractMetaData(utc->shared->ctx->ectx,
- utc->meta,
- utc->filename,
- utc->shared->extractors);
- while (OK == ECRS_delFromMetaData(utc->meta,
- EXTRACTOR_FILENAME,
- NULL)) ;
+ ECRS_extractMetaData (utc->shared->ctx->ectx,
+ utc->meta, utc->filename, utc->shared->extractors);
+ while (OK == ECRS_delFromMetaData (utc->meta, EXTRACTOR_FILENAME, NULL));
/* only publish the last part of the path
-- we do not want to publish $HOME or similar
trivially deanonymizing information */
- tpos = strlen(utc->filename) - 1;
- if ( (utc->filename[tpos] == DIR_SEPARATOR) &&
- (tpos > 0) )
+ tpos = strlen (utc->filename) - 1;
+ if ((utc->filename[tpos] == DIR_SEPARATOR) && (tpos > 0))
tpos--;
- while ( (tpos > 0) &&
- (utc->filename[tpos] != DIR_SEPARATOR) )
+ while ((tpos > 0) && (utc->filename[tpos] != DIR_SEPARATOR))
tpos--;
- pfn = MALLOC(strlen(&utc->filename[tpos+1]) + 2);
- strcpy(pfn, &utc->filename[tpos+1]);
- if ( (utc->child != NULL) &&
- ( (strlen(pfn) == 0) ||
- (pfn[strlen(pfn)-1] != DIR_SEPARATOR) ) )
- strcat(pfn, DIR_SEPARATOR_STR);
- ECRS_addToMetaData(utc->meta,
- EXTRACTOR_FILENAME,
- pfn);
- FREE(pfn);
- if ( (utc->shared->anonymityLevel == 0) &&
- (utc->shared->doIndex == YES) ) {
- /* generate location URI for non-anonymous download */
- struct ClientServerConnection * sock;
- P2P_hello_MESSAGE * hello;
+ pfn = MALLOC (strlen (&utc->filename[tpos + 1]) + 2);
+ strcpy (pfn, &utc->filename[tpos + 1]);
+ if ((utc->child != NULL) &&
+ ((strlen (pfn) == 0) || (pfn[strlen (pfn) - 1] != DIR_SEPARATOR)))
+ strcat (pfn, DIR_SEPARATOR_STR);
+ ECRS_addToMetaData (utc->meta, EXTRACTOR_FILENAME, pfn);
+ FREE (pfn);
+ if ((utc->shared->anonymityLevel == 0) && (utc->shared->doIndex == YES))
+ {
+ /* generate location URI for non-anonymous download */
+ struct ClientServerConnection *sock;
+ P2P_hello_MESSAGE *hello;
- sock = client_connection_create(utc->shared->ctx->ectx,
- utc->shared->ctx->cfg);
-
- if (OK == gnunet_identity_get_self(sock,
- &hello)) {
- loc = ECRS_uriFromLocation(utc->uri,
- &hello->publicKey,
- ntohl(hello->expirationTime),
- (ECRS_SignFunction) &gnunet_identity_sign_function,
- sock);
-
- FREE(hello);
- } else {
- /* may happen if no transports are available... */
- loc = ECRS_dupUri(utc->uri);
+ sock = client_connection_create (utc->shared->ctx->ectx,
+ utc->shared->ctx->cfg);
+
+ if (OK == gnunet_identity_get_self (sock, &hello))
+ {
+ loc = ECRS_uriFromLocation (utc->uri,
+ &hello->publicKey,
+ ntohl (hello->expirationTime),
+ (ECRS_SignFunction) &
+ gnunet_identity_sign_function, sock);
+
+ FREE (hello);
+ }
+ else
+ {
+ /* may happen if no transports are available... */
+ loc = ECRS_dupUri (utc->uri);
+ }
+ connection_destroy (sock);
}
- connection_destroy(sock);
- } else {
- /* no location URI, use standard URI
- (copied here to allow free later) */
- loc = ECRS_dupUri(utc->uri);
- }
+ else
+ {
+ /* no location URI, use standard URI
+ (copied here to allow free later) */
+ loc = ECRS_dupUri (utc->uri);
+ }
if (utc->shared->global_keywords != NULL)
- ECRS_addToKeyspace(ectx,
- utc->shared->ctx->cfg,
- utc->shared->global_keywords,
- utc->shared->anonymityLevel,
- utc->shared->priority,
- utc->shared->expiration,
- loc,
- utc->meta);
+ ECRS_addToKeyspace (ectx,
+ utc->shared->ctx->cfg,
+ utc->shared->global_keywords,
+ utc->shared->anonymityLevel,
+ utc->shared->priority,
+ utc->shared->expiration, loc, utc->meta);
if (utc->keywords != NULL)
- ECRS_addToKeyspace(ectx,
- utc->shared->ctx->cfg,
- utc->keywords,
- utc->shared->anonymityLevel,
- utc->shared->priority,
- utc->shared->expiration,
- loc,
- utc->meta);
- if (utc->shared->individualKeywords == YES) {
- uri = ECRS_metaDataToUri(utc->meta);
- ECRS_addToKeyspace(ectx,
- utc->shared->ctx->cfg,
- uri,
- utc->shared->anonymityLevel,
- utc->shared->priority,
- utc->shared->expiration,
- loc,
- utc->meta);
- ECRS_freeUri(uri);
- }
- ECRS_freeUri(loc);
+ ECRS_addToKeyspace (ectx,
+ utc->shared->ctx->cfg,
+ utc->keywords,
+ utc->shared->anonymityLevel,
+ utc->shared->priority,
+ utc->shared->expiration, loc, utc->meta);
+ if (utc->shared->individualKeywords == YES)
+ {
+ uri = ECRS_metaDataToUri (utc->meta);
+ ECRS_addToKeyspace (ectx,
+ utc->shared->ctx->cfg,
+ uri,
+ utc->shared->anonymityLevel,
+ utc->shared->priority,
+ utc->shared->expiration, loc, utc->meta);
+ ECRS_freeUri (uri);
+ }
+ ECRS_freeUri (loc);
loc = NULL;
- while (OK == ECRS_delFromMetaData(utc->meta,
- EXTRACTOR_SPLIT,
- NULL)) ;
+ while (OK == ECRS_delFromMetaData (utc->meta, EXTRACTOR_SPLIT, NULL));
fi.meta = utc->meta;
fi.uri = utc->uri;
- URITRACK_trackURI(ectx,
- utc->shared->ctx->cfg,
- &fi);
- URITRACK_addState(ectx,
- utc->shared->ctx->cfg,
- utc->uri,
- utc->shared->doIndex == YES ? URITRACK_INDEXED : URITRACK_INSERTED);
+ URITRACK_trackURI (ectx, utc->shared->ctx->cfg, &fi);
+ URITRACK_addState (ectx,
+ utc->shared->ctx->cfg,
+ utc->uri,
+ utc->shared->doIndex ==
+ YES ? URITRACK_INDEXED : URITRACK_INSERTED);
event.type = FSUI_upload_completed;
event.data.UploadCompleted.uc.pos = utc;
event.data.UploadCompleted.uc.cctx = utc->cctx;
@@ -438,96 +423,101 @@
event.data.UploadCompleted.total = utc->total;
event.data.UploadCompleted.filename = utc->filename;
event.data.UploadCompleted.uri = utc->uri;
- utc->shared->ctx->ecb(utc->shared->ctx->ecbClosure,
- &event);
+ utc->shared->ctx->ecb (utc->shared->ctx->ecbClosure, &event);
if (utc->child != NULL)
- UNLINK(filename);
- FREE(filename);
- GE_free_context(ee);
- GE_memory_free(mem);
+ UNLINK (filename);
+ FREE (filename);
+ GE_free_context (ee);
+ GE_memory_free (mem);
return NULL;
}
/**
* Thread that does the upload.
*/
-static void * FSUI_uploadThreadEvent(void * cls) {
- FSUI_UploadList * utc = cls;
+static void *
+FSUI_uploadThreadEvent (void *cls)
+{
+ FSUI_UploadList *utc = cls;
- if (utc->parent == &utc->shared->ctx->activeUploads) {
- /* top-level call: signal client! */
- signalUploadStarted(utc, 1);
- }
- return FSUI_uploadThread(utc);
+ if (utc->parent == &utc->shared->ctx->activeUploads)
+ {
+ /* top-level call: signal client! */
+ signalUploadStarted (utc, 1);
+ }
+ return FSUI_uploadThread (utc);
}
-static void freeUploadList(struct FSUI_UploadList * ul) {
- struct FSUI_UploadList * next;
- struct FSUI_Context * ctx;
+static void
+freeUploadList (struct FSUI_UploadList *ul)
+{
+ struct FSUI_UploadList *next;
+ struct FSUI_Context *ctx;
ctx = ul->shared->ctx;
while (ul->child != NULL)
- freeUploadList(ul->child);
- MUTEX_LOCK(ctx->lock);
- FREE(ul->filename);
+ freeUploadList (ul->child);
+ MUTEX_LOCK (ctx->lock);
+ FREE (ul->filename);
if (ul->keywords != NULL)
- ECRS_freeUri(ul->keywords);
+ ECRS_freeUri (ul->keywords);
if (ul->uri != NULL)
- ECRS_freeUri(ul->uri);
+ ECRS_freeUri (ul->uri);
if (ul->meta != NULL)
- ECRS_freeMetaData(ul->meta);
+ ECRS_freeMetaData (ul->meta);
/* unlink from parent */
next = ul->parent->child;
- if (next == NULL) {
- GE_BREAK(NULL, 0);
- MUTEX_UNLOCK(ctx->lock);
- return;
- }
- if (next == ul) {
- ul->parent->child = ul->next;
- } else {
- while (next->next != ul) {
- next = next->next;
- if (next == NULL) {
- GE_BREAK(NULL, 0);
- MUTEX_UNLOCK(ctx->lock);
- return;
- }
+ if (next == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ MUTEX_UNLOCK (ctx->lock);
+ return;
}
- next->next = ul->next;
- }
- FREE(ul);
- MUTEX_UNLOCK(ctx->lock);
+ if (next == ul)
+ {
+ ul->parent->child = ul->next;
+ }
+ else
+ {
+ while (next->next != ul)
+ {
+ next = next->next;
+ if (next == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ MUTEX_UNLOCK (ctx->lock);
+ return;
+ }
+ }
+ next->next = ul->next;
+ }
+ FREE (ul);
+ MUTEX_UNLOCK (ctx->lock);
}
-static struct FSUI_UploadList *
-addUploads(struct FSUI_UploadShared * shared,
- const char * filename,
- const struct ECRS_URI * keywords,
- const struct ECRS_MetaData * md,
- struct FSUI_UploadList * parent);
+static struct FSUI_UploadList *addUploads (struct FSUI_UploadShared *shared,
+ const char *filename,
+ const struct ECRS_URI *keywords,
+ const struct ECRS_MetaData *md,
+ struct FSUI_UploadList *parent);
-static int addChildUpload(const char * name,
- const char * dirName,
- void * data) {
- struct FSUI_UploadList * parent = data;
- char * filename;
- struct FSUI_UploadList * child;
- struct ECRS_MetaData * md;
+static int
+addChildUpload (const char *name, const char *dirName, void *data)
+{
+ struct FSUI_UploadList *parent = data;
+ char *filename;
+ struct FSUI_UploadList *child;
+ struct ECRS_MetaData *md;
- filename = MALLOC(strlen(dirName) + strlen(name) + 2);
- strcpy(filename, dirName);
- strcat(filename, DIR_SEPARATOR_STR);
- strcat(filename, name);
- md = ECRS_createMetaData();
- child = addUploads(parent->shared,
- filename,
- NULL,
- md,
- parent);
- FREE(filename);
- ECRS_freeMetaData(md);
+ filename = MALLOC (strlen (dirName) + strlen (name) + 2);
+ strcpy (filename, dirName);
+ strcat (filename, DIR_SEPARATOR_STR);
+ strcat (filename, name);
+ md = ECRS_createMetaData ();
+ child = addUploads (parent->shared, filename, NULL, md, parent);
+ FREE (filename);
+ ECRS_freeMetaData (md);
if (child == NULL)
return SYSERR;
parent->total += child->total;
@@ -535,90 +525,92 @@
}
static struct FSUI_UploadList *
-addUploads(struct FSUI_UploadShared * shared,
- const char * filename,
- const struct ECRS_URI * keywords,
- const struct ECRS_MetaData * md,
- struct FSUI_UploadList * parent) {
- FSUI_UploadList * utc;
+addUploads (struct FSUI_UploadShared *shared,
+ const char *filename,
+ const struct ECRS_URI *keywords,
+ const struct ECRS_MetaData *md, struct FSUI_UploadList *parent)
+{
+ FSUI_UploadList *utc;
- utc = MALLOC(sizeof(FSUI_UploadList));
+ utc = MALLOC (sizeof (FSUI_UploadList));
utc->completed = 0;
- utc->total = 0; /* to be set later */
- utc->start_time = get_time();
+ utc->total = 0; /* to be set later */
+ utc->start_time = get_time ();
utc->shared = shared;
utc->next = NULL;
utc->child = NULL;
utc->parent = parent;
utc->uri = NULL;
- utc->cctx = NULL; /* to be set later */
+ utc->cctx = NULL; /* to be set later */
utc->state = FSUI_ACTIVE;
- if (YES == disk_file_test(shared->ctx->ectx,
- filename)) {
- /* add this file */
- if (OK != disk_file_size(shared->ctx->ectx,
- filename,
- &utc->total,
- YES)) {
- FREE(utc);
- return NULL;
+ if (YES == disk_file_test (shared->ctx->ectx, filename))
+ {
+ /* add this file */
+ if (OK != disk_file_size (shared->ctx->ectx,
+ filename, &utc->total, YES))
+ {
+ FREE (utc);
+ return NULL;
+ }
+ utc->meta = ECRS_dupMetaData (md);
}
- utc->meta = ECRS_dupMetaData(md);
- } else {
- if (SYSERR == shared->dsc(shared->dscClosure,
- filename,
- &addChildUpload,
- utc)) {
- /* error scanning upload directory */
- while (utc->child != NULL)
- freeUploadList(utc->child);
- FREE(utc);
- return NULL;
+ else
+ {
+ if (SYSERR == shared->dsc (shared->dscClosure,
+ filename, &addChildUpload, utc))
+ {
+ /* error scanning upload directory */
+ while (utc->child != NULL)
+ freeUploadList (utc->child);
+ FREE (utc);
+ return NULL;
+ }
+ utc->meta = ECRS_dupMetaData (md);
+ ECRS_addToMetaData (utc->meta,
+ EXTRACTOR_MIMETYPE, GNUNET_DIRECTORY_MIME);
}
- utc->meta = ECRS_dupMetaData(md);
- ECRS_addToMetaData(utc->meta,
- EXTRACTOR_MIMETYPE,
- GNUNET_DIRECTORY_MIME);
- }
if (keywords != NULL)
- utc->keywords = ECRS_dupUri(keywords);
+ utc->keywords = ECRS_dupUri (keywords);
else
utc->keywords = NULL;
- utc->filename = STRDUP(filename);
+ utc->filename = STRDUP (filename);
/* finally, link with parent */
- MUTEX_LOCK(shared->ctx->lock);
+ MUTEX_LOCK (shared->ctx->lock);
utc->next = parent->child;
parent->child = utc;
- MUTEX_UNLOCK(shared->ctx->lock);
+ MUTEX_UNLOCK (shared->ctx->lock);
return utc;
}
-static void signalUploadStopped(struct FSUI_UploadList * ul,
- int first_only) {
+static void
+signalUploadStopped (struct FSUI_UploadList *ul, int first_only)
+{
FSUI_Event event;
- while (ul != NULL) {
- signalUploadStopped(ul->child, 0);
- event.type = FSUI_upload_stopped;
- event.data.UploadStopped.uc.pos = ul;
- event.data.UploadStopped.uc.cctx = ul->cctx;
- event.data.UploadStopped.uc.ppos = ul->parent;
- event.data.UploadStopped.uc.pcctx = ul->parent->cctx;
- ul->shared->ctx->ecb(ul->shared->ctx->ecbClosure,
- &event);
- if (first_only)
- break;
- ul = ul->next;
- }
+ while (ul != NULL)
+ {
+ signalUploadStopped (ul->child, 0);
+ event.type = FSUI_upload_stopped;
+ event.data.UploadStopped.uc.pos = ul;
+ event.data.UploadStopped.uc.cctx = ul->cctx;
+ event.data.UploadStopped.uc.ppos = ul->parent;
+ event.data.UploadStopped.uc.pcctx = ul->parent->cctx;
+ ul->shared->ctx->ecb (ul->shared->ctx->ecbClosure, &event);
+ if (first_only)
+ break;
+ ul = ul->next;
+ }
}
-static void freeShared(struct FSUI_UploadShared * shared) {
+static void
+freeShared (struct FSUI_UploadShared *shared)
+{
if (shared->global_keywords != NULL)
- ECRS_freeUri(shared->global_keywords);
- EXTRACTOR_removeAll(shared->extractors);
- FREENONNULL(shared->extractor_config);
- FREE(shared);
+ ECRS_freeUri (shared->global_keywords);
+ EXTRACTOR_removeAll (shared->extractors);
+ FREENONNULL (shared->extractor_config);
+ FREE (shared);
}
/**
@@ -632,77 +624,72 @@
* running
*/
struct FSUI_UploadList *
-FSUI_startUpload(struct FSUI_Context * ctx,
- const char * filename,
- DirectoryScanCallback dsc,
- void * dscClosure,
- unsigned int anonymityLevel,
- unsigned int priority,
- int doIndex,
- int doExtract,
- int individualKeywords,
- cron_t expiration,
- const struct ECRS_MetaData * md,
- const struct ECRS_URI * globalURI,
- const struct ECRS_URI * keyUri) {
- char * config;
- EXTRACTOR_ExtractorList * extractors;
- struct FSUI_UploadShared * shared;
- struct FSUI_UploadList * ul;
+FSUI_startUpload (struct FSUI_Context *ctx,
+ const char *filename,
+ DirectoryScanCallback dsc,
+ void *dscClosure,
+ unsigned int anonymityLevel,
+ unsigned int priority,
+ int doIndex,
+ int doExtract,
+ int individualKeywords,
+ cron_t expiration,
+ const struct ECRS_MetaData *md,
+ const struct ECRS_URI *globalURI,
+ const struct ECRS_URI *keyUri)
+{
+ char *config;
+ EXTRACTOR_ExtractorList *extractors;
+ struct FSUI_UploadShared *shared;
+ struct FSUI_UploadList *ul;
config = NULL;
extractors = NULL;
- if (doExtract) {
- extractors = EXTRACTOR_loadDefaultLibraries();
- if (GC_have_configuration_value(ctx->cfg,
- "FS",
- "EXTRACTORS")) {
- GC_get_configuration_value_string(ctx->cfg,
- "FS",
- "EXTRACTORS",
- NULL,
- &config);
- if (config != NULL) {
- extractors = EXTRACTOR_loadConfigLibraries(extractors,
- config);
- }
+ if (doExtract)
+ {
+ extractors = EXTRACTOR_loadDefaultLibraries ();
+ if (GC_have_configuration_value (ctx->cfg, "FS", "EXTRACTORS"))
+ {
+ GC_get_configuration_value_string (ctx->cfg,
+ "FS",
+ "EXTRACTORS", NULL, &config);
+ if (config != NULL)
+ {
+ extractors = EXTRACTOR_loadConfigLibraries (extractors, config);
+ }
+ }
}
- }
- shared = MALLOC(sizeof(FSUI_UploadShared));
+ shared = MALLOC (sizeof (FSUI_UploadShared));
shared->dsc = dsc;
shared->dscClosure = dscClosure;
shared->extractors = extractors;
shared->expiration = expiration;
shared->ctx = ctx;
shared->handle = NULL;
- shared->global_keywords = globalURI != NULL ? ECRS_dupUri(globalURI) : NULL;
+ shared->global_keywords =
+ globalURI != NULL ? ECRS_dupUri (globalURI) : NULL;
shared->extractor_config = config;
shared->doIndex = doIndex;
shared->anonymityLevel = anonymityLevel;
shared->priority = priority;
shared->individualKeywords = individualKeywords;
shared->handle = NULL;
- ul = addUploads(shared,
- filename,
- keyUri,
- md,
- &ctx->activeUploads);
- if (ul == NULL) {
- freeShared(shared);
- return NULL;
- }
- shared->handle = PTHREAD_CREATE(&FSUI_uploadThreadEvent,
- ul,
- 128 * 1024);
- if (shared->handle == NULL) {
- GE_LOG_STRERROR(ctx->ectx,
- GE_ERROR | GE_USER | GE_BULK,
- "PTHREAD_CREATE");
- freeUploadList(ul);
- freeShared(shared);
- return NULL;
- }
- GE_ASSERT(ctx->ectx, ul->shared == shared);
+ ul = addUploads (shared, filename, keyUri, md, &ctx->activeUploads);
+ if (ul == NULL)
+ {
+ freeShared (shared);
+ return NULL;
+ }
+ shared->handle = PTHREAD_CREATE (&FSUI_uploadThreadEvent, ul, 128 * 1024);
+ if (shared->handle == NULL)
+ {
+ GE_LOG_STRERROR (ctx->ectx,
+ GE_ERROR | GE_USER | GE_BULK, "PTHREAD_CREATE");
+ freeUploadList (ul);
+ freeShared (shared);
+ return NULL;
+ }
+ GE_ASSERT (ctx->ectx, ul->shared == shared);
return ul;
}
@@ -715,30 +702,35 @@
*
* @return SYSERR on error
*/
-int FSUI_abortUpload(struct FSUI_Context * ctx,
- struct FSUI_UploadList * ul) {
- FSUI_UploadList * c;
+int
+FSUI_abortUpload (struct FSUI_Context *ctx, struct FSUI_UploadList *ul)
+{
+ FSUI_UploadList *c;
- GE_ASSERT(ctx->ectx, ul != NULL);
- if ( (ul->state != FSUI_ACTIVE) &&
- (ul->state != FSUI_PENDING) )
+ GE_ASSERT (ctx->ectx, ul != NULL);
+ if ((ul->state != FSUI_ACTIVE) && (ul->state != FSUI_PENDING))
return NO;
- if (ul->state == FSUI_ACTIVE) {
- ul->state = FSUI_ABORTED;
- c = ul->child;
- while (c != NULL) {
- FSUI_abortUpload(ctx, c);
- c = c->next;
+ if (ul->state == FSUI_ACTIVE)
+ {
+ ul->state = FSUI_ABORTED;
+ c = ul->child;
+ while (c != NULL)
+ {
+ FSUI_abortUpload (ctx, c);
+ c = c->next;
+ }
+ PTHREAD_STOP_SLEEP (ul->shared->handle);
}
- PTHREAD_STOP_SLEEP(ul->shared->handle);
- } else {
- ul->state = FSUI_ABORTED_JOINED;
- c = ul->child;
- while (c != NULL) {
- FSUI_abortUpload(ctx, c);
- c = c->next;
+ else
+ {
+ ul->state = FSUI_ABORTED_JOINED;
+ c = ul->child;
+ while (c != NULL)
+ {
+ FSUI_abortUpload (ctx, c);
+ c = c->next;
+ }
}
- }
return OK;
}
@@ -748,32 +740,34 @@
*
* @return SYSERR on error
*/
-int FSUI_stopUpload(struct FSUI_Context * ctx,
- struct FSUI_UploadList * ul) {
- void * unused;
- struct FSUI_UploadShared * shared;
+int
+FSUI_stopUpload (struct FSUI_Context *ctx, struct FSUI_UploadList *ul)
+{
+ void *unused;
+ struct FSUI_UploadShared *shared;
- GE_ASSERT(ctx->ectx, ul != NULL);
- GE_ASSERT(ctx->ectx, ul->parent == &ctx->activeUploads);
- if ( (ul->state == FSUI_ACTIVE) ||
- (ul->state == FSUI_COMPLETED) ||
- (ul->state == FSUI_ABORTED) ||
- (ul->state == FSUI_ERROR) ) {
- GE_ASSERT(ctx->ectx, ul->shared->handle != NULL);
- PTHREAD_JOIN(ul->shared->handle,
- &unused);
- ul->shared->handle = NULL;
- if (ul->state == FSUI_ACTIVE)
- ul->state = FSUI_PENDING;
- else
- ul->state++; /* add _JOINED */
- } else {
- GE_ASSERT(ctx->ectx, ul->shared->handle == NULL);
- }
- signalUploadStopped(ul, 1);
+ GE_ASSERT (ctx->ectx, ul != NULL);
+ GE_ASSERT (ctx->ectx, ul->parent == &ctx->activeUploads);
+ if ((ul->state == FSUI_ACTIVE) ||
+ (ul->state == FSUI_COMPLETED) ||
+ (ul->state == FSUI_ABORTED) || (ul->state == FSUI_ERROR))
+ {
+ GE_ASSERT (ctx->ectx, ul->shared->handle != NULL);
+ PTHREAD_JOIN (ul->shared->handle, &unused);
+ ul->shared->handle = NULL;
+ if (ul->state == FSUI_ACTIVE)
+ ul->state = FSUI_PENDING;
+ else
+ ul->state++; /* add _JOINED */
+ }
+ else
+ {
+ GE_ASSERT (ctx->ectx, ul->shared->handle == NULL);
+ }
+ signalUploadStopped (ul, 1);
shared = ul->shared;
- freeUploadList(ul);
- freeShared(shared);
+ freeUploadList (ul);
+ freeShared (shared);
return OK;
}
Modified: GNUnet/src/applications/fs/lib/fslib.c
===================================================================
--- GNUnet/src/applications/fs/lib/fslib.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/lib/fslib.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -32,19 +32,21 @@
#define DEBUG_FSLIB NO
-typedef struct FS_SEARCH_HANDLE {
- CS_fs_request_search_MESSAGE * req;
+typedef struct FS_SEARCH_HANDLE
+{
+ CS_fs_request_search_MESSAGE *req;
Datum_Iterator callback;
- void * closure;
+ void *closure;
} SEARCH_HANDLE;
-typedef struct FS_SEARCH_CONTEXT {
- struct GC_Configuration * cfg;
- struct GE_Context * ectx;
- struct ClientServerConnection * sock;
- struct PTHREAD * thread;
- struct MUTEX * lock;
- SEARCH_HANDLE ** handles;
+typedef struct FS_SEARCH_CONTEXT
+{
+ struct GC_Configuration *cfg;
+ struct GE_Context *ectx;
+ struct ClientServerConnection *sock;
+ struct PTHREAD *thread;
+ struct MUTEX *lock;
+ SEARCH_HANDLE **handles;
unsigned int handleCount;
unsigned int handleSize;
int abort;
@@ -60,147 +62,151 @@
* Thread that processes replies from gnunetd and
* calls the appropriate callback.
*/
-static void * processReplies(void * cls) {
- SEARCH_CONTEXT * ctx = cls;
- MESSAGE_HEADER * hdr;
+static void *
+processReplies (void *cls)
+{
+ SEARCH_CONTEXT *ctx = cls;
+ MESSAGE_HEADER *hdr;
int i;
int matched;
- const CS_fs_reply_content_MESSAGE * rep;
+ const CS_fs_reply_content_MESSAGE *rep;
HashCode512 query;
unsigned int size;
cron_t delay;
delay = 100 * cronMILLIS;
- while (ctx->abort == NO) {
- hdr = NULL;
- if (OK == connection_read(ctx->sock,
- &hdr)) {
+ while (ctx->abort == NO)
+ {
+ hdr = NULL;
+ if (OK == connection_read (ctx->sock, &hdr))
+ {
#if DEBUG_FSLIB
- GE_LOG(ctx->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSLIB: received message from gnunetd\n");
+ GE_LOG (ctx->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FSLIB: received message from gnunetd\n");
#endif
- delay = 100 * cronMILLIS;
- /* verify hdr, if reply, process, otherwise
- signal protocol problem; if ok, find
- matching callback, call on value */
- if ( (ntohs(hdr->size) < sizeof(CS_fs_reply_content_MESSAGE)) ||
- (ntohs(hdr->type) != CS_PROTO_gap_RESULT) ) {
- GE_BREAK(ctx->ectx, 0);
- FREE(hdr);
- continue;
- }
- rep = (const CS_fs_reply_content_MESSAGE*) hdr;
- size = ntohs(hdr->size) - sizeof(CS_fs_reply_content_MESSAGE);
- if (OK != getQueryFor(size,
- (DBlock*)&rep[1],
- NO, /* gnunetd will have checked already */
- &query)) {
- GE_BREAK(ctx->ectx, 0);
- FREE(hdr);
- continue;
- }
- matched = 0;
- MUTEX_LOCK(ctx->lock);
- for (i=ctx->handleCount-1;i>=0;i--) {
- if (equalsHashCode512(&query,
- &ctx->handles[i]->req->query[0])) {
- Datastore_Value * value;
+ delay = 100 * cronMILLIS;
+ /* verify hdr, if reply, process, otherwise
+ signal protocol problem; if ok, find
+ matching callback, call on value */
+ if ((ntohs (hdr->size) < sizeof (CS_fs_reply_content_MESSAGE)) ||
+ (ntohs (hdr->type) != CS_PROTO_gap_RESULT))
+ {
+ GE_BREAK (ctx->ectx, 0);
+ FREE (hdr);
+ continue;
+ }
+ rep = (const CS_fs_reply_content_MESSAGE *) hdr;
+ size = ntohs (hdr->size) - sizeof (CS_fs_reply_content_MESSAGE);
+ if (OK != getQueryFor (size, (DBlock *) & rep[1], NO, /* gnunetd
will have checked already */
+ &query))
+ {
+ GE_BREAK (ctx->ectx, 0);
+ FREE (hdr);
+ continue;
+ }
+ matched = 0;
+ MUTEX_LOCK (ctx->lock);
+ for (i = ctx->handleCount - 1; i >= 0; i--)
+ {
+ if (equalsHashCode512 (&query, &ctx->handles[i]->req->query[0]))
+ {
+ Datastore_Value *value;
- matched++;
- if (ctx->handles[i]->callback != NULL) {
- value = MALLOC(sizeof(Datastore_Value) + size);
- value->size = htonl(size + sizeof(Datastore_Value));
- value->type = htonl(getTypeOfBlock(size,
- (DBlock*) &rep[1]));
- value->prio = htonl(0);
- value->anonymityLevel = rep->anonymityLevel;
- value->expirationTime = rep->expirationTime;
- memcpy(&value[1],
- &rep[1],
- size);
- if (SYSERR == ctx->handles[i]->callback(&query,
- value,
- ctx->handles[i]->closure)) {
- ctx->handles[i]->callback = NULL;
- }
- FREE(value);
- }
- }
- }
- MUTEX_UNLOCK(ctx->lock);
+ matched++;
+ if (ctx->handles[i]->callback != NULL)
+ {
+ value = MALLOC (sizeof (Datastore_Value) + size);
+ value->size = htonl (size + sizeof (Datastore_Value));
+ value->type = htonl (getTypeOfBlock (size,
+ (DBlock *) &
+ rep[1]));
+ value->prio = htonl (0);
+ value->anonymityLevel = rep->anonymityLevel;
+ value->expirationTime = rep->expirationTime;
+ memcpy (&value[1], &rep[1], size);
+ if (SYSERR == ctx->handles[i]->callback (&query,
+ value,
+ ctx->
+ handles[i]->
+ closure))
+ {
+ ctx->handles[i]->callback = NULL;
+ }
+ FREE (value);
+ }
+ }
+ }
+ MUTEX_UNLOCK (ctx->lock);
#if DEBUG_FSLIB
- if (matched == 0)
- GE_LOG(ctx->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSLIB: received content but have no pending request\n");
+ if (matched == 0)
+ GE_LOG (ctx->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FSLIB: received content but have no pending request\n");
#endif
- } else {
+ }
+ else
+ {
#if DEBUG_FSLIB
- GE_LOG(ctx->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSLIB: error communicating with gnunetd; sleeping for %ums\n",
- delay);
+ GE_LOG (ctx->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FSLIB: error communicating with gnunetd; sleeping for
%ums\n",
+ delay);
#endif
- if (ctx->abort == NO)
- PTHREAD_SLEEP(delay);
- delay *= 2;
- if (delay > 5 * cronSECONDS)
- delay = 5 * cronSECONDS;
+ if (ctx->abort == NO)
+ PTHREAD_SLEEP (delay);
+ delay *= 2;
+ if (delay > 5 * cronSECONDS)
+ delay = 5 * cronSECONDS;
+ }
+ FREENONNULL (hdr);
}
- FREENONNULL(hdr);
- }
return NULL;
}
SEARCH_CONTEXT *
-FS_SEARCH_makeContext(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct MUTEX * lock) {
- SEARCH_CONTEXT * ret;
+FS_SEARCH_makeContext (struct GE_Context * ectx,
+ struct GC_Configuration * cfg, struct MUTEX * lock)
+{
+ SEARCH_CONTEXT *ret;
- GE_ASSERT(ectx, lock != NULL);
- ret = MALLOC(sizeof(SEARCH_CONTEXT));
+ GE_ASSERT (ectx, lock != NULL);
+ ret = MALLOC (sizeof (SEARCH_CONTEXT));
ret->ectx = ectx;
ret->cfg = cfg;
ret->lock = lock;
- ret->sock = client_connection_create(ectx, cfg);
- if (ret->sock == NULL) {
- FREE(ret);
- return NULL;
- }
+ ret->sock = client_connection_create (ectx, cfg);
+ if (ret->sock == NULL)
+ {
+ FREE (ret);
+ return NULL;
+ }
ret->handles = NULL;
ret->handleCount = 0;
ret->handleSize = 0;
ret->abort = NO;
- ret->thread = PTHREAD_CREATE(&processReplies,
- ret,
- 128 * 1024);
+ ret->thread = PTHREAD_CREATE (&processReplies, ret, 128 * 1024);
if (ret->thread == NULL)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_BULK,
- "PTHREAD_CREATE");
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_ADMIN | GE_BULK, "PTHREAD_CREATE");
return ret;
}
-void FS_SEARCH_destroyContext(struct FS_SEARCH_CONTEXT * ctx) {
- void * unused;
+void
+FS_SEARCH_destroyContext (struct FS_SEARCH_CONTEXT *ctx)
+{
+ void *unused;
- MUTEX_LOCK(ctx->lock);
- GE_ASSERT(ctx->ectx,
- ctx->handleCount == 0);
+ MUTEX_LOCK (ctx->lock);
+ GE_ASSERT (ctx->ectx, ctx->handleCount == 0);
ctx->abort = YES;
- connection_close_forever(ctx->sock);
- MUTEX_UNLOCK(ctx->lock);
- PTHREAD_STOP_SLEEP(ctx->thread);
- PTHREAD_JOIN(ctx->thread,
- &unused);
+ connection_close_forever (ctx->sock);
+ MUTEX_UNLOCK (ctx->lock);
+ PTHREAD_STOP_SLEEP (ctx->thread);
+ PTHREAD_JOIN (ctx->thread, &unused);
ctx->lock = NULL;
- connection_destroy(ctx->sock);
- GROW(ctx->handles,
- ctx->handleSize,
- 0);
- FREE(ctx);
+ connection_destroy (ctx->sock);
+ GROW (ctx->handles, ctx->handleSize, 0);
+ FREE (ctx);
}
/**
@@ -214,79 +220,69 @@
* @param prio priority to use for the search
*/
SEARCH_HANDLE *
-FS_start_search(SEARCH_CONTEXT * ctx,
- const PeerIdentity * target,
- unsigned int type,
- unsigned int keyCount,
- const HashCode512 * keys,
- unsigned int anonymityLevel,
- unsigned int prio,
- cron_t timeout,
- Datum_Iterator callback,
- void * closure) {
- SEARCH_HANDLE * ret;
- CS_fs_request_search_MESSAGE * req;
+FS_start_search (SEARCH_CONTEXT * ctx,
+ const PeerIdentity * target,
+ unsigned int type,
+ unsigned int keyCount,
+ const HashCode512 * keys,
+ unsigned int anonymityLevel,
+ unsigned int prio,
+ cron_t timeout, Datum_Iterator callback, void *closure)
+{
+ SEARCH_HANDLE *ret;
+ CS_fs_request_search_MESSAGE *req;
#if DEBUG_FSLIB
EncName enc;
#endif
- ret = MALLOC(sizeof(SEARCH_HANDLE));
+ ret = MALLOC (sizeof (SEARCH_HANDLE));
#if DEBUG_FSLIB
- GE_LOG(ctx->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSLIB: start search (%p)\n",
- ret);
+ GE_LOG (ctx->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "FSLIB: start search (%p)\n", ret);
#endif
- req = MALLOC(sizeof(CS_fs_request_search_MESSAGE) + (keyCount-1) *
sizeof(HashCode512));
- req->header.size = htons(sizeof(CS_fs_request_search_MESSAGE) + (keyCount-1)
* sizeof(HashCode512));
- req->header.type = htons(CS_PROTO_gap_QUERY_START);
- req->prio = htonl(prio);
- req->anonymityLevel = htonl(anonymityLevel);
- req->expiration = htonll(timeout);
- req->type = htonl(type);
+ req =
+ MALLOC (sizeof (CS_fs_request_search_MESSAGE) +
+ (keyCount - 1) * sizeof (HashCode512));
+ req->header.size =
+ htons (sizeof (CS_fs_request_search_MESSAGE) +
+ (keyCount - 1) * sizeof (HashCode512));
+ req->header.type = htons (CS_PROTO_gap_QUERY_START);
+ req->prio = htonl (prio);
+ req->anonymityLevel = htonl (anonymityLevel);
+ req->expiration = htonll (timeout);
+ req->type = htonl (type);
if (target != NULL)
req->target = *target;
else
- memset(&req->target,
- 0,
- sizeof(PeerIdentity));
- memcpy(&req->query[0],
- keys,
- keyCount * sizeof(HashCode512));
+ memset (&req->target, 0, sizeof (PeerIdentity));
+ memcpy (&req->query[0], keys, keyCount * sizeof (HashCode512));
ret->req = req;
ret->callback = callback;
ret->closure = closure;
- MUTEX_LOCK(ctx->lock);
- if (ctx->handleCount == ctx->handleSize) {
- GROW(ctx->handles,
- ctx->handleSize,
- ctx->handleSize * 2 + 4);
- }
+ MUTEX_LOCK (ctx->lock);
+ if (ctx->handleCount == ctx->handleSize)
+ {
+ GROW (ctx->handles, ctx->handleSize, ctx->handleSize * 2 + 4);
+ }
ctx->handles[ctx->handleCount++] = ret;
- MUTEX_UNLOCK(ctx->lock);
+ MUTEX_UNLOCK (ctx->lock);
#if DEBUG_FSLIB
- IF_GELOG(ctx->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&req->query[0],
- &enc));
- GE_LOG(ctx->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSLIB: initiating search for `%s' of type %u\n",
- &enc,
- type);
+ IF_GELOG (ctx->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (&req->query[0], &enc));
+ GE_LOG (ctx->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FSLIB: initiating search for `%s' of type %u\n", &enc, type);
#endif
- GE_ASSERT(NULL, ctx->sock != NULL);
- if (OK != connection_write(ctx->sock,
- &req->header)) {
- FS_stop_search(ctx,
- ret);
- return NULL;
- }
+ GE_ASSERT (NULL, ctx->sock != NULL);
+ if (OK != connection_write (ctx->sock, &req->header))
+ {
+ FS_stop_search (ctx, ret);
+ return NULL;
+ }
#if DEBUG_FSLIB
- GE_LOG(ctx->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSLIB: search started (%p)\n",
- ret);
+ GE_LOG (ctx->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FSLIB: search started (%p)\n", ret);
#endif
return ret;
}
@@ -294,56 +290,56 @@
/**
* Stop searching.
*/
-void FS_stop_search(SEARCH_CONTEXT * ctx,
- SEARCH_HANDLE * handle) {
+void
+FS_stop_search (SEARCH_CONTEXT * ctx, SEARCH_HANDLE * handle)
+{
int i;
#if DEBUG_FSLIB
- GE_LOG(ctx->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSLIB: stop search (%p)\n",
- handle);
+ GE_LOG (ctx->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FSLIB: stop search (%p)\n", handle);
#endif
- handle->req->header.type = htons(CS_PROTO_gap_QUERY_STOP);
- GE_ASSERT(NULL, ctx->sock != NULL);
- if (OK != connection_write(ctx->sock,
- &handle->req->header)) {
- GE_LOG(ctx->ectx,
- GE_WARNING | GE_REQUEST | GE_DEVELOPER,
- "FSLIB: failed to request stop search with gnunetd\n");
- }
- MUTEX_LOCK(ctx->lock);
- for (i=ctx->handleCount-1;i>=0;i--)
- if (ctx->handles[i] == handle) {
- ctx->handles[i] = ctx->handles[--ctx->handleCount];
- break;
+ handle->req->header.type = htons (CS_PROTO_gap_QUERY_STOP);
+ GE_ASSERT (NULL, ctx->sock != NULL);
+ if (OK != connection_write (ctx->sock, &handle->req->header))
+ {
+ GE_LOG (ctx->ectx,
+ GE_WARNING | GE_REQUEST | GE_DEVELOPER,
+ "FSLIB: failed to request stop search with gnunetd\n");
}
- MUTEX_UNLOCK(ctx->lock);
- FREE(handle->req);
+ MUTEX_LOCK (ctx->lock);
+ for (i = ctx->handleCount - 1; i >= 0; i--)
+ if (ctx->handles[i] == handle)
+ {
+ ctx->handles[i] = ctx->handles[--ctx->handleCount];
+ break;
+ }
+ MUTEX_UNLOCK (ctx->lock);
+ FREE (handle->req);
#if DEBUG_FSLIB
- GE_LOG(ctx->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FSLIB: search stopped (%p)\n",
- handle);
+ GE_LOG (ctx->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FSLIB: search stopped (%p)\n", handle);
#endif
- FREE(handle);
+ FREE (handle);
}
/**
* What is the current average priority of entries
* in the routing table like? Returns -1 on error.
*/
-int FS_getAveragePriority(struct ClientServerConnection * sock) {
+int
+FS_getAveragePriority (struct ClientServerConnection *sock)
+{
MESSAGE_HEADER req;
int ret;
- req.size = htons(sizeof(MESSAGE_HEADER));
- req.type = htons(CS_PROTO_gap_GET_AVG_PRIORITY);
- if (OK != connection_write(sock,
- &req))
+ req.size = htons (sizeof (MESSAGE_HEADER));
+ req.type = htons (CS_PROTO_gap_GET_AVG_PRIORITY);
+ if (OK != connection_write (sock, &req))
return -1;
- if (OK != connection_read_result(sock,
- &ret))
+ if (OK != connection_read_result (sock, &ret))
return -1;
return ret;
}
@@ -354,91 +350,88 @@
* @param block the block (properly encoded and all)
* @return OK on success, SYSERR on error, NO on transient error
*/
-int FS_insert(struct ClientServerConnection * sock,
- const Datastore_Value * block) {
+int
+FS_insert (struct ClientServerConnection *sock, const Datastore_Value * block)
+{
int ret;
- CS_fs_request_insert_MESSAGE * ri;
+ CS_fs_request_insert_MESSAGE *ri;
unsigned int size;
int retry;
- if (ntohl(block->size) <= sizeof(Datastore_Value)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- size = ntohl(block->size) - sizeof(Datastore_Value);
- ri = MALLOC(sizeof(CS_fs_request_insert_MESSAGE) + size);
- ri->header.size = htons(sizeof(CS_fs_request_insert_MESSAGE) + size);
- ri->header.type = htons(CS_PROTO_gap_INSERT);
+ if (ntohl (block->size) <= sizeof (Datastore_Value))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ size = ntohl (block->size) - sizeof (Datastore_Value);
+ ri = MALLOC (sizeof (CS_fs_request_insert_MESSAGE) + size);
+ ri->header.size = htons (sizeof (CS_fs_request_insert_MESSAGE) + size);
+ ri->header.type = htons (CS_PROTO_gap_INSERT);
ri->prio = block->prio;
ri->expiration = block->expirationTime;
ri->anonymityLevel = block->anonymityLevel;
- memcpy(&ri[1],
- &block[1],
- size);
+ memcpy (&ri[1], &block[1], size);
retry = AUTO_RETRY;
- do {
- if (OK != connection_write(sock,
- &ri->header)) {
- FREE(ri);
- return SYSERR;
+ do
+ {
+ if (OK != connection_write (sock, &ri->header))
+ {
+ FREE (ri);
+ return SYSERR;
+ }
+ if (OK != connection_read_result (sock, &ret))
+ {
+ GE_BREAK (NULL, 0);
+ FREE (ri);
+ return SYSERR;
+ }
}
- if (OK != connection_read_result(sock,
- &ret)) {
- GE_BREAK(NULL, 0);
- FREE(ri);
- return SYSERR;
- }
- } while ( (ret == NO) &&
- (retry-- > 0) );
- FREE(ri);
+ while ((ret == NO) && (retry-- > 0));
+ FREE (ri);
return ret;
}
/**
* Initialize to index a file
*/
-int FS_initIndex(struct ClientServerConnection * sock,
- const HashCode512 * fileHc,
- const char * fn) {
+int
+FS_initIndex (struct ClientServerConnection *sock,
+ const HashCode512 * fileHc, const char *fn)
+{
int ret;
- CS_fs_request_init_index_MESSAGE * ri;
+ CS_fs_request_init_index_MESSAGE *ri;
unsigned int size;
size_t fnSize;
- fnSize = strlen(fn);
+ fnSize = strlen (fn);
fnSize = (fnSize + 7) & (~7); /* align */
- size = sizeof(CS_fs_request_init_index_MESSAGE) + fnSize;
- GE_ASSERT(NULL, size < 65536);
- ri = MALLOC(size);
- memset(ri,
- 0,
- size);
- ri->header.size = htons(size);
- ri->header.type = htons(CS_PROTO_gap_INIT_INDEX);
- ri->reserved = htonl(0);
+ size = sizeof (CS_fs_request_init_index_MESSAGE) + fnSize;
+ GE_ASSERT (NULL, size < 65536);
+ ri = MALLOC (size);
+ memset (ri, 0, size);
+ ri->header.size = htons (size);
+ ri->header.type = htons (CS_PROTO_gap_INIT_INDEX);
+ ri->reserved = htonl (0);
ri->fileId = *fileHc;
- memcpy(&ri[1],
- fn,
- strlen(fn));
+ memcpy (&ri[1], fn, strlen (fn));
#if DEBUG_FSLIB
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Sending index initialization request to gnunetd\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Sending index initialization request to gnunetd\n");
#endif
- if (OK != connection_write(sock,
- &ri->header)) {
- FREE(ri);
- return SYSERR;
- }
- FREE(ri);
+ if (OK != connection_write (sock, &ri->header))
+ {
+ FREE (ri);
+ return SYSERR;
+ }
+ FREE (ri);
#if DEBUG_FSLIB
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Waiting for confirmation of index initialization request by gnunetd\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Waiting for confirmation of index initialization request by
gnunetd\n");
#endif
- if (OK != connection_read_result(sock,
- &ret))
+ if (OK != connection_read_result (sock, &ret))
return SYSERR;
return ret;
}
@@ -451,52 +444,52 @@
* @param offset the offset of the block into the file
* @return OK on success, SYSERR on error
*/
-int FS_index(struct ClientServerConnection * sock,
- const HashCode512 * fileHc,
- const Datastore_Value * block,
- unsigned long long offset) {
+int
+FS_index (struct ClientServerConnection *sock,
+ const HashCode512 * fileHc,
+ const Datastore_Value * block, unsigned long long offset)
+{
int ret;
- CS_fs_request_index_MESSAGE * ri;
+ CS_fs_request_index_MESSAGE *ri;
unsigned int size;
int retry;
- size = ntohl(block->size) - sizeof(Datastore_Value);
- ri = MALLOC(sizeof(CS_fs_request_index_MESSAGE) + size);
- ri->header.size = htons(sizeof(CS_fs_request_index_MESSAGE) + size);
- ri->header.type = htons(CS_PROTO_gap_INDEX);
+ size = ntohl (block->size) - sizeof (Datastore_Value);
+ ri = MALLOC (sizeof (CS_fs_request_index_MESSAGE) + size);
+ ri->header.size = htons (sizeof (CS_fs_request_index_MESSAGE) + size);
+ ri->header.type = htons (CS_PROTO_gap_INDEX);
ri->prio = block->prio;
ri->expiration = block->expirationTime;
ri->anonymityLevel = block->anonymityLevel;
ri->fileId = *fileHc;
- ri->fileOffset = htonll(offset);
- memcpy(&ri[1],
- &block[1],
- size);
+ ri->fileOffset = htonll (offset);
+ memcpy (&ri[1], &block[1], size);
#if DEBUG_FSLIB
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Sending index request to gnunetd\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Sending index request to gnunetd\n");
#endif
retry = AUTO_RETRY;
- do {
- if (OK != connection_write(sock,
- &ri->header)) {
- FREE(ri);
- return SYSERR;
- }
+ do
+ {
+ if (OK != connection_write (sock, &ri->header))
+ {
+ FREE (ri);
+ return SYSERR;
+ }
#if DEBUG_FSLIB
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Waiting for confirmation of index request by gnunetd\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Waiting for confirmation of index request by gnunetd\n");
#endif
- if (OK != connection_read_result(sock,
- &ret)) {
- FREE(ri);
- return SYSERR;
+ if (OK != connection_read_result (sock, &ret))
+ {
+ FREE (ri);
+ return SYSERR;
+ }
}
- } while ( (ret == NO) &&
- (retry-- > 0) );
- FREE(ri);
+ while ((ret == NO) && (retry-- > 0));
+ FREE (ri);
return ret;
}
@@ -508,37 +501,37 @@
* @return number of items deleted on success,
* SYSERR on error
*/
-int FS_delete(struct ClientServerConnection * sock,
- const Datastore_Value * block) {
+int
+FS_delete (struct ClientServerConnection *sock, const Datastore_Value * block)
+{
int ret;
- CS_fs_request_delete_MESSAGE * rd;
+ CS_fs_request_delete_MESSAGE *rd;
unsigned int size;
int retry;
- size = ntohl(block->size) - sizeof(Datastore_Value);
- rd = MALLOC(sizeof(CS_fs_request_delete_MESSAGE) + size);
- rd->header.size = htons(sizeof(CS_fs_request_delete_MESSAGE) + size);
- rd->header.type = htons(CS_PROTO_gap_DELETE);
- memcpy(&rd[1],
- &block[1],
- size);
+ size = ntohl (block->size) - sizeof (Datastore_Value);
+ rd = MALLOC (sizeof (CS_fs_request_delete_MESSAGE) + size);
+ rd->header.size = htons (sizeof (CS_fs_request_delete_MESSAGE) + size);
+ rd->header.type = htons (CS_PROTO_gap_DELETE);
+ memcpy (&rd[1], &block[1], size);
retry = AUTO_RETRY;
- do {
- if (OK != connection_write(sock,
- &rd->header)) {
- FREE(rd);
- GE_BREAK(NULL, 0);
- return SYSERR;
+ do
+ {
+ if (OK != connection_write (sock, &rd->header))
+ {
+ FREE (rd);
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ if (OK != connection_read_result (sock, &ret))
+ {
+ GE_BREAK (NULL, 0);
+ FREE (rd);
+ return SYSERR;
+ }
}
- if (OK != connection_read_result(sock,
- &ret)) {
- GE_BREAK(NULL, 0);
- FREE(rd);
- return SYSERR;
- }
- } while ( (ret == NO) &&
- (retry-- > 0) );
- FREE(rd);
+ while ((ret == NO) && (retry-- > 0));
+ FREE (rd);
return ret;
}
@@ -548,21 +541,20 @@
* @param hc the hash of the entire file
* @return OK on success, SYSERR on error
*/
-int FS_unindex(struct ClientServerConnection * sock,
- unsigned int blocksize,
- const HashCode512 * hc) {
+int
+FS_unindex (struct ClientServerConnection *sock,
+ unsigned int blocksize, const HashCode512 * hc)
+{
int ret;
CS_fs_request_unindex_MESSAGE ru;
- ru.header.size = htons(sizeof(CS_fs_request_unindex_MESSAGE));
- ru.header.type = htons(CS_PROTO_gap_UNINDEX);
- ru.blocksize = htonl(blocksize);
+ ru.header.size = htons (sizeof (CS_fs_request_unindex_MESSAGE));
+ ru.header.type = htons (CS_PROTO_gap_UNINDEX);
+ ru.blocksize = htonl (blocksize);
ru.fileId = *hc;
- if (OK != connection_write(sock,
- &ru.header))
+ if (OK != connection_write (sock, &ru.header))
return SYSERR;
- if (OK != connection_read_result(sock,
- &ret))
+ if (OK != connection_read_result (sock, &ret))
return SYSERR;
return ret;
}
@@ -573,20 +565,19 @@
* @param hc the hash of the entire file
* @return YES if so, NO if not, SYSERR on error
*/
-int FS_testIndexed(struct ClientServerConnection * sock,
- const HashCode512 * hc) {
+int
+FS_testIndexed (struct ClientServerConnection *sock, const HashCode512 * hc)
+{
RequestTestindex ri;
int ret;
- ri.header.size = htons(sizeof(RequestTestindex));
- ri.header.type = htons(CS_PROTO_gap_TESTINDEX);
- ri.reserved = htonl(0);
+ ri.header.size = htons (sizeof (RequestTestindex));
+ ri.header.type = htons (CS_PROTO_gap_TESTINDEX);
+ ri.reserved = htonl (0);
ri.fileId = *hc;
- if (OK != connection_write(sock,
- &ri.header))
+ if (OK != connection_write (sock, &ri.header))
return SYSERR;
- if (OK != connection_read_result(sock,
- &ret))
+ if (OK != connection_read_result (sock, &ret))
return SYSERR;
return ret;
}
Modified: GNUnet/src/applications/fs/lib/fslibtest.c
===================================================================
--- GNUnet/src/applications/fs/lib/fslibtest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/lib/fslibtest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -34,358 +34,314 @@
#define CHECK(a) if (!(a)) { ok = NO; GE_BREAK(NULL, 0); goto FAILURE; }
-static struct CronManager * cron;
+static struct CronManager *cron;
static cron_t now;
-static struct PTHREAD * mainThread;
+static struct PTHREAD *mainThread;
-static Datastore_Value * makeBlock(int i) {
- Datastore_Value * block;
- DBlock * db;
+static Datastore_Value *
+makeBlock (int i)
+{
+ Datastore_Value *block;
+ DBlock *db;
- block = MALLOC(sizeof(Datastore_Value) +
- sizeof(DBlock) + i);
- block->size = htonl(sizeof(Datastore_Value) +
- sizeof(DBlock) + i);
- block->type = htonl(D_BLOCK);
- block->prio = htonl(0);
- block->anonymityLevel = htonl(0);
- block->expirationTime = htonll(now + 1 * cronHOURS);
- db = (DBlock*) &block[1];
- db->type = htonl(D_BLOCK);
- memset(&db[1],
- i + (i /253),
- i);
+ block = MALLOC (sizeof (Datastore_Value) + sizeof (DBlock) + i);
+ block->size = htonl (sizeof (Datastore_Value) + sizeof (DBlock) + i);
+ block->type = htonl (D_BLOCK);
+ block->prio = htonl (0);
+ block->anonymityLevel = htonl (0);
+ block->expirationTime = htonll (now + 1 * cronHOURS);
+ db = (DBlock *) & block[1];
+ db->type = htonl (D_BLOCK);
+ memset (&db[1], i + (i / 253), i);
return block;
}
-static Datastore_Value * makeKBlock(unsigned int i,
- const HashCode512 * key,
- HashCode512 * query) {
- Datastore_Value * block;
- KBlock * db;
- struct PrivateKey * kkey;
+static Datastore_Value *
+makeKBlock (unsigned int i, const HashCode512 * key, HashCode512 * query)
+{
+ Datastore_Value *block;
+ KBlock *db;
+ struct PrivateKey *kkey;
- block = MALLOC(sizeof(Datastore_Value) +
- sizeof(KBlock) + i);
- block->size = htonl(sizeof(Datastore_Value) +
- sizeof(KBlock) + i);
- block->type = htonl(K_BLOCK);
- block->prio = htonl(0);
- block->anonymityLevel = htonl(0);
- block->expirationTime = htonll(now + 1 * cronHOURS);
- db = (KBlock*) &block[1];
- db->type = htonl(K_BLOCK);
- memset(&db[1],
- i + (i /253),
- i);
- kkey = makeKblockKey(key);
- sign(kkey,
- i,
- &db[1],
- &db->signature);
- getPublicKey(kkey,
- &db->keyspace);
- hash(&db->keyspace,
- sizeof(PublicKey),
- query);
- freePrivateKey(kkey);
+ block = MALLOC (sizeof (Datastore_Value) + sizeof (KBlock) + i);
+ block->size = htonl (sizeof (Datastore_Value) + sizeof (KBlock) + i);
+ block->type = htonl (K_BLOCK);
+ block->prio = htonl (0);
+ block->anonymityLevel = htonl (0);
+ block->expirationTime = htonll (now + 1 * cronHOURS);
+ db = (KBlock *) & block[1];
+ db->type = htonl (K_BLOCK);
+ memset (&db[1], i + (i / 253), i);
+ kkey = makeKblockKey (key);
+ sign (kkey, i, &db[1], &db->signature);
+ getPublicKey (kkey, &db->keyspace);
+ hash (&db->keyspace, sizeof (PublicKey), query);
+ freePrivateKey (kkey);
return block;
}
-typedef struct {
- struct SEMAPHORE * sem;
+typedef struct
+{
+ struct SEMAPHORE *sem;
int found;
int i;
} TSC;
-static void abortSem(void * cls) {
- struct SEMAPHORE * sem = cls;
- SEMAPHORE_UP(sem);
+static void
+abortSem (void *cls)
+{
+ struct SEMAPHORE *sem = cls;
+ SEMAPHORE_UP (sem);
}
/**
* Search result callback that just counts down
* a counter.
*/
-static int countCallback(const HashCode512 * key,
- const Datastore_Value * value,
- void * cls) {
- int * cnt = cls;
+static int
+countCallback (const HashCode512 * key,
+ const Datastore_Value * value, void *cls)
+{
+ int *cnt = cls;
(*cnt)--;
- fprintf(stderr, "*");
+ fprintf (stderr, "*");
if (*cnt <= 0)
- PTHREAD_STOP_SLEEP(mainThread);
+ PTHREAD_STOP_SLEEP (mainThread);
return OK;
}
-static int searchResultCB(const HashCode512 * key,
- const Datastore_Value * value,
- TSC * cls) {
+static int
+searchResultCB (const HashCode512 * key,
+ const Datastore_Value * value, TSC * cls)
+{
HashCode512 ekey;
- Datastore_Value * blk;
- Datastore_Value * eblk;
+ Datastore_Value *blk;
+ Datastore_Value *eblk;
int ret;
- blk = makeBlock(cls->i);
- fileBlockGetQuery((DBlock*) &blk[1],
- ntohl(blk->size) - sizeof(Datastore_Value),
- &ekey);
- GE_ASSERT(NULL, OK ==
- fileBlockEncode((DBlock*) &blk[1],
- ntohl(blk->size) - sizeof(Datastore_Value),
- &ekey,
- &eblk));
- if ( (equalsHashCode512(&ekey,
- key)) &&
- (value->size == blk->size) &&
- (0 == memcmp(&value[1],
- &eblk[1],
- ntohl(value->size) - sizeof(Datastore_Value))) ) {
- cls->found = YES;
- SEMAPHORE_UP(cls->sem);
- ret = SYSERR;
- } else {
- GE_BREAK(NULL, 0);
- printf("Received unexpected result.\n");
- ret = OK;
- }
- FREE(eblk);
- FREE(blk);
+ blk = makeBlock (cls->i);
+ fileBlockGetQuery ((DBlock *) & blk[1],
+ ntohl (blk->size) - sizeof (Datastore_Value), &ekey);
+ GE_ASSERT (NULL, OK ==
+ fileBlockEncode ((DBlock *) & blk[1],
+ ntohl (blk->size) - sizeof (Datastore_Value),
+ &ekey, &eblk));
+ if ((equalsHashCode512 (&ekey,
+ key)) &&
+ (value->size == blk->size) &&
+ (0 == memcmp (&value[1],
+ &eblk[1],
+ ntohl (value->size) - sizeof (Datastore_Value))))
+ {
+ cls->found = YES;
+ SEMAPHORE_UP (cls->sem);
+ ret = SYSERR;
+ }
+ else
+ {
+ GE_BREAK (NULL, 0);
+ printf ("Received unexpected result.\n");
+ ret = OK;
+ }
+ FREE (eblk);
+ FREE (blk);
return ret;
}
-static int trySearch(struct FS_SEARCH_CONTEXT * ctx,
- int i) {
- struct FS_SEARCH_HANDLE * handle;
+static int
+trySearch (struct FS_SEARCH_CONTEXT *ctx, int i)
+{
+ struct FS_SEARCH_HANDLE *handle;
cron_t now;
HashCode512 query;
TSC closure;
- Datastore_Value * dv;
- DBlock * db;
+ Datastore_Value *dv;
+ DBlock *db;
- dv = makeBlock(i);
- db = (DBlock*) &dv[1];
- fileBlockGetQuery(db,
- ntohl(dv->size) - sizeof(Datastore_Value),
- &query);
- FREE(dv);
+ dv = makeBlock (i);
+ db = (DBlock *) & dv[1];
+ fileBlockGetQuery (db, ntohl (dv->size) - sizeof (Datastore_Value), &query);
+ FREE (dv);
closure.found = NO;
closure.i = i;
- closure.sem = SEMAPHORE_CREATE(0);
- now = get_time();
- handle = FS_start_search(ctx,
- NULL,
- D_BLOCK,
- 1,
- &query,
- 0,
- 0,
- now + 30 * cronSECONDS,
- (Datum_Iterator)&searchResultCB,
- &closure);
- cron_add_job(cron,
- &abortSem,
- 30 * cronSECONDS,
- 0,
- closure.sem);
- SEMAPHORE_DOWN(closure.sem, YES);
- FS_stop_search(ctx,
- handle);
- cron_suspend(cron, NO);
- cron_del_job(cron,
- &abortSem, 0, closure.sem);
- cron_resume_jobs(cron, NO);
- SEMAPHORE_DESTROY(closure.sem);
+ closure.sem = SEMAPHORE_CREATE (0);
+ now = get_time ();
+ handle = FS_start_search (ctx,
+ NULL,
+ D_BLOCK,
+ 1,
+ &query,
+ 0,
+ 0,
+ now + 30 * cronSECONDS,
+ (Datum_Iterator) & searchResultCB, &closure);
+ cron_add_job (cron, &abortSem, 30 * cronSECONDS, 0, closure.sem);
+ SEMAPHORE_DOWN (closure.sem, YES);
+ FS_stop_search (ctx, handle);
+ cron_suspend (cron, NO);
+ cron_del_job (cron, &abortSem, 0, closure.sem);
+ cron_resume_jobs (cron, NO);
+ SEMAPHORE_DESTROY (closure.sem);
return closure.found;
}
#define START_DAEMON 1
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
#if START_DAEMON
pid_t daemon;
#endif
int ok;
- struct FS_SEARCH_CONTEXT * ctx = NULL;
- struct FS_SEARCH_HANDLE * hnd;
- struct MUTEX * lock;
- struct ClientServerConnection * sock;
- Datastore_Value * block;
- Datastore_Value * eblock;
+ struct FS_SEARCH_CONTEXT *ctx = NULL;
+ struct FS_SEARCH_HANDLE *hnd;
+ struct MUTEX *lock;
+ struct ClientServerConnection *sock;
+ Datastore_Value *block;
+ Datastore_Value *eblock;
HashCode512 hc;
HashCode512 query;
int i;
- char * tmpName;
+ char *tmpName;
int fd;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- now = get_time();
- cron = cron_create(NULL);
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ now = get_time ();
+ cron = cron_create (NULL);
#if START_DAEMON
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
#endif
ok = YES;
- cron_start(cron);
- lock = MUTEX_CREATE(NO);
- GE_ASSERT(NULL,
- OK == connection_wait_for_running(NULL,
- cfg,
- 60 * cronSECONDS));
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
- sock = client_connection_create(NULL, cfg);
- CHECK(sock != NULL);
- ctx = FS_SEARCH_makeContext(NULL,
- cfg,
- lock);
- CHECK(ctx != NULL);
+ cron_start (cron);
+ lock = MUTEX_CREATE (NO);
+ GE_ASSERT (NULL,
+ OK == connection_wait_for_running (NULL, cfg, 60 * cronSECONDS));
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
+ sock = client_connection_create (NULL, cfg);
+ CHECK (sock != NULL);
+ ctx = FS_SEARCH_makeContext (NULL, cfg, lock);
+ CHECK (ctx != NULL);
/* ACTUAL TEST CODE */
- for (i=1;i<32;i++) {
- fprintf(stderr, ".");
- block = makeBlock(i);
- fileBlockGetQuery((DBlock*) &block[1],
- ntohl(block->size) - sizeof(Datastore_Value),
- &query);
- CHECK(OK == fileBlockEncode((DBlock*) &block[1],
- ntohl(block->size) - sizeof(Datastore_Value),
- &query,
- &eblock));
- eblock->expirationTime = block->expirationTime;
- eblock->prio = block->prio;
- CHECK(OK == FS_insert(sock,
- eblock));
- CHECK(OK == trySearch(ctx, i));
- CHECK(SYSERR != FS_delete(sock,
- eblock));
- FREE(eblock);
- hash(&((DBlock*)&block[1])[1],
- ntohl(block->size) - sizeof(Datastore_Value) - sizeof(DBlock),
- &hc);
- /* indexing without symlink */
- CHECK(OK == FS_index(sock,
- &hc,
- block,
- 0));
- CHECK(OK == trySearch(ctx, i));
- CHECK(OK == FS_unindex(sock,
- MAX_BUFFER_SIZE,
- &hc));
- /* indexing with symlink */
- tmpName = STRDUP("/tmp/symlinkTestXXXXXX");
- CHECK(-1 != (fd = mkstemp(tmpName)));
- CHECK(-1 != WRITE(fd,
- &((DBlock*)&block[1])[1],
- ntohl(block->size) - sizeof(Datastore_Value) - sizeof(DBlock)));
- CLOSE(fd);
- CHECK(FS_initIndex(sock,
- &hc,
- tmpName) == YES);
- CHECK(OK == FS_index(sock,
- &hc,
- block,
- 0));
- CHECK(OK == trySearch(ctx, i));
- CHECK(OK == FS_unindex(sock,
- MAX_BUFFER_SIZE,
- &hc));
- UNLINK(tmpName);
- FREE(tmpName);
- FREE(block);
- }
- fprintf(stderr, "\n");
- for (i=32;i<MAX_BUFFER_SIZE;i*=2) {
- fprintf(stderr, ".");
- block = makeBlock(i);
- fileBlockGetQuery((DBlock*) &block[1],
- ntohl(block->size) - sizeof(Datastore_Value),
- &query);
- CHECK(OK == fileBlockEncode((DBlock*) &block[1],
- ntohl(block->size) - sizeof(Datastore_Value),
- &query,
- &eblock));
- eblock->expirationTime = block->expirationTime;
- eblock->prio = block->prio;
- CHECK(OK == FS_insert(sock,
- eblock));
- CHECK(OK == trySearch(ctx, i));
- CHECK(1 == FS_delete(sock,
- eblock));
- FREE(eblock);
- hash(&((DBlock*)&block[1])[1],
- ntohl(block->size) - sizeof(Datastore_Value) - sizeof(DBlock),
- &hc);
- CHECK(OK == FS_index(sock,
- &hc,
- block,
- 0));
- CHECK(OK == trySearch(ctx, i));
- CHECK(OK == FS_unindex(sock,
- MAX_BUFFER_SIZE,
- &hc));
- FREE(block);
- }
- fprintf(stderr, "\n");
+ for (i = 1; i < 32; i++)
+ {
+ fprintf (stderr, ".");
+ block = makeBlock (i);
+ fileBlockGetQuery ((DBlock *) & block[1],
+ ntohl (block->size) - sizeof (Datastore_Value),
+ &query);
+ CHECK (OK == fileBlockEncode ((DBlock *) & block[1],
+ ntohl (block->size) -
+ sizeof (Datastore_Value), &query,
+ &eblock));
+ eblock->expirationTime = block->expirationTime;
+ eblock->prio = block->prio;
+ CHECK (OK == FS_insert (sock, eblock));
+ CHECK (OK == trySearch (ctx, i));
+ CHECK (SYSERR != FS_delete (sock, eblock));
+ FREE (eblock);
+ hash (&((DBlock *) & block[1])[1],
+ ntohl (block->size) - sizeof (Datastore_Value) - sizeof (DBlock),
+ &hc);
+ /* indexing without symlink */
+ CHECK (OK == FS_index (sock, &hc, block, 0));
+ CHECK (OK == trySearch (ctx, i));
+ CHECK (OK == FS_unindex (sock, MAX_BUFFER_SIZE, &hc));
+ /* indexing with symlink */
+ tmpName = STRDUP ("/tmp/symlinkTestXXXXXX");
+ CHECK (-1 != (fd = mkstemp (tmpName)));
+ CHECK (-1 != WRITE (fd,
+ &((DBlock *) & block[1])[1],
+ ntohl (block->size) - sizeof (Datastore_Value) -
+ sizeof (DBlock)));
+ CLOSE (fd);
+ CHECK (FS_initIndex (sock, &hc, tmpName) == YES);
+ CHECK (OK == FS_index (sock, &hc, block, 0));
+ CHECK (OK == trySearch (ctx, i));
+ CHECK (OK == FS_unindex (sock, MAX_BUFFER_SIZE, &hc));
+ UNLINK (tmpName);
+ FREE (tmpName);
+ FREE (block);
+ }
+ fprintf (stderr, "\n");
+ for (i = 32; i < MAX_BUFFER_SIZE; i *= 2)
+ {
+ fprintf (stderr, ".");
+ block = makeBlock (i);
+ fileBlockGetQuery ((DBlock *) & block[1],
+ ntohl (block->size) - sizeof (Datastore_Value),
+ &query);
+ CHECK (OK == fileBlockEncode ((DBlock *) & block[1],
+ ntohl (block->size) -
+ sizeof (Datastore_Value), &query,
+ &eblock));
+ eblock->expirationTime = block->expirationTime;
+ eblock->prio = block->prio;
+ CHECK (OK == FS_insert (sock, eblock));
+ CHECK (OK == trySearch (ctx, i));
+ CHECK (1 == FS_delete (sock, eblock));
+ FREE (eblock);
+ hash (&((DBlock *) & block[1])[1],
+ ntohl (block->size) - sizeof (Datastore_Value) - sizeof (DBlock),
+ &hc);
+ CHECK (OK == FS_index (sock, &hc, block, 0));
+ CHECK (OK == trySearch (ctx, i));
+ CHECK (OK == FS_unindex (sock, MAX_BUFFER_SIZE, &hc));
+ FREE (block);
+ }
+ fprintf (stderr, "\n");
/* multiple search results test */
- makeRandomId(&hc);
- block = makeKBlock(40, &hc, &query);
- CHECK(OK == FS_insert(sock,
- block));
- FREE(block);
- block = makeKBlock(60, &hc, &query);
- CHECK(OK == FS_insert(sock,
- block));
- FREE(block);
+ makeRandomId (&hc);
+ block = makeKBlock (40, &hc, &query);
+ CHECK (OK == FS_insert (sock, block));
+ FREE (block);
+ block = makeKBlock (60, &hc, &query);
+ CHECK (OK == FS_insert (sock, block));
+ FREE (block);
i = 2;
- mainThread = PTHREAD_GET_SELF();
- hnd = FS_start_search(ctx,
- NULL,
- ANY_BLOCK,
- 1,
- &query,
- 0,
- 0,
- 10 * cronSECONDS,
- &countCallback,
- &i);
- CHECK(hnd != NULL);
- PTHREAD_SLEEP(10 * cronSECONDS);
- FS_stop_search(ctx, hnd);
- PTHREAD_REL_SELF(mainThread);
- CHECK(i <= 0);
-
+ mainThread = PTHREAD_GET_SELF ();
+ hnd = FS_start_search (ctx,
+ NULL,
+ ANY_BLOCK,
+ 1,
+ &query, 0, 0, 10 * cronSECONDS, &countCallback, &i);
+ CHECK (hnd != NULL);
+ PTHREAD_SLEEP (10 * cronSECONDS);
+ FS_stop_search (ctx, hnd);
+ PTHREAD_REL_SELF (mainThread);
+ CHECK (i <= 0);
+
/* just to check if it crashes... */
- FS_getAveragePriority(sock);
+ FS_getAveragePriority (sock);
/* END OF TEST CODE */
- FAILURE:
- fprintf(stderr, "\n");
+FAILURE:
+ fprintf (stderr, "\n");
if (ctx != NULL)
- FS_SEARCH_destroyContext(ctx);
+ FS_SEARCH_destroyContext (ctx);
if (sock != NULL)
- connection_destroy(sock);
- MUTEX_DESTROY(lock);
- cron_stop(cron);
- cron_destroy(cron);
+ connection_destroy (sock);
+ MUTEX_DESTROY (lock);
+ cron_stop (cron);
+ cron_destroy (cron);
#if START_DAEMON
- GE_ASSERT(NULL, OK == os_daemon_stop(NULL, daemon));
+ GE_ASSERT (NULL, OK == os_daemon_stop (NULL, daemon));
#endif
- GC_free(cfg);
+ GC_free (cfg);
return (ok == YES) ? 0 : 1;
}
Modified: GNUnet/src/applications/fs/module/anonymity.c
===================================================================
--- GNUnet/src/applications/fs/module/anonymity.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/module/anonymity.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -42,9 +42,10 @@
*
* @return OK if cover traffic is sufficient
*/
-int checkCoverTraffic(struct GE_Context * ectx,
- Traffic_ServiceAPI * traffic,
- unsigned int level) {
+int
+checkCoverTraffic (struct GE_Context *ectx,
+ Traffic_ServiceAPI * traffic, unsigned int level)
+{
unsigned int count;
unsigned int peers;
unsigned int sizes;
@@ -55,49 +56,46 @@
level--;
if (traffic == NULL)
return SYSERR;
- if (OK != traffic->get(5 * cronSECONDS / TRAFFIC_TIME_UNIT, /*
TTL_DECREMENT/TTU */
- P2P_PROTO_gap_RESULT,
- TC_RECEIVED,
- &count,
- &peers,
- &sizes,
- &timevect)) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Failed to get traffic stats.\n"));
- return SYSERR;
- }
- if (level > 1000) {
- if (peers < level / 1000) {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Not enough cover traffic to satisfy anonymity requirements (%u, %u
peers). "
- "Result dropped.\n",
- level,
- peers);
+ if (OK != traffic->get (5 * cronSECONDS / TRAFFIC_TIME_UNIT, /*
TTL_DECREMENT/TTU */
+ P2P_PROTO_gap_RESULT,
+ TC_RECEIVED, &count, &peers, &sizes, &timevect))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Failed to get traffic stats.\n"));
return SYSERR;
}
- if (count < level % 1000) {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Not enough cover traffic to satisfy anonymity requirements (%u, %u
messages). "
- "Result dropped.\n",
- level,
- count);
- return SYSERR;
+ if (level > 1000)
+ {
+ if (peers < level / 1000)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Not enough cover traffic to satisfy anonymity requirements
(%u, %u peers). "
+ "Result dropped.\n", level, peers);
+ return SYSERR;
+ }
+ if (count < level % 1000)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Not enough cover traffic to satisfy anonymity requirements
(%u, %u messages). "
+ "Result dropped.\n", level, count);
+ return SYSERR;
+ }
}
- } else {
- if (count < level) {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Not enough cover traffic to satisfy anonymity requirements (%u, %u
messages). "
- "Result dropped.\n",
- level,
- count);
- return SYSERR;
+ else
+ {
+ if (count < level)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Not enough cover traffic to satisfy anonymity requirements
(%u, %u messages). "
+ "Result dropped.\n", level, count);
+ return SYSERR;
+ }
}
- }
return OK;
}
-
+
/* end of anonymity.c */
Modified: GNUnet/src/applications/fs/module/anonymity.h
===================================================================
--- GNUnet/src/applications/fs/module/anonymity.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/module/anonymity.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -43,8 +43,7 @@
*
* @return OK if cover traffic is sufficient
*/
-int checkCoverTraffic(struct GE_Context * ectx,
- Traffic_ServiceAPI * traffic,
- unsigned int level);
+int checkCoverTraffic (struct GE_Context *ectx,
+ Traffic_ServiceAPI * traffic, unsigned int level);
#endif
Modified: GNUnet/src/applications/fs/module/dht_push.c
===================================================================
--- GNUnet/src/applications/fs/module/dht_push.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/module/dht_push.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -43,23 +43,23 @@
/**
* DHT service. Set to NULL to terminate
*/
-static DHT_ServiceAPI * dht;
+static DHT_ServiceAPI *dht;
/**
* Global core API.
*/
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
/**
* SQStore service.
*/
-static SQstore_ServiceAPI * sqstore;
+static SQstore_ServiceAPI *sqstore;
/**
* Thread that does the pushing.
*/
-static struct PTHREAD * thread;
+static struct PTHREAD *thread;
/**
* Total number of entries with anonymity 0.
@@ -68,14 +68,15 @@
*/
static int total;
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static int stat_push_count;
-static int push_callback(const HashCode512 * key,
- const Datastore_Value * value,
- void * closure) {
+static int
+push_callback (const HashCode512 * key,
+ const Datastore_Value * value, void *closure)
+{
cron_t delay;
if (dht == NULL)
@@ -87,34 +88,31 @@
delay = 5 * cronSECONDS;
if (delay > 60 * cronSECONDS)
delay = 60 * cronSECONDS;
- PTHREAD_SLEEP(delay);
+ PTHREAD_SLEEP (delay);
if (dht == NULL)
return SYSERR;
- dht->put(key,
- ntohl(value->type),
- ntohl(value->size) - sizeof(Datastore_Value),
- ntohll(value->expirationTime),
- (const char*) &value[1]);
+ dht->put (key,
+ ntohl (value->type),
+ ntohl (value->size) - sizeof (Datastore_Value),
+ ntohll (value->expirationTime), (const char *) &value[1]);
if (stats != NULL)
- stats->change(stat_push_count, 1);
+ stats->change (stat_push_count, 1);
if (dht == NULL)
return SYSERR;
return OK;
}
-static void * push_thread(void * cls) {
- while ( (dht != NULL) &&
- (sqstore != NULL) ) {
- if (total == 0)
- total = 1;
- total = sqstore->iterateNonAnonymous(0,
- YES,
- &push_callback,
- NULL);
- if ( (dht != NULL) &&
- (total == 0) )
- PTHREAD_SLEEP(15 * cronMINUTES);
- }
+static void *
+push_thread (void *cls)
+{
+ while ((dht != NULL) && (sqstore != NULL))
+ {
+ if (total == 0)
+ total = 1;
+ total = sqstore->iterateNonAnonymous (0, YES, &push_callback, NULL);
+ if ((dht != NULL) && (total == 0))
+ PTHREAD_SLEEP (15 * cronMINUTES);
+ }
return NULL;
}
@@ -122,41 +120,46 @@
/**
* Initialize the migration module.
*/
-void init_dht_push(CoreAPIForApplication * capi,
- DHT_ServiceAPI * d) {
+void
+init_dht_push (CoreAPIForApplication * capi, DHT_ServiceAPI * d)
+{
coreAPI = capi;
dht = d;
- sqstore = capi->requestService("sqstore");
- if (sqstore == NULL) {
- GE_BREAK(capi->ectx, 0);
- return;
- }
- stats = capi->requestService("stats");
+ sqstore = capi->requestService ("sqstore");
+ if (sqstore == NULL)
+ {
+ GE_BREAK (capi->ectx, 0);
+ return;
+ }
+ stats = capi->requestService ("stats");
if (stats != NULL)
stat_push_count
- = stats->create(gettext_noop("# blocks pushed into DHT"));
- if (! NO_PUSH) {
- thread = PTHREAD_CREATE(&push_thread,
- NULL,
- 1024 * 128);
- }
+ = stats->create (gettext_noop ("# blocks pushed into DHT"));
+ if (!NO_PUSH)
+ {
+ thread = PTHREAD_CREATE (&push_thread, NULL, 1024 * 128);
+ }
}
-void done_dht_push(void) {
- void * unused;
+void
+done_dht_push (void)
+{
+ void *unused;
if (sqstore == NULL)
return;
dht = NULL;
- if (thread != NULL) {
- PTHREAD_STOP_SLEEP(thread);
- PTHREAD_JOIN(thread, &unused);
- }
- coreAPI->releaseService(sqstore);
- if (stats != NULL) {
- coreAPI->releaseService(stats);
- stats = NULL;
- }
+ if (thread != NULL)
+ {
+ PTHREAD_STOP_SLEEP (thread);
+ PTHREAD_JOIN (thread, &unused);
+ }
+ coreAPI->releaseService (sqstore);
+ if (stats != NULL)
+ {
+ coreAPI->releaseService (stats);
+ stats = NULL;
+ }
coreAPI = NULL;
}
Modified: GNUnet/src/applications/fs/module/dht_push.h
===================================================================
--- GNUnet/src/applications/fs/module/dht_push.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/module/dht_push.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -34,10 +34,9 @@
/**
* Initialize the migration module.
*/
-void init_dht_push(CoreAPIForApplication * capi,
- DHT_ServiceAPI * s);
+void init_dht_push (CoreAPIForApplication * capi, DHT_ServiceAPI * s);
-void done_dht_push(void);
+void done_dht_push (void);
/* end of dht_push.h */
#endif
Modified: GNUnet/src/applications/fs/module/fs.c
===================================================================
--- GNUnet/src/applications/fs/module/fs.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/fs/module/fs.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -45,99 +45,99 @@
#define DEBUG_FS NO
-typedef struct {
- struct DHT_GET_RECORD * rec;
+typedef struct
+{
+ struct DHT_GET_RECORD *rec;
unsigned int prio;
} DHT_GET_CLS;
-typedef struct LG_Job {
+typedef struct LG_Job
+{
unsigned int keyCount;
unsigned int type;
- HashCode512 * queries;
- struct LG_Job * next;
+ HashCode512 *queries;
+ struct LG_Job *next;
} LG_Job;
/**
* Global core API.
*/
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
/**
* GAP service.
*/
-static GAP_ServiceAPI * gap;
+static GAP_ServiceAPI *gap;
/**
* DHT service. Maybe NULL!
*/
-static DHT_ServiceAPI * dht;
+static DHT_ServiceAPI *dht;
/**
* Datastore service.
*/
-static Datastore_ServiceAPI * datastore;
+static Datastore_ServiceAPI *datastore;
/**
* Traffic service.
*/
-static Traffic_ServiceAPI * traffic;
+static Traffic_ServiceAPI *traffic;
/**
* Stats service.
*/
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static int stat_expired_replies_dropped;
static int stat_valid_replies_received;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
static int migration;
-static struct SEMAPHORE * ltgSignal;
+static struct SEMAPHORE *ltgSignal;
-static struct PTHREAD * localGetProcessor;
+static struct PTHREAD *localGetProcessor;
-static LG_Job * lg_jobs;
+static LG_Job *lg_jobs;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
static Datastore_Value *
-gapWrapperToDatastoreValue(const DataContainer * value,
- int prio) {
- Datastore_Value * dv;
- const GapWrapper * gw;
+gapWrapperToDatastoreValue (const DataContainer * value, int prio)
+{
+ Datastore_Value *dv;
+ const GapWrapper *gw;
unsigned int size;
cron_t et;
cron_t now;
- if (ntohl(value->size) < sizeof(GapWrapper)) {
- GE_BREAK(ectx, 0);
- return NULL;
- }
- gw = (const GapWrapper*) value;
- size = ntohl(gw->dc.size)
- - sizeof(GapWrapper)
- + sizeof(Datastore_Value);
- dv = MALLOC(size);
- dv->size = htonl(size);
- dv->type = htonl(getTypeOfBlock(size - sizeof(Datastore_Value),
- (DBlock*) &gw[1]));
- dv->prio = htonl(prio);
- dv->anonymityLevel = htonl(0);
- et = ntohll(gw->timeout);
- now = get_time();
+ if (ntohl (value->size) < sizeof (GapWrapper))
+ {
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
+ gw = (const GapWrapper *) value;
+ size = ntohl (gw->dc.size) - sizeof (GapWrapper) + sizeof (Datastore_Value);
+ dv = MALLOC (size);
+ dv->size = htonl (size);
+ dv->type = htonl (getTypeOfBlock (size - sizeof (Datastore_Value),
+ (DBlock *) & gw[1]));
+ dv->prio = htonl (prio);
+ dv->anonymityLevel = htonl (0);
+ et = ntohll (gw->timeout);
+ now = get_time ();
/* bound ET to MAX_MIGRATION_EXP from now */
- if (et > now) {
- et -= now;
- et = et % MAX_MIGRATION_EXP;
- et += now;
- }
- dv->expirationTime = htonll(et);
- memcpy(&dv[1],
- &gw[1],
- size - sizeof(Datastore_Value));
+ if (et > now)
+ {
+ et -= now;
+ et = et % MAX_MIGRATION_EXP;
+ et += now;
+ }
+ dv->expirationTime = htonll (et);
+ memcpy (&dv[1], &gw[1], size - sizeof (Datastore_Value));
return dv;
}
@@ -152,12 +152,13 @@
* NO if the value verifies but is not stored,
* SYSERR if the value is malformed
*/
-static int gapPut(void * closure,
- const HashCode512 * query,
- const DataContainer * value,
- unsigned int prio) {
- Datastore_Value * dv;
- const GapWrapper * gw;
+static int
+gapPut (void *closure,
+ const HashCode512 * query,
+ const DataContainer * value, unsigned int prio)
+{
+ Datastore_Value *dv;
+ const GapWrapper *gw;
unsigned int size;
int ret;
HashCode512 hc;
@@ -165,109 +166,98 @@
EncName enc;
#endif
- gw = (const GapWrapper*) value;
- size = ntohl(gw->dc.size) - sizeof(GapWrapper);
- if ( (OK != getQueryFor(size,
- (const DBlock*) &gw[1],
- YES,
- &hc)) ||
- (! equalsHashCode512(&hc, query)) ) {
- GE_BREAK_OP(ectx, 0); /* value failed verification! */
- return SYSERR;
- }
- dv = gapWrapperToDatastoreValue(value, prio);
- if (dv == NULL) {
- GE_BREAK_OP(ectx, 0);
- return SYSERR;
- }
- if (YES != isDatumApplicable(ntohl(dv->type),
- ntohl(dv->size) - sizeof(Datastore_Value),
- (const DBlock*) &dv[1],
- &hc,
- 0,
- query)) {
- GE_BREAK(ectx, 0);
- FREE(dv);
- return SYSERR;
- }
+ gw = (const GapWrapper *) value;
+ size = ntohl (gw->dc.size) - sizeof (GapWrapper);
+ if ((OK != getQueryFor (size,
+ (const DBlock *) &gw[1],
+ YES, &hc)) || (!equalsHashCode512 (&hc, query)))
+ {
+ GE_BREAK_OP (ectx, 0); /* value failed verification! */
+ return SYSERR;
+ }
+ dv = gapWrapperToDatastoreValue (value, prio);
+ if (dv == NULL)
+ {
+ GE_BREAK_OP (ectx, 0);
+ return SYSERR;
+ }
+ if (YES != isDatumApplicable (ntohl (dv->type),
+ ntohl (dv->size) - sizeof (Datastore_Value),
+ (const DBlock *) &dv[1], &hc, 0, query))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (dv);
+ return SYSERR;
+ }
if (stats != NULL)
- stats->change(stat_valid_replies_received, 1);
- if (ntohll(dv->expirationTime) < get_time()) {
- /* do not do anything with expired data
- _except_ if it is pure content that one
- of our clients has requested -- then we
- should ignore expiration */
- if (ntohl(dv->type) == D_BLOCK)
- processResponse(query, dv);
- else if (stats != NULL)
- stats->change(stat_expired_replies_dropped, 1);
+ stats->change (stat_valid_replies_received, 1);
+ if (ntohll (dv->expirationTime) < get_time ())
+ {
+ /* do not do anything with expired data
+ _except_ if it is pure content that one
+ of our clients has requested -- then we
+ should ignore expiration */
+ if (ntohl (dv->type) == D_BLOCK)
+ processResponse (query, dv);
+ else if (stats != NULL)
+ stats->change (stat_expired_replies_dropped, 1);
- FREE(dv);
- return NO;
- }
- processResponse(query, dv);
+ FREE (dv);
+ return NO;
+ }
+ processResponse (query, dv);
#if DEBUG_FS
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(query,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FS received GAP-PUT request (query: `%s')\n",
- &enc);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (query, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FS received GAP-PUT request (query: `%s')\n", &enc);
#endif
if (migration)
- ret = datastore->putUpdate(query,
- dv);
+ ret = datastore->putUpdate (query, dv);
else
ret = OK;
- FREE(dv);
+ FREE (dv);
return ret;
}
-static int get_result_callback(const HashCode512 * query,
- const DataContainer * value,
- void * ctx) {
- DHT_GET_CLS * cls = ctx;
- const GapWrapper * gw;
+static int
+get_result_callback (const HashCode512 * query,
+ const DataContainer * value, void *ctx)
+{
+ DHT_GET_CLS *cls = ctx;
+ const GapWrapper *gw;
unsigned int size;
HashCode512 hc;
#if DEBUG_FS
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(query,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Found reply to query `%s'.\n",
- &enc);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (query, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Found reply to query `%s'.\n", &enc);
#endif
- gw = (const GapWrapper*) value;
- size = ntohl(gw->dc.size) - sizeof(GapWrapper);
- if ( (OK != getQueryFor(size,
- (const DBlock*) &gw[1],
- YES,
- &hc)) ||
- (! equalsHashCode512(&hc, query)) ) {
- GE_BREAK(NULL, 0);
- return OK;
- }
+ gw = (const GapWrapper *) value;
+ size = ntohl (gw->dc.size) - sizeof (GapWrapper);
+ if ((OK != getQueryFor (size,
+ (const DBlock *) &gw[1],
+ YES, &hc)) || (!equalsHashCode512 (&hc, query)))
+ {
+ GE_BREAK (NULL, 0);
+ return OK;
+ }
- gapPut(NULL,
- query,
- value,
- cls->prio);
+ gapPut (NULL, query, value, cls->prio);
return OK;
-}
+}
-static void get_complete_callback(void * ctx) {
- DHT_GET_CLS * cls = ctx;
- dht->get_stop(cls->rec);
- FREE(cls);
+static void
+get_complete_callback (void *ctx)
+{
+ DHT_GET_CLS *cls = ctx;
+ dht->get_stop (cls->rec);
+ FREE (cls);
}
/**
@@ -275,32 +265,33 @@
*
* @return SYSERR if the TCP connection should be closed, otherwise OK
*/
-static int csHandleRequestQueryStop(struct ClientHandle * sock,
- const MESSAGE_HEADER * req) {
- const CS_fs_request_search_MESSAGE * rs;
+static int
+csHandleRequestQueryStop (struct ClientHandle *sock,
+ const MESSAGE_HEADER * req)
+{
+ const CS_fs_request_search_MESSAGE *rs;
#if DEBUG_FS
EncName enc;
#endif
- if (ntohs(req->size) < sizeof(CS_fs_request_search_MESSAGE)) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- rs = (const CS_fs_request_search_MESSAGE*) req;
+ if (ntohs (req->size) < sizeof (CS_fs_request_search_MESSAGE))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ rs = (const CS_fs_request_search_MESSAGE *) req;
#if DEBUG_FS
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&rs->query[0],
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FS received QUERY STOP (query: `%s')\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (&rs->query[0], &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FS received QUERY STOP (query: `%s')\n", &enc);
#endif
- gap->get_stop(ntohl(rs->type),
- 1 + (ntohs(req->size) - sizeof(CS_fs_request_search_MESSAGE)) /
sizeof(HashCode512),
- &rs->query[0]);
- untrackQuery(&rs->query[0], sock);
+ gap->get_stop (ntohl (rs->type),
+ 1 + (ntohs (req->size) -
+ sizeof (CS_fs_request_search_MESSAGE)) /
+ sizeof (HashCode512), &rs->query[0]);
+ untrackQuery (&rs->query[0], sock);
return OK;
}
@@ -309,11 +300,13 @@
*
* @return SYSERR if the TCP connection should be closed, otherwise OK
*/
-static int csHandleCS_fs_request_insert_MESSAGE(struct ClientHandle * sock,
- const MESSAGE_HEADER * req) {
- const CS_fs_request_insert_MESSAGE * ri;
- Datastore_Value * datum;
- struct GE_Context * cectx;
+static int
+csHandleCS_fs_request_insert_MESSAGE (struct ClientHandle *sock,
+ const MESSAGE_HEADER * req)
+{
+ const CS_fs_request_insert_MESSAGE *ri;
+ Datastore_Value *datum;
+ struct GE_Context *cectx;
HashCode512 query;
int ret;
unsigned int type;
@@ -321,157 +314,150 @@
EncName enc;
#endif
- cectx = coreAPI->createClientLogContext(GE_USER | GE_EVENTKIND |
GE_ROUTEKIND,
- sock);
- if (ntohs(req->size) < sizeof(CS_fs_request_insert_MESSAGE)) {
- GE_BREAK(ectx, 0);
- GE_BREAK(cectx, 0);
- GE_free_context(cectx);
- return SYSERR;
- }
- ri = (const CS_fs_request_insert_MESSAGE*) req;
- datum = MALLOC(sizeof(Datastore_Value) +
- ntohs(req->size) - sizeof(CS_fs_request_insert_MESSAGE));
- datum->size = htonl(sizeof(Datastore_Value) +
- ntohs(req->size) - sizeof(CS_fs_request_insert_MESSAGE));
+ cectx =
+ coreAPI->createClientLogContext (GE_USER | GE_EVENTKIND | GE_ROUTEKIND,
+ sock);
+ if (ntohs (req->size) < sizeof (CS_fs_request_insert_MESSAGE))
+ {
+ GE_BREAK (ectx, 0);
+ GE_BREAK (cectx, 0);
+ GE_free_context (cectx);
+ return SYSERR;
+ }
+ ri = (const CS_fs_request_insert_MESSAGE *) req;
+ datum = MALLOC (sizeof (Datastore_Value) +
+ ntohs (req->size) - sizeof (CS_fs_request_insert_MESSAGE));
+ datum->size = htonl (sizeof (Datastore_Value) +
+ ntohs (req->size) -
+ sizeof (CS_fs_request_insert_MESSAGE));
datum->expirationTime = ri->expiration;
datum->prio = ri->prio;
datum->anonymityLevel = ri->anonymityLevel;
- if (OK != getQueryFor(ntohs(ri->header.size) -
sizeof(CS_fs_request_insert_MESSAGE),
- (const DBlock*)&ri[1],
- YES,
- &query)) {
- GE_BREAK(ectx, 0);
- GE_BREAK(cectx, 0);
- FREE(datum);
- GE_free_context(cectx);
- return SYSERR;
- }
- type = getTypeOfBlock(ntohs(ri->header.size) -
sizeof(CS_fs_request_insert_MESSAGE),
- (const DBlock*) &ri[1]);
+ if (OK !=
+ getQueryFor (ntohs (ri->header.size) -
+ sizeof (CS_fs_request_insert_MESSAGE),
+ (const DBlock *) &ri[1], YES, &query))
+ {
+ GE_BREAK (ectx, 0);
+ GE_BREAK (cectx, 0);
+ FREE (datum);
+ GE_free_context (cectx);
+ return SYSERR;
+ }
+ type =
+ getTypeOfBlock (ntohs (ri->header.size) -
+ sizeof (CS_fs_request_insert_MESSAGE),
+ (const DBlock *) &ri[1]);
#if DEBUG_FS
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&query,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FS received REQUEST INSERT (query: `%s', type: %u, priority %u)\n",
- &enc,
- type,
- ntohl(ri->prio));
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (&query, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FS received REQUEST INSERT (query: `%s', type: %u, priority %u)\n",
+ &enc, type, ntohl (ri->prio));
#endif
- datum->type = htonl(type);
- memcpy(&datum[1],
- &ri[1],
- ntohs(req->size) - sizeof(CS_fs_request_insert_MESSAGE));
- MUTEX_LOCK(lock);
- if ( (type != D_BLOCK) ||
- (0 == datastore->get(&query,
- type,
- NULL,
- NULL)) )
- ret = datastore->put(&query,
- datum);
+ datum->type = htonl (type);
+ memcpy (&datum[1],
+ &ri[1], ntohs (req->size) - sizeof (CS_fs_request_insert_MESSAGE));
+ MUTEX_LOCK (lock);
+ if ((type != D_BLOCK) || (0 == datastore->get (&query, type, NULL, NULL)))
+ ret = datastore->put (&query, datum);
else
ret = OK;
- MUTEX_UNLOCK(lock);
- if ( (ntohl(ri->anonymityLevel) == 0) &&
- (dht != NULL) ) {
- GapWrapper * gw;
- unsigned int size;
- cron_t now;
- cron_t et;
- HashCode512 hc;
+ MUTEX_UNLOCK (lock);
+ if ((ntohl (ri->anonymityLevel) == 0) && (dht != NULL))
+ {
+ GapWrapper *gw;
+ unsigned int size;
+ cron_t now;
+ cron_t et;
+ HashCode512 hc;
- size = sizeof(GapWrapper) +
- ntohs(ri->header.size) - sizeof(CS_fs_request_insert_MESSAGE);
- gw = MALLOC(size);
- gw->reserved = 0;
- gw->dc.size = htonl(size);
- et = ntohll(ri->expiration);
- /* expiration time normalization and randomization */
- now = get_time();
- if (et > now) {
- et -= now;
- et = et % MAX_MIGRATION_EXP;
- if (et > 0)
- et = weak_randomi(et);
- et = et + now;
+ size = sizeof (GapWrapper) +
+ ntohs (ri->header.size) - sizeof (CS_fs_request_insert_MESSAGE);
+ gw = MALLOC (size);
+ gw->reserved = 0;
+ gw->dc.size = htonl (size);
+ et = ntohll (ri->expiration);
+ /* expiration time normalization and randomization */
+ now = get_time ();
+ if (et > now)
+ {
+ et -= now;
+ et = et % MAX_MIGRATION_EXP;
+ if (et > 0)
+ et = weak_randomi (et);
+ et = et + now;
+ }
+ gw->timeout = htonll (et);
+ memcpy (&gw[1], &ri[1], size - sizeof (GapWrapper));
+ /* sanity check */
+ if ((OK != getQueryFor (size - sizeof (GapWrapper),
+ (const DBlock *) &gw[1],
+ YES,
+ &hc)) || (!equalsHashCode512 (&hc, &query)))
+ {
+ GE_BREAK (NULL, 0);
+ }
+ else
+ {
+ dht->put (&query, type, size, et, (const char *) gw);
+ }
+ FREE (gw);
}
- gw->timeout = htonll(et);
- memcpy(&gw[1],
- &ri[1],
- size - sizeof(GapWrapper));
- /* sanity check */
- if ( (OK != getQueryFor(size - sizeof(GapWrapper),
- (const DBlock*) &gw[1],
- YES,
- &hc)) ||
- (! equalsHashCode512(&hc, &query)) ) {
- GE_BREAK(NULL, 0);
- } else {
- dht->put(&query,
- type,
- size,
- et,
- (const char*) gw);
- }
- FREE(gw);
- }
- FREE(datum);
- GE_free_context(cectx);
- return coreAPI->sendValueToClient(sock,
- ret);
+ FREE (datum);
+ GE_free_context (cectx);
+ return coreAPI->sendValueToClient (sock, ret);
}
/**
* Process a request to symlink a file
*/
-static int csHandleCS_fs_request_init_index_MESSAGE(struct ClientHandle * sock,
- const MESSAGE_HEADER * req) {
+static int
+csHandleCS_fs_request_init_index_MESSAGE (struct ClientHandle *sock,
+ const MESSAGE_HEADER * req)
+{
int ret;
char *fn;
CS_fs_request_init_index_MESSAGE *ri;
int fnLen;
- struct GE_Context * cectx;
+ struct GE_Context *cectx;
- cectx = coreAPI->createClientLogContext(GE_USER | GE_EVENTKIND |
GE_ROUTEKIND,
- sock);
- if (ntohs(req->size) < sizeof(CS_fs_request_init_index_MESSAGE)) {
- GE_BREAK(ectx, 0);
- GE_BREAK(cectx, 0);
- GE_free_context(cectx);
- return SYSERR;
- }
+ cectx =
+ coreAPI->createClientLogContext (GE_USER | GE_EVENTKIND | GE_ROUTEKIND,
+ sock);
+ if (ntohs (req->size) < sizeof (CS_fs_request_init_index_MESSAGE))
+ {
+ GE_BREAK (ectx, 0);
+ GE_BREAK (cectx, 0);
+ GE_free_context (cectx);
+ return SYSERR;
+ }
ri = (CS_fs_request_init_index_MESSAGE *) req;
- fnLen = ntohs(ri->header.size) - sizeof(CS_fs_request_init_index_MESSAGE);
+ fnLen = ntohs (ri->header.size) - sizeof (CS_fs_request_init_index_MESSAGE);
#if WINDOWS
- if (fnLen > _MAX_PATH) {
- GE_BREAK(cectx, 0);
- GE_free_context(cectx);
- return SYSERR;
- }
+ if (fnLen > _MAX_PATH)
+ {
+ GE_BREAK (cectx, 0);
+ GE_free_context (cectx);
+ return SYSERR;
+ }
#endif
- fn = MALLOC(fnLen + 1);
- strncpy(fn, (char*) &ri[1], fnLen+1);
+ fn = MALLOC (fnLen + 1);
+ strncpy (fn, (char *) &ri[1], fnLen + 1);
fn[fnLen] = 0;
- ret = ONDEMAND_initIndex(cectx,
- &ri->fileId,
- fn);
+ ret = ONDEMAND_initIndex (cectx, &ri->fileId, fn);
- FREE(fn);
+ FREE (fn);
#if DEBUG_FS
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Sending confirmation (%s) of index initialization request to client\n",
- ret == OK ? "success" : "failure");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Sending confirmation (%s) of index initialization request to
client\n",
+ ret == OK ? "success" : "failure");
#endif
- GE_free_context(cectx);
- return coreAPI->sendValueToClient(sock,
- ret);
+ GE_free_context (cectx);
+ return coreAPI->sendValueToClient (sock, ret);
}
/**
@@ -479,39 +465,43 @@
*
* @return SYSERR if the TCP connection should be closed, otherwise OK
*/
-static int csHandleCS_fs_request_index_MESSAGE(struct ClientHandle * sock,
- const MESSAGE_HEADER * req) {
+static int
+csHandleCS_fs_request_index_MESSAGE (struct ClientHandle *sock,
+ const MESSAGE_HEADER * req)
+{
int ret;
- const CS_fs_request_index_MESSAGE * ri;
- struct GE_Context * cectx;
+ const CS_fs_request_index_MESSAGE *ri;
+ struct GE_Context *cectx;
- cectx = coreAPI->createClientLogContext(GE_USER | GE_EVENTKIND |
GE_ROUTEKIND,
- sock);
- if (ntohs(req->size) < sizeof(CS_fs_request_index_MESSAGE)) {
- GE_BREAK(ectx, 0);
- GE_BREAK(cectx, 0);
- GE_free_context(cectx);
- return SYSERR;
- }
- ri = (const CS_fs_request_index_MESSAGE*) req;
- ret = ONDEMAND_index(cectx,
- datastore,
- ntohl(ri->prio),
- ntohll(ri->expiration),
- ntohll(ri->fileOffset),
- ntohl(ri->anonymityLevel),
- &ri->fileId,
- ntohs(ri->header.size) - sizeof(CS_fs_request_index_MESSAGE),
- (const DBlock*) &ri[1]);
+ cectx =
+ coreAPI->createClientLogContext (GE_USER | GE_EVENTKIND | GE_ROUTEKIND,
+ sock);
+ if (ntohs (req->size) < sizeof (CS_fs_request_index_MESSAGE))
+ {
+ GE_BREAK (ectx, 0);
+ GE_BREAK (cectx, 0);
+ GE_free_context (cectx);
+ return SYSERR;
+ }
+ ri = (const CS_fs_request_index_MESSAGE *) req;
+ ret = ONDEMAND_index (cectx,
+ datastore,
+ ntohl (ri->prio),
+ ntohll (ri->expiration),
+ ntohll (ri->fileOffset),
+ ntohl (ri->anonymityLevel),
+ &ri->fileId,
+ ntohs (ri->header.size) -
+ sizeof (CS_fs_request_index_MESSAGE),
+ (const DBlock *) &ri[1]);
#if DEBUG_FS
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Sending confirmation (%s) of index request to client\n",
- ret == OK ? "success" : "failure");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Sending confirmation (%s) of index request to client\n",
+ ret == OK ? "success" : "failure");
#endif
- GE_free_context(cectx);
- return coreAPI->sendValueToClient(sock,
- ret);
+ GE_free_context (cectx);
+ return coreAPI->sendValueToClient (sock, ret);
}
/**
@@ -520,31 +510,30 @@
* abort the iteration: we found what we're looing for. Otherwise
* continue.
*/
-static int completeValue(const HashCode512 * key,
- const Datastore_Value * value,
- void * closure) {
- Datastore_Value * comp = closure;
+static int
+completeValue (const HashCode512 * key,
+ const Datastore_Value * value, void *closure)
+{
+ Datastore_Value *comp = closure;
- if ( (comp->size != value->size) ||
- (0 != memcmp(&value[1],
- &comp[1],
- ntohl(value->size) - sizeof(Datastore_Value))) ) {
+ if ((comp->size != value->size) ||
+ (0 != memcmp (&value[1],
+ &comp[1],
+ ntohl (value->size) - sizeof (Datastore_Value))))
+ {
#if DEBUG_FS
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "`%s' found value that does not match (%u, %u).\n",
- __FUNCTION__,
- ntohl(comp->size),
- ntohl(value->size));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "`%s' found value that does not match (%u, %u).\n",
+ __FUNCTION__, ntohl (comp->size), ntohl (value->size));
#endif
- return OK;
- }
- *comp = *value; /* make copy! */
+ return OK;
+ }
+ *comp = *value; /* make copy! */
#if DEBUG_FS
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "`%s' found value that matches.\n",
- __FUNCTION__);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "`%s' found value that matches.\n", __FUNCTION__);
#endif
return SYSERR;
}
@@ -554,160 +543,160 @@
*
* @return SYSERR if the TCP connection should be closed, otherwise OK
*/
-static int csHandleCS_fs_request_delete_MESSAGE(struct ClientHandle * sock,
- const MESSAGE_HEADER * req) {
+static int
+csHandleCS_fs_request_delete_MESSAGE (struct ClientHandle *sock,
+ const MESSAGE_HEADER * req)
+{
int ret;
- const CS_fs_request_delete_MESSAGE * rd;
- Datastore_Value * value;
+ const CS_fs_request_delete_MESSAGE *rd;
+ Datastore_Value *value;
HashCode512 query;
unsigned int type;
#if DEBUG_FS
EncName enc;
#endif
- struct GE_Context * cectx;
+ struct GE_Context *cectx;
- cectx = coreAPI->createClientLogContext(GE_USER | GE_EVENTKIND |
GE_ROUTEKIND,
- sock);
- if (ntohs(req->size) < sizeof(CS_fs_request_delete_MESSAGE)) {
- GE_BREAK(ectx, 0);
- GE_BREAK(cectx, 0);
- GE_free_context(cectx);
- return SYSERR;
- }
- rd = (const CS_fs_request_delete_MESSAGE*) req;
- value = MALLOC(sizeof(Datastore_Value) +
- ntohs(req->size) - sizeof(CS_fs_request_delete_MESSAGE));
- value->size = ntohl(sizeof(Datastore_Value) +
- ntohs(req->size) - sizeof(CS_fs_request_delete_MESSAGE));
- type = getTypeOfBlock(ntohs(rd->header.size) -
sizeof(CS_fs_request_delete_MESSAGE),
- (const DBlock*)&rd[1]);
- value->type = htonl(type);
- memcpy(&value[1],
- &rd[1],
- ntohs(req->size) - sizeof(CS_fs_request_delete_MESSAGE));
- if (OK != getQueryFor(ntohs(rd->header.size) -
sizeof(CS_fs_request_delete_MESSAGE),
- (const DBlock*)&rd[1],
- NO,
- &query)) {
- FREE(value);
- GE_BREAK(ectx, 0);
- GE_BREAK(cectx, 0);
- GE_free_context(cectx);
- return SYSERR;
- }
+ cectx =
+ coreAPI->createClientLogContext (GE_USER | GE_EVENTKIND | GE_ROUTEKIND,
+ sock);
+ if (ntohs (req->size) < sizeof (CS_fs_request_delete_MESSAGE))
+ {
+ GE_BREAK (ectx, 0);
+ GE_BREAK (cectx, 0);
+ GE_free_context (cectx);
+ return SYSERR;
+ }
+ rd = (const CS_fs_request_delete_MESSAGE *) req;
+ value = MALLOC (sizeof (Datastore_Value) +
+ ntohs (req->size) - sizeof (CS_fs_request_delete_MESSAGE));
+ value->size = ntohl (sizeof (Datastore_Value) +
+ ntohs (req->size) -
+ sizeof (CS_fs_request_delete_MESSAGE));
+ type =
+ getTypeOfBlock (ntohs (rd->header.size) -
+ sizeof (CS_fs_request_delete_MESSAGE),
+ (const DBlock *) &rd[1]);
+ value->type = htonl (type);
+ memcpy (&value[1],
+ &rd[1], ntohs (req->size) - sizeof (CS_fs_request_delete_MESSAGE));
+ if (OK !=
+ getQueryFor (ntohs (rd->header.size) -
+ sizeof (CS_fs_request_delete_MESSAGE),
+ (const DBlock *) &rd[1], NO, &query))
+ {
+ FREE (value);
+ GE_BREAK (ectx, 0);
+ GE_BREAK (cectx, 0);
+ GE_free_context (cectx);
+ return SYSERR;
+ }
#if DEBUG_FS
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&query,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FS received REQUEST DELETE (query: `%s', type: %u)\n",
- &enc,
- type);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (&query, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FS received REQUEST DELETE (query: `%s', type: %u)\n", &enc, type);
#endif
- MUTEX_LOCK(lock);
- if (SYSERR == datastore->get(&query,
- type,
- &completeValue,
- value)) /* aborted == found! */
- ret = datastore->del(&query,
- value);
- else /* not found */
+ MUTEX_LOCK (lock);
+ if (SYSERR == datastore->get (&query, type, &completeValue, value)) /*
aborted == found! */
+ ret = datastore->del (&query, value);
+ else /* not found */
ret = SYSERR;
- MUTEX_UNLOCK(lock);
- FREE(value);
+ MUTEX_UNLOCK (lock);
+ FREE (value);
#if DEBUG_FS
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Sending confirmation (%s) of delete request to client\n",
- ret != SYSERR ? "success" : "failure");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Sending confirmation (%s) of delete request to client\n",
+ ret != SYSERR ? "success" : "failure");
#endif
- GE_free_context(cectx);
- return coreAPI->sendValueToClient(sock,
- ret);
+ GE_free_context (cectx);
+ return coreAPI->sendValueToClient (sock, ret);
}
/**
* Process a client request unindex content.
*/
-static int csHandleCS_fs_request_unindex_MESSAGE(struct ClientHandle * sock,
- const MESSAGE_HEADER * req) {
+static int
+csHandleCS_fs_request_unindex_MESSAGE (struct ClientHandle *sock,
+ const MESSAGE_HEADER * req)
+{
int ret;
- const CS_fs_request_unindex_MESSAGE * ru;
- struct GE_Context * cectx;
+ const CS_fs_request_unindex_MESSAGE *ru;
+ struct GE_Context *cectx;
- cectx = coreAPI->createClientLogContext(GE_USER | GE_EVENTKIND |
GE_ROUTEKIND,
- sock);
- if (ntohs(req->size) != sizeof(CS_fs_request_unindex_MESSAGE)) {
- GE_BREAK(ectx, 0);
- GE_BREAK(cectx, 0);
- GE_free_context(cectx);
- return SYSERR;
- }
- ru = (const CS_fs_request_unindex_MESSAGE*) req;
+ cectx =
+ coreAPI->createClientLogContext (GE_USER | GE_EVENTKIND | GE_ROUTEKIND,
+ sock);
+ if (ntohs (req->size) != sizeof (CS_fs_request_unindex_MESSAGE))
+ {
+ GE_BREAK (ectx, 0);
+ GE_BREAK (cectx, 0);
+ GE_free_context (cectx);
+ return SYSERR;
+ }
+ ru = (const CS_fs_request_unindex_MESSAGE *) req;
#if DEBUG_FS
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FS received REQUEST UNINDEX\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "FS received REQUEST UNINDEX\n");
#endif
- ret = ONDEMAND_unindex(cectx,
- datastore,
- ntohl(ru->blocksize),
- &ru->fileId);
- GE_free_context(cectx);
- return coreAPI->sendValueToClient(sock,
- ret);
+ ret = ONDEMAND_unindex (cectx,
+ datastore, ntohl (ru->blocksize), &ru->fileId);
+ GE_free_context (cectx);
+ return coreAPI->sendValueToClient (sock, ret);
}
/**
* Process a client request to test if certain
* data is indexed.
*/
-static int csHandleCS_fs_request_test_index_MESSAGEed(struct ClientHandle *
sock,
- const MESSAGE_HEADER * req) {
+static int
+csHandleCS_fs_request_test_index_MESSAGEed (struct ClientHandle *sock,
+ const MESSAGE_HEADER * req)
+{
int ret;
- const RequestTestindex * ru;
+ const RequestTestindex *ru;
- if (ntohs(req->size) != sizeof(RequestTestindex)) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- ru = (const RequestTestindex*) req;
+ if (ntohs (req->size) != sizeof (RequestTestindex))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ ru = (const RequestTestindex *) req;
#if DEBUG_FS
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FS received REQUEST TESTINDEXED\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FS received REQUEST TESTINDEXED\n");
#endif
- ret = ONDEMAND_testindexed(datastore,
- &ru->fileId);
- return coreAPI->sendValueToClient(sock,
- ret);
+ ret = ONDEMAND_testindexed (datastore, &ru->fileId);
+ return coreAPI->sendValueToClient (sock, ret);
}
/**
* Process a client request to obtain the current
* averge priority.
*/
-static int csHandleRequestGetAvgPriority(struct ClientHandle * sock,
- const MESSAGE_HEADER * req) {
+static int
+csHandleRequestGetAvgPriority (struct ClientHandle *sock,
+ const MESSAGE_HEADER * req)
+{
#if DEBUG_FS
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FS received REQUEST GETAVGPRIORITY\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FS received REQUEST GETAVGPRIORITY\n");
#endif
- return coreAPI->sendValueToClient(sock,
- gap->getAvgPriority());
+ return coreAPI->sendValueToClient (sock, gap->getAvgPriority ());
}
/**
* Closure for the gapGetConverter method.
*/
-typedef struct {
+typedef struct
+{
DataProcessor resultCallback;
- void * resCallbackClosure;
+ void *resCallbackClosure;
unsigned int keyCount;
- const HashCode512 * keys;
+ const HashCode512 *keys;
int count;
} GGC;
@@ -716,17 +705,18 @@
* from the datastore to Blockstore values for the
* gap routing protocol.
*/
-static int gapGetConverter(const HashCode512 * key,
- const Datastore_Value * invalue,
- void * cls) {
- GGC * ggc = (GGC*) cls;
- GapWrapper * gw;
+static int
+gapGetConverter (const HashCode512 * key,
+ const Datastore_Value * invalue, void *cls)
+{
+ GGC *ggc = (GGC *) cls;
+ GapWrapper *gw;
int ret;
unsigned int size;
cron_t et;
cron_t now;
- const Datastore_Value * value;
- Datastore_Value * xvalue;
+ const Datastore_Value *value;
+ Datastore_Value *xvalue;
unsigned int level;
EncName enc;
#if EXTRA_CHECKS
@@ -734,123 +724,102 @@
#endif
#if DEBUG_FS
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(key,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Converting reply for query `%s' for gap.\n",
- &enc);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (key, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Converting reply for query `%s' for gap.\n", &enc);
#endif
- et = ntohll(invalue->expirationTime);
- now = get_time();
- if ( (et <= now) &&
- (ntohl(invalue->type) != D_BLOCK) ) {
- /* content expired and not just data -- drop! */
- return OK;
- }
+ et = ntohll (invalue->expirationTime);
+ now = get_time ();
+ if ((et <= now) && (ntohl (invalue->type) != D_BLOCK))
+ {
+ /* content expired and not just data -- drop! */
+ return OK;
+ }
- if (ntohl(invalue->type) == ONDEMAND_BLOCK) {
- if (OK != ONDEMAND_getIndexed(datastore,
- invalue,
- key,
- &xvalue))
- return SYSERR;
- value = xvalue;
- } else {
- xvalue = NULL;
- value = invalue;
- }
+ if (ntohl (invalue->type) == ONDEMAND_BLOCK)
+ {
+ if (OK != ONDEMAND_getIndexed (datastore, invalue, key, &xvalue))
+ return SYSERR;
+ value = xvalue;
+ }
+ else
+ {
+ xvalue = NULL;
+ value = invalue;
+ }
#if EXTRA_CHECKS
- if ( (OK != getQueryFor(ntohl(value->size) - sizeof(Datastore_Value),
- (const DBlock*) &value[1],
- YES,
- &hc)) ||
- (! equalsHashCode512(&hc, key)) ) {
- GE_BREAK(ectx, 0); /* value failed verification! */
- return SYSERR;
- }
+ if ((OK != getQueryFor (ntohl (value->size) - sizeof (Datastore_Value),
+ (const DBlock *) &value[1],
+ YES, &hc)) || (!equalsHashCode512 (&hc, key)))
+ {
+ GE_BREAK (ectx, 0); /* value failed verification! */
+ return SYSERR;
+ }
#endif
- ret = isDatumApplicable(ntohl(value->type),
- ntohl(value->size) - sizeof(Datastore_Value),
- (const DBlock*) &value[1],
- key,
- ggc->keyCount,
- ggc->keys);
- if (ret == SYSERR) {
- IF_GELOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- hash2enc(key,
- &enc));
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- "Converting reply for query `%s' for gap failed (datum not
applicable).\n",
- &enc);
- FREENONNULL(xvalue);
- return SYSERR; /* no query will ever match */
- }
- if (ret == NO) {
- IF_GELOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- hash2enc(key,
- &enc));
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- "Converting reply for query `%s' for gap failed (type not applicable).\n",
- &enc);
- FREENONNULL(xvalue);
- return OK; /* Additional filtering based on type;
- i.e., namespace request and namespace
- in reply does not match namespace in query */
- }
- size = sizeof(GapWrapper) +
- ntohl(value->size) -
- sizeof(Datastore_Value);
+ ret = isDatumApplicable (ntohl (value->type),
+ ntohl (value->size) - sizeof (Datastore_Value),
+ (const DBlock *) &value[1],
+ key, ggc->keyCount, ggc->keys);
+ if (ret == SYSERR)
+ {
+ IF_GELOG (ectx, GE_WARNING | GE_BULK | GE_USER, hash2enc (key, &enc));
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ "Converting reply for query `%s' for gap failed (datum not
applicable).\n",
+ &enc);
+ FREENONNULL (xvalue);
+ return SYSERR; /* no query will ever match */
+ }
+ if (ret == NO)
+ {
+ IF_GELOG (ectx, GE_WARNING | GE_BULK | GE_USER, hash2enc (key, &enc));
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ "Converting reply for query `%s' for gap failed (type not
applicable).\n",
+ &enc);
+ FREENONNULL (xvalue);
+ return OK; /* Additional filtering based on type;
+ i.e., namespace request and namespace
+ in reply does not match namespace in query
*/
+ }
+ size = sizeof (GapWrapper) + ntohl (value->size) - sizeof (Datastore_Value);
- level
- = ntohl(value->anonymityLevel);
- if (OK != checkCoverTraffic(ectx,
- traffic,
- level)) {
- /* traffic required by module not loaded;
- refuse to hand out data that requires
- anonymity! */
- FREENONNULL(xvalue);
- IF_GELOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- hash2enc(key,
- &enc));
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- "Converting reply for query `%s' for gap failed (insufficient cover
traffic).\n",
- &enc);
- return OK;
- }
- gw = MALLOC(size);
- gw->dc.size = htonl(size);
+ level = ntohl (value->anonymityLevel);
+ if (OK != checkCoverTraffic (ectx, traffic, level))
+ {
+ /* traffic required by module not loaded;
+ refuse to hand out data that requires
+ anonymity! */
+ FREENONNULL (xvalue);
+ IF_GELOG (ectx, GE_WARNING | GE_BULK | GE_USER, hash2enc (key, &enc));
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ "Converting reply for query `%s' for gap failed (insufficient
cover traffic).\n",
+ &enc);
+ return OK;
+ }
+ gw = MALLOC (size);
+ gw->dc.size = htonl (size);
/* expiration time normalization and randomization */
- if (et > now) {
- et -= now;
- et = et % MAX_MIGRATION_EXP;
- if (et > 0)
- et = weak_randomi(et);
- et = et + now;
- }
- gw->timeout = htonll(et);
- memcpy(&gw[1],
- &value[1],
- size - sizeof(GapWrapper));
+ if (et > now)
+ {
+ et -= now;
+ et = et % MAX_MIGRATION_EXP;
+ if (et > 0)
+ et = weak_randomi (et);
+ et = et + now;
+ }
+ gw->timeout = htonll (et);
+ memcpy (&gw[1], &value[1], size - sizeof (GapWrapper));
if (ggc->resultCallback != NULL)
- ret = ggc->resultCallback(key,
- &gw->dc,
- ggc->resCallbackClosure);
+ ret = ggc->resultCallback (key, &gw->dc, ggc->resCallbackClosure);
else
ret = OK;
ggc->count++;
- FREE(gw);
- FREENONNULL(xvalue);
+ FREE (gw);
+ FREENONNULL (xvalue);
return ret;
}
@@ -862,27 +831,23 @@
* @param resCallbackClosure extra argument to resultCallback
* @return number of results, SYSERR on error
*/
-static int gapGet(void * closure,
- unsigned int type,
- unsigned int prio,
- unsigned int keyCount,
- const HashCode512 * keys,
- DataProcessor resultCallback,
- void * resCallbackClosure) {
+static int
+gapGet (void *closure,
+ unsigned int type,
+ unsigned int prio,
+ unsigned int keyCount,
+ const HashCode512 * keys,
+ DataProcessor resultCallback, void *resCallbackClosure)
+{
int ret;
GGC myClosure;
#if DEBUG_FS
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&keys[0],
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "GAP requests content for `%s' of type %u\n",
- &enc,
- type);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (&keys[0], &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "GAP requests content for `%s' of type %u\n", &enc, type);
#endif
myClosure.count = 0;
myClosure.keyCount = keyCount;
@@ -890,21 +855,17 @@
myClosure.resultCallback = resultCallback;
myClosure.resCallbackClosure = resCallbackClosure;
ret = OK;
- if (type == D_BLOCK) {
- ret = datastore->get(&keys[0],
- ONDEMAND_BLOCK,
- &gapGetConverter,
- &myClosure);
- }
+ if (type == D_BLOCK)
+ {
+ ret = datastore->get (&keys[0],
+ ONDEMAND_BLOCK, &gapGetConverter, &myClosure);
+ }
if (ret != SYSERR)
- ret = datastore->get(&keys[0],
- type,
- &gapGetConverter,
- &myClosure);
+ ret = datastore->get (&keys[0], type, &gapGetConverter, &myClosure);
if (ret != SYSERR)
- ret = myClosure.count; /* return number of actual
- results (unfiltered) that
- were found */
+ ret = myClosure.count; /* return number of actual
+ results (unfiltered) that
+ were found */
return ret;
}
@@ -915,10 +876,10 @@
* @param value the value to remove, NULL for all values of the key
* @return OK if the value could be removed, SYSERR if not (i.e. not present)
*/
-static int gapDel(void * closure,
- const HashCode512 * key,
- const DataContainer * value) {
- GE_BREAK(ectx, 0); /* gap does not use 'del'! */
+static int
+gapDel (void *closure, const HashCode512 * key, const DataContainer * value)
+{
+ GE_BREAK (ectx, 0); /* gap does not use 'del'! */
return SYSERR;
}
@@ -929,76 +890,81 @@
* @param cls argument to processor
* @return number of results, SYSERR on error
*/
-static int gapIterate(void * closure,
- DataProcessor processor,
- void * cls) {
- GE_BREAK(ectx, 0); /* gap does not use 'iterate' */
+static int
+gapIterate (void *closure, DataProcessor processor, void *cls)
+{
+ GE_BREAK (ectx, 0); /* gap does not use 'iterate' */
return SYSERR;
}
-static int replyHashFunction(const DataContainer * content,
- HashCode512 * id) {
- const GapWrapper * gw;
+static int
+replyHashFunction (const DataContainer * content, HashCode512 * id)
+{
+ const GapWrapper *gw;
unsigned int size;
- size = ntohl(content->size);
- if (size < sizeof(GapWrapper)) {
- GE_BREAK(ectx, 0);
- memset(id, 0, sizeof(HashCode512));
- return SYSERR;
- }
- gw = (const GapWrapper*) content;
- hash(&gw[1],
- size - sizeof(GapWrapper),
- id);
+ size = ntohl (content->size);
+ if (size < sizeof (GapWrapper))
+ {
+ GE_BREAK (ectx, 0);
+ memset (id, 0, sizeof (HashCode512));
+ return SYSERR;
+ }
+ gw = (const GapWrapper *) content;
+ hash (&gw[1], size - sizeof (GapWrapper), id);
return OK;
}
-static int uniqueReplyIdentifier(const DataContainer * content,
- unsigned int type,
- int verify,
- const HashCode512 * primaryKey) {
+static int
+uniqueReplyIdentifier (const DataContainer * content,
+ unsigned int type,
+ int verify, const HashCode512 * primaryKey)
+{
HashCode512 q;
unsigned int t;
- const GapWrapper * gw;
+ const GapWrapper *gw;
unsigned int size;
- size = ntohl(content->size);
- if (size < sizeof(GapWrapper)) {
- GE_BREAK(ectx, 0);
- return NO;
- }
- gw = (const GapWrapper*) content;
- if ( (OK == getQueryFor(size - sizeof(GapWrapper),
- (const DBlock*) &gw[1],
- verify,
- &q)) &&
- (equalsHashCode512(&q,
- primaryKey)) &&
- ( (type == ANY_BLOCK) ||
- (type == (t = getTypeOfBlock(size - sizeof(GapWrapper),
- (const DBlock*)&gw[1]) ) ) ) ) {
- switch(type) {
- case D_BLOCK:
- return YES;
- default:
+ size = ntohl (content->size);
+ if (size < sizeof (GapWrapper))
+ {
+ GE_BREAK (ectx, 0);
return NO;
}
- } else
+ gw = (const GapWrapper *) content;
+ if ((OK == getQueryFor (size - sizeof (GapWrapper),
+ (const DBlock *) &gw[1],
+ verify,
+ &q)) &&
+ (equalsHashCode512 (&q,
+ primaryKey)) &&
+ ((type == ANY_BLOCK) ||
+ (type == (t = getTypeOfBlock (size - sizeof (GapWrapper),
+ (const DBlock *) &gw[1])))))
+ {
+ switch (type)
+ {
+ case D_BLOCK:
+ return YES;
+ default:
+ return NO;
+ }
+ }
+ else
return NO;
}
-static int fastPathProcessor(const HashCode512 * query,
- const DataContainer * value,
- void * cls) {
- Datastore_Value * dv;
+static int
+fastPathProcessor (const HashCode512 * query,
+ const DataContainer * value, void *cls)
+{
+ Datastore_Value *dv;
- dv = gapWrapperToDatastoreValue(value, 0);
+ dv = gapWrapperToDatastoreValue (value, 0);
if (dv == NULL)
return SYSERR;
- processResponse(query,
- dv);
- FREE(dv);
+ processResponse (query, dv);
+ FREE (dv);
return OK;
}
@@ -1007,23 +973,20 @@
* (essentially to establish "done" == uniqueReplyIdentifier
* as true or false.
*/
-static int fastPathProcessorFirst(const HashCode512 * query,
- const DataContainer * value,
- void * cls) {
- int * done = cls;
- Datastore_Value * dv;
+static int
+fastPathProcessorFirst (const HashCode512 * query,
+ const DataContainer * value, void *cls)
+{
+ int *done = cls;
+ Datastore_Value *dv;
- dv = gapWrapperToDatastoreValue(value, 0);
+ dv = gapWrapperToDatastoreValue (value, 0);
if (dv == NULL)
return SYSERR;
- processResponse(query,
- dv);
- if (YES == uniqueReplyIdentifier(value,
- ntohl(dv->type),
- NO,
- query))
+ processResponse (query, dv);
+ if (YES == uniqueReplyIdentifier (value, ntohl (dv->type), NO, query))
*done = YES;
- FREE(dv);
+ FREE (dv);
return SYSERR;
}
@@ -1031,47 +994,47 @@
* Thread to lookup local replies to search queries
* asynchronously.
*/
-static void * localGetter(void * noargs) {
- LG_Job * job;
- while (1) {
- SEMAPHORE_DOWN(ltgSignal, YES);
- MUTEX_LOCK(lock);
- if (lg_jobs == NULL) {
- MUTEX_UNLOCK(lock);
- break;
+static void *
+localGetter (void *noargs)
+{
+ LG_Job *job;
+ while (1)
+ {
+ SEMAPHORE_DOWN (ltgSignal, YES);
+ MUTEX_LOCK (lock);
+ if (lg_jobs == NULL)
+ {
+ MUTEX_UNLOCK (lock);
+ break;
+ }
+ job = lg_jobs;
+ lg_jobs = job->next;
+ MUTEX_UNLOCK (lock);
+ gapGet (NULL,
+ job->type,
+ EXTREME_PRIORITY,
+ job->keyCount, job->queries, &fastPathProcessor, NULL);
+ FREE (job->queries);
+ FREE (job);
}
- job = lg_jobs;
- lg_jobs = job->next;
- MUTEX_UNLOCK(lock);
- gapGet(NULL,
- job->type,
- EXTREME_PRIORITY,
- job->keyCount,
- job->queries,
- &fastPathProcessor,
- NULL);
- FREE(job->queries);
- FREE(job);
- }
return NULL;
}
-static void queueLG_Job(unsigned int type,
- unsigned int keyCount,
- const HashCode512 * queries) {
- LG_Job * job;
+static void
+queueLG_Job (unsigned int type,
+ unsigned int keyCount, const HashCode512 * queries)
+{
+ LG_Job *job;
- job = MALLOC(sizeof(LG_Job));
+ job = MALLOC (sizeof (LG_Job));
job->keyCount = keyCount;
- job->queries = MALLOC(sizeof(HashCode512) * keyCount);
- memcpy(job->queries,
- queries,
- sizeof(HashCode512) * keyCount);
- MUTEX_LOCK(lock);
+ job->queries = MALLOC (sizeof (HashCode512) * keyCount);
+ memcpy (job->queries, queries, sizeof (HashCode512) * keyCount);
+ MUTEX_LOCK (lock);
job->next = lg_jobs;
lg_jobs = job;
- MUTEX_UNLOCK(lock);
- SEMAPHORE_UP(ltgSignal);
+ MUTEX_UNLOCK (lock);
+ SEMAPHORE_UP (ltgSignal);
}
/**
@@ -1079,10 +1042,12 @@
*
* @return SYSERR if the TCP connection should be closed, otherwise OK
*/
-static int csHandleRequestQueryStart(struct ClientHandle * sock,
- const MESSAGE_HEADER * req) {
+static int
+csHandleRequestQueryStart (struct ClientHandle *sock,
+ const MESSAGE_HEADER * req)
+{
static PeerIdentity all_zeros;
- const CS_fs_request_search_MESSAGE * rs;
+ const CS_fs_request_search_MESSAGE *rs;
unsigned int keyCount;
#if DEBUG_FS
EncName enc;
@@ -1091,88 +1056,77 @@
int done;
int have_target;
- if (ntohs(req->size) < sizeof(CS_fs_request_search_MESSAGE)) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- rs = (const CS_fs_request_search_MESSAGE*) req;
- if (memcmp(&all_zeros,
- &rs->target,
- sizeof(PeerIdentity)) == 0)
+ if (ntohs (req->size) < sizeof (CS_fs_request_search_MESSAGE))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ rs = (const CS_fs_request_search_MESSAGE *) req;
+ if (memcmp (&all_zeros, &rs->target, sizeof (PeerIdentity)) == 0)
have_target = NO;
else
have_target = YES;
#if DEBUG_FS
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&rs->query[0],
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FS received QUERY START (query: `%s', ttl %llu, priority %u, anonymity
%u)\n",
- &enc,
- ntohll(rs->expiration) - get_time(),
- ntohl(rs->prio),
- ntohl(rs->anonymityLevel));
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (&rs->query[0], &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FS received QUERY START (query: `%s', ttl %llu, priority %u,
anonymity %u)\n",
+ &enc,
+ ntohll (rs->expiration) - get_time (),
+ ntohl (rs->prio), ntohl (rs->anonymityLevel));
#endif
- type = ntohl(rs->type);
- trackQuery(&rs->query[0],
- type,
- sock);
- keyCount = 1 + (ntohs(req->size) - sizeof(CS_fs_request_search_MESSAGE)) /
sizeof(HashCode512);
+ type = ntohl (rs->type);
+ trackQuery (&rs->query[0], type, sock);
+ keyCount =
+ 1 + (ntohs (req->size) -
+ sizeof (CS_fs_request_search_MESSAGE)) / sizeof (HashCode512);
/* try a "fast path" avoiding gap/dht if unique reply is locally available */
done = NO;
- gapGet(NULL,
- type,
- EXTREME_PRIORITY,
- keyCount,
- &rs->query[0],
- &fastPathProcessorFirst,
- &done);
- if (done == YES) {
+ gapGet (NULL,
+ type,
+ EXTREME_PRIORITY,
+ keyCount, &rs->query[0], &fastPathProcessorFirst, &done);
+ if (done == YES)
+ {
#if DEBUG_FS
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "FS successfully took GAP shortcut for `%s'.\n",
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "FS successfully took GAP shortcut for `%s'.\n", &enc);
#endif
- return OK;
- }
+ return OK;
+ }
/* run gapGet asynchronously (since it may take a while due to lots of IO) */
- queueLG_Job(type,
- keyCount,
- &rs->query[0]);
- gap->get_start(have_target == NO ? NULL : &rs->target,
- type,
- ntohl(rs->anonymityLevel),
- keyCount,
- &rs->query[0],
- ntohll(rs->expiration),
- ntohl(rs->prio));
- if ( (ntohl(rs->anonymityLevel) == 0) &&
- (have_target == NO) &&
- (dht != NULL) ) {
- DHT_GET_CLS * cls;
+ queueLG_Job (type, keyCount, &rs->query[0]);
+ gap->get_start (have_target == NO ? NULL : &rs->target,
+ type,
+ ntohl (rs->anonymityLevel),
+ keyCount,
+ &rs->query[0], ntohll (rs->expiration), ntohl (rs->prio));
+ if ((ntohl (rs->anonymityLevel) == 0) &&
+ (have_target == NO) && (dht != NULL))
+ {
+ DHT_GET_CLS *cls;
- cls = MALLOC(sizeof(DHT_GET_CLS));
- cls->prio = ntohl(rs->prio);
- cls->rec = dht->get_start(type,
- &rs->query[0],
- ntohll(rs->expiration),
- &get_result_callback,
- cls,
- &get_complete_callback,
- cls);
- if (cls->rec == NULL)
- FREE(cls); /* should never happen...*/
- }
+ cls = MALLOC (sizeof (DHT_GET_CLS));
+ cls->prio = ntohl (rs->prio);
+ cls->rec = dht->get_start (type,
+ &rs->query[0],
+ ntohll (rs->expiration),
+ &get_result_callback,
+ cls, &get_complete_callback, cls);
+ if (cls->rec == NULL)
+ FREE (cls); /* should never happen... */
+ }
return OK;
}
-static int fastGet(const HashCode512 * key) {
- return datastore->fast_get(key);
+static int
+fastGet (const HashCode512 * key)
+{
+ return datastore->fast_get (key);
}
/**
@@ -1181,196 +1135,222 @@
*
* @return SYSERR on errors
*/
-int initialize_module_fs(CoreAPIForApplication * capi) {
+int
+initialize_module_fs (CoreAPIForApplication * capi)
+{
static Blockstore dsGap;
unsigned long long quota;
ectx = capi->ectx;
- GE_ASSERT(ectx, sizeof(CHK) == 128);
- GE_ASSERT(ectx, sizeof(DBlock) == 4);
- GE_ASSERT(ectx, sizeof(IBlock) == 132);
- GE_ASSERT(ectx, sizeof(KBlock) == 524);
- GE_ASSERT(ectx, sizeof(SBlock) == 724);
- GE_ASSERT(ectx, sizeof(NBlock) == 716);
- GE_ASSERT(ectx, sizeof(KNBlock) == 1244);
- migration = GC_get_configuration_value_yesno(capi->cfg,
- "FS",
- "ACTIVEMIGRATION",
- YES);
+ GE_ASSERT (ectx, sizeof (CHK) == 128);
+ GE_ASSERT (ectx, sizeof (DBlock) == 4);
+ GE_ASSERT (ectx, sizeof (IBlock) == 132);
+ GE_ASSERT (ectx, sizeof (KBlock) == 524);
+ GE_ASSERT (ectx, sizeof (SBlock) == 724);
+ GE_ASSERT (ectx, sizeof (NBlock) == 716);
+ GE_ASSERT (ectx, sizeof (KNBlock) == 1244);
+ migration = GC_get_configuration_value_yesno (capi->cfg,
+ "FS", "ACTIVEMIGRATION", YES);
if (migration == SYSERR)
return SYSERR;
- if (GC_get_configuration_value_number(capi->cfg,
- "FS",
- "QUOTA",
- 1,
- ((unsigned long long)-1)/1024,
- 1024,
- "a) == -1) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("You must specify a postive number for `%s' in the configuration in
section `%s'.\n"),
- "QUOTA", "FS");
- return SYSERR;
- }
- datastore = capi->requestService("datastore");
- if (datastore == NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- traffic = capi->requestService("traffic");
- stats = capi->requestService("stats");
- if (stats != NULL) {
- stat_expired_replies_dropped
- = stats->create(gettext_noop("# FS expired replies dropped"));
- stat_valid_replies_received
- = stats->create(gettext_noop("# FS valid replies received"));
- }
- gap = capi->requestService("gap");
- if (gap == NULL) {
- GE_BREAK(ectx, 0);
- capi->releaseService(datastore);
- if (stats != NULL)
- capi->releaseService(stats);
- capi->releaseService(traffic);
- return SYSERR;
- }
- dht = capi->requestService("dht");
+ if (GC_get_configuration_value_number (capi->cfg,
+ "FS",
+ "QUOTA",
+ 1,
+ ((unsigned long long) -1) / 1024,
+ 1024, "a) == -1)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("You must specify a postive number for `%s' in the
configuration in section `%s'.\n"),
+ "QUOTA", "FS");
+ return SYSERR;
+ }
+ datastore = capi->requestService ("datastore");
+ if (datastore == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ traffic = capi->requestService ("traffic");
+ stats = capi->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_expired_replies_dropped
+ = stats->create (gettext_noop ("# FS expired replies dropped"));
+ stat_valid_replies_received
+ = stats->create (gettext_noop ("# FS valid replies received"));
+ }
+ gap = capi->requestService ("gap");
+ if (gap == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ capi->releaseService (datastore);
+ if (stats != NULL)
+ capi->releaseService (stats);
+ capi->releaseService (traffic);
+ return SYSERR;
+ }
+ dht = capi->requestService ("dht");
if (dht != NULL)
- init_dht_push(capi, dht);
- ltgSignal = SEMAPHORE_CREATE(0);
- localGetProcessor = PTHREAD_CREATE(&localGetter,
- NULL,
- 128 * 1024);
+ init_dht_push (capi, dht);
+ ltgSignal = SEMAPHORE_CREATE (0);
+ localGetProcessor = PTHREAD_CREATE (&localGetter, NULL, 128 * 1024);
if (localGetProcessor == NULL)
- GE_DIE_STRERROR(ectx,
- GE_ADMIN | GE_FATAL | GE_BULK,
- "pthread_create");
+ GE_DIE_STRERROR (ectx, GE_ADMIN | GE_FATAL | GE_BULK, "pthread_create");
coreAPI = capi;
- ONDEMAND_init(capi);
- lock = MUTEX_CREATE(NO);
+ ONDEMAND_init (capi);
+ lock = MUTEX_CREATE (NO);
dsGap.closure = NULL;
dsGap.get = &gapGet;
dsGap.put = &gapPut;
dsGap.del = &gapDel;
dsGap.iterate = &gapIterate;
dsGap.fast_get = &fastGet;
- initQueryManager(capi);
- gap->init(&dsGap,
- &uniqueReplyIdentifier,
- (ReplyHashFunction) &replyHashFunction);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _("`%s' registering client handlers %d %d %d %d %d %d %d %d %d\n"),
- "fs",
- CS_PROTO_gap_QUERY_START,
- CS_PROTO_gap_QUERY_STOP,
- CS_PROTO_gap_INSERT,
- CS_PROTO_gap_INDEX,
- CS_PROTO_gap_DELETE,
- CS_PROTO_gap_UNINDEX,
- CS_PROTO_gap_TESTINDEX,
- CS_PROTO_gap_GET_AVG_PRIORITY,
- CS_PROTO_gap_INIT_INDEX);
+ initQueryManager (capi);
+ gap->init (&dsGap,
+ &uniqueReplyIdentifier, (ReplyHashFunction) & replyHashFunction);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ _("`%s' registering client handlers %d %d %d %d %d %d %d %d %d\n"),
+ "fs",
+ CS_PROTO_gap_QUERY_START,
+ CS_PROTO_gap_QUERY_STOP,
+ CS_PROTO_gap_INSERT,
+ CS_PROTO_gap_INDEX,
+ CS_PROTO_gap_DELETE,
+ CS_PROTO_gap_UNINDEX,
+ CS_PROTO_gap_TESTINDEX,
+ CS_PROTO_gap_GET_AVG_PRIORITY, CS_PROTO_gap_INIT_INDEX);
- GE_ASSERT(ectx, SYSERR !=
capi->registerClientHandler(CS_PROTO_gap_QUERY_START,
- &csHandleRequestQueryStart));
- GE_ASSERT(ectx, SYSERR !=
capi->registerClientHandler(CS_PROTO_gap_QUERY_STOP,
- &csHandleRequestQueryStop));
- GE_ASSERT(ectx, SYSERR != capi->registerClientHandler(CS_PROTO_gap_INSERT,
-
&csHandleCS_fs_request_insert_MESSAGE));
- GE_ASSERT(ectx, SYSERR != capi->registerClientHandler(CS_PROTO_gap_INDEX,
-
&csHandleCS_fs_request_index_MESSAGE));
- GE_ASSERT(ectx, SYSERR !=
capi->registerClientHandler(CS_PROTO_gap_INIT_INDEX,
-
&csHandleCS_fs_request_init_index_MESSAGE));
- GE_ASSERT(ectx, SYSERR != capi->registerClientHandler(CS_PROTO_gap_DELETE,
-
&csHandleCS_fs_request_delete_MESSAGE));
- GE_ASSERT(ectx, SYSERR != capi->registerClientHandler(CS_PROTO_gap_UNINDEX,
-
&csHandleCS_fs_request_unindex_MESSAGE));
- GE_ASSERT(ectx, SYSERR != capi->registerClientHandler(CS_PROTO_gap_TESTINDEX,
-
&csHandleCS_fs_request_test_index_MESSAGEed));
- GE_ASSERT(ectx, SYSERR !=
capi->registerClientHandler(CS_PROTO_gap_GET_AVG_PRIORITY,
- &csHandleRequestGetAvgPriority));
- initMigration(capi,
- datastore,
- gap,
- dht,
- traffic);
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "fs",
- gettext_noop("enables (anonymous)
file-sharing")));
+ GE_ASSERT (ectx,
+ SYSERR != capi->registerClientHandler (CS_PROTO_gap_QUERY_START,
+
&csHandleRequestQueryStart));
+ GE_ASSERT (ectx,
+ SYSERR != capi->registerClientHandler (CS_PROTO_gap_QUERY_STOP,
+
&csHandleRequestQueryStop));
+ GE_ASSERT (ectx,
+ SYSERR != capi->registerClientHandler (CS_PROTO_gap_INSERT,
+
&csHandleCS_fs_request_insert_MESSAGE));
+ GE_ASSERT (ectx,
+ SYSERR != capi->registerClientHandler (CS_PROTO_gap_INDEX,
+
&csHandleCS_fs_request_index_MESSAGE));
+ GE_ASSERT (ectx,
+ SYSERR != capi->registerClientHandler (CS_PROTO_gap_INIT_INDEX,
+
&csHandleCS_fs_request_init_index_MESSAGE));
+ GE_ASSERT (ectx,
+ SYSERR != capi->registerClientHandler (CS_PROTO_gap_DELETE,
+
&csHandleCS_fs_request_delete_MESSAGE));
+ GE_ASSERT (ectx,
+ SYSERR != capi->registerClientHandler (CS_PROTO_gap_UNINDEX,
+
&csHandleCS_fs_request_unindex_MESSAGE));
+ GE_ASSERT (ectx,
+ SYSERR != capi->registerClientHandler (CS_PROTO_gap_TESTINDEX,
+
&csHandleCS_fs_request_test_index_MESSAGEed));
+ GE_ASSERT (ectx,
+ SYSERR !=
+ capi->registerClientHandler (CS_PROTO_gap_GET_AVG_PRIORITY,
+ &csHandleRequestGetAvgPriority));
+ initMigration (capi, datastore, gap, dht, traffic);
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "fs",
+ gettext_noop
+ ("enables (anonymous)
file-sharing")));
return OK;
}
-void done_module_fs() {
- LG_Job * job;
- void * unused;
+void
+done_module_fs ()
+{
+ LG_Job *job;
+ void *unused;
- doneMigration();
- GE_ASSERT(ectx, SYSERR !=
coreAPI->unregisterClientHandler(CS_PROTO_gap_QUERY_START,
- &csHandleRequestQueryStart));
- GE_ASSERT(ectx, SYSERR !=
coreAPI->unregisterClientHandler(CS_PROTO_gap_QUERY_STOP,
- &csHandleRequestQueryStop));
- GE_ASSERT(ectx, SYSERR !=
coreAPI->unregisterClientHandler(CS_PROTO_gap_INSERT,
-
&csHandleCS_fs_request_insert_MESSAGE));
- GE_ASSERT(ectx, SYSERR !=
coreAPI->unregisterClientHandler(CS_PROTO_gap_INDEX,
-
&csHandleCS_fs_request_index_MESSAGE));
- GE_ASSERT(ectx, SYSERR !=
coreAPI->unregisterClientHandler(CS_PROTO_gap_INIT_INDEX,
-
&csHandleCS_fs_request_init_index_MESSAGE));
- GE_ASSERT(ectx, SYSERR !=
coreAPI->unregisterClientHandler(CS_PROTO_gap_DELETE,
-
&csHandleCS_fs_request_delete_MESSAGE));
- GE_ASSERT(ectx, SYSERR !=
coreAPI->unregisterClientHandler(CS_PROTO_gap_UNINDEX,
-
&csHandleCS_fs_request_unindex_MESSAGE));
- GE_ASSERT(ectx, SYSERR !=
coreAPI->unregisterClientHandler(CS_PROTO_gap_TESTINDEX,
-
&csHandleCS_fs_request_test_index_MESSAGEed));
- GE_ASSERT(ectx, SYSERR !=
coreAPI->unregisterClientHandler(CS_PROTO_gap_GET_AVG_PRIORITY,
-
&csHandleRequestGetAvgPriority));
- doneQueryManager();
- while (lg_jobs != NULL) {
- job = lg_jobs->next;
- FREE(lg_jobs->queries);
- FREE(lg_jobs);
- lg_jobs = job;
- }
- SEMAPHORE_UP(ltgSignal); /* lg_jobs == NULL => thread will terminate */
- PTHREAD_JOIN(localGetProcessor,
- &unused);
- coreAPI->releaseService(datastore);
+ doneMigration ();
+ GE_ASSERT (ectx,
+ SYSERR !=
+ coreAPI->unregisterClientHandler (CS_PROTO_gap_QUERY_START,
+ &csHandleRequestQueryStart));
+ GE_ASSERT (ectx,
+ SYSERR !=
+ coreAPI->unregisterClientHandler (CS_PROTO_gap_QUERY_STOP,
+ &csHandleRequestQueryStop));
+ GE_ASSERT (ectx,
+ SYSERR != coreAPI->unregisterClientHandler (CS_PROTO_gap_INSERT,
+
&csHandleCS_fs_request_insert_MESSAGE));
+ GE_ASSERT (ectx,
+ SYSERR != coreAPI->unregisterClientHandler (CS_PROTO_gap_INDEX,
+
&csHandleCS_fs_request_index_MESSAGE));
+ GE_ASSERT (ectx,
+ SYSERR !=
+ coreAPI->unregisterClientHandler (CS_PROTO_gap_INIT_INDEX,
+
&csHandleCS_fs_request_init_index_MESSAGE));
+ GE_ASSERT (ectx,
+ SYSERR != coreAPI->unregisterClientHandler (CS_PROTO_gap_DELETE,
+
&csHandleCS_fs_request_delete_MESSAGE));
+ GE_ASSERT (ectx,
+ SYSERR != coreAPI->unregisterClientHandler (CS_PROTO_gap_UNINDEX,
+
&csHandleCS_fs_request_unindex_MESSAGE));
+ GE_ASSERT (ectx,
+ SYSERR !=
+ coreAPI->unregisterClientHandler (CS_PROTO_gap_TESTINDEX,
+
&csHandleCS_fs_request_test_index_MESSAGEed));
+ GE_ASSERT (ectx,
+ SYSERR !=
+ coreAPI->unregisterClientHandler (CS_PROTO_gap_GET_AVG_PRIORITY,
+
&csHandleRequestGetAvgPriority));
+ doneQueryManager ();
+ while (lg_jobs != NULL)
+ {
+ job = lg_jobs->next;
+ FREE (lg_jobs->queries);
+ FREE (lg_jobs);
+ lg_jobs = job;
+ }
+ SEMAPHORE_UP (ltgSignal); /* lg_jobs == NULL => thread will terminate */
+ PTHREAD_JOIN (localGetProcessor, &unused);
+ coreAPI->releaseService (datastore);
datastore = NULL;
- if (stats != NULL) {
- coreAPI->releaseService(stats);
- stats = NULL;
- }
- coreAPI->releaseService(gap);
+ if (stats != NULL)
+ {
+ coreAPI->releaseService (stats);
+ stats = NULL;
+ }
+ coreAPI->releaseService (gap);
gap = NULL;
- if (dht != NULL) {
- done_dht_push();
- coreAPI->releaseService(dht);
- dht = NULL;
- }
- if (traffic != NULL) {
- coreAPI->releaseService(traffic);
- traffic = NULL;
- }
+ if (dht != NULL)
+ {
+ done_dht_push ();
+ coreAPI->releaseService (dht);
+ dht = NULL;
+ }
+ if (traffic != NULL)
+ {
+ coreAPI->releaseService (traffic);
+ traffic = NULL;
+ }
coreAPI = NULL;
- MUTEX_DESTROY(lock);
+ MUTEX_DESTROY (lock);
lock = NULL;
- ONDEMAND_done();
- SEMAPHORE_DESTROY(ltgSignal);
+ ONDEMAND_done ();
+ SEMAPHORE_DESTROY (ltgSignal);
ltgSignal = NULL;
}
/**
* Update FS module.
*/
-void update_module_fs(UpdateAPI * uapi) {
+void
+update_module_fs (UpdateAPI * uapi)
+{
/* general sub-module updates */
- uapi->updateModule("datastore");
- uapi->updateModule("dht");
- uapi->updateModule("gap");
- uapi->updateModule("traffic");
+ uapi->updateModule ("datastore");
+ uapi->updateModule ("dht");
+ uapi->updateModule ("gap");
+ uapi->updateModule ("traffic");
}
/* end of fs.c */
Modified: GNUnet/src/applications/fs/module/migration.c
===================================================================
--- GNUnet/src/applications/fs/module/migration.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/module/migration.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -56,29 +56,29 @@
/**
* Datastore service.
*/
-static Datastore_ServiceAPI * datastore;
+static Datastore_ServiceAPI *datastore;
/**
* Global core API.
*/
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
/**
* GAP service.
*/
-static GAP_ServiceAPI * gap;
+static GAP_ServiceAPI *gap;
/**
* DHT service. Maybe NULL!
*/
-static DHT_ServiceAPI * dht;
+static DHT_ServiceAPI *dht;
/**
* Traffic service.
*/
-static Traffic_ServiceAPI * traffic;
+static Traffic_ServiceAPI *traffic;
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static int stat_migration_count;
@@ -89,10 +89,11 @@
/**
* Lock used to access content.
*/
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-struct MigrationRecord {
- Datastore_Value * value;
+struct MigrationRecord
+{
+ Datastore_Value *value;
HashCode512 key;
unsigned int receiverIndices[MAX_RECEIVERS];
unsigned int sentCount;
@@ -100,7 +101,7 @@
static struct MigrationRecord content[MAX_RECORDS];
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
/**
* Callback method for pushing content into the network.
@@ -118,17 +119,17 @@
* that buffer (must be a positive number).
*/
static unsigned int
-activeMigrationCallback(const PeerIdentity * receiver,
- void * position,
- unsigned int padding) {
+activeMigrationCallback (const PeerIdentity * receiver,
+ void *position, unsigned int padding)
+{
unsigned int ret;
- GapWrapper * gw;
+ GapWrapper *gw;
unsigned int size;
cron_t et;
cron_t now;
unsigned int anonymity;
- Datastore_Value * enc;
- Datastore_Value * value;
+ Datastore_Value *enc;
+ Datastore_Value *value;
unsigned int index;
int entry;
int discard_entry;
@@ -139,195 +140,207 @@
unsigned int dist;
unsigned int minDist;
- index = coreAPI->computeIndex(receiver);
- MUTEX_LOCK(lock);
+ index = coreAPI->computeIndex (receiver);
+ MUTEX_LOCK (lock);
entry = -1;
discard_entry = -1;
discard_match = -1;
- minDist = -1; /* max */
- for (i=0;i<MAX_RECORDS;i++) {
- if (content[i].value == NULL) {
- discard_entry = i;
- discard_match = MAX_RECEIVERS + 1;
- continue;
+ minDist = -1; /* max */
+ for (i = 0; i < MAX_RECORDS; i++)
+ {
+ if (content[i].value == NULL)
+ {
+ discard_entry = i;
+ discard_match = MAX_RECEIVERS + 1;
+ continue;
+ }
+ match = 1;
+ if (ntohl (content[i].value->size) + sizeof (GapWrapper) -
+ sizeof (Datastore_Value) <= padding)
+ {
+ match = 0;
+ for (j = 0; j < content[i].sentCount; j++)
+ {
+ if (content[i].receiverIndices[j] == index)
+ {
+ match = 1;
+ break;
+ }
+ }
+ }
+ if (match == 0)
+ {
+ dist = distanceHashCode512 (&content[i].key, &receiver->hashPubKey);
+ if (dist <= minDist)
+ {
+ entry = i;
+ minDist = dist;
+ break;
+ }
+ }
+ else
+ {
+ if ((content[i].sentCount > discard_match) || (discard_match == -1))
+ {
+ discard_match = content[i].sentCount;
+ discard_entry = i;
+ }
+ }
}
- match = 1;
- if (ntohl(content[i].value->size) + sizeof(GapWrapper) -
sizeof(Datastore_Value) <= padding) {
- match = 0;
- for (j=0;j<content[i].sentCount;j++) {
- if (content[i].receiverIndices[j] == index) {
- match = 1;
- break;
- }
- }
- }
- if (match == 0) {
- dist = distanceHashCode512(&content[i].key,
- &receiver->hashPubKey);
- if (dist <= minDist) {
- entry = i;
- minDist = dist;
- break;
- }
- } else {
- if ( (content[i].sentCount > discard_match) ||
- (discard_match == -1) ) {
- discard_match = content[i].sentCount;
- discard_entry = i;
- }
- }
- }
- if (entry == -1) {
- entry = discard_entry;
- GE_ASSERT(NULL,
- entry != -1);
- FREENONNULL(content[entry].value);
- content[entry].value = NULL;
- content[entry].sentCount = 0;
- if (OK != datastore->getRandom(&receiver->hashPubKey,
- padding,
- &content[entry].key,
- &content[entry].value,
- 0)) {
- content[entry].value = NULL; /* just to be sure...*/
- MUTEX_UNLOCK(lock);
+ if (entry == -1)
+ {
+ entry = discard_entry;
+ GE_ASSERT (NULL, entry != -1);
+ FREENONNULL (content[entry].value);
+ content[entry].value = NULL;
+ content[entry].sentCount = 0;
+ if (OK != datastore->getRandom (&receiver->hashPubKey,
+ padding,
+ &content[entry].key,
+ &content[entry].value, 0))
+ {
+ content[entry].value = NULL; /* just to be sure... */
+ MUTEX_UNLOCK (lock);
#if DEBUG_MIGRATION
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Migration: random lookup in datastore failed.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Migration: random lookup in datastore failed.\n");
#endif
+ return 0;
+ }
+ if (stats != NULL)
+ stats->change (stat_migration_factor, 1);
+ }
+ value = content[entry].value;
+ if (value == NULL)
+ {
+ GE_ASSERT (NULL, 0);
+ MUTEX_UNLOCK (lock);
return 0;
}
- if (stats != NULL)
- stats->change(stat_migration_factor, 1);
- }
- value = content[entry].value;
- if (value == NULL) {
- GE_ASSERT(NULL, 0);
- MUTEX_UNLOCK(lock);
- return 0;
- }
- size = sizeof(GapWrapper) + ntohl(value->size) - sizeof(Datastore_Value);
- if (size > padding) {
- MUTEX_UNLOCK(lock);
- return 0;
- }
+ size = sizeof (GapWrapper) + ntohl (value->size) - sizeof (Datastore_Value);
+ if (size > padding)
+ {
+ MUTEX_UNLOCK (lock);
+ return 0;
+ }
#if DEBUG_MIGRATION
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- "Migration: random lookup in datastore returned type %d.\n",
- ntohl(value->type));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_BULK | GE_USER,
+ "Migration: random lookup in datastore returned type %d.\n",
+ ntohl (value->type));
#endif
- if (ntohl(value->type) == ONDEMAND_BLOCK) {
- if (ONDEMAND_getIndexed(datastore,
- value,
- &content[entry].key,
- &enc) != OK) {
- FREENONNULL(value);
- content[entry].value = NULL;
- MUTEX_UNLOCK(lock);
+ if (ntohl (value->type) == ONDEMAND_BLOCK)
+ {
+ if (ONDEMAND_getIndexed (datastore,
+ value, &content[entry].key, &enc) != OK)
+ {
+ FREENONNULL (value);
+ content[entry].value = NULL;
+ MUTEX_UNLOCK (lock);
+ return 0;
+ }
+ if (stats != NULL)
+ stats->change (stat_on_demand_migration_attempts, 1);
+ content[entry].value = enc;
+ FREE (value);
+ value = enc;
+ }
+
+ size = sizeof (GapWrapper) + ntohl (value->size) - sizeof (Datastore_Value);
+ if (size > padding)
+ {
+ MUTEX_UNLOCK (lock);
return 0;
}
- if (stats != NULL)
- stats->change(stat_on_demand_migration_attempts, 1);
- content[entry].value = enc;
- FREE(value);
- value = enc;
- }
-
- size = sizeof(GapWrapper) + ntohl(value->size) - sizeof(Datastore_Value);
- if (size > padding) {
- MUTEX_UNLOCK(lock);
- return 0;
- }
- et = ntohll(value->expirationTime);
- now = get_time();
- if (et > now) {
- et -= now;
- et = et % MAX_MIGRATION_EXP;
- et += now;
- }
- anonymity = ntohl(value->anonymityLevel);
+ et = ntohll (value->expirationTime);
+ now = get_time ();
+ if (et > now)
+ {
+ et -= now;
+ et = et % MAX_MIGRATION_EXP;
+ et += now;
+ }
+ anonymity = ntohl (value->anonymityLevel);
ret = 0;
- if (anonymity == 0) {
- value->anonymityLevel = htonl(1);
- anonymity = 1;
- }
- if (OK == checkCoverTraffic(ectx,
- traffic,
- anonymity)) {
- gw = MALLOC(size);
- gw->dc.size = htonl(size);
- gw->timeout = htonll(et);
- memcpy(&gw[1],
- &value[1],
- size - sizeof(GapWrapper));
- ret = gap->tryMigrate(&gw->dc,
- &content[entry].key,
- position,
- padding);
- FREE(gw);
+ if (anonymity == 0)
+ {
+ value->anonymityLevel = htonl (1);
+ anonymity = 1;
+ }
+ if (OK == checkCoverTraffic (ectx, traffic, anonymity))
+ {
+ gw = MALLOC (size);
+ gw->dc.size = htonl (size);
+ gw->timeout = htonll (et);
+ memcpy (&gw[1], &value[1], size - sizeof (GapWrapper));
+ ret = gap->tryMigrate (&gw->dc, &content[entry].key, position, padding);
+ FREE (gw);
#if DEBUG_MIGRATION
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "gap's tryMigrate returned %u\n",
- ret);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "gap's tryMigrate returned %u\n", ret);
#endif
- if (ret != 0)
- content[entry].receiverIndices[content[entry].sentCount++] = index;
- }
- MUTEX_UNLOCK(lock);
- if ( (ret > 0)&&
- (stats != NULL) )
- stats->change(stat_migration_count, 1);
- GE_BREAK(NULL, ret <= padding);
+ if (ret != 0)
+ content[entry].receiverIndices[content[entry].sentCount++] = index;
+ }
+ MUTEX_UNLOCK (lock);
+ if ((ret > 0) && (stats != NULL))
+ stats->change (stat_migration_count, 1);
+ GE_BREAK (NULL, ret <= padding);
return ret;
}
-void initMigration(CoreAPIForApplication * capi,
- Datastore_ServiceAPI * ds,
- GAP_ServiceAPI * g,
- DHT_ServiceAPI * d,
- Traffic_ServiceAPI * t) {
+void
+initMigration (CoreAPIForApplication * capi,
+ Datastore_ServiceAPI * ds,
+ GAP_ServiceAPI * g, DHT_ServiceAPI * d, Traffic_ServiceAPI * t)
+{
ectx = capi->ectx;
- lock = MUTEX_CREATE(NO);
+ lock = MUTEX_CREATE (NO);
coreAPI = capi;
datastore = ds;
gap = g;
dht = d;
traffic = t;
- coreAPI->registerSendCallback(GAP_ESTIMATED_DATA_SIZE,
- &activeMigrationCallback);
- stats = capi->requestService("stats");
- if (stats != NULL) {
- stat_migration_count
- = stats->create(gettext_noop("# blocks migrated"));
- stat_migration_factor
- = stats->create(gettext_noop("# blocks fetched for migration"));
- stat_on_demand_migration_attempts
- = stats->create(gettext_noop("# on-demand block migration attempts"));
- }
+ coreAPI->registerSendCallback (GAP_ESTIMATED_DATA_SIZE,
+ &activeMigrationCallback);
+ stats = capi->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_migration_count
+ = stats->create (gettext_noop ("# blocks migrated"));
+ stat_migration_factor
+ = stats->create (gettext_noop ("# blocks fetched for migration"));
+ stat_on_demand_migration_attempts
+ =
+ stats->create (gettext_noop ("# on-demand block migration attempts"));
+ }
}
-void doneMigration() {
+void
+doneMigration ()
+{
int i;
- coreAPI->unregisterSendCallback(GAP_ESTIMATED_DATA_SIZE,
- &activeMigrationCallback);
- if (stats != NULL) {
- coreAPI->releaseService(stats);
- stats = NULL;
- }
+ coreAPI->unregisterSendCallback (GAP_ESTIMATED_DATA_SIZE,
+ &activeMigrationCallback);
+ if (stats != NULL)
+ {
+ coreAPI->releaseService (stats);
+ stats = NULL;
+ }
datastore = NULL;
gap = NULL;
dht = NULL;
coreAPI = NULL;
traffic = NULL;
- for (i=0;i<MAX_RECORDS;i++) {
- FREENONNULL(content[i].value);
- content[i].value = NULL;
- }
- MUTEX_DESTROY(lock);
+ for (i = 0; i < MAX_RECORDS; i++)
+ {
+ FREENONNULL (content[i].value);
+ content[i].value = NULL;
+ }
+ MUTEX_DESTROY (lock);
lock = NULL;
}
Modified: GNUnet/src/applications/fs/module/migration.h
===================================================================
--- GNUnet/src/applications/fs/module/migration.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/module/migration.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -81,13 +81,12 @@
/**
* Initialize the migration module.
*/
-void initMigration(CoreAPIForApplication * capi,
- Datastore_ServiceAPI * s,
- GAP_ServiceAPI * g,
- DHT_ServiceAPI * d,
- Traffic_ServiceAPI * t);
+void initMigration (CoreAPIForApplication * capi,
+ Datastore_ServiceAPI * s,
+ GAP_ServiceAPI * g,
+ DHT_ServiceAPI * d, Traffic_ServiceAPI * t);
-void doneMigration(void);
+void doneMigration (void);
/* end of migration.h */
#endif
Modified: GNUnet/src/applications/fs/module/ondemand.c
===================================================================
--- GNUnet/src/applications/fs/module/ondemand.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/module/ondemand.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -40,7 +40,8 @@
/**
* Format of an on-demand block.
*/
-typedef struct {
+typedef struct
+{
Datastore_Value header;
unsigned int type;
@@ -66,24 +67,25 @@
} OnDemandBlock;
-static char * index_directory;
+static char *index_directory;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static State_ServiceAPI * state;
+static State_ServiceAPI *state;
-static char * getOnDemandFile(const HashCode512 * fileId) {
+static char *
+getOnDemandFile (const HashCode512 * fileId)
+{
EncName enc;
- char * fn;
+ char *fn;
- hash2enc(fileId,
- &enc);
- fn = MALLOC(strlen(index_directory) + sizeof(EncName) + 1);
- strcpy(fn, index_directory);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, (char*) &enc);
+ hash2enc (fileId, &enc);
+ fn = MALLOC (strlen (index_directory) + sizeof (EncName) + 1);
+ strcpy (fn, index_directory);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, (char *) &enc);
return fn;
}
@@ -93,15 +95,16 @@
* present in the datastore. Presence is indicated
* by aborting the iteration.
*/
-static int checkPresent(const HashCode512 * key,
- const Datastore_Value * value,
- void * closure) {
- Datastore_Value * comp = closure;
+static int
+checkPresent (const HashCode512 * key,
+ const Datastore_Value * value, void *closure)
+{
+ Datastore_Value *comp = closure;
- if ( (comp->size != value->size) ||
- (0 != memcmp(&value[1],
- &comp[1],
- ntohl(value->size) - sizeof(Datastore_Value))) )
+ if ((comp->size != value->size) ||
+ (0 != memcmp (&value[1],
+ &comp[1],
+ ntohl (value->size) - sizeof (Datastore_Value))))
return OK;
return SYSERR;
}
@@ -114,53 +117,44 @@
* @return SYSERR on error, NO if symlinking failed,
* YES on success
*/
-int ONDEMAND_initIndex(struct GE_Context * cectx,
- const HashCode512 * fileId,
- const char *fn) {
+int
+ONDEMAND_initIndex (struct GE_Context *cectx,
+ const HashCode512 * fileId, const char *fn)
+{
EncName enc;
- char * serverFN;
+ char *serverFN;
char unavail_key[256];
HashCode512 linkId;
- if ( (SYSERR == getFileHash(cectx,
- fn,
- &linkId)) ||
- (! equalsHashCode512(&linkId,
- fileId)) ) {
- return NO;
- }
+ if ((SYSERR == getFileHash (cectx,
+ fn,
+ &linkId)) ||
+ (!equalsHashCode512 (&linkId, fileId)))
+ {
+ return NO;
+ }
- serverFN = MALLOC(strlen(index_directory) + 2 + sizeof(EncName));
- strcpy(serverFN,
- index_directory);
- strcat(serverFN,
- DIR_SEPARATOR_STR);
- hash2enc(fileId,
- &enc);
- strcat(serverFN,
- (char*)&enc);
- UNLINK(serverFN);
- disk_directory_create_for_file(cectx,
- serverFN);
- if (0 != SYMLINK(fn, serverFN)) {
- GE_LOG_STRERROR_FILE(cectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "symlink",
- fn);
- GE_LOG_STRERROR_FILE(cectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "symlink",
- serverFN);
- FREE(serverFN);
- return NO;
- }
- SNPRINTF(unavail_key,
- 256,
- "FIRST_UNAVAILABLE-%s",
- (char*)&enc);
- state->unlink(ectx,
- unavail_key);
- FREE(serverFN);
+ serverFN = MALLOC (strlen (index_directory) + 2 + sizeof (EncName));
+ strcpy (serverFN, index_directory);
+ strcat (serverFN, DIR_SEPARATOR_STR);
+ hash2enc (fileId, &enc);
+ strcat (serverFN, (char *) &enc);
+ UNLINK (serverFN);
+ disk_directory_create_for_file (cectx, serverFN);
+ if (0 != SYMLINK (fn, serverFN))
+ {
+ GE_LOG_STRERROR_FILE (cectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "symlink", fn);
+ GE_LOG_STRERROR_FILE (cectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "symlink", serverFN);
+ FREE (serverFN);
+ return NO;
+ }
+ SNPRINTF (unavail_key, 256, "FIRST_UNAVAILABLE-%s", (char *) &enc);
+ state->unlink (ectx, unavail_key);
+ FREE (serverFN);
return YES;
}
@@ -171,141 +165,135 @@
* @return NO if already present, YES on success,
* SYSERR on other error (i.e. datastore full)
*/
-int ONDEMAND_index(struct GE_Context * cectx,
- Datastore_ServiceAPI * datastore,
- unsigned int prio,
- cron_t expiration,
- unsigned long long fileOffset,
- unsigned int anonymityLevel,
- const HashCode512 * fileId,
- unsigned int size,
- const DBlock * content) {
+int
+ONDEMAND_index (struct GE_Context *cectx,
+ Datastore_ServiceAPI * datastore,
+ unsigned int prio,
+ cron_t expiration,
+ unsigned long long fileOffset,
+ unsigned int anonymityLevel,
+ const HashCode512 * fileId,
+ unsigned int size, const DBlock * content)
+{
int ret;
OnDemandBlock odb;
HashCode512 key;
struct stat sbuf;
- char * fn;
+ char *fn;
#if DEBUG_ONDEMAND
EncName enc;
#endif
- if (size <= sizeof(DBlock)) {
- GE_BREAK(cectx, 0);
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ if (size <= sizeof (DBlock))
+ {
+ GE_BREAK (cectx, 0);
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
- fn = getOnDemandFile(fileId);
- if ( (0 != LSTAT(fn,
- &sbuf))
+ fn = getOnDemandFile (fileId);
+ if ((0 != LSTAT (fn, &sbuf))
#ifdef S_ISLNK
- || (! S_ISLNK(sbuf.st_mode))
+ || (!S_ISLNK (sbuf.st_mode))
#endif
- ) {
- int fd;
+ )
+ {
+ int fd;
- /* not sym-linked, write content to offset! */
+ /* not sym-linked, write content to offset! */
#if DEBUG_ONDEMAND
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Storing on-demand encoded data in `%s'.\n",
- fn);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Storing on-demand encoded data in `%s'.\n", fn);
#endif
- fd = disk_file_open(cectx,
- fn,
- O_LARGEFILE | O_CREAT|O_WRONLY,
- S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); /* 644 */
- if(fd == -1) {
- FREE(fn);
- return SYSERR;
+ fd = disk_file_open (cectx, fn, O_LARGEFILE | O_CREAT | O_WRONLY,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); /* 644 */
+ if (fd == -1)
+ {
+ FREE (fn);
+ return SYSERR;
+ }
+ lseek (fd, fileOffset, SEEK_SET);
+ ret = WRITE (fd, &content[1], size - sizeof (DBlock));
+ if (ret == size - sizeof (DBlock))
+ {
+ ret = OK;
+ }
+ else
+ {
+ GE_LOG_STRERROR_FILE (cectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "write", fn);
+ ret = SYSERR;
+ }
+ CLOSE (fd);
+ if (ret == SYSERR)
+ {
+ FREE (fn);
+ return ret;
+ }
}
- lseek(fd,
- fileOffset,
- SEEK_SET);
- ret = WRITE(fd,
- &content[1],
- size - sizeof(DBlock));
- if (ret == size - sizeof(DBlock)) {
- ret = OK;
- } else {
- GE_LOG_STRERROR_FILE(cectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "write",
- fn);
- ret = SYSERR;
- }
- CLOSE(fd);
- if (ret == SYSERR) {
- FREE(fn);
- return ret;
- }
- }
- FREE(fn);
+ FREE (fn);
- odb.header.size = htonl(sizeof(OnDemandBlock));
- odb.header.type = htonl(ONDEMAND_BLOCK);
- odb.header.prio = htonl(prio);
- odb.header.anonymityLevel = htonl(anonymityLevel);
- odb.header.expirationTime = htonll(expiration);
- odb.type = htonl(ONDEMAND_BLOCK);
- odb.fileOffset = htonll(fileOffset);
- odb.blockSize = htonl(size - sizeof(DBlock));
+ odb.header.size = htonl (sizeof (OnDemandBlock));
+ odb.header.type = htonl (ONDEMAND_BLOCK);
+ odb.header.prio = htonl (prio);
+ odb.header.anonymityLevel = htonl (anonymityLevel);
+ odb.header.expirationTime = htonll (expiration);
+ odb.type = htonl (ONDEMAND_BLOCK);
+ odb.fileOffset = htonll (fileOffset);
+ odb.blockSize = htonl (size - sizeof (DBlock));
odb.fileId = *fileId;
/* compute the primary key */
- fileBlockGetQuery(content,
- size,
- &key);
+ fileBlockGetQuery (content, size, &key);
#if EXTRA_CHECKS
{
- Datastore_Value * dsvalue;
- if (OK != fileBlockEncode(content,
- size,
- &key,
- &dsvalue)) {
- GE_BREAK(cectx, 0);
- GE_BREAK(ectx, 0);
- } else {
- FREE(dsvalue);
- }
+ Datastore_Value *dsvalue;
+ if (OK != fileBlockEncode (content, size, &key, &dsvalue))
+ {
+ GE_BREAK (cectx, 0);
+ GE_BREAK (ectx, 0);
+ }
+ else
+ {
+ FREE (dsvalue);
+ }
}
#endif
#if DEBUG_ONDEMAND
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&key, &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Storing on-demand content for query `%s'\n",
- &enc);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (&key, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Storing on-demand content for query `%s'\n", &enc);
#endif
- ret = datastore->get(&key,
- ONDEMAND_BLOCK,
- &checkPresent,
- &odb.header);
- if (ret >= 0) {
- ret = datastore->put(&key,
- &odb.header);
- } else {
- ret = NO; /* already present! */
- }
+ ret = datastore->get (&key, ONDEMAND_BLOCK, &checkPresent, &odb.header);
+ if (ret >= 0)
+ {
+ ret = datastore->put (&key, &odb.header);
+ }
+ else
+ {
+ ret = NO; /* already present! */
+ }
return ret;
}
-struct adJ {
- Datastore_ServiceAPI * datastore;
- Datastore_Value * dbv;
+struct adJ
+{
+ Datastore_ServiceAPI *datastore;
+ Datastore_Value *dbv;
HashCode512 query;
};
-static void asyncDelJob(void * cls) {
- struct adJ * job = cls;
- job->datastore->del(&job->query,
- job->dbv);
- FREE(job->dbv);
- FREE(job);
+static void
+asyncDelJob (void *cls)
+{
+ struct adJ *job = cls;
+ job->datastore->del (&job->query, job->dbv);
+ FREE (job->dbv);
+ FREE (job);
}
/**
@@ -313,35 +301,29 @@
* must be done asynchronously since we are in the "get" iterator and
* a del operation during "get" would deadlock!
*/
-static void asyncDelete(Datastore_ServiceAPI * datastore,
- const Datastore_Value * dbv,
- const HashCode512 * query) {
- struct adJ * job;
+static void
+asyncDelete (Datastore_ServiceAPI * datastore,
+ const Datastore_Value * dbv, const HashCode512 * query)
+{
+ struct adJ *job;
#if DEBUG_ONDEMAND
EncName enc;
#endif
- job = MALLOC(sizeof(struct adJ));
+ job = MALLOC (sizeof (struct adJ));
job->datastore = datastore;
job->query = *query;
- job->dbv = MALLOC(ntohl(dbv->size));
- memcpy(job->dbv,
- dbv,
- ntohl(dbv->size));
+ job->dbv = MALLOC (ntohl (dbv->size));
+ memcpy (job->dbv, dbv, ntohl (dbv->size));
#if DEBUG_ONDEMAND
- hash2enc(query,
- &enc);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _("Indexed file disappeared, deleting block for query `%s'\n"),
- &enc);
+ hash2enc (query, &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ _("Indexed file disappeared, deleting block for query `%s'\n"),
+ &enc);
#endif
/* schedule for "immediate" execution */
- cron_add_job(coreAPI->cron,
- &asyncDelJob,
- 0,
- 0,
- job);
+ cron_add_job (coreAPI->cron, &asyncDelJob, 0, 0, job);
}
/**
@@ -353,172 +335,166 @@
*
* @return OK on success, SYSERR if there was an error
*/
-int ONDEMAND_getIndexed(Datastore_ServiceAPI * datastore,
- const Datastore_Value * dbv,
- const HashCode512 * query,
- Datastore_Value ** enc) {
- char * fn;
- char * iobuf;
+int
+ONDEMAND_getIndexed (Datastore_ServiceAPI * datastore,
+ const Datastore_Value * dbv,
+ const HashCode512 * query, Datastore_Value ** enc)
+{
+ char *fn;
+ char *iobuf;
int blen;
int fileHandle;
int ret;
- OnDemandBlock * odb;
- DBlock * db;
+ OnDemandBlock *odb;
+ DBlock *db;
- if (ntohl(dbv->size) != sizeof(OnDemandBlock)) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- odb = (OnDemandBlock*) dbv;
- fn = getOnDemandFile(&odb->fileId);
- if ( (YES != disk_file_test(ectx,
- fn)) ||
- (-1 == (fileHandle = disk_file_open(ectx,
- fn,
- O_LARGEFILE | O_RDONLY,
- 0))) ) {
- char unavail_key[256];
- EncName enc;
- unsigned long long * first_unavail;
- struct stat linkStat;
+ if (ntohl (dbv->size) != sizeof (OnDemandBlock))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ odb = (OnDemandBlock *) dbv;
+ fn = getOnDemandFile (&odb->fileId);
+ if ((YES != disk_file_test (ectx,
+ fn)) ||
+ (-1 == (fileHandle = disk_file_open (ectx,
+ fn, O_LARGEFILE | O_RDONLY, 0))))
+ {
+ char unavail_key[256];
+ EncName enc;
+ unsigned long long *first_unavail;
+ struct stat linkStat;
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
- "open",
- fn);
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
+ "open", fn);
- /* Is the symlink there? */
- if (LSTAT(fn, &linkStat) == -1) {
- asyncDelete(datastore, dbv, query);
- } else {
- /* For how long has the file been unavailable? */
- hash2enc(&odb->fileId,
- &enc);
- SNPRINTF(unavail_key,
- 256,
- "FIRST_UNVAILABLE-%s",
- (char *) &enc);
- if (state->read(ectx,
- unavail_key,
- (void*)&first_unavail) != sizeof(cron_t)) {
- unsigned long long now = htonll(get_time());
- state->write(ectx,
- unavail_key,
- sizeof(cron_t),
- (void *) &now);
- } else {
- /* Delete it after 3 days */
- if (ntohll(*first_unavail) - get_time() > 3 * cronDAYS) {
- unsigned int len;
- char * ofn;
- int ret;
+ /* Is the symlink there? */
+ if (LSTAT (fn, &linkStat) == -1)
+ {
+ asyncDelete (datastore, dbv, query);
+ }
+ else
+ {
+ /* For how long has the file been unavailable? */
+ hash2enc (&odb->fileId, &enc);
+ SNPRINTF (unavail_key, 256, "FIRST_UNVAILABLE-%s", (char *) &enc);
+ if (state->read (ectx,
+ unavail_key,
+ (void *) &first_unavail) != sizeof (cron_t))
+ {
+ unsigned long long now = htonll (get_time ());
+ state->write (ectx,
+ unavail_key, sizeof (cron_t), (void *) &now);
+ }
+ else
+ {
+ /* Delete it after 3 days */
+ if (ntohll (*first_unavail) - get_time () > 3 * cronDAYS)
+ {
+ unsigned int len;
+ char *ofn;
+ int ret;
- len = 256;
- ofn = MALLOC(len);
- while ( ((ret = READLINK(fn, ofn, len)) == -1) &&
- (errno == ENAMETOOLONG) &&
- (len < 4 * 1024 * 1024) )
- if (len * 2 < len) {
- GE_BREAK(ectx, 0);
- GROW(ofn, len, 0);
- FREE(fn);
- return SYSERR;
- }
- GROW(ofn,
- len,
- len*2);
-
- if (ret != -1) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Because the file `%s' has been unavailable for 3 days"
- " it got removed from your share. Please unindex files before"
- " deleting them as the index now contains invalid references!\n"),
- ofn);
- }
- FREE(ofn);
- asyncDelete(datastore, dbv, query);
- state->unlink(ectx,
- unavail_key);
- UNLINK(fn);
+ len = 256;
+ ofn = MALLOC (len);
+ while (((ret = READLINK (fn, ofn, len)) == -1) &&
+ (errno == ENAMETOOLONG) && (len < 4 * 1024 * 1024))
+ if (len * 2 < len)
+ {
+ GE_BREAK (ectx, 0);
+ GROW (ofn, len, 0);
+ FREE (fn);
+ return SYSERR;
+ }
+ GROW (ofn, len, len * 2);
+
+ if (ret != -1)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("Because the file `%s' has been unavailable for
3 days"
+ " it got removed from your share. Please
unindex files before"
+ " deleting them as the index now contains
invalid references!\n"),
+ ofn);
+ }
+ FREE (ofn);
+ asyncDelete (datastore, dbv, query);
+ state->unlink (ectx, unavail_key);
+ UNLINK (fn);
+ }
+ }
}
- }
+
+ FREE (fn);
+ return SYSERR;
}
- FREE(fn);
- return SYSERR;
- }
-
#if TRACK_INDEXED_FILES
{
- FILE * fp;
- char * afsDir;
- char * scratch;
+ FILE *fp;
+ char *afsDir;
+ char *scratch;
int n;
- afsDir = getFileName("FS",
- "DIR",
- _("Configuration file must specify directory for"
- " storage of FS data in section `%s'"
- " under `%s'.\n"));
- n = strlen(afsDir)+strlen(TRACKFILE)+8;
- scratch = MALLOC(n);
- SNPRINTF(scratch,
- n,
- "%s/%s", afsDir, TRACKFILE);
- fp = FOPEN(scratch, "a");
- FPRINTF(fp,
- "%u %llu\n",
- ntohs(ce->fileNameIndex),
- (unsigned long long)TIME(NULL));
- fclose(fp);
- FREE(scratch);
- FREE(afsDir);
+ afsDir = getFileName ("FS",
+ "DIR",
+ _("Configuration file must specify directory for"
+ " storage of FS data in section `%s'"
+ " under `%s'.\n"));
+ n = strlen (afsDir) + strlen (TRACKFILE) + 8;
+ scratch = MALLOC (n);
+ SNPRINTF (scratch, n, "%s/%s", afsDir, TRACKFILE);
+ fp = FOPEN (scratch, "a");
+ FPRINTF (fp,
+ "%u %llu\n",
+ ntohs (ce->fileNameIndex), (unsigned long long) TIME (NULL));
+ fclose (fp);
+ FREE (scratch);
+ FREE (afsDir);
}
#endif
- if (ntohll(odb->fileOffset) != lseek(fileHandle,
- ntohll(odb->fileOffset),
- SEEK_SET)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
- "lseek",
- fn);
- FREE(fn);
- CLOSE(fileHandle);
- asyncDelete(datastore, dbv, query);
- return SYSERR;
- }
- db = MALLOC(sizeof(DBlock) + ntohl(odb->blockSize));
- db->type = htonl(D_BLOCK);
- iobuf = (char*) &db[1];
- blen = READ(fileHandle,
- iobuf,
- ntohl(odb->blockSize));
- if (blen != ntohl(odb->blockSize)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
- "read",
- fn);
- FREE(fn);
- FREE(db);
- CLOSE(fileHandle);
- asyncDelete(datastore, dbv, query);
- return SYSERR;
- }
- CLOSE(fileHandle);
- ret = fileBlockEncode(db,
- ntohl(odb->blockSize) + sizeof(DBlock),
- query,
- enc);
- FREE(db);
- FREE(fn);
- if (ret == SYSERR) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Indexed content changed (does not match its hash).\n"));
- asyncDelete(datastore, dbv, query);
- return SYSERR;
- }
+ if (ntohll (odb->fileOffset) != lseek (fileHandle,
+ ntohll (odb->fileOffset), SEEK_SET))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
+ "lseek", fn);
+ FREE (fn);
+ CLOSE (fileHandle);
+ asyncDelete (datastore, dbv, query);
+ return SYSERR;
+ }
+ db = MALLOC (sizeof (DBlock) + ntohl (odb->blockSize));
+ db->type = htonl (D_BLOCK);
+ iobuf = (char *) &db[1];
+ blen = READ (fileHandle, iobuf, ntohl (odb->blockSize));
+ if (blen != ntohl (odb->blockSize))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
+ "read", fn);
+ FREE (fn);
+ FREE (db);
+ CLOSE (fileHandle);
+ asyncDelete (datastore, dbv, query);
+ return SYSERR;
+ }
+ CLOSE (fileHandle);
+ ret = fileBlockEncode (db,
+ ntohl (odb->blockSize) + sizeof (DBlock),
+ query, enc);
+ FREE (db);
+ FREE (fn);
+ if (ret == SYSERR)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Indexed content changed (does not match its hash).\n"));
+ asyncDelete (datastore, dbv, query);
+ return SYSERR;
+ }
(*enc)->anonymityLevel = dbv->anonymityLevel;
(*enc)->expirationTime = dbv->expirationTime;
@@ -531,19 +507,19 @@
* indexed.
* @return YES if so, NO if not.
*/
-int ONDEMAND_testindexed(Datastore_ServiceAPI * datastore,
- const HashCode512 * fileId) {
- char * fn;
+int
+ONDEMAND_testindexed (Datastore_ServiceAPI * datastore,
+ const HashCode512 * fileId)
+{
+ char *fn;
int fd;
- fn = getOnDemandFile(fileId);
- fd = disk_file_open(ectx,
- fn,
- O_RDONLY);
- FREE(fn);
- if(fd == -1)
+ fn = getOnDemandFile (fileId);
+ fd = disk_file_open (ectx, fn, O_RDONLY);
+ FREE (fn);
+ if (fd == -1)
return NO;
- CLOSE(fd);
+ CLOSE (fd);
return YES;
}
@@ -554,31 +530,30 @@
* abort the iteration: we found what we're looing for. Otherwise
* continue.
*/
-static int completeValue(const HashCode512 * key,
- const Datastore_Value * value,
- void * closure) {
- Datastore_Value * comp = closure;
+static int
+completeValue (const HashCode512 * key,
+ const Datastore_Value * value, void *closure)
+{
+ Datastore_Value *comp = closure;
- if ( (comp->size != value->size) ||
- (0 != memcmp(&value[1],
- &comp[1],
- ntohl(value->size) - sizeof(Datastore_Value))) ) {
+ if ((comp->size != value->size) ||
+ (0 != memcmp (&value[1],
+ &comp[1],
+ ntohl (value->size) - sizeof (Datastore_Value))))
+ {
#if DEBUG_ONDEMAND
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "`%s' found value that does not match (%u, %u).\n",
- __FUNCTION__,
- ntohl(comp->size),
- ntohl(value->size));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "`%s' found value that does not match (%u, %u).\n",
+ __FUNCTION__, ntohl (comp->size), ntohl (value->size));
#endif
- return OK;
- }
- *comp = *value; /* make copy! */
+ return OK;
+ }
+ *comp = *value; /* make copy! */
#if DEBUG_ONDEMAND
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "`%s' found value that matches.\n",
- __FUNCTION__);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "`%s' found value that matches.\n", __FUNCTION__);
#endif
return SYSERR;
}
@@ -593,11 +568,12 @@
* up the file properly when computing
* the keys of the odb blocks).
*/
-int ONDEMAND_unindex(struct GE_Context * cectx,
- Datastore_ServiceAPI * datastore,
- unsigned int blocksize,
- const HashCode512 * fileId) {
- char * fn;
+int
+ONDEMAND_unindex (struct GE_Context *cectx,
+ Datastore_ServiceAPI * datastore,
+ unsigned int blocksize, const HashCode512 * fileId)
+{
+ char *fn;
int fd;
int ret;
OnDemandBlock odb;
@@ -605,137 +581,118 @@
unsigned long long pos;
unsigned long long size;
unsigned long long delta;
- DBlock * block;
+ DBlock *block;
EncName enc;
char unavail_key[256];
- fn = getOnDemandFile(fileId);
+ fn = getOnDemandFile (fileId);
#if DEBUG_ONDEMAND
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Removing on-demand encoded data stored in `%s'.\n",
- fn);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Removing on-demand encoded data stored in `%s'.\n", fn);
#endif
- fd = disk_file_open(cectx,
- fn,
- O_RDONLY | O_LARGEFILE,
- S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); /* 644 */
- if(fd == -1) {
- FREE(fn);
- return SYSERR;
- }
+ fd = disk_file_open (cectx, fn, O_RDONLY | O_LARGEFILE, S_IRUSR | S_IWUSR |
S_IRGRP | S_IROTH); /* 644 */
+ if (fd == -1)
+ {
+ FREE (fn);
+ return SYSERR;
+ }
pos = 0;
- if (OK != disk_file_size(cectx,
- fn,
- &size,
- YES)) {
- FREE(fn);
- return SYSERR;
- }
- block = MALLOC(sizeof(DBlock) + blocksize);
- block->type = htonl(D_BLOCK);
- while (pos < size) {
- delta = size - pos;
- if (delta > blocksize)
- delta = blocksize;
- if (delta != READ(fd,
- &block[1],
- delta)) {
- GE_LOG_STRERROR_FILE(cectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "read",
- fn);
- CLOSE(fd);
- FREE(fn);
- FREE(block);
+ if (OK != disk_file_size (cectx, fn, &size, YES))
+ {
+ FREE (fn);
return SYSERR;
}
- odb.header.size = htonl(sizeof(OnDemandBlock));
- odb.header.type = htonl(ONDEMAND_BLOCK);
- odb.header.prio = 0;
- odb.header.anonymityLevel = 0;
- odb.header.expirationTime = 0;
- odb.type = htonl(ONDEMAND_BLOCK);
- odb.fileOffset = htonll(pos);
- odb.blockSize = htonl(delta);
- odb.fileId = *fileId;
- /* compute the primary key */
- fileBlockGetQuery(block,
- delta + sizeof(DBlock),
- &key);
- if (SYSERR == datastore->get(&key,
- ONDEMAND_BLOCK,
- &completeValue,
- &odb.header)) /* aborted == found! */
- ret = datastore->del(&key,
- &odb.header);
- else /* not found */
- ret = SYSERR;
- if (ret == SYSERR) {
- IF_GELOG(cectx,
- GE_WARNING | GE_BULK | GE_USER,
- hash2enc(&key,
- &enc));
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Unindexed ODB block `%s' from offset %llu already missing from
datastore.\n"),
- &enc,
- pos);
+ block = MALLOC (sizeof (DBlock) + blocksize);
+ block->type = htonl (D_BLOCK);
+ while (pos < size)
+ {
+ delta = size - pos;
+ if (delta > blocksize)
+ delta = blocksize;
+ if (delta != READ (fd, &block[1], delta))
+ {
+ GE_LOG_STRERROR_FILE (cectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "read", fn);
+ CLOSE (fd);
+ FREE (fn);
+ FREE (block);
+ return SYSERR;
+ }
+ odb.header.size = htonl (sizeof (OnDemandBlock));
+ odb.header.type = htonl (ONDEMAND_BLOCK);
+ odb.header.prio = 0;
+ odb.header.anonymityLevel = 0;
+ odb.header.expirationTime = 0;
+ odb.type = htonl (ONDEMAND_BLOCK);
+ odb.fileOffset = htonll (pos);
+ odb.blockSize = htonl (delta);
+ odb.fileId = *fileId;
+ /* compute the primary key */
+ fileBlockGetQuery (block, delta + sizeof (DBlock), &key);
+ if (SYSERR == datastore->get (&key, ONDEMAND_BLOCK, &completeValue,
&odb.header)) /* aborted == found! */
+ ret = datastore->del (&key, &odb.header);
+ else /* not found */
+ ret = SYSERR;
+ if (ret == SYSERR)
+ {
+ IF_GELOG (cectx,
+ GE_WARNING | GE_BULK | GE_USER, hash2enc (&key, &enc));
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("Unindexed ODB block `%s' from offset %llu already missing
from datastore.\n"),
+ &enc, pos);
+ }
+ pos += delta;
}
- pos += delta;
- }
- FREE(block);
- CLOSE(fd);
- UNLINK(fn);
+ FREE (block);
+ CLOSE (fd);
+ UNLINK (fn);
/* Remove information about unavailability */
- hash2enc(fileId,
- &enc);
- SNPRINTF(unavail_key,
- 256,
- "FIRST_UNAVAILABLE-%s",
- (char*)&enc);
- state->unlink(ectx,
- unavail_key);
- FREE(fn);
+ hash2enc (fileId, &enc);
+ SNPRINTF (unavail_key, 256, "FIRST_UNAVAILABLE-%s", (char *) &enc);
+ state->unlink (ectx, unavail_key);
+ FREE (fn);
return OK;
}
-int ONDEMAND_init(CoreAPIForApplication * capi) {
- char * tmp;
+int
+ONDEMAND_init (CoreAPIForApplication * capi)
+{
+ char *tmp;
coreAPI = capi;
- state = capi->requestService("state");
- if (state == NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ state = capi->requestService ("state");
+ if (state == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
ectx = capi->ectx;
- GC_get_configuration_value_filename(capi->cfg,
- "GNUNETD",
- "GNUNETD_HOME",
- VAR_DAEMON_DIRECTORY,
- &tmp);
- GE_ASSERT(ectx,
- NULL != tmp);
- tmp = REALLOC(tmp,
- strlen(tmp) +
- strlen("/data/shared/") + 1);
- strcat(tmp, "/data/shared/");
- GC_get_configuration_value_filename(capi->cfg,
- "FS",
- "INDEX-DIRECTORY",
- tmp,
- &index_directory);
- FREE(tmp);
- disk_directory_create(ectx,
- index_directory); /* just in case */
+ GC_get_configuration_value_filename (capi->cfg,
+ "GNUNETD",
+ "GNUNETD_HOME",
+ VAR_DAEMON_DIRECTORY, &tmp);
+ GE_ASSERT (ectx, NULL != tmp);
+ tmp = REALLOC (tmp, strlen (tmp) + strlen ("/data/shared/") + 1);
+ strcat (tmp, "/data/shared/");
+ GC_get_configuration_value_filename (capi->cfg,
+ "FS",
+ "INDEX-DIRECTORY",
+ tmp, &index_directory);
+ FREE (tmp);
+ disk_directory_create (ectx, index_directory); /* just in case */
return OK;
}
-int ONDEMAND_done() {
- coreAPI->releaseService(state);
+int
+ONDEMAND_done ()
+{
+ coreAPI->releaseService (state);
state = NULL;
- FREE(index_directory);
+ FREE (index_directory);
return OK;
}
Modified: GNUnet/src/applications/fs/module/ondemand.h
===================================================================
--- GNUnet/src/applications/fs/module/ondemand.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/module/ondemand.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -38,23 +38,21 @@
* @return SYSERR on error, NO if symlinking failed,
* YES on success
*/
-int ONDEMAND_initIndex(struct GE_Context * cectx,
- const HashCode512 * fileId,
- const char *fn);
+int ONDEMAND_initIndex (struct GE_Context *cectx,
+ const HashCode512 * fileId, const char *fn);
/**
* @return NO if already present, YES on success,
* SYSERR on other error (i.e. datastore full)
*/
-int ONDEMAND_index(struct GE_Context * cectx,
- Datastore_ServiceAPI * datastore,
- unsigned int prio,
- cron_t expiration,
- unsigned long long fileOffset,
- unsigned int anonymityLevel,
- const HashCode512 * fileId,
- unsigned int size,
- const DBlock * content);
+int ONDEMAND_index (struct GE_Context *cectx,
+ Datastore_ServiceAPI * datastore,
+ unsigned int prio,
+ cron_t expiration,
+ unsigned long long fileOffset,
+ unsigned int anonymityLevel,
+ const HashCode512 * fileId,
+ unsigned int size, const DBlock * content);
/**
* A query on the datastore resulted in the on-demand
@@ -64,10 +62,9 @@
* this function also removes the OD-Entry
* @return OK on success, SYSERR if there was an error
*/
-int ONDEMAND_getIndexed(Datastore_ServiceAPI * datastore,
- const Datastore_Value * odb,
- const HashCode512 * query,
- Datastore_Value ** enc);
+int ONDEMAND_getIndexed (Datastore_ServiceAPI * datastore,
+ const Datastore_Value * odb,
+ const HashCode512 * query, Datastore_Value ** enc);
/**
* Unindex the file with the given ID. Removes the file from the
@@ -79,22 +76,21 @@
* up the file properly when computing
* the keys of the odb blocks).
*/
-int ONDEMAND_unindex(struct GE_Context * cectx,
- Datastore_ServiceAPI * datastore,
- unsigned int blocksize,
- const HashCode512 * fileId);
+int ONDEMAND_unindex (struct GE_Context *cectx,
+ Datastore_ServiceAPI * datastore,
+ unsigned int blocksize, const HashCode512 * fileId);
/**
* Test if the file with the given ID is
* indexed.
* @return YES if so, NO if not.
*/
-int ONDEMAND_testindexed(Datastore_ServiceAPI * datastore,
- const HashCode512 * fileId);
+int ONDEMAND_testindexed (Datastore_ServiceAPI * datastore,
+ const HashCode512 * fileId);
-int ONDEMAND_init(CoreAPIForApplication * capi);
+int ONDEMAND_init (CoreAPIForApplication * capi);
-int ONDEMAND_done(void);
+int ONDEMAND_done (void);
/* end of ondemand.h */
#endif
Modified: GNUnet/src/applications/fs/module/querymanager.c
===================================================================
--- GNUnet/src/applications/fs/module/querymanager.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/module/querymanager.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -34,17 +34,18 @@
#define DEBUG_QUERYMANAGER NO
-typedef struct {
+typedef struct
+{
HashCode512 query;
unsigned int type;
- struct ClientHandle * client;
+ struct ClientHandle *client;
} TrackRecord;
/**
* Stats service.
*/
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static int stat_queries_tracked;
@@ -53,7 +54,7 @@
/**
* Array of the queries we are currently sending out.
*/
-static TrackRecord ** trackers;
+static TrackRecord **trackers;
static unsigned int trackerCount;
@@ -62,31 +63,34 @@
/**
* Mutex for all query manager structures.
*/
-static struct MUTEX * queryManagerLock;
+static struct MUTEX *queryManagerLock;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static void removeEntry(unsigned int off) {
- GE_ASSERT(ectx, off < trackerCount);
- FREE(trackers[off]);
+static void
+removeEntry (unsigned int off)
+{
+ GE_ASSERT (ectx, off < trackerCount);
+ FREE (trackers[off]);
if (stats != NULL)
- stats->change(stat_queries_tracked, -1);
+ stats->change (stat_queries_tracked, -1);
trackers[off] = trackers[--trackerCount];
trackers[trackerCount] = NULL;
- if ( (trackerSize > 64) &&
- (trackerSize > 2 * trackerCount) )
- GROW(trackers, trackerSize, trackerSize / 2);
+ if ((trackerSize > 64) && (trackerSize > 2 * trackerCount))
+ GROW (trackers, trackerSize, trackerSize / 2);
}
-static void ceh(struct ClientHandle * client) {
+static void
+ceh (struct ClientHandle *client)
+{
int i;
- MUTEX_LOCK(queryManagerLock);
- for (i=trackerCount-1;i>=0;i--)
+ MUTEX_LOCK (queryManagerLock);
+ for (i = trackerCount - 1; i >= 0; i--)
if (trackers[i]->client == client)
- removeEntry(i);
- MUTEX_UNLOCK(queryManagerLock);
+ removeEntry (i);
+ MUTEX_UNLOCK (queryManagerLock);
}
/**
@@ -96,23 +100,22 @@
* @param msg the query
* @param client where did the query come from?
*/
-void trackQuery(const HashCode512 * query,
- unsigned int type,
- struct ClientHandle * client) {
- GE_ASSERT(ectx, client != NULL);
- MUTEX_LOCK(queryManagerLock);
+void
+trackQuery (const HashCode512 * query,
+ unsigned int type, struct ClientHandle *client)
+{
+ GE_ASSERT (ectx, client != NULL);
+ MUTEX_LOCK (queryManagerLock);
if (trackerSize == trackerCount)
- GROW(trackers,
- trackerSize,
- trackerSize * 2);
- trackers[trackerCount] = MALLOC(sizeof(TrackRecord));
+ GROW (trackers, trackerSize, trackerSize * 2);
+ trackers[trackerCount] = MALLOC (sizeof (TrackRecord));
trackers[trackerCount]->query = *query;
trackers[trackerCount]->type = type;
trackers[trackerCount]->client = client;
trackerCount++;
if (stats != NULL)
- stats->change(stat_queries_tracked, 1);
- MUTEX_UNLOCK(queryManagerLock);
+ stats->change (stat_queries_tracked, 1);
+ MUTEX_UNLOCK (queryManagerLock);
}
/**
@@ -121,20 +124,21 @@
* @param msg the query
* @param client where did the query come from?
*/
-void untrackQuery(const HashCode512 * query,
- struct ClientHandle * client) {
+void
+untrackQuery (const HashCode512 * query, struct ClientHandle *client)
+{
int i;
- MUTEX_LOCK(queryManagerLock);
- for (i=trackerCount-1;i>=0;i--)
- if ( (trackers[i]->client == client) &&
- (equalsHashCode512(&trackers[i]->query,
- query)) ) {
- removeEntry(i);
- MUTEX_UNLOCK(queryManagerLock);
- return;
- }
- MUTEX_UNLOCK(queryManagerLock);
+ MUTEX_LOCK (queryManagerLock);
+ for (i = trackerCount - 1; i >= 0; i--)
+ if ((trackers[i]->client == client) &&
+ (equalsHashCode512 (&trackers[i]->query, query)))
+ {
+ removeEntry (i);
+ MUTEX_UNLOCK (queryManagerLock);
+ return;
+ }
+ MUTEX_UNLOCK (queryManagerLock);
}
/**
@@ -143,110 +147,110 @@
*
* @param value the response
*/
-void processResponse(const HashCode512 * key,
- const Datastore_Value * value) {
+void
+processResponse (const HashCode512 * key, const Datastore_Value * value)
+{
int i;
- CS_fs_reply_content_MESSAGE * rc;
+ CS_fs_reply_content_MESSAGE *rc;
unsigned int matchCount;
#if DEBUG_QUERYMANAGER
EncName enc;
#endif
- GE_ASSERT(ectx,
- ntohl(value->size) > sizeof(Datastore_Value));
- if ( (ntohll(value->expirationTime) < get_time()) &&
- (ntohl(value->type) != D_BLOCK) )
- return; /* ignore expired, non-data responses! */
+ GE_ASSERT (ectx, ntohl (value->size) > sizeof (Datastore_Value));
+ if ((ntohll (value->expirationTime) < get_time ()) &&
+ (ntohl (value->type) != D_BLOCK))
+ return; /* ignore expired, non-data responses! */
matchCount = 0;
#if DEBUG_QUERYMANAGER
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(key,
- &enc));
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (key, &enc));
#endif
- MUTEX_LOCK(queryManagerLock);
- for (i=trackerCount-1;i>=0;i--) {
- if ( (equalsHashCode512(&trackers[i]->query,
- key)) &&
- ( (trackers[i]->type == ANY_BLOCK) ||
- (trackers[i]->type == ntohl(value->type)) ) ) {
- matchCount++;
- rc = MALLOC(sizeof(CS_fs_reply_content_MESSAGE) +
- ntohl(value->size) - sizeof(Datastore_Value));
- rc->header.size = htons(sizeof(CS_fs_reply_content_MESSAGE) +
- ntohl(value->size) - sizeof(Datastore_Value));
- rc->header.type = htons(CS_PROTO_gap_RESULT);
- rc->anonymityLevel = value->anonymityLevel;
- rc->expirationTime = value->expirationTime;
- memcpy(&rc[1],
- &value[1],
- ntohl(value->size) - sizeof(Datastore_Value));
+ MUTEX_LOCK (queryManagerLock);
+ for (i = trackerCount - 1; i >= 0; i--)
+ {
+ if ((equalsHashCode512 (&trackers[i]->query,
+ key)) &&
+ ((trackers[i]->type == ANY_BLOCK) ||
+ (trackers[i]->type == ntohl (value->type))))
+ {
+ matchCount++;
+ rc = MALLOC (sizeof (CS_fs_reply_content_MESSAGE) +
+ ntohl (value->size) - sizeof (Datastore_Value));
+ rc->header.size = htons (sizeof (CS_fs_reply_content_MESSAGE) +
+ ntohl (value->size) -
+ sizeof (Datastore_Value));
+ rc->header.type = htons (CS_PROTO_gap_RESULT);
+ rc->anonymityLevel = value->anonymityLevel;
+ rc->expirationTime = value->expirationTime;
+ memcpy (&rc[1],
+ &value[1], ntohl (value->size) - sizeof (Datastore_Value));
#if DEBUG_QUERYMANAGER
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Sending reply for `%s' to client waiting in slot %u.\n",
- &enc,
- i);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Sending reply for `%s' to client waiting in slot %u.\n",
+ &enc, i);
#endif
- if (stats != NULL)
- stats->change(stat_replies_transmitted,
- 1);
- coreAPI->sendToClient(trackers[i]->client,
- &rc->header);
- FREE(rc);
+ if (stats != NULL)
+ stats->change (stat_replies_transmitted, 1);
+ coreAPI->sendToClient (trackers[i]->client, &rc->header);
+ FREE (rc);
+ }
}
- }
#if DEBUG_QUERYMANAGER && 0
- if (matchCount == 0) {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Reply `%s' did not match any request.\n",
- &enc);
- }
+ if (matchCount == 0)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Reply `%s' did not match any request.\n", &enc);
+ }
#endif
- MUTEX_UNLOCK(queryManagerLock);
+ MUTEX_UNLOCK (queryManagerLock);
}
/**
* Initialize the query management.
*/
-int initQueryManager(CoreAPIForApplication * capi) {
+int
+initQueryManager (CoreAPIForApplication * capi)
+{
coreAPI = capi;
ectx = capi->ectx;
- capi->registerClientExitHandler(&ceh);
- GROW(trackers,
- trackerSize,
- 64);
- queryManagerLock = MUTEX_CREATE(NO);
- stats = capi->requestService("stats");
- if (stats != NULL) {
- stat_queries_tracked
- = stats->create(gettext_noop("# FS currently tracked queries from
clients"));
- stat_replies_transmitted
- = stats->create(gettext_noop("# FS replies passed to clients"));
- }
+ capi->registerClientExitHandler (&ceh);
+ GROW (trackers, trackerSize, 64);
+ queryManagerLock = MUTEX_CREATE (NO);
+ stats = capi->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_queries_tracked
+ =
+ stats->
+ create (gettext_noop ("# FS currently tracked queries from clients"));
+ stat_replies_transmitted =
+ stats->create (gettext_noop ("# FS replies passed to clients"));
+ }
return OK;
}
-void doneQueryManager() {
+void
+doneQueryManager ()
+{
int i;
- for (i=trackerCount-1;i>=0;i--)
- FREE(trackers[i]);
+ for (i = trackerCount - 1; i >= 0; i--)
+ FREE (trackers[i]);
- GROW(trackers,
- trackerSize,
- 0);
+ GROW (trackers, trackerSize, 0);
trackerCount = 0;
- if (stats != NULL) {
- stats->set(stat_queries_tracked, 0);
- coreAPI->releaseService(stats);
- stats = NULL;
- }
+ if (stats != NULL)
+ {
+ stats->set (stat_queries_tracked, 0);
+ coreAPI->releaseService (stats);
+ stats = NULL;
+ }
- coreAPI->unregisterClientExitHandler(&ceh);
- MUTEX_DESTROY(queryManagerLock);
+ coreAPI->unregisterClientExitHandler (&ceh);
+ MUTEX_DESTROY (queryManagerLock);
coreAPI = NULL;
ectx = NULL;
}
Modified: GNUnet/src/applications/fs/module/querymanager.h
===================================================================
--- GNUnet/src/applications/fs/module/querymanager.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/module/querymanager.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -31,12 +31,12 @@
/**
* Initialize the query management.
*/
-int initQueryManager(CoreAPIForApplication * capi);
+int initQueryManager (CoreAPIForApplication * capi);
/**
* Shutdown query management.
*/
-void doneQueryManager(void);
+void doneQueryManager (void);
/**
* Keep track of a query. If a matching response
@@ -45,9 +45,8 @@
* @param msg the query
* @param client where did the query come from?
*/
-void trackQuery(const HashCode512 * query,
- unsigned int type,
- struct ClientHandle * client);
+void trackQuery (const HashCode512 * query,
+ unsigned int type, struct ClientHandle *client);
/**
* Stop keeping track of a query.
@@ -55,8 +54,7 @@
* @param msg the query
* @param client where did the query come from?
*/
-void untrackQuery(const HashCode512 * query,
- struct ClientHandle * client);
+void untrackQuery (const HashCode512 * query, struct ClientHandle *client);
/**
* We received a reply from 'responder'.
@@ -64,7 +62,6 @@
*
* @param value the response
*/
-void processResponse(const HashCode512 * key,
- const Datastore_Value * value);
+void processResponse (const HashCode512 * key, const Datastore_Value * value);
#endif
Modified: GNUnet/src/applications/fs/namespace/namespace_info.c
===================================================================
--- GNUnet/src/applications/fs/namespace/namespace_info.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/fs/namespace/namespace_info.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -36,166 +36,151 @@
#define NS_UPDATE_DIR "data" DIR_SEPARATOR_STR "namespace-updates"
DIR_SEPARATOR_STR
#define NS_ROOTS "data" DIR_SEPARATOR_STR "namespace-root" DIR_SEPARATOR_STR
-struct DiscoveryCallback {
- struct DiscoveryCallback * next;
+struct DiscoveryCallback
+{
+ struct DiscoveryCallback *next;
NS_NamespaceIterator callback;
- void * closure;
+ void *closure;
};
-static struct DiscoveryCallback * head;
+static struct DiscoveryCallback *head;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
/**
* Internal notification about new tracked URI.
*/
-static void internal_notify(const char * name,
- const HashCode512 * id,
- const struct ECRS_MetaData * md,
- int rating) {
- struct DiscoveryCallback * pos;
+static void
+internal_notify (const char *name,
+ const HashCode512 * id,
+ const struct ECRS_MetaData *md, int rating)
+{
+ struct DiscoveryCallback *pos;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
pos = head;
- while (pos != NULL) {
- pos->callback(pos->closure,
- name,
- id,
- md,
- rating);
- pos = pos->next;
- }
- MUTEX_UNLOCK(lock);
+ while (pos != NULL)
+ {
+ pos->callback (pos->closure, name, id, md, rating);
+ pos = pos->next;
+ }
+ MUTEX_UNLOCK (lock);
}
-static void writeNamespaceInfo(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * namespaceName,
- const struct ECRS_MetaData * meta,
- int ranking) {
+static void
+writeNamespaceInfo (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *namespaceName,
+ const struct ECRS_MetaData *meta, int ranking)
+{
unsigned int size;
unsigned int tag;
- char * buf;
- char * fn;
- char * fnBase;
+ char *buf;
+ char *fn;
+ char *fnBase;
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &fnBase);
- fn = MALLOC(strlen(fnBase) +
- strlen(NS_DIR) +
- strlen(namespaceName) +
- 6);
- strcpy(fn, fnBase);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, NS_DIR);
- disk_directory_create(ectx, fn);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, namespaceName);
- FREE(fnBase);
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &fnBase);
+ fn = MALLOC (strlen (fnBase) +
+ strlen (NS_DIR) + strlen (namespaceName) + 6);
+ strcpy (fn, fnBase);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, NS_DIR);
+ disk_directory_create (ectx, fn);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, namespaceName);
+ FREE (fnBase);
- size = ECRS_sizeofMetaData(meta,
- ECRS_SERIALIZE_FULL);
- tag = size + sizeof(int);
- buf = MALLOC(tag);
- ((int *) buf)[0] = htonl(ranking); /* ranking */
- GE_ASSERT(ectx,
- size == ECRS_serializeMetaData(ectx,
- meta,
- &buf[sizeof(int)],
- size,
- ECRS_SERIALIZE_FULL));
- disk_file_write(ectx,
- fn,
- buf,
- tag,
- "660");
- FREE(fn);
- FREE(buf);
+ size = ECRS_sizeofMetaData (meta, ECRS_SERIALIZE_FULL);
+ tag = size + sizeof (int);
+ buf = MALLOC (tag);
+ ((int *) buf)[0] = htonl (ranking); /* ranking */
+ GE_ASSERT (ectx,
+ size == ECRS_serializeMetaData (ectx,
+ meta,
+ &buf[sizeof (int)],
+ size, ECRS_SERIALIZE_FULL));
+ disk_file_write (ectx, fn, buf, tag, "660");
+ FREE (fn);
+ FREE (buf);
}
-static int readNamespaceInfo(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * namespaceName,
- struct ECRS_MetaData ** meta,
- int * ranking) {
+static int
+readNamespaceInfo (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *namespaceName,
+ struct ECRS_MetaData **meta, int *ranking)
+{
unsigned long long len;
unsigned int size;
- char * buf;
- char * fn;
- char * fnBase;
+ char *buf;
+ char *fn;
+ char *fnBase;
*meta = NULL;
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &fnBase);
- fn = MALLOC(strlen(fnBase) +
- strlen(NS_DIR) +
- strlen(namespaceName) +
- 6);
- strcpy(fn, fnBase);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, NS_DIR);
- disk_directory_create(ectx,
- fn);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, namespaceName);
- FREE(fnBase);
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &fnBase);
+ fn = MALLOC (strlen (fnBase) +
+ strlen (NS_DIR) + strlen (namespaceName) + 6);
+ strcpy (fn, fnBase);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, NS_DIR);
+ disk_directory_create (ectx, fn);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, namespaceName);
+ FREE (fnBase);
- if ( (OK != disk_file_test(ectx,
- fn) ||
- (OK != disk_file_size(ectx,
- fn,
- &len,
- YES)) ) ) {
- FREE(fn);
- return SYSERR;
- }
- if (len <= sizeof(int)) {
- FREE(fn);
- return SYSERR;
- }
- if (len > 16 * 1024 * 1024) {
- /* too big, must be invalid! remove! */
- GE_BREAK(ectx, 0);
- UNLINK(fn);
- FREE(fn);
- return SYSERR;
- }
- buf = MALLOC(len);
- if (len != disk_file_read(ectx,
- fn,
- len,
- buf)) {
- FREE(buf);
- FREE(fn);
- return SYSERR;
- }
+ if ((OK != disk_file_test (ectx,
+ fn) ||
+ (OK != disk_file_size (ectx, fn, &len, YES))))
+ {
+ FREE (fn);
+ return SYSERR;
+ }
+ if (len <= sizeof (int))
+ {
+ FREE (fn);
+ return SYSERR;
+ }
+ if (len > 16 * 1024 * 1024)
+ {
+ /* too big, must be invalid! remove! */
+ GE_BREAK (ectx, 0);
+ UNLINK (fn);
+ FREE (fn);
+ return SYSERR;
+ }
+ buf = MALLOC (len);
+ if (len != disk_file_read (ectx, fn, len, buf))
+ {
+ FREE (buf);
+ FREE (fn);
+ return SYSERR;
+ }
- size = len - sizeof(int);
- *ranking = ntohl(((int *) buf)[0]);
- *meta = ECRS_deserializeMetaData(ectx,
- &buf[sizeof(int)],
- size);
- if ((*meta) == NULL) {
- /* invalid data! remove! */
- GE_BREAK(ectx, 0);
- UNLINK(fn);
- FREE(buf);
- FREE(fn);
- return SYSERR;
- }
- FREE(fn);
- FREE(buf);
+ size = len - sizeof (int);
+ *ranking = ntohl (((int *) buf)[0]);
+ *meta = ECRS_deserializeMetaData (ectx, &buf[sizeof (int)], size);
+ if ((*meta) == NULL)
+ {
+ /* invalid data! remove! */
+ GE_BREAK (ectx, 0);
+ UNLINK (fn);
+ FREE (buf);
+ FREE (fn);
+ return SYSERR;
+ }
+ FREE (fn);
+ FREE (buf);
return OK;
}
-
+
/**
* Create a new namespace (and publish an advertismement).
* This function is synchronous, but may block the system
@@ -205,48 +190,38 @@
* @return namespace root URI on success, NULL on error (namespace already
exists)
*/
struct ECRS_URI *
-NS_createNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- unsigned int anonymityLevel,
- unsigned int insertPriority,
- cron_t insertExpiration,
- const char * namespaceName,
- const struct ECRS_MetaData * meta,
- const struct ECRS_URI * advertisementURI,
- const HashCode512 * rootEntry) {
- struct ECRS_URI * ret;
+NS_createNamespace (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ unsigned int anonymityLevel,
+ unsigned int insertPriority,
+ cron_t insertExpiration,
+ const char *namespaceName,
+ const struct ECRS_MetaData *meta,
+ const struct ECRS_URI *advertisementURI,
+ const HashCode512 * rootEntry)
+{
+ struct ECRS_URI *ret;
- ret = ECRS_createNamespace(ectx,
- cfg,
- namespaceName,
- meta,
- anonymityLevel,
- insertPriority,
- insertExpiration,
- advertisementURI,
- rootEntry);
+ ret = ECRS_createNamespace (ectx,
+ cfg,
+ namespaceName,
+ meta,
+ anonymityLevel,
+ insertPriority,
+ insertExpiration, advertisementURI, rootEntry);
/* store binding of namespaceName to 'meta' in state DB! */
- if (ret != NULL) {
- HashCode512 id;
- char * name;
+ if (ret != NULL)
+ {
+ HashCode512 id;
+ char *name;
- NS_setNamespaceRoot(ectx,
- cfg,
- ret);
- ECRS_getNamespaceId(ret,
- &id);
- name = ECRS_getNamespaceName(&id);
- writeNamespaceInfo(ectx,
- cfg,
- name,
- meta,
- 0);
- internal_notify(namespaceName,
- &id,
- meta,
- 0);
- FREE(name);
- }
+ NS_setNamespaceRoot (ectx, cfg, ret);
+ ECRS_getNamespaceId (ret, &id);
+ name = ECRS_getNamespaceName (&id);
+ writeNamespaceInfo (ectx, cfg, name, meta, 0);
+ internal_notify (namespaceName, &id, meta, 0);
+ FREE (name);
+ }
return ret;
}
@@ -256,29 +231,29 @@
*
* @return OK on success, SYSERR on error
*/
-int NS_deleteNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * namespaceName) {
+int
+NS_deleteNamespace (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, const char *namespaceName)
+{
int ret;
- char * tmp;
- char * fn;
+ char *tmp;
+ char *fn;
- ret = ECRS_deleteNamespace(ectx, cfg, namespaceName);
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &tmp);
- fn = MALLOC(strlen(tmp) + strlen(NS_UPDATE_DIR) +
- strlen(namespaceName) + 20);
- strcpy(fn, tmp);
- FREE(tmp);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, NS_UPDATE_DIR);
- strcat(fn, namespaceName);
- strcat(fn, DIR_SEPARATOR_STR);
- disk_directory_remove(ectx, fn);
- FREE(fn);
+ ret = ECRS_deleteNamespace (ectx, cfg, namespaceName);
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &tmp);
+ fn = MALLOC (strlen (tmp) + strlen (NS_UPDATE_DIR) +
+ strlen (namespaceName) + 20);
+ strcpy (fn, tmp);
+ FREE (tmp);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, NS_UPDATE_DIR);
+ strcat (fn, namespaceName);
+ strcat (fn, DIR_SEPARATOR_STR);
+ disk_directory_remove (ectx, fn);
+ FREE (fn);
return ret;
}
@@ -293,96 +268,78 @@
* changed?
* @return new rating of the namespace
*/
-int NS_rankNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * ns,
- int delta) {
- struct ECRS_MetaData * meta;
+int
+NS_rankNamespace (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, const char *ns, int delta)
+{
+ struct ECRS_MetaData *meta;
int ret;
int ranking;
- ret = readNamespaceInfo(ectx,
- cfg,
- ns,
- &meta,
- &ranking);
- if (ret == SYSERR) {
- ranking = 0;
- meta = ECRS_createMetaData();
- }
+ ret = readNamespaceInfo (ectx, cfg, ns, &meta, &ranking);
+ if (ret == SYSERR)
+ {
+ ranking = 0;
+ meta = ECRS_createMetaData ();
+ }
ranking += delta;
- writeNamespaceInfo(ectx,
- cfg,
- ns,
- meta,
- ranking);
- ECRS_freeMetaData(meta);
+ writeNamespaceInfo (ectx, cfg, ns, meta, ranking);
+ ECRS_freeMetaData (meta);
return ranking;
}
-typedef struct {
+typedef struct
+{
NS_NamespaceIterator iterator;
- void * closure;
- struct GE_Context * ectx;
- struct GC_Configuration * cfg;
+ void *closure;
+ struct GE_Context *ectx;
+ struct GC_Configuration *cfg;
} LNClosure;
-static int localListNamespaceHelper(const HashCode512 * nsid,
- const char * name,
- void * cls) {
- LNClosure * c = cls;
+static int
+localListNamespaceHelper (const HashCode512 * nsid,
+ const char *name, void *cls)
+{
+ LNClosure *c = cls;
int ret;
- struct ECRS_MetaData * meta;
+ struct ECRS_MetaData *meta;
int rating;
meta = NULL;
rating = 0;
- readNamespaceInfo(c->ectx,
- c->cfg,
- name,
- &meta,
- &rating);
+ readNamespaceInfo (c->ectx, c->cfg, name, &meta, &rating);
if (meta == NULL)
- meta = ECRS_createMetaData();
- if (c->iterator != NULL) {
- ret = c->iterator(c->closure,
- name,
- nsid,
- meta,
- rating);
- } else
+ meta = ECRS_createMetaData ();
+ if (c->iterator != NULL)
+ {
+ ret = c->iterator (c->closure, name, nsid, meta, rating);
+ }
+ else
ret = OK;
- ECRS_freeMetaData(meta);
+ ECRS_freeMetaData (meta);
return ret;
}
-static int listNamespaceHelper(const char * fn,
- const char * dirName,
- void * cls) {
- LNClosure * c = cls;
+static int
+listNamespaceHelper (const char *fn, const char *dirName, void *cls)
+{
+ LNClosure *c = cls;
int ret;
- struct ECRS_MetaData * meta;
+ struct ECRS_MetaData *meta;
int rating;
HashCode512 id;
- if (OK != enc2hash(fn,
- &id))
- return OK; /* invalid name */
- if (OK != readNamespaceInfo(c->ectx,
- c->cfg,
- fn,
- &meta,
- &rating))
- return OK; /* ignore entry */
- if (c->iterator != NULL) {
- ret = c->iterator(c->closure,
- fn,
- &id,
- meta,
- rating);
- } else
+ if (OK != enc2hash (fn, &id))
+ return OK; /* invalid name */
+ if (OK != readNamespaceInfo (c->ectx, c->cfg, fn, &meta, &rating))
+ return OK; /* ignore entry */
+ if (c->iterator != NULL)
+ {
+ ret = c->iterator (c->closure, fn, &id, meta, rating);
+ }
+ else
ret = OK;
- ECRS_freeMetaData(meta);
+ ECRS_freeMetaData (meta);
return OK;
}
@@ -390,13 +347,14 @@
* List all available (local and non-local) namespaces.
*
*/
-int NS_listNamespaces(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- NS_NamespaceIterator iterator,
- void * closure) {
+int
+NS_listNamespaces (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ NS_NamespaceIterator iterator, void *closure)
+{
LNClosure cls;
- char * fn;
- char * fnBase;
+ char *fn;
+ char *fnBase;
int ret1;
int ret2;
@@ -404,30 +362,21 @@
cls.closure = closure;
cls.ectx = ectx;
cls.cfg = cfg;
- ret1 = ECRS_listNamespaces(ectx,
- cfg,
- &localListNamespaceHelper,
- &cls);
+ ret1 = ECRS_listNamespaces (ectx, cfg, &localListNamespaceHelper, &cls);
if (ret1 == -1)
return ret1;
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &fnBase);
- fn = MALLOC(strlen(fnBase) +
- strlen(NS_DIR) +
- 4);
- strcpy(fn, fnBase);
- FREE(fnBase);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, NS_DIR);
- disk_directory_create(ectx, fn);
- ret2 = disk_directory_scan(ectx,
- fn,
- &listNamespaceHelper,
- &cls);
- FREE(fn);
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &fnBase);
+ fn = MALLOC (strlen (fnBase) + strlen (NS_DIR) + 4);
+ strcpy (fn, fnBase);
+ FREE (fnBase);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, NS_DIR);
+ disk_directory_create (ectx, fn);
+ ret2 = disk_directory_scan (ectx, fn, &listNamespaceHelper, &cls);
+ FREE (fn);
if (ret2 == -1)
return ret2;
return ret1 + ret2;
@@ -438,37 +387,39 @@
* namespace and content identifier.
* @param lastId maybe NULL
*/
-static char * getUpdateDataFilename(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * nsname,
- const HashCode512 * lastId) {
- char * tmp;
- char * ret;
+static char *
+getUpdateDataFilename (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *nsname, const HashCode512 * lastId)
+{
+ char *tmp;
+ char *ret;
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &tmp);
- ret = MALLOC(strlen(tmp) + strlen(NS_UPDATE_DIR) +
- strlen(nsname) + sizeof(EncName) + 20);
- strcpy(ret, tmp);
- FREE(tmp);
- strcat(ret, DIR_SEPARATOR_STR);
- strcat(ret, NS_UPDATE_DIR);
- strcat(ret, nsname);
- strcat(ret, DIR_SEPARATOR_STR);
- disk_directory_create(ectx, ret);
- if (lastId != NULL) {
- EncName enc;
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &tmp);
+ ret = MALLOC (strlen (tmp) + strlen (NS_UPDATE_DIR) +
+ strlen (nsname) + sizeof (EncName) + 20);
+ strcpy (ret, tmp);
+ FREE (tmp);
+ strcat (ret, DIR_SEPARATOR_STR);
+ strcat (ret, NS_UPDATE_DIR);
+ strcat (ret, nsname);
+ strcat (ret, DIR_SEPARATOR_STR);
+ disk_directory_create (ectx, ret);
+ if (lastId != NULL)
+ {
+ EncName enc;
- hash2enc(lastId, &enc);
- strcat(ret, (char*) &enc);
- }
+ hash2enc (lastId, &enc);
+ strcat (ret, (char *) &enc);
+ }
return ret;
}
-struct UpdateData {
+struct UpdateData
+{
TIME_T updateInterval;
TIME_T lastPubTime;
HashCode512 nextId;
@@ -482,191 +433,167 @@
* @param fi maybe NULL
* @return OK if update data was found, SYSERR if not.
*/
-static int readUpdateData(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * nsname,
- const HashCode512 * lastId,
- HashCode512 * nextId,
- ECRS_FileInfo * fi,
- TIME_T * updateInterval,
- TIME_T * lastPubTime) {
- char * fn;
- struct UpdateData * buf;
- char * uri;
+static int
+readUpdateData (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *nsname,
+ const HashCode512 * lastId,
+ HashCode512 * nextId,
+ ECRS_FileInfo * fi,
+ TIME_T * updateInterval, TIME_T * lastPubTime)
+{
+ char *fn;
+ struct UpdateData *buf;
+ char *uri;
unsigned long long size;
size_t pos;
- fn = getUpdateDataFilename(ectx,
- cfg,
- nsname,
- lastId);
- if (OK != disk_file_size(ectx,
- fn,
- &size,
- YES)) {
- FREE(fn);
- return SYSERR;
- }
- if ( (size == 0) ||
- (size <= sizeof(struct UpdateData)) ||
- (size > 1024 * 1024 * 16) ) {
- FREE(fn);
- return SYSERR;
- }
+ fn = getUpdateDataFilename (ectx, cfg, nsname, lastId);
+ if (OK != disk_file_size (ectx, fn, &size, YES))
+ {
+ FREE (fn);
+ return SYSERR;
+ }
+ if ((size == 0) ||
+ (size <= sizeof (struct UpdateData)) || (size > 1024 * 1024 * 16))
+ {
+ FREE (fn);
+ return SYSERR;
+ }
- buf = MALLOC(size);
- if (size != disk_file_read(ectx,
- fn,
- size,
- buf)) {
- FREE(buf);
- FREE(fn);
- return SYSERR;
- }
- FREE(fn);
- if ( ! equalsHashCode512(lastId,
- &buf->thisId)) {
- FREE(buf);
- return SYSERR;
- }
- uri = (char*) &buf[1];
- size -= sizeof(struct UpdateData);
+ buf = MALLOC (size);
+ if (size != disk_file_read (ectx, fn, size, buf))
+ {
+ FREE (buf);
+ FREE (fn);
+ return SYSERR;
+ }
+ FREE (fn);
+ if (!equalsHashCode512 (lastId, &buf->thisId))
+ {
+ FREE (buf);
+ return SYSERR;
+ }
+ uri = (char *) &buf[1];
+ size -= sizeof (struct UpdateData);
pos = 0;
- while ( (pos < size) &&
- (uri[pos] != '\0') )
+ while ((pos < size) && (uri[pos] != '\0'))
pos++;
pos++;
size -= pos;
- if (size == 0) {
- FREE(buf);
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- if (fi != NULL) {
- fi->meta = ECRS_deserializeMetaData(ectx,
- &uri[pos],
- size);
- if (fi->meta == NULL) {
- FREE(buf);
- GE_BREAK(ectx, 0);
+ if (size == 0)
+ {
+ FREE (buf);
+ GE_BREAK (ectx, 0);
return SYSERR;
}
- fi->uri = ECRS_stringToUri(ectx,
- uri);
- if (fi->uri == NULL) {
- ECRS_freeMetaData(fi->meta);
- fi->meta = NULL;
- FREE(buf);
- GE_BREAK(ectx, 0);
- return SYSERR;
+ if (fi != NULL)
+ {
+ fi->meta = ECRS_deserializeMetaData (ectx, &uri[pos], size);
+ if (fi->meta == NULL)
+ {
+ FREE (buf);
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ fi->uri = ECRS_stringToUri (ectx, uri);
+ if (fi->uri == NULL)
+ {
+ ECRS_freeMetaData (fi->meta);
+ fi->meta = NULL;
+ FREE (buf);
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
}
- }
if (updateInterval != NULL)
- *updateInterval = ntohl(buf->updateInterval);
+ *updateInterval = ntohl (buf->updateInterval);
if (lastPubTime != NULL)
- *lastPubTime = ntohl(buf->lastPubTime);
+ *lastPubTime = ntohl (buf->lastPubTime);
if (nextId != NULL)
*nextId = buf->nextId;
- FREE(buf);
+ FREE (buf);
return OK;
}
/**
* Write content update information.
*/
-static int writeUpdateData(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * nsname,
- const HashCode512 * thisId,
- const HashCode512 * nextId,
- const ECRS_FileInfo * fi,
- const TIME_T updateInterval,
- const TIME_T lastPubTime) {
- char * fn;
- char * uri;
+static int
+writeUpdateData (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *nsname,
+ const HashCode512 * thisId,
+ const HashCode512 * nextId,
+ const ECRS_FileInfo * fi,
+ const TIME_T updateInterval, const TIME_T lastPubTime)
+{
+ char *fn;
+ char *uri;
size_t metaSize;
size_t size;
- struct UpdateData * buf;
+ struct UpdateData *buf;
- uri = ECRS_uriToString(fi->uri);
- metaSize = ECRS_sizeofMetaData(fi->meta,
- ECRS_SERIALIZE_FULL);
- size = sizeof(struct UpdateData) + metaSize + strlen(uri) + 1;
- buf = MALLOC(size);
+ uri = ECRS_uriToString (fi->uri);
+ metaSize = ECRS_sizeofMetaData (fi->meta, ECRS_SERIALIZE_FULL);
+ size = sizeof (struct UpdateData) + metaSize + strlen (uri) + 1;
+ buf = MALLOC (size);
buf->nextId = *nextId;
buf->thisId = *thisId;
- buf->updateInterval = htonl(updateInterval);
- buf->lastPubTime = htonl(lastPubTime);
- memcpy(&buf[1],
- uri,
- strlen(uri)+1);
- GE_ASSERT(ectx,
- metaSize ==
- ECRS_serializeMetaData(ectx,
- fi->meta,
- &((char*)&buf[1])[strlen(uri)+1],
- metaSize,
- ECRS_SERIALIZE_FULL));
- FREE(uri);
- fn = getUpdateDataFilename(ectx,
- cfg,
- nsname,
- thisId);
- disk_file_write(ectx,
- fn,
- buf,
- size,
- "400"); /* no editing, just deletion */
- FREE(fn);
- FREE(buf);
+ buf->updateInterval = htonl (updateInterval);
+ buf->lastPubTime = htonl (lastPubTime);
+ memcpy (&buf[1], uri, strlen (uri) + 1);
+ GE_ASSERT (ectx,
+ metaSize ==
+ ECRS_serializeMetaData (ectx,
+ fi->meta,
+ &((char *) &buf[1])[strlen (uri) + 1],
+ metaSize, ECRS_SERIALIZE_FULL));
+ FREE (uri);
+ fn = getUpdateDataFilename (ectx, cfg, nsname, thisId);
+ disk_file_write (ectx, fn, buf, size, "400"); /* no editing, just deletion */
+ FREE (fn);
+ FREE (buf);
return OK;
}
-
+
/**
* Compute the next ID for peridodically updated content.
* @param updateInterval MUST be a peridic interval (not NONE or SPORADIC)
* @param thisId MUST be known to NAMESPACE
* @return OK on success, SYSERR on error
*/
-int NS_computeNextId(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name,
- const HashCode512 * lastId,
- const HashCode512 * thisId,
- TIME_T updateInterval,
- HashCode512 * nextId) {
+int
+NS_computeNextId (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *name,
+ const HashCode512 * lastId,
+ const HashCode512 * thisId,
+ TIME_T updateInterval, HashCode512 * nextId)
+{
HashCode512 delta;
cron_t now;
TIME_T tnow;
TIME_T lastTime;
TIME_T ui;
- if ( (updateInterval == ECRS_SBLOCK_UPDATE_SPORADIC) ||
- (updateInterval == ECRS_SBLOCK_UPDATE_NONE) )
+ if ((updateInterval == ECRS_SBLOCK_UPDATE_SPORADIC) ||
+ (updateInterval == ECRS_SBLOCK_UPDATE_NONE))
return SYSERR;
- if (OK != readUpdateData(ectx,
- cfg,
- name,
- lastId,
- NULL,
- NULL,
- &ui,
- &lastTime))
+ if (OK != readUpdateData (ectx,
+ cfg, name, lastId, NULL, NULL, &ui, &lastTime))
return SYSERR;
- deltaId(lastId,
- thisId,
- &delta);
- now = get_time();
- TIME(&tnow);
+ deltaId (lastId, thisId, &delta);
+ now = get_time ();
+ TIME (&tnow);
*nextId = *thisId;
- while (lastTime < tnow + updateInterval/2) {
- lastTime += updateInterval;
- addHashCodes(nextId,
- &delta,
- nextId);
- }
+ while (lastTime < tnow + updateInterval / 2)
+ {
+ lastTime += updateInterval;
+ addHashCodes (nextId, &delta, nextId);
+ }
return OK;
}
@@ -686,18 +613,18 @@
* @param uri set to the resulting URI
*/
struct ECRS_URI *
-NS_addToNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- unsigned int anonymityLevel,
- unsigned int insertPriority,
- cron_t insertExpiration,
- const char * name,
- TIME_T updateInterval,
- const HashCode512 * lastId,
- const HashCode512 * thisId,
- const HashCode512 * nextId,
- const struct ECRS_URI * dst,
- const struct ECRS_MetaData * md) {
+NS_addToNamespace (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ unsigned int anonymityLevel,
+ unsigned int insertPriority,
+ cron_t insertExpiration,
+ const char *name,
+ TIME_T updateInterval,
+ const HashCode512 * lastId,
+ const HashCode512 * thisId,
+ const HashCode512 * nextId,
+ const struct ECRS_URI *dst, const struct ECRS_MetaData *md)
+{
TIME_T creationTime;
HashCode512 nid;
HashCode512 tid;
@@ -705,140 +632,146 @@
TIME_T lastTime;
TIME_T lastInterval;
ECRS_FileInfo fi;
- char * old;
- struct ECRS_URI * uri;
+ char *old;
+ struct ECRS_URI *uri;
/* computation of IDs of update(s). Not as terrible as
it looks, just enumerating all of the possible cases
of periodic/sporadic updates and how IDs are computed. */
- creationTime = TIME(&now);
- if (updateInterval != ECRS_SBLOCK_UPDATE_NONE) {
- if ( (lastId != NULL) &&
- (OK == readUpdateData(ectx,
- cfg,
- name,
- lastId,
- &tid,
- NULL,
- &lastInterval,
- &lastTime)) ) {
- if (lastInterval != updateInterval) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Publication interval for periodic publication changed."));
- }
- /* try to compute tid and/or
- nid based on information read from lastId */
+ creationTime = TIME (&now);
+ if (updateInterval != ECRS_SBLOCK_UPDATE_NONE)
+ {
+ if ((lastId != NULL) &&
+ (OK == readUpdateData (ectx,
+ cfg,
+ name,
+ lastId,
+ &tid, NULL, &lastInterval, &lastTime)))
+ {
+ if (lastInterval != updateInterval)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("Publication interval for periodic publication
changed."));
+ }
+ /* try to compute tid and/or
+ nid based on information read from lastId */
- if (updateInterval != ECRS_SBLOCK_UPDATE_SPORADIC) {
- HashCode512 delta;
+ if (updateInterval != ECRS_SBLOCK_UPDATE_SPORADIC)
+ {
+ HashCode512 delta;
- deltaId(lastId,
- &tid,
- &delta);
+ deltaId (lastId, &tid, &delta);
- creationTime = lastTime + updateInterval;
- while (creationTime < now - updateInterval) {
- creationTime += updateInterval;
- addHashCodes(&tid,
- &delta,
- &tid);
- }
- if (creationTime > get_time() + 7 * cronDAYS) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Publishing update for periodically updated "
- "content more than a week ahead of schedule.\n"));
- }
- if (thisId != NULL)
- tid = *thisId; /* allow override! */
- addHashCodes(&tid,
- &delta,
- &nid);
- if (nextId != NULL)
- nid = *nextId; /* again, allow override */
- } else {
- /* sporadic ones are unpredictable,
- tid has been obtained from IO, pick random nid if
- not specified */
- if (thisId != NULL)
- tid = *thisId; /* allow user override */
- if (nextId == NULL) {
- makeRandomId(&nid);
- } else {
- nid = *nextId;
- }
- }
- } else { /* no previous ID found or given */
- if (nextId == NULL) {
- /* no previous block found and nextId not specified;
- pick random nid */
- makeRandomId(&nid);
- } else {
- nid = *nextId;
- }
- if (thisId != NULL) {
- tid = *thisId;
- } else {
- makeRandomId(&tid);
- }
+ creationTime = lastTime + updateInterval;
+ while (creationTime < now - updateInterval)
+ {
+ creationTime += updateInterval;
+ addHashCodes (&tid, &delta, &tid);
+ }
+ if (creationTime > get_time () + 7 * cronDAYS)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Publishing update for periodically updated "
+ "content more than a week ahead of schedule.\n"));
+ }
+ if (thisId != NULL)
+ tid = *thisId; /* allow override! */
+ addHashCodes (&tid, &delta, &nid);
+ if (nextId != NULL)
+ nid = *nextId; /* again, allow override */
+ }
+ else
+ {
+ /* sporadic ones are unpredictable,
+ tid has been obtained from IO, pick random nid if
+ not specified */
+ if (thisId != NULL)
+ tid = *thisId; /* allow user override */
+ if (nextId == NULL)
+ {
+ makeRandomId (&nid);
+ }
+ else
+ {
+ nid = *nextId;
+ }
+ }
+ }
+ else
+ { /* no previous ID found or given */
+ if (nextId == NULL)
+ {
+ /* no previous block found and nextId not specified;
+ pick random nid */
+ makeRandomId (&nid);
+ }
+ else
+ {
+ nid = *nextId;
+ }
+ if (thisId != NULL)
+ {
+ tid = *thisId;
+ }
+ else
+ {
+ makeRandomId (&tid);
+ }
+ }
}
- } else {
- if (thisId != NULL) {
- nid = tid = *thisId;
- } else {
- makeRandomId(&tid);
- nid = tid;
+ else
+ {
+ if (thisId != NULL)
+ {
+ nid = tid = *thisId;
+ }
+ else
+ {
+ makeRandomId (&tid);
+ nid = tid;
+ }
}
- }
- uri = ECRS_addToNamespace(ectx,
- cfg,
- name,
- anonymityLevel,
- insertPriority,
- insertExpiration,
- creationTime,
- updateInterval,
- &tid,
- &nid,
- dst,
- md);
- if ( (uri != NULL) &&
- (dst != NULL) ) {
- fi.uri = ECRS_dupUri(dst);
- fi.meta = (struct ECRS_MetaData*) md;
- writeUpdateData(ectx,
- cfg,
- name,
- &tid,
- &nid,
- &fi,
- updateInterval,
- creationTime);
- ECRS_freeUri(fi.uri);
- if (lastId != NULL) {
- old = getUpdateDataFilename(ectx,
- cfg,
- name,
- lastId);
- UNLINK(old);
- FREE(old);
+ uri = ECRS_addToNamespace (ectx,
+ cfg,
+ name,
+ anonymityLevel,
+ insertPriority,
+ insertExpiration,
+ creationTime,
+ updateInterval, &tid, &nid, dst, md);
+ if ((uri != NULL) && (dst != NULL))
+ {
+ fi.uri = ECRS_dupUri (dst);
+ fi.meta = (struct ECRS_MetaData *) md;
+ writeUpdateData (ectx,
+ cfg,
+ name, &tid, &nid, &fi, updateInterval, creationTime);
+ ECRS_freeUri (fi.uri);
+ if (lastId != NULL)
+ {
+ old = getUpdateDataFilename (ectx, cfg, name, lastId);
+ UNLINK (old);
+ FREE (old);
+ }
}
- }
return uri;
}
-struct lNCC {
- const char * name;
+struct lNCC
+{
+ const char *name;
NS_UpdateIterator it;
- void * closure;
+ void *closure;
int cnt;
- struct GE_Context * ectx;
- struct GC_Configuration * cfg;
+ struct GE_Context *ectx;
+ struct GC_Configuration *cfg;
};
-static int lNCHelper(const char * fil,
- const char * dir,
- void * ptr) {
- struct lNCC * cls = ptr;
+static int
+lNCHelper (const char *fil, const char *dir, void *ptr)
+{
+ struct lNCC *cls = ptr;
ECRS_FileInfo fi;
HashCode512 lastId;
HashCode512 nextId;
@@ -847,61 +780,59 @@
TIME_T nextTime;
TIME_T now;
- if (OK != enc2hash(fil,
- &lastId)) {
- GE_BREAK(cls->ectx, 0);
- return OK;
- }
+ if (OK != enc2hash (fil, &lastId))
+ {
+ GE_BREAK (cls->ectx, 0);
+ return OK;
+ }
fi.uri = NULL;
fi.meta = NULL;
- if (OK != readUpdateData(cls->ectx,
- cls->cfg,
- cls->name,
- &lastId,
- &nextId,
- &fi,
- &pubFreq,
- &lastTime)) {
- GE_BREAK(cls->ectx, 0);
- return OK;
- }
+ if (OK != readUpdateData (cls->ectx,
+ cls->cfg,
+ cls->name,
+ &lastId, &nextId, &fi, &pubFreq, &lastTime))
+ {
+ GE_BREAK (cls->ectx, 0);
+ return OK;
+ }
cls->cnt++;
- if (pubFreq == ECRS_SBLOCK_UPDATE_SPORADIC) {
- nextTime = 0;
- } else {
- TIME(&now);
- nextTime = lastTime;
- if ( (nextTime + pubFreq < now) &&
- (nextTime + pubFreq > nextTime) )
- nextTime += pubFreq * ((now - nextTime) / pubFreq);
- }
- if (cls->it != NULL) {
- if (OK != cls->it(cls->closure,
- &fi,
- &lastId,
- &nextId,
- pubFreq,
- nextTime)) {
- ECRS_freeUri(fi.uri);
- ECRS_freeMetaData(fi.meta);
- return SYSERR;
+ if (pubFreq == ECRS_SBLOCK_UPDATE_SPORADIC)
+ {
+ nextTime = 0;
}
- }
- ECRS_freeUri(fi.uri);
- ECRS_freeMetaData(fi.meta);
+ else
+ {
+ TIME (&now);
+ nextTime = lastTime;
+ if ((nextTime + pubFreq < now) && (nextTime + pubFreq > nextTime))
+ nextTime += pubFreq * ((now - nextTime) / pubFreq);
+ }
+ if (cls->it != NULL)
+ {
+ if (OK != cls->it (cls->closure,
+ &fi, &lastId, &nextId, pubFreq, nextTime))
+ {
+ ECRS_freeUri (fi.uri);
+ ECRS_freeMetaData (fi.meta);
+ return SYSERR;
+ }
+ }
+ ECRS_freeUri (fi.uri);
+ ECRS_freeMetaData (fi.meta);
return OK;
}
/**
* List all updateable content in a given namespace.
*/
-int NS_listNamespaceContent(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name,
- NS_UpdateIterator iterator,
- void * closure) {
+int
+NS_listNamespaceContent (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *name,
+ NS_UpdateIterator iterator, void *closure)
+{
struct lNCC cls;
- char * dirName;
+ char *dirName;
cls.name = name;
cls.it = iterator;
@@ -909,29 +840,22 @@
cls.cnt = 0;
cls.ectx = ectx;
cls.cfg = cfg;
- dirName = getUpdateDataFilename(ectx,
- cfg,
- name,
- NULL);
- disk_directory_create(ectx, dirName);
- if (SYSERR == disk_directory_scan(ectx,
- dirName,
- &lNCHelper,
- &cls)) {
- FREE(dirName);
- return SYSERR;
- }
- FREE(dirName);
+ dirName = getUpdateDataFilename (ectx, cfg, name, NULL);
+ disk_directory_create (ectx, dirName);
+ if (SYSERR == disk_directory_scan (ectx, dirName, &lNCHelper, &cls))
+ {
+ FREE (dirName);
+ return SYSERR;
+ }
+ FREE (dirName);
return cls.cnt;
}
-static int mergeMeta(EXTRACTOR_KeywordType type,
- const char * data,
- void * cls) {
- struct ECRS_MetaData * meta = cls;
- ECRS_addToMetaData(meta,
- type,
- data);
+static int
+mergeMeta (EXTRACTOR_KeywordType type, const char *data, void *cls)
+{
+ struct ECRS_MetaData *meta = cls;
+ ECRS_addToMetaData (meta, type, data);
return OK;
}
@@ -942,53 +866,42 @@
*
* @param ns the namespace identifier
*/
-void NS_addNamespaceInfo(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri,
- const struct ECRS_MetaData * meta) {
- char * name;
+void
+NS_addNamespaceInfo (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const struct ECRS_URI *uri,
+ const struct ECRS_MetaData *meta)
+{
+ char *name;
int ranking;
- struct ECRS_MetaData * old;
+ struct ECRS_MetaData *old;
HashCode512 id;
- if (! ECRS_isNamespaceUri(uri)) {
- GE_BREAK(ectx, 0);
- return;
- }
- ECRS_getNamespaceId(uri,
- &id);
- name = ECRS_getNamespaceName(&id);
- if (name == NULL) {
- GE_BREAK(ectx, 0);
- return;
- }
+ if (!ECRS_isNamespaceUri (uri))
+ {
+ GE_BREAK (ectx, 0);
+ return;
+ }
+ ECRS_getNamespaceId (uri, &id);
+ name = ECRS_getNamespaceName (&id);
+ if (name == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return;
+ }
ranking = 0;
- if (OK == readNamespaceInfo(ectx,
- cfg,
- name,
- &old,
- &ranking)) {
- ECRS_getMetaData(meta,
- &mergeMeta,
- old);
- writeNamespaceInfo(ectx,
- cfg,
- name,
- old,
- ranking);
- ECRS_freeMetaData(old);
- } else {
- writeNamespaceInfo(ectx,
- cfg,
- name,
- meta,
- ranking);
- }
- internal_notify(name,
- &id,
- meta,
- ranking);
- FREE(name);
+ if (OK == readNamespaceInfo (ectx, cfg, name, &old, &ranking))
+ {
+ ECRS_getMetaData (meta, &mergeMeta, old);
+ writeNamespaceInfo (ectx, cfg, name, old, ranking);
+ ECRS_freeMetaData (old);
+ }
+ else
+ {
+ writeNamespaceInfo (ectx, cfg, name, meta, ranking);
+ }
+ internal_notify (name, &id, meta, ranking);
+ FREE (name);
}
@@ -996,145 +909,134 @@
* Get the root of the namespace (if we have one).
* @return SYSERR on error, OK on success
*/
-int NS_getNamespaceRoot(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * ns,
- HashCode512 * root) {
- char * fn;
- char * fnBase;
+int
+NS_getNamespaceRoot (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *ns, HashCode512 * root)
+{
+ char *fn;
+ char *fnBase;
int ret;
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &fnBase);
- fn = MALLOC(strlen(fnBase) +
- strlen(NS_ROOTS) +
- strlen(ns) +
- 6);
- strcpy(fn, fnBase);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, NS_ROOTS);
- disk_directory_create(ectx, fn);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, ns);
- FREE(fnBase);
- if (sizeof(HashCode512)
- == disk_file_read(ectx,
- fn,
- sizeof(HashCode512),
- root))
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &fnBase);
+ fn = MALLOC (strlen (fnBase) + strlen (NS_ROOTS) + strlen (ns) + 6);
+ strcpy (fn, fnBase);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, NS_ROOTS);
+ disk_directory_create (ectx, fn);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, ns);
+ FREE (fnBase);
+ if (sizeof (HashCode512)
+ == disk_file_read (ectx, fn, sizeof (HashCode512), root))
ret = OK;
else
ret = SYSERR;
- FREE(fn);
+ FREE (fn);
return ret;
}
-void NS_setNamespaceRoot(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri) {
- char * fn;
- char * fnBase;
+void
+NS_setNamespaceRoot (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, const struct ECRS_URI *uri)
+{
+ char *fn;
+ char *fnBase;
HashCode512 ns;
- char * name;
+ char *name;
- if (OK != ECRS_getNamespaceId(uri,
- &ns)) {
- GE_BREAK(ectx, 0);
- return;
- }
- name = ECRS_getNamespaceName(&ns);
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &fnBase);
- fn = MALLOC(strlen(fnBase) +
- strlen(NS_ROOTS) +
- strlen(name) +
- 6);
- strcpy(fn, fnBase);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, NS_ROOTS);
- disk_directory_create(ectx, fn);
- strcat(fn, DIR_SEPARATOR_STR);
- strcat(fn, name);
- FREE(name);
- FREE(fnBase);
- if (OK == ECRS_getSKSContentHash(uri,
- &ns)) {
- disk_file_write(ectx,
- fn,
- &ns,
- sizeof(HashCode512),
- "644");
- }
- FREE(fn);
+ if (OK != ECRS_getNamespaceId (uri, &ns))
+ {
+ GE_BREAK (ectx, 0);
+ return;
+ }
+ name = ECRS_getNamespaceName (&ns);
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &fnBase);
+ fn = MALLOC (strlen (fnBase) + strlen (NS_ROOTS) + strlen (name) + 6);
+ strcpy (fn, fnBase);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, NS_ROOTS);
+ disk_directory_create (ectx, fn);
+ strcat (fn, DIR_SEPARATOR_STR);
+ strcat (fn, name);
+ FREE (name);
+ FREE (fnBase);
+ if (OK == ECRS_getSKSContentHash (uri, &ns))
+ {
+ disk_file_write (ectx, fn, &ns, sizeof (HashCode512), "644");
+ }
+ FREE (fn);
}
/**
* Register callback to be invoked whenever we discover
* a new namespace.
*/
-int NS_registerDiscoveryCallback(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- NS_NamespaceIterator iterator,
- void * closure) {
- struct DiscoveryCallback * list;
+int
+NS_registerDiscoveryCallback (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ NS_NamespaceIterator iterator, void *closure)
+{
+ struct DiscoveryCallback *list;
- list = MALLOC(sizeof(struct DiscoveryCallback));
+ list = MALLOC (sizeof (struct DiscoveryCallback));
list->callback = iterator;
list->closure = closure;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
list->next = head;
head = list;
- NS_listNamespaces(ectx,
- cfg,
- iterator,
- closure);
- MUTEX_UNLOCK(lock);
+ NS_listNamespaces (ectx, cfg, iterator, closure);
+ MUTEX_UNLOCK (lock);
return OK;
}
/**
* Unregister namespace discovery callback.
*/
-int NS_unregisterDiscoveryCallback(NS_NamespaceIterator iterator,
- void * closure) {
- struct DiscoveryCallback * prev;
- struct DiscoveryCallback * pos;
+int
+NS_unregisterDiscoveryCallback (NS_NamespaceIterator iterator, void *closure)
+{
+ struct DiscoveryCallback *prev;
+ struct DiscoveryCallback *pos;
prev = NULL;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
pos = head;
- while ( (pos != NULL) &&
- ( (pos->callback != iterator) ||
- (pos->closure != closure) ) ) {
- prev = pos;
- pos = pos->next;
- }
- if (pos == NULL) {
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
+ while ((pos != NULL) &&
+ ((pos->callback != iterator) || (pos->closure != closure)))
+ {
+ prev = pos;
+ pos = pos->next;
+ }
+ if (pos == NULL)
+ {
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
if (prev == NULL)
head = pos->next;
else
prev->next = pos->next;
- FREE(pos);
- MUTEX_UNLOCK(lock);
+ FREE (pos);
+ MUTEX_UNLOCK (lock);
return OK;
}
-void __attribute__ ((constructor)) gnunet_namespace_ltdl_init() {
- lock = MUTEX_CREATE(NO);
+void __attribute__ ((constructor)) gnunet_namespace_ltdl_init ()
+{
+ lock = MUTEX_CREATE (NO);
}
-void __attribute__ ((destructor)) gnunet_namespace_ltdl_fini() {
- MUTEX_DESTROY(lock);
+void __attribute__ ((destructor)) gnunet_namespace_ltdl_fini ()
+{
+ MUTEX_DESTROY (lock);
lock = NULL;
}
Modified: GNUnet/src/applications/fs/namespace/namespace_infotest.c
===================================================================
--- GNUnet/src/applications/fs/namespace/namespace_infotest.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/fs/namespace/namespace_infotest.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -35,106 +35,72 @@
#define CHECK(a) if (!(a)) { ok = NO; GE_BREAK(ectx, 0); goto FAILURE; }
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
pid_t daemon;
int ok;
- struct ECRS_URI * uri = NULL;
- struct ECRS_URI * euri = NULL;
- struct ECRS_MetaData * meta = NULL;
+ struct ECRS_URI *uri = NULL;
+ struct ECRS_URI *euri = NULL;
+ struct ECRS_MetaData *meta = NULL;
HashCode512 root;
int old;
int newVal;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- daemon = os_daemon_start(NULL,
- cfg,
- "peer.conf",
- NO);
- GE_ASSERT(NULL, daemon > 0);
- CHECK(OK == connection_wait_for_running(NULL,
- cfg,
- 30 * cronSECONDS));
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ daemon = os_daemon_start (NULL, cfg, "peer.conf", NO);
+ GE_ASSERT (NULL, daemon > 0);
+ CHECK (OK == connection_wait_for_running (NULL, cfg, 30 * cronSECONDS));
ok = YES;
- NS_deleteNamespace(ectx,
- cfg,
- "test");
- PTHREAD_SLEEP(5 * cronSECONDS); /* give apps time to start */
+ NS_deleteNamespace (ectx, cfg, "test");
+ PTHREAD_SLEEP (5 * cronSECONDS); /* give apps time to start */
/* ACTUAL TEST CODE */
- old = NS_listNamespaces(ectx,
- cfg,
- NULL,
- NULL);
-
- meta = ECRS_createMetaData();
- ECRS_addToMetaData(meta,
- 0,
- "test");
- makeRandomId(&root);
- uri = NS_createNamespace(ectx,
- cfg,
- 1,
- 1,
- get_time() + 10 * cronMINUTES,
- "test",
- meta,
- NULL,
- &root);
- CHECK(uri != NULL);
- newVal = NS_listNamespaces(ectx,
- cfg,
- NULL,
- NULL);
- CHECK(old < newVal);
- old = NS_listNamespaceContent(ectx,
- cfg,
- "test",
- NULL,
- NULL);
- euri = NS_addToNamespace(ectx,
- cfg,
- 1,
- 1,
- get_time() + 10 * cronMINUTES,
- "test",
- 42,
- NULL,
- &root,
- NULL,
- uri,
- meta);
- CHECK(euri != NULL);
- newVal = NS_listNamespaceContent(ectx,
- cfg,
- "test",
- NULL,
- NULL);
- CHECK(old < newVal);
- CHECK(OK == NS_deleteNamespace(ectx,
- cfg,
- "test"));
+ old = NS_listNamespaces (ectx, cfg, NULL, NULL);
+
+ meta = ECRS_createMetaData ();
+ ECRS_addToMetaData (meta, 0, "test");
+ makeRandomId (&root);
+ uri = NS_createNamespace (ectx,
+ cfg,
+ 1,
+ 1,
+ get_time () + 10 * cronMINUTES,
+ "test", meta, NULL, &root);
+ CHECK (uri != NULL);
+ newVal = NS_listNamespaces (ectx, cfg, NULL, NULL);
+ CHECK (old < newVal);
+ old = NS_listNamespaceContent (ectx, cfg, "test", NULL, NULL);
+ euri = NS_addToNamespace (ectx,
+ cfg,
+ 1,
+ 1,
+ get_time () + 10 * cronMINUTES,
+ "test", 42, NULL, &root, NULL, uri, meta);
+ CHECK (euri != NULL);
+ newVal = NS_listNamespaceContent (ectx, cfg, "test", NULL, NULL);
+ CHECK (old < newVal);
+ CHECK (OK == NS_deleteNamespace (ectx, cfg, "test"));
/* END OF TEST CODE */
- FAILURE:
+FAILURE:
if (uri != NULL)
- ECRS_freeUri(uri);
+ ECRS_freeUri (uri);
if (euri != NULL)
- ECRS_freeUri(euri);
+ ECRS_freeUri (euri);
if (meta != NULL)
- ECRS_freeMetaData(meta);
- ECRS_deleteNamespace(ectx,
- cfg,
- "test");
+ ECRS_freeMetaData (meta);
+ ECRS_deleteNamespace (ectx, cfg, "test");
- GE_ASSERT(NULL, OK == os_daemon_stop(NULL, daemon));
- GC_free(cfg);
+ GE_ASSERT (NULL, OK == os_daemon_stop (NULL, daemon));
+ GC_free (cfg);
return (ok == YES) ? 0 : 1;
}
Modified: GNUnet/src/applications/fs/tools/gnunet-directory.c
===================================================================
--- GNUnet/src/applications/fs/tools/gnunet-directory.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/tools/gnunet-directory.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -32,7 +32,7 @@
#include "gnunet_uritrack_lib.h"
#include "gnunet_util_boot.h"
-static char * cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
+static char *cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
static int do_list;
@@ -40,155 +40,141 @@
static int do_track;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static int itemPrinter(EXTRACTOR_KeywordType type,
- const char * data,
- void * closure) {
- printf("\t%20s: %s\n",
- dgettext("libextractor",
- EXTRACTOR_getKeywordTypeAsString(type)),
- data);
+static int
+itemPrinter (EXTRACTOR_KeywordType type, const char *data, void *closure)
+{
+ printf ("\t%20s: %s\n",
+ dgettext ("libextractor",
+ EXTRACTOR_getKeywordTypeAsString (type)), data);
return OK;
}
-static void printMeta(const struct ECRS_MetaData * meta) {
- ECRS_getMetaData(meta,
- &itemPrinter,
- NULL);
+static void
+printMeta (const struct ECRS_MetaData *meta)
+{
+ ECRS_getMetaData (meta, &itemPrinter, NULL);
}
-static int printNode(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * unused) {
- char * string;
+static int
+printNode (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *unused)
+{
+ char *string;
- string = ECRS_uriToString(fi->uri);
- printf("%s:\n", string);
- FREE(string);
- printMeta(fi->meta);
+ string = ECRS_uriToString (fi->uri);
+ printf ("%s:\n", string);
+ FREE (string);
+ printMeta (fi->meta);
return OK;
}
-static void printDirectory(const char * filename) {
+static void
+printDirectory (const char *filename)
+{
unsigned long long len;
- struct ECRS_MetaData * md;
- char * data;
+ struct ECRS_MetaData *md;
+ char *data;
int ret;
- char * name;
+ char *name;
int fd;
- name = string_expandFileName(ectx, filename);
- printf(_("==> Directory `%s':\n"),
- name);
- if ( (OK != disk_file_size(ectx,
- name,
- &len,
- YES)) ||
- (len == 0) ) {
- printf(_("=\tError reading directory.\n"));
- FREE(name);
- return;
- }
+ name = string_expandFileName (ectx, filename);
+ printf (_("==> Directory `%s':\n"), name);
+ if ((OK != disk_file_size (ectx, name, &len, YES)) || (len == 0))
+ {
+ printf (_("=\tError reading directory.\n"));
+ FREE (name);
+ return;
+ }
md = NULL;
- fd = disk_file_open(ectx,
- name,
- O_LARGEFILE | O_RDONLY);
- if (fd == -1) {
- ret = -1;
- } else {
- data = MMAP(NULL,
- len,
- PROT_READ,
- MAP_SHARED,
- fd,
- 0);
- if (data == MAP_FAILED) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "mmap",
- name);
+ fd = disk_file_open (ectx, name, O_LARGEFILE | O_RDONLY);
+ if (fd == -1)
+ {
ret = -1;
- } else {
- ret = ECRS_listDirectory(ectx,
- data,
- len,
- &md,
- &printNode,
- NULL);
- MUNMAP(data, len);
}
- CLOSE(fd);
- }
+ else
+ {
+ data = MMAP (NULL, len, PROT_READ, MAP_SHARED, fd, 0);
+ if (data == MAP_FAILED)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK, "mmap", name);
+ ret = -1;
+ }
+ else
+ {
+ ret = ECRS_listDirectory (ectx, data, len, &md, &printNode, NULL);
+ MUNMAP (data, len);
+ }
+ CLOSE (fd);
+ }
if (ret == -1)
- printf(_("File format error (not a GNUnet directory?)\n"));
+ printf (_("File format error (not a GNUnet directory?)\n"));
else
- printf(_("%d files found in directory.\n"),
- ret);
- if (md != NULL) {
- printMeta(md);
- ECRS_freeMetaData(md);
- }
- printf("\n");
- FREE(name);
+ printf (_("%d files found in directory.\n"), ret);
+ if (md != NULL)
+ {
+ printMeta (md);
+ ECRS_freeMetaData (md);
+ }
+ printf ("\n");
+ FREE (name);
}
/**
* All gnunet-directory command line options
*/
static struct CommandLineOption gnunetdirectoryOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- COMMAND_LINE_OPTION_HELP(gettext_noop("Perform directory related
operations.")), /* -h */
- { 'k', "kill", NULL,
- gettext_noop("remove all entries from the directory database and stop
tracking URIs"),
- 0, &gnunet_getopt_configure_set_one, &do_kill },
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'l', "list", NULL,
- gettext_noop("list entries from the directory database"),
- 1, &gnunet_getopt_configure_set_one, &do_list },
- { 't', "track", NULL,
- gettext_noop("start tracking entries for the directory database"),
- 1, &gnunet_getopt_configure_set_one, &do_track },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Perform directory related
operations.")), /* -h */
+ {'k', "kill", NULL,
+ gettext_noop
+ ("remove all entries from the directory database and stop tracking URIs"),
+ 0, &gnunet_getopt_configure_set_one, &do_kill},
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'l', "list", NULL,
+ gettext_noop ("list entries from the directory database"),
+ 1, &gnunet_getopt_configure_set_one, &do_list},
+ {'t', "track", NULL,
+ gettext_noop ("start tracking entries for the directory database"),
+ 1, &gnunet_getopt_configure_set_one, &do_track},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_VERBOSE,
COMMAND_LINE_OPTION_END,
};
-int main(int argc,
- char * const * argv) {
+int
+main (int argc, char *const *argv)
+{
int i;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
- i = GNUNET_init(argc,
- argv,
- "gnunet-directory [OPTIONS] [FILENAMES]",
- &cfgFilename,
- gnunetdirectoryOptions,
- &ectx,
- &cfg);
- if (i == -1) {
- GNUNET_fini(ectx, cfg);
- return -1;
- }
+ i = GNUNET_init (argc,
+ argv,
+ "gnunet-directory [OPTIONS] [FILENAMES]",
+ &cfgFilename, gnunetdirectoryOptions, &ectx, &cfg);
+ if (i == -1)
+ {
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
if (do_list)
- printf(_("Listed %d matching entries.\n"),
- URITRACK_listURIs(ectx,
- cfg,
- YES,
- &printNode,
- NULL));
- if (do_kill) {
- URITRACK_trackURIS(ectx, cfg, NO);
- URITRACK_clearTrackedURIS(ectx, cfg);
- }
+ printf (_("Listed %d matching entries.\n"),
+ URITRACK_listURIs (ectx, cfg, YES, &printNode, NULL));
+ if (do_kill)
+ {
+ URITRACK_trackURIS (ectx, cfg, NO);
+ URITRACK_clearTrackedURIS (ectx, cfg);
+ }
if (do_track)
- URITRACK_trackURIS(ectx, cfg, YES);
+ URITRACK_trackURIS (ectx, cfg, YES);
while (i < argc)
- printDirectory(argv[i++]);
+ printDirectory (argv[i++]);
- GNUNET_fini(ectx, cfg);
+ GNUNET_fini (ectx, cfg);
return 0;
}
Modified: GNUnet/src/applications/fs/tools/gnunet-download.c
===================================================================
--- GNUnet/src/applications/fs/tools/gnunet-download.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/tools/gnunet-download.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -29,9 +29,9 @@
#include "gnunet_fsui_lib.h"
#include "gnunet_util_boot.h"
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
static unsigned long long verbose;
@@ -39,9 +39,9 @@
static int do_directory;
-static char * cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
+static char *cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
-static char * filename;
+static char *filename;
static unsigned int anonymity = 1;
@@ -49,42 +49,44 @@
static cron_t start_time;
-static struct FSUI_DownloadList * dl;
+static struct FSUI_DownloadList *dl;
static int errorCode;
static unsigned int downloads_running;
-static struct FSUI_DownloadList ** downloads;
+static struct FSUI_DownloadList **downloads;
static unsigned int downloads_size;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
/**
* All gnunet-download command line options
*/
static struct CommandLineOption gnunetdownloadOptions[] = {
- { 'a', "anonymity", "LEVEL",
- gettext_noop("set the desired LEVEL of sender-anonymity"),
- 1, &gnunet_getopt_configure_set_uint, &anonymity },
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- { 'd', "directory", NULL,
- gettext_noop("download a GNUnet directory that has already been
downloaded. Requires that a filename of an existing file is specified instead
of the URI. The download will only download the top-level files in the
directory unless the `-R' option is also specified."),
- 0, &gnunet_getopt_configure_set_one, &do_directory },
- COMMAND_LINE_OPTION_HELP(gettext_noop("Download files from GNUnet.")), /* -h
*/
+ {'a', "anonymity", "LEVEL",
+ gettext_noop ("set the desired LEVEL of sender-anonymity"),
+ 1, &gnunet_getopt_configure_set_uint, &anonymity},
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ {'d', "directory", NULL,
+ gettext_noop
+ ("download a GNUnet directory that has already been downloaded. Requires
that a filename of an existing file is specified instead of the URI. The
download will only download the top-level files in the directory unless the
`-R' option is also specified."),
+ 0, &gnunet_getopt_configure_set_one, &do_directory},
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Download files from GNUnet.")),
/* -h */
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'o', "output", "FILENAME",
- gettext_noop("write the file to FILENAME"),
- 1, &gnunet_getopt_configure_set_string, &filename },
- { 'p', "parallelism", "DOWNLOADS",
- gettext_noop("set the maximum number of parallel downloads that are
allowed"),
- 1, &gnunet_getopt_configure_set_uint, ¶llelism },
- { 'R', "recursive", NULL,
- gettext_noop("download a GNUnet directory recursively"),
- 0, &gnunet_getopt_configure_set_one, &do_recursive },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'o', "output", "FILENAME",
+ gettext_noop ("write the file to FILENAME"),
+ 1, &gnunet_getopt_configure_set_string, &filename},
+ {'p', "parallelism", "DOWNLOADS",
+ gettext_noop
+ ("set the maximum number of parallel downloads that are allowed"),
+ 1, &gnunet_getopt_configure_set_uint, ¶llelism},
+ {'R', "recursive", NULL,
+ gettext_noop ("download a GNUnet directory recursively"),
+ 0, &gnunet_getopt_configure_set_one, &do_recursive},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_VERBOSE,
COMMAND_LINE_OPTION_END,
};
@@ -94,105 +96,98 @@
* The current incarnation just ensures that the main
* method exits once the download is complete.
*/
-static void * progressModel(void * unused,
- const FSUI_Event * event) {
- MUTEX_LOCK(lock);
- switch (event->type) {
- case FSUI_download_progress:
- if (verbose) {
- PRINTF(_("Download of file `%s' at "
- "%16llu out of %16llu bytes (%8.3f KiB/s)\n"),
- event->data.DownloadProgress.filename,
- event->data.DownloadProgress.completed,
- event->data.DownloadProgress.total,
- (event->data.DownloadProgress.completed/1024.0) /
- (((double)(get_time()-(start_time - 1)))
- / (double)cronSECONDS) );
+static void *
+progressModel (void *unused, const FSUI_Event * event)
+{
+ MUTEX_LOCK (lock);
+ switch (event->type)
+ {
+ case FSUI_download_progress:
+ if (verbose)
+ {
+ PRINTF (_("Download of file `%s' at "
+ "%16llu out of %16llu bytes (%8.3f KiB/s)\n"),
+ event->data.DownloadProgress.filename,
+ event->data.DownloadProgress.completed,
+ event->data.DownloadProgress.total,
+ (event->data.DownloadProgress.completed / 1024.0) /
+ (((double) (get_time () - (start_time - 1)))
+ / (double) cronSECONDS));
+ }
+ break;
+ case FSUI_download_aborted:
+ if (dl == event->data.DownloadError.dc.pos)
+ {
+ /* top-download aborted */
+ printf (_("Download aborted.\n"));
+ errorCode = 2;
+ GNUNET_SHUTDOWN_INITIATE ();
+ }
+ break;
+ case FSUI_download_error:
+ printf (_("Error downloading: %s\n"),
+ event->data.DownloadError.message);
+ errorCode = 3;
+ GNUNET_SHUTDOWN_INITIATE ();
+ break;
+ case FSUI_download_completed:
+ PRINTF (_("Download of file `%s' complete. "
+ "Speed was %8.3f KiB per second.\n"),
+ event->data.DownloadCompleted.filename,
+ (event->data.DownloadCompleted.total / 1024.0) /
+ (((double) (get_time () - (start_time - 1)))
+ / (double) cronSECONDS));
+ downloads_running--;
+ if (downloads_running == 0)
+ {
+ errorCode = 0;
+ GNUNET_SHUTDOWN_INITIATE ();
+ }
+ break;
+ case FSUI_download_started:
+ downloads_running++;
+ APPEND (downloads, downloads_size, event->data.DownloadStarted.dc.pos);
+ case FSUI_download_stopped:
+ break;
+ default:
+ GE_BREAK (ectx, 0);
+ break;
}
- break;
- case FSUI_download_aborted:
- if (dl == event->data.DownloadError.dc.pos) {
- /* top-download aborted */
- printf(_("Download aborted.\n"));
- errorCode = 2;
- GNUNET_SHUTDOWN_INITIATE();
- }
- break;
- case FSUI_download_error:
- printf(_("Error downloading: %s\n"),
- event->data.DownloadError.message);
- errorCode = 3;
- GNUNET_SHUTDOWN_INITIATE();
- break;
- case FSUI_download_completed:
- PRINTF(_("Download of file `%s' complete. "
- "Speed was %8.3f KiB per second.\n"),
- event->data.DownloadCompleted.filename,
- (event->data.DownloadCompleted.total/1024.0) /
- (((double)(get_time()-(start_time - 1)))
- / (double)cronSECONDS) );
- downloads_running--;
- if (downloads_running == 0) {
- errorCode = 0;
- GNUNET_SHUTDOWN_INITIATE();
- }
- break;
- case FSUI_download_started:
- downloads_running++;
- APPEND(downloads,
- downloads_size,
- event->data.DownloadStarted.dc.pos);
- case FSUI_download_stopped:
- break;
- default:
- GE_BREAK(ectx, 0);
- break;
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return NULL;
}
static int
-directoryIterator(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * cls) {
- struct FSUI_Context * ctx = cls;
- struct ECRS_MetaData * meta;
- char * fn;
- char * f;
+directoryIterator (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *cls)
+{
+ struct FSUI_Context *ctx = cls;
+ struct ECRS_MetaData *meta;
+ char *fn;
+ char *f;
- f = ECRS_getFirstFromMetaData(fi->meta,
- EXTRACTOR_FILENAME,
- EXTRACTOR_TITLE,
- EXTRACTOR_ARTIST,
- EXTRACTOR_AUTHOR,
- EXTRACTOR_PUBLISHER,
- EXTRACTOR_CREATOR,
- EXTRACTOR_PRODUCER,
- EXTRACTOR_UNKNOWN,
- -1);
+ f = ECRS_getFirstFromMetaData (fi->meta,
+ EXTRACTOR_FILENAME,
+ EXTRACTOR_TITLE,
+ EXTRACTOR_ARTIST,
+ EXTRACTOR_AUTHOR,
+ EXTRACTOR_PUBLISHER,
+ EXTRACTOR_CREATOR,
+ EXTRACTOR_PRODUCER, EXTRACTOR_UNKNOWN, -1);
if (f == NULL)
- f = STRDUP(_("no name given"));
- fn = MALLOC(strlen(filename) + strlen(f) + 4);
- strcpy(fn, filename);
- strcat(fn, "/");
- strcat(fn, f);
+ f = STRDUP (_("no name given"));
+ fn = MALLOC (strlen (filename) + strlen (f) + 4);
+ strcpy (fn, filename);
+ strcat (fn, "/");
+ strcat (fn, f);
if (verbose > 1)
- printf(_("Starting download `%s'\n"),
- f);
- FREE(f);
- meta = ECRS_createMetaData();
- FSUI_startDownload(ctx,
- anonymity,
- do_recursive,
- fi->uri,
- meta,
- fn,
- NULL,
- NULL);
- ECRS_freeMetaData(meta);
- FREE(fn);
+ printf (_("Starting download `%s'\n"), f);
+ FREE (f);
+ meta = ECRS_createMetaData ();
+ FSUI_startDownload (ctx,
+ anonymity, do_recursive, fi->uri, meta, fn, NULL, NULL);
+ ECRS_freeMetaData (meta);
+ FREE (fn);
return OK;
}
@@ -204,199 +199,190 @@
* @param argv command line arguments
* @return return value from download file: 0: ok, -1, 1: error
*/
-int main(int argc,
- char * const * argv) {
+int
+main (int argc, char *const *argv)
+{
int ok;
int try_rename;
- struct FSUI_Context * ctx;
- struct ECRS_URI * uri;
- struct ECRS_MetaData * meta;
+ struct FSUI_Context *ctx;
+ struct ECRS_URI *uri;
+ struct ECRS_MetaData *meta;
int i;
- i = GNUNET_init(argc,
- argv,
- "gnunet-download [OPTIONS] URI",
- &cfgFilename,
- gnunetdownloadOptions,
- &ectx,
- &cfg);
- if (i == -1) {
- errorCode = -1;
- goto quit;
- }
- if (i == argc) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Not enough arguments. "
- "You must specify a GNUnet file URI\n"));
- errorCode = -1;
- goto quit;
- }
- GC_get_configuration_value_number(cfg,
- "GNUNET",
- "VERBOSE",
- 0,
- 9999,
- 0,
- &verbose);
- uri = NULL;
- if (! do_directory) {
- uri = ECRS_stringToUri(ectx,
- argv[i]);
- if ( (NULL == uri) ||
- (! (ECRS_isLocationUri(uri) ||
- ECRS_isFileUri(uri)) ) ) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("URI `%s' invalid for gnunet-download.\n"),
- argv[i]);
+ i = GNUNET_init (argc,
+ argv,
+ "gnunet-download [OPTIONS] URI",
+ &cfgFilename, gnunetdownloadOptions, &ectx, &cfg);
+ if (i == -1)
+ {
errorCode = -1;
goto quit;
}
- }
+ if (i == argc)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Not enough arguments. "
+ "You must specify a GNUnet file URI\n"));
+ errorCode = -1;
+ goto quit;
+ }
+ GC_get_configuration_value_number (cfg,
+ "GNUNET",
+ "VERBOSE", 0, 9999, 0, &verbose);
+ uri = NULL;
+ if (!do_directory)
+ {
+ uri = ECRS_stringToUri (ectx, argv[i]);
+ if ((NULL == uri) ||
+ (!(ECRS_isLocationUri (uri) || ECRS_isFileUri (uri))))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("URI `%s' invalid for gnunet-download.\n"), argv[i]);
+ errorCode = -1;
+ goto quit;
+ }
+ }
try_rename = NO;
- if (filename == NULL) {
- if (do_directory) {
- if (NULL != strstr(argv[i], GNUNET_DIRECTORY_EXT)) {
- filename = STRDUP(argv[i]);
- strstr(filename, GNUNET_DIRECTORY_EXT)[0] = '\0';
- } else {
- filename = MALLOC(strlen(argv[i]) + strlen(GNUNET_DIRECTORY_EXT) + 2);
- strcpy(filename, argv[i]);
- strcat(filename, DIR_SEPARATOR_STR);
- strcat(filename, GNUNET_DIRECTORY_EXT);
- }
- try_rename = NO;
- } else {
- GE_ASSERT(ectx,
- strlen(argv[i]) >
- strlen(ECRS_URI_PREFIX) +
- strlen(ECRS_FILE_INFIX));
- filename = string_expandFileName(ectx,
- &argv[i][strlen(ECRS_URI_PREFIX)+
- strlen(ECRS_FILE_INFIX)]);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _("No filename specified, using `%s' instead (for now).\n"),
- filename);
- try_rename = YES;
+ if (filename == NULL)
+ {
+ if (do_directory)
+ {
+ if (NULL != strstr (argv[i], GNUNET_DIRECTORY_EXT))
+ {
+ filename = STRDUP (argv[i]);
+ strstr (filename, GNUNET_DIRECTORY_EXT)[0] = '\0';
+ }
+ else
+ {
+ filename =
+ MALLOC (strlen (argv[i]) + strlen (GNUNET_DIRECTORY_EXT) + 2);
+ strcpy (filename, argv[i]);
+ strcat (filename, DIR_SEPARATOR_STR);
+ strcat (filename, GNUNET_DIRECTORY_EXT);
+ }
+ try_rename = NO;
+ }
+ else
+ {
+ GE_ASSERT (ectx,
+ strlen (argv[i]) >
+ strlen (ECRS_URI_PREFIX) + strlen (ECRS_FILE_INFIX));
+ filename = string_expandFileName (ectx,
+ &argv[i][strlen (ECRS_URI_PREFIX)
+ +
+ strlen
+ (ECRS_FILE_INFIX)]);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ _("No filename specified, using `%s' instead (for now).\n"),
+ filename);
+ try_rename = YES;
+ }
}
- }
ok = NO;
- lock = MUTEX_CREATE(NO);
- ctx = FSUI_start(ectx,
- cfg,
- "gnunet-download",
- parallelism == 0 ? 1 : parallelism,
- NO,
- &progressModel,
- NULL);
- start_time = get_time();
+ lock = MUTEX_CREATE (NO);
+ ctx = FSUI_start (ectx,
+ cfg,
+ "gnunet-download",
+ parallelism == 0 ? 1 : parallelism,
+ NO, &progressModel, NULL);
+ start_time = get_time ();
errorCode = 1;
- if (do_directory) {
- void * data;
- struct stat sbuf;
- int fd;
- int count;
- char * efn;
+ if (do_directory)
+ {
+ void *data;
+ struct stat sbuf;
+ int fd;
+ int count;
+ char *efn;
- fd = -1;
- efn = string_expandFileName(ectx, argv[i]);
- data = NULL;
- if ( (0 != STAT(efn,
- &sbuf)) ||
- (! S_ISREG(sbuf.st_mode)) ||
- (0 != ACCESS(efn,
- R_OK)) ||
- (-1 == (fd = disk_file_open(ectx,
- efn,
- O_LARGEFILE | O_RDONLY)) ) ||
- (MAP_FAILED == (data = MMAP(NULL,
- sbuf.st_size,
- PROT_READ,
- MAP_SHARED,
- fd,
- 0))) ) {
- if (fd != -1)
- CLOSE(fd);
- GE_LOG(ectx,
- GE_ERROR | GE_IMMEDIATE | GE_USER,
- _("Could not access gnunet-directory file `%s'\n"),
- efn);
- FSUI_stop(ctx);
- MUTEX_DESTROY(lock);
- FREE(efn);
- goto quit;
+ fd = -1;
+ efn = string_expandFileName (ectx, argv[i]);
+ data = NULL;
+ if ((0 != STAT (efn,
+ &sbuf)) ||
+ (!S_ISREG (sbuf.st_mode)) ||
+ (0 != ACCESS (efn,
+ R_OK)) ||
+ (-1 == (fd = disk_file_open (ectx,
+ efn,
+ O_LARGEFILE | O_RDONLY))) ||
+ (MAP_FAILED == (data = MMAP (NULL,
+ sbuf.st_size,
+ PROT_READ, MAP_SHARED, fd, 0))))
+ {
+ if (fd != -1)
+ CLOSE (fd);
+ GE_LOG (ectx,
+ GE_ERROR | GE_IMMEDIATE | GE_USER,
+ _("Could not access gnunet-directory file `%s'\n"), efn);
+ FSUI_stop (ctx);
+ MUTEX_DESTROY (lock);
+ FREE (efn);
+ goto quit;
+ }
+ meta = ECRS_createMetaData ();
+ count = ECRS_listDirectory (ectx,
+ data,
+ sbuf.st_size,
+ &meta, &directoryIterator, ctx);
+ ECRS_freeMetaData (meta);
+ MUNMAP (data, sbuf.st_size);
+ CLOSE (fd);
+ FREE (efn);
+ if (verbose > 0)
+ {
+ if (count > 0)
+ printf (_("Downloading %d files from directory `%s'.\n"),
+ count, argv[i]);
+ else
+ printf (_("Did not find any files in directory `%s'\n"), argv[i]);
+ }
}
- meta = ECRS_createMetaData();
- count = ECRS_listDirectory(ectx,
- data,
- sbuf.st_size,
- &meta,
- &directoryIterator,
- ctx);
- ECRS_freeMetaData(meta);
- MUNMAP(data, sbuf.st_size);
- CLOSE(fd);
- FREE(efn);
- if (verbose > 0) {
- if (count > 0)
- printf(_("Downloading %d files from directory `%s'.\n"),
- count,
- argv[i]);
- else
- printf(_("Did not find any files in directory `%s'\n"),
- argv[i]);
+ else
+ {
+ meta = ECRS_createMetaData ();
+ dl = FSUI_startDownload (ctx,
+ anonymity,
+ do_recursive, uri, meta, filename, NULL, NULL);
+ ECRS_freeMetaData (meta);
+ if (dl == NULL)
+ {
+ FSUI_stop (ctx);
+ MUTEX_DESTROY (lock);
+ goto quit;
+ }
}
- } else {
- meta = ECRS_createMetaData();
- dl = FSUI_startDownload(ctx,
- anonymity,
- do_recursive,
- uri,
- meta,
- filename,
- NULL,
- NULL);
- ECRS_freeMetaData(meta);
- if (dl == NULL) {
- FSUI_stop(ctx);
- MUTEX_DESTROY(lock);
- goto quit;
+ GNUNET_SHUTDOWN_WAITFOR ();
+ if (errorCode == 1)
+ {
+ for (i = 0; i < downloads_size; i++)
+ FSUI_abortDownload (ctx, downloads[i]);
}
- }
- GNUNET_SHUTDOWN_WAITFOR();
- if (errorCode == 1) {
- for (i=0;i<downloads_size;i++)
- FSUI_abortDownload(ctx, downloads[i]);
- }
- for (i=0;i<downloads_size;i++)
- FSUI_stopDownload(ctx, downloads[i]);
- GROW(downloads,
- downloads_size,
- 0);
- FSUI_stop(ctx);
- MUTEX_DESTROY(lock);
+ for (i = 0; i < downloads_size; i++)
+ FSUI_stopDownload (ctx, downloads[i]);
+ GROW (downloads, downloads_size, 0);
+ FSUI_stop (ctx);
+ MUTEX_DESTROY (lock);
- if ( (errorCode == 0) &&
- (dl != NULL) &&
- (try_rename == YES) ) {
- char * newname = ECRS_suggestFilename(ectx,
- filename);
+ if ((errorCode == 0) && (dl != NULL) && (try_rename == YES))
+ {
+ char *newname = ECRS_suggestFilename (ectx,
+ filename);
- if (newname != NULL) {
- fprintf(stdout,
- _("File stored as `%s'.\n"),
- newname);
- FREE(newname);
+ if (newname != NULL)
+ {
+ fprintf (stdout, _("File stored as `%s'.\n"), newname);
+ FREE (newname);
+ }
}
- }
- FREE(filename);
+ FREE (filename);
if (uri != NULL)
- ECRS_freeUri(uri);
- quit:
- GNUNET_fini(ectx, cfg);
+ ECRS_freeUri (uri);
+quit:
+ GNUNET_fini (ectx, cfg);
return errorCode;
}
Modified: GNUnet/src/applications/fs/tools/gnunet-insert.c
===================================================================
--- GNUnet/src/applications/fs/tools/gnunet-insert.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/tools/gnunet-insert.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -36,33 +36,31 @@
/* hmm. Man says time.h, but that doesn't yield the
prototype. Strange... */
-extern char *strptime(const char *s,
- const char *format,
- struct tm *tm);
+extern char *strptime (const char *s, const char *format, struct tm *tm);
static int errorCode;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct FSUI_Context * ctx;
+static struct FSUI_Context *ctx;
-static struct FSUI_UploadList * ul;
+static struct FSUI_UploadList *ul;
static cron_t start_time;
/* ************ config options ******** */
-static char * cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
+static char *cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
-static struct ECRS_MetaData * meta;
+static struct ECRS_MetaData *meta;
-static struct ECRS_URI * topKeywords;
+static struct ECRS_URI *topKeywords;
-static struct ECRS_URI * gloKeywords;
+static struct ECRS_URI *gloKeywords;
-static struct ECRS_MetaData * meta;
+static struct ECRS_MetaData *meta;
static unsigned int anonymity = 1;
@@ -70,15 +68,15 @@
static unsigned int interval = 0;
-static char * next_id;
+static char *next_id;
-static char * this_id;
+static char *this_id;
-static char * prev_id;
+static char *prev_id;
-static char * creation_time;
+static char *creation_time;
-static char * pseudonym;
+static char *pseudonym;
static int do_insert;
@@ -92,176 +90,172 @@
static int do_disable_creation_time;
-static void convertId(const char * s,
- HashCode512 * id) {
- if ( (s != NULL) &&
- (enc2hash(s,
- id) == SYSERR) )
- hash(s,
- strlen(s),
- id);
+static void
+convertId (const char *s, HashCode512 * id)
+{
+ if ((s != NULL) && (enc2hash (s, id) == SYSERR))
+ hash (s, strlen (s), id);
}
/**
* We're done with the upload of the file, do the
* post-processing.
*/
-static void postProcess(const struct ECRS_URI * uri) {
+static void
+postProcess (const struct ECRS_URI *uri)
+{
HashCode512 prevId;
HashCode512 thisId;
HashCode512 nextId;
- struct ECRS_URI * nsuri;
- char * us;
+ struct ECRS_URI *nsuri;
+ char *us;
if (pseudonym == NULL)
return;
- convertId(next_id, &nextId);
- convertId(this_id, &thisId);
- convertId(prev_id, &prevId);
- nsuri = NS_addToNamespace(ectx,
- cfg,
- anonymity,
- priority,
- get_time() + 2 * cronYEARS,
- pseudonym,
- (TIME_T) interval,
- prev_id == NULL ? NULL : &prevId,
- this_id == NULL ? NULL : &thisId,
- next_id == NULL ? NULL : &nextId,
- uri,
- meta);
- if (nsuri != NULL) {
- us = ECRS_uriToString(nsuri);
- ECRS_freeUri(nsuri);
- printf(_("Created entry `%s' in namespace `%s'\n"),
- us,
- pseudonym);
- FREE(us);
- } else {
- printf(_("Failed to add entry to namespace `%s' (does it exist?)\n"),
- pseudonym);
- }
- FREE(pseudonym);
+ convertId (next_id, &nextId);
+ convertId (this_id, &thisId);
+ convertId (prev_id, &prevId);
+ nsuri = NS_addToNamespace (ectx,
+ cfg,
+ anonymity,
+ priority,
+ get_time () + 2 * cronYEARS,
+ pseudonym,
+ (TIME_T) interval,
+ prev_id == NULL ? NULL : &prevId,
+ this_id == NULL ? NULL : &thisId,
+ next_id == NULL ? NULL : &nextId, uri, meta);
+ if (nsuri != NULL)
+ {
+ us = ECRS_uriToString (nsuri);
+ ECRS_freeUri (nsuri);
+ printf (_("Created entry `%s' in namespace `%s'\n"), us, pseudonym);
+ FREE (us);
+ }
+ else
+ {
+ printf (_("Failed to add entry to namespace `%s' (does it exist?)\n"),
+ pseudonym);
+ }
+ FREE (pseudonym);
pseudonym = NULL;
}
-static int listKeywords(const char * fn,
- const char * dir,
- void * cls) {
- EXTRACTOR_ExtractorList * l = cls;
- char * fullName;
+static int
+listKeywords (const char *fn, const char *dir, void *cls)
+{
+ EXTRACTOR_ExtractorList *l = cls;
+ char *fullName;
struct stat buf;
- EXTRACTOR_KeywordList * list;
+ EXTRACTOR_KeywordList *list;
- fullName = MALLOC(strlen(dir) + strlen(fn) + 2);
- strcpy(fullName, dir);
- if (dir[strlen(dir)-1] != DIR_SEPARATOR)
- strcat(fullName, DIR_SEPARATOR_STR);
- strcat(fullName, fn);
- printf(_("Keywords for file `%s':\n"),
- fullName);
- if (0 != STAT(fullName,
- &buf)) {
- FREE(fullName);
- return OK;
- }
- if (S_ISDIR(buf.st_mode)) {
- printf("%s - %s\n",
- dgettext("libextractor", "filename"),
- fn);
- printf("%s - %s\n",
- dgettext("libextractor", "mimetype"),
- "application/gnunet-directory");
- disk_directory_scan(NULL,
- fullName,
- &listKeywords,
- cls);
- } else {
- list = EXTRACTOR_getKeywords(l, fullName);
- list = EXTRACTOR_removeDuplicateKeywords(list,
- EXTRACTOR_DUPLICATES_TYPELESS);
- EXTRACTOR_printKeywords(stdout,
- list);
- EXTRACTOR_freeKeywords(list);
- }
- FREE(fullName);
+ fullName = MALLOC (strlen (dir) + strlen (fn) + 2);
+ strcpy (fullName, dir);
+ if (dir[strlen (dir) - 1] != DIR_SEPARATOR)
+ strcat (fullName, DIR_SEPARATOR_STR);
+ strcat (fullName, fn);
+ printf (_("Keywords for file `%s':\n"), fullName);
+ if (0 != STAT (fullName, &buf))
+ {
+ FREE (fullName);
+ return OK;
+ }
+ if (S_ISDIR (buf.st_mode))
+ {
+ printf ("%s - %s\n", dgettext ("libextractor", "filename"), fn);
+ printf ("%s - %s\n",
+ dgettext ("libextractor", "mimetype"),
+ "application/gnunet-directory");
+ disk_directory_scan (NULL, fullName, &listKeywords, cls);
+ }
+ else
+ {
+ list = EXTRACTOR_getKeywords (l, fullName);
+ list = EXTRACTOR_removeDuplicateKeywords (list,
+ EXTRACTOR_DUPLICATES_TYPELESS);
+ EXTRACTOR_printKeywords (stdout, list);
+ EXTRACTOR_freeKeywords (list);
+ }
+ FREE (fullName);
return OK;
}
-
+
/**
* Print progess message.
*/
-static void * printstatus(void * ctx,
- const FSUI_Event * event) {
- unsigned long long * verboselevel = ctx;
+static void *
+printstatus (void *ctx, const FSUI_Event * event)
+{
+ unsigned long long *verboselevel = ctx;
unsigned long long delta;
- char * fstring;
+ char *fstring;
- switch(event->type) {
- case FSUI_upload_progress:
- if (*verboselevel) {
- char * ret;
- cron_t now;
+ switch (event->type)
+ {
+ case FSUI_upload_progress:
+ if (*verboselevel)
+ {
+ char *ret;
+ cron_t now;
- now = get_time();
- delta = event->data.UploadProgress.eta - now;
- if (event->data.UploadProgress.eta < now)
- delta = 0;
- ret = string_get_fancy_time_interval(delta);
- PRINTF(_("%16llu of %16llu bytes inserted "
- "(estimating %6s to completion) - %s\n"),
- event->data.UploadProgress.completed,
- event->data.UploadProgress.total,
- ret,
- event->data.UploadProgress.filename);
- FREE(ret);
+ now = get_time ();
+ delta = event->data.UploadProgress.eta - now;
+ if (event->data.UploadProgress.eta < now)
+ delta = 0;
+ ret = string_get_fancy_time_interval (delta);
+ PRINTF (_("%16llu of %16llu bytes inserted "
+ "(estimating %6s to completion) - %s\n"),
+ event->data.UploadProgress.completed,
+ event->data.UploadProgress.total,
+ ret, event->data.UploadProgress.filename);
+ FREE (ret);
+ }
+ break;
+ case FSUI_upload_completed:
+ if (*verboselevel)
+ {
+ delta = get_time () - start_time;
+ PRINTF (_("Upload of `%s' complete, "
+ "%llu bytes took %llu seconds (%8.3f KiB/s).\n"),
+ event->data.UploadCompleted.filename,
+ event->data.UploadCompleted.total,
+ delta / cronSECONDS,
+ (delta == 0)
+ ? (double) (-1.0)
+ : (double) (event->data.UploadCompleted.total
+ / 1024.0 * cronSECONDS / delta));
+ }
+ fstring = ECRS_uriToString (event->data.UploadCompleted.uri);
+ printf (_("File `%s' has URI: %s\n"),
+ event->data.UploadCompleted.filename, fstring);
+ FREE (fstring);
+ if (ul == event->data.UploadCompleted.uc.pos)
+ {
+ postProcess (event->data.UploadCompleted.uri);
+ errorCode = 0;
+ GNUNET_SHUTDOWN_INITIATE ();
+ }
+ break;
+ case FSUI_upload_aborted:
+ printf (_("\nUpload aborted.\n"));
+ errorCode = 2;
+ GNUNET_SHUTDOWN_INITIATE ();
+ break;
+ case FSUI_upload_error:
+ printf (_("\nError uploading file: %s"),
+ event->data.UploadError.message);
+ errorCode = 3;
+ GNUNET_SHUTDOWN_INITIATE ();
+ break;
+ case FSUI_upload_started:
+ case FSUI_upload_stopped:
+ break;
+ default:
+ printf (_("\nUnexpected event: %d\n"), event->type);
+ GE_BREAK (ectx, 0);
+ break;
}
- break;
- case FSUI_upload_completed:
- if (*verboselevel) {
- delta = get_time() - start_time;
- PRINTF(_("Upload of `%s' complete, "
- "%llu bytes took %llu seconds (%8.3f KiB/s).\n"),
- event->data.UploadCompleted.filename,
- event->data.UploadCompleted.total,
- delta / cronSECONDS,
- (delta == 0)
- ? (double) (-1.0)
- : (double) (event->data.UploadCompleted.total
- / 1024.0 * cronSECONDS / delta));
- }
- fstring = ECRS_uriToString(event->data.UploadCompleted.uri);
- printf(_("File `%s' has URI: %s\n"),
- event->data.UploadCompleted.filename,
- fstring);
- FREE(fstring);
- if (ul == event->data.UploadCompleted.uc.pos) {
- postProcess(event->data.UploadCompleted.uri);
- errorCode = 0;
- GNUNET_SHUTDOWN_INITIATE();
- }
- break;
- case FSUI_upload_aborted:
- printf(_("\nUpload aborted.\n"));
- errorCode = 2;
- GNUNET_SHUTDOWN_INITIATE();
- break;
- case FSUI_upload_error:
- printf(_("\nError uploading file: %s"),
- event->data.UploadError.message);
- errorCode = 3;
- GNUNET_SHUTDOWN_INITIATE();
- break;
- case FSUI_upload_started:
- case FSUI_upload_stopped:
- break;
- default:
- printf(_("\nUnexpected event: %d\n"),
- event->type);
- GE_BREAK(ectx, 0);
- break;
- }
return NULL;
}
@@ -269,71 +263,78 @@
* All gnunet-insert command line options
*/
static struct CommandLineOption gnunetinsertOptions[] = {
- { 'a', "anonymity", "LEVEL",
- gettext_noop("set the desired LEVEL of sender-anonymity"),
- 1, &gnunet_getopt_configure_set_uint, &anonymity },
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- { 'C', "copy", NULL,
- gettext_noop("even if gnunetd is running on the local machine, force the"
- " creation of a copy instead of making a link to the GNUnet share
directory"),
- 0, &gnunet_getopt_configure_set_one, &do_copy },
- { 'd', "disable-creation-time", NULL,
- gettext_noop("disable adding the creation time to the metadata of the
uploaded file"),
- 0, &gnunet_getopt_configure_set_one, &do_disable_creation_time },
- { 'D', "disable-direct", NULL,
- gettext_noop("do not use libextractor to add additional references to
directory entries and/or the published file"),
- 0, &gnunet_getopt_configure_set_one, &do_no_direct_references },
- { 'e', "extract", NULL,
- gettext_noop("print list of extracted keywords that would be used, but do
not perform upload"),
- 0, &gnunet_getopt_configure_set_one, &extract_only },
- COMMAND_LINE_OPTION_HELP(gettext_noop("Make files available to GNUnet for
sharing.")), /* -h */
+ {'a', "anonymity", "LEVEL",
+ gettext_noop ("set the desired LEVEL of sender-anonymity"),
+ 1, &gnunet_getopt_configure_set_uint, &anonymity},
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ {'C', "copy", NULL,
+ gettext_noop ("even if gnunetd is running on the local machine, force the"
+ " creation of a copy instead of making a link to the GNUnet
share directory"),
+ 0, &gnunet_getopt_configure_set_one, &do_copy},
+ {'d', "disable-creation-time", NULL,
+ gettext_noop
+ ("disable adding the creation time to the metadata of the uploaded file"),
+ 0, &gnunet_getopt_configure_set_one, &do_disable_creation_time},
+ {'D', "disable-direct", NULL,
+ gettext_noop
+ ("do not use libextractor to add additional references to directory entries
and/or the published file"),
+ 0, &gnunet_getopt_configure_set_one, &do_no_direct_references},
+ {'e', "extract", NULL,
+ gettext_noop
+ ("print list of extracted keywords that would be used, but do not perform
upload"),
+ 0, &gnunet_getopt_configure_set_one, &extract_only},
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Make files available to GNUnet for
sharing.")), /* -h */
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- { 'i', "interval", "SECONDS",
- gettext_noop("set interval for availability of updates to SECONDS"
- " (for namespace insertions only)"),
- 1, &gnunet_getopt_configure_set_uint, &interval },
- { 'k', "key", "KEYWORD",
- gettext_noop("add an additional keyword for the top-level file or
directory"
- " (this option can be specified multiple times)"),
- 1, &gnunet_getopt_configure_set_keywords, &topKeywords },
- { 'K', "global-key", "KEYWORD",
- gettext_noop("add an additional keyword for all files and directories"
- " (this option can be specified multiple times)"),
- 1, &gnunet_getopt_configure_set_keywords, &gloKeywords },
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'm', "meta", "TYPE:VALUE",
- gettext_noop("set the meta-data for the given TYPE to the given VALUE"),
- 1, &gnunet_getopt_configure_set_metadata, &meta },
- { 'n', "noindex", NULL,
- gettext_noop("do not index, perform full insertion (stores entire "
- "file in encrypted form in GNUnet database)"),
- 0, &gnunet_getopt_configure_set_one, &do_insert },
- { 'N', "next", "ID",
- gettext_noop("specify ID of an updated version to be published in the
future"
- " (for namespace insertions only)"),
- 1, &gnunet_getopt_configure_set_string, &next_id },
- { 'p', "priority", "PRIORITY",
- gettext_noop("specify the priority of the content"),
- 1, &gnunet_getopt_configure_set_uint, &priority },
- { 'P', "pseudonym", "NAME",
- gettext_noop("publish the files under the pseudonym NAME (place file into
namespace)"),
- 1, &gnunet_getopt_configure_set_string, &pseudonym },
- { 'S', "sporadic", NULL,
- gettext_noop("specifies this as an aperiodic but updated publication"
- " (for namespace insertions only)"),
- 0, &gnunet_getopt_configure_set_one, &is_sporadic },
- { 't', "this", "ID",
- gettext_noop("set the ID of this version of the publication"
- " (for namespace insertions only)"),
- 1, &gnunet_getopt_configure_set_string, &this_id },
- { 'T', "time", "TIME",
- gettext_noop("specify creation time for SBlock (see man-page for format)"),
- 1, &gnunet_getopt_configure_set_string, &creation_time },
- { 'u', "update", "ID",
- gettext_noop("ID of the previous version of the content"
- " (for namespace update only)"),
- 1, &gnunet_getopt_configure_set_string, &prev_id },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ {'i', "interval", "SECONDS",
+ gettext_noop ("set interval for availability of updates to SECONDS"
+ " (for namespace insertions only)"),
+ 1, &gnunet_getopt_configure_set_uint, &interval},
+ {'k', "key", "KEYWORD",
+ gettext_noop
+ ("add an additional keyword for the top-level file or directory"
+ " (this option can be specified multiple times)"),
+ 1, &gnunet_getopt_configure_set_keywords, &topKeywords},
+ {'K', "global-key", "KEYWORD",
+ gettext_noop ("add an additional keyword for all files and directories"
+ " (this option can be specified multiple times)"),
+ 1, &gnunet_getopt_configure_set_keywords, &gloKeywords},
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'m', "meta", "TYPE:VALUE",
+ gettext_noop ("set the meta-data for the given TYPE to the given VALUE"),
+ 1, &gnunet_getopt_configure_set_metadata, &meta},
+ {'n', "noindex", NULL,
+ gettext_noop ("do not index, perform full insertion (stores entire "
+ "file in encrypted form in GNUnet database)"),
+ 0, &gnunet_getopt_configure_set_one, &do_insert},
+ {'N', "next", "ID",
+ gettext_noop
+ ("specify ID of an updated version to be published in the future"
+ " (for namespace insertions only)"),
+ 1, &gnunet_getopt_configure_set_string, &next_id},
+ {'p', "priority", "PRIORITY",
+ gettext_noop ("specify the priority of the content"),
+ 1, &gnunet_getopt_configure_set_uint, &priority},
+ {'P', "pseudonym", "NAME",
+ gettext_noop
+ ("publish the files under the pseudonym NAME (place file into namespace)"),
+ 1, &gnunet_getopt_configure_set_string, &pseudonym},
+ {'S', "sporadic", NULL,
+ gettext_noop ("specifies this as an aperiodic but updated publication"
+ " (for namespace insertions only)"),
+ 0, &gnunet_getopt_configure_set_one, &is_sporadic},
+ {'t', "this", "ID",
+ gettext_noop ("set the ID of this version of the publication"
+ " (for namespace insertions only)"),
+ 1, &gnunet_getopt_configure_set_string, &this_id},
+ {'T', "time", "TIME",
+ gettext_noop
+ ("specify creation time for SBlock (see man-page for format)"),
+ 1, &gnunet_getopt_configure_set_string, &creation_time},
+ {'u', "update", "ID",
+ gettext_noop ("ID of the previous version of the content"
+ " (for namespace update only)"),
+ 1, &gnunet_getopt_configure_set_string, &prev_id},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_VERBOSE,
COMMAND_LINE_OPTION_END,
};
@@ -345,189 +346,181 @@
* @param argv command line arguments
* @return return 0 for ok, -1 on error
*/
-int main(int argc,
- char * const * argv) {
- const char * filename;
+int
+main (int argc, char *const *argv)
+{
+ const char *filename;
int i;
- char * tmp;
+ char *tmp;
unsigned long long verbose;
- meta = ECRS_createMetaData();
- i = GNUNET_init(argc,
- argv,
- "gnunet-insert [OPTIONS] FILENAME",
- &cfgFilename,
- gnunetinsertOptions,
- &ectx,
- &cfg);
- if (i == -1) {
- errorCode = -1;
- goto quit;
- }
- if (i != argc - 1) {
- printf(_("You must specify one and only one filename for insertion.\n"));
- errorCode = -1;
- goto quit;
- }
+ meta = ECRS_createMetaData ();
+ i = GNUNET_init (argc,
+ argv,
+ "gnunet-insert [OPTIONS] FILENAME",
+ &cfgFilename, gnunetinsertOptions, &ectx, &cfg);
+ if (i == -1)
+ {
+ errorCode = -1;
+ goto quit;
+ }
+ if (i != argc - 1)
+ {
+ printf (_
+ ("You must specify one and only one filename for insertion.\n"));
+ errorCode = -1;
+ goto quit;
+ }
filename = argv[i];
- if (extract_only) {
- EXTRACTOR_ExtractorList * l;
- char * ex;
- char * dirname;
- char * fname;
+ if (extract_only)
+ {
+ EXTRACTOR_ExtractorList *l;
+ char *ex;
+ char *dirname;
+ char *fname;
- l = EXTRACTOR_loadDefaultLibraries();
- ex = NULL;
- GC_get_configuration_value_string(cfg,
- "FS",
- "EXTRACTORS",
- "",
- &ex);
- if (strlen(ex) > 0)
- l = EXTRACTOR_loadConfigLibraries(l,
- ex);
- FREE(ex);
- dirname = string_expandFileName(ectx, filename);
- GE_ASSERT(ectx, dirname != NULL);
- while ( (strlen(dirname) > 0) &&
- (dirname[strlen(dirname)-1] == DIR_SEPARATOR) )
- dirname[strlen(dirname)-1] = '\0';
- fname = dirname;
- while (strstr(fname, DIR_SEPARATOR_STR) != NULL)
- fname = strstr(fname, DIR_SEPARATOR_STR) + 1;
- GE_ASSERT(ectx,
- fname != dirname);
- fname[-1] = '\0';
- listKeywords(fname,
- dirname,
- l);
- FREE(dirname);
- EXTRACTOR_removeAll(l);
- ECRS_freeMetaData(meta);
+ l = EXTRACTOR_loadDefaultLibraries ();
+ ex = NULL;
+ GC_get_configuration_value_string (cfg, "FS", "EXTRACTORS", "", &ex);
+ if (strlen (ex) > 0)
+ l = EXTRACTOR_loadConfigLibraries (l, ex);
+ FREE (ex);
+ dirname = string_expandFileName (ectx, filename);
+ GE_ASSERT (ectx, dirname != NULL);
+ while ((strlen (dirname) > 0) &&
+ (dirname[strlen (dirname) - 1] == DIR_SEPARATOR))
+ dirname[strlen (dirname) - 1] = '\0';
+ fname = dirname;
+ while (strstr (fname, DIR_SEPARATOR_STR) != NULL)
+ fname = strstr (fname, DIR_SEPARATOR_STR) + 1;
+ GE_ASSERT (ectx, fname != dirname);
+ fname[-1] = '\0';
+ listKeywords (fname, dirname, l);
+ FREE (dirname);
+ EXTRACTOR_removeAll (l);
+ ECRS_freeMetaData (meta);
- errorCode = 0;
- goto quit;
- }
+ errorCode = 0;
+ goto quit;
+ }
- GC_get_configuration_value_number(cfg,
- "GNUNET",
- "VERBOSE",
- 0,
- 9999,
- 0,
- &verbose);
+ GC_get_configuration_value_number (cfg,
+ "GNUNET",
+ "VERBOSE", 0, 9999, 0, &verbose);
/* check arguments */
- if (pseudonym != NULL) {
- if (OK != ECRS_testNamespaceExists(ectx,
- cfg,
- pseudonym,
- NULL)) {
- printf(_("Could not access namespace `%s' (does not exist?).\n"),
- pseudonym);
- errorCode = -1;
- goto quit;
- }
- if (creation_time != NULL) {
- struct tm t;
- const char * fmt;
+ if (pseudonym != NULL)
+ {
+ if (OK != ECRS_testNamespaceExists (ectx, cfg, pseudonym, NULL))
+ {
+ printf (_("Could not access namespace `%s' (does not exist?).\n"),
+ pseudonym);
+ errorCode = -1;
+ goto quit;
+ }
+ if (creation_time != NULL)
+ {
+ struct tm t;
+ const char *fmt;
#if ENABLE_NLS
- fmt = nl_langinfo(D_T_FMT);
+ fmt = nl_langinfo (D_T_FMT);
#else
- fmt = "%Y-%m-%d";
+ fmt = "%Y-%m-%d";
#endif
- if ((NULL == strptime(creation_time,
- fmt,
- &t))) {
- GE_LOG_STRERROR(ectx,
- GE_FATAL | GE_USER | GE_IMMEDIATE,
- "strptime");
- printf(_("Parsing time failed. Use `%s' format.\n"),
- fmt);
- errorCode = -1;
- goto quit;
- }
+ if ((NULL == strptime (creation_time, fmt, &t)))
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_FATAL | GE_USER | GE_IMMEDIATE, "strptime");
+ printf (_("Parsing time failed. Use `%s' format.\n"), fmt);
+ errorCode = -1;
+ goto quit;
+ }
+ }
}
- } else { /* ordinary insertion checks */
- if (NULL != next_id) {
- fprintf(stderr,
- _("Option `%s' makes no sense without option `%s'.\n"),
- "-N", "-P");
- errorCode = -1;
- goto quit;
+ else
+ { /* ordinary insertion checks */
+ if (NULL != next_id)
+ {
+ fprintf (stderr,
+ _("Option `%s' makes no sense without option `%s'.\n"),
+ "-N", "-P");
+ errorCode = -1;
+ goto quit;
+ }
+ if (NULL != prev_id)
+ {
+ fprintf (stderr,
+ _("Option `%s' makes no sense without option `%s'.\n"),
+ "-u", "-P");
+ errorCode = -1;
+ goto quit;
+ }
+ if (NULL != this_id)
+ {
+ fprintf (stderr,
+ _("Option `%s' makes no sense without option `%s'.\n"),
+ "-t", "-P");
+ errorCode = -1;
+ goto quit;
+ }
+ if (0 != interval)
+ {
+ fprintf (stderr,
+ _("Option `%s' makes no sense without option `%s'.\n"),
+ "-i", "-P");
+ errorCode = -1;
+ goto quit;
+ }
+ if (is_sporadic)
+ {
+ fprintf (stderr,
+ _("Option `%s' makes no sense without option `%s'.\n"),
+ "-S", "-P");
+ errorCode = -1;
+ goto quit;
+ }
}
- if (NULL != prev_id) {
- fprintf(stderr, _("Option `%s' makes no sense without option `%s'.\n"),
- "-u", "-P");
- errorCode = -1;
- goto quit;
- }
- if (NULL != this_id) {
- fprintf(stderr, _("Option `%s' makes no sense without option `%s'.\n"),
- "-t", "-P");
- errorCode = -1;
- goto quit;
- }
- if (0 != interval) {
- fprintf(stderr, _("Option `%s' makes no sense without option `%s'.\n"),
- "-i", "-P");
- errorCode = -1;
- goto quit;
- }
- if (is_sporadic) {
- fprintf(stderr, _("Option `%s' makes no sense without option `%s'.\n"),
- "-S", "-P");
- errorCode = -1;
- goto quit;
- }
- }
/* fundamental init */
- ctx = FSUI_start(ectx,
- cfg,
- "gnunet-insert",
- NO,
- 32, /* make configurable */
- &printstatus,
- &verbose);
+ ctx = FSUI_start (ectx, cfg, "gnunet-insert", NO, 32, /* make configurable */
+ &printstatus, &verbose);
/* first insert all of the top-level files or directories */
- tmp = string_expandFileName(ectx, filename);
- if (! do_disable_creation_time)
- ECRS_addPublicationDateToMetaData(meta);
- start_time = get_time();
+ tmp = string_expandFileName (ectx, filename);
+ if (!do_disable_creation_time)
+ ECRS_addPublicationDateToMetaData (meta);
+ start_time = get_time ();
errorCode = 1;
- ul = FSUI_startUpload(ctx,
- tmp,
- (DirectoryScanCallback) &disk_directory_scan,
- ectx,
- anonymity,
- priority,
- ! do_insert,
- YES,
- ! do_no_direct_references,
- start_time + 2 * cronYEARS,
- meta,
- gloKeywords,
- topKeywords);
+ ul = FSUI_startUpload (ctx,
+ tmp,
+ (DirectoryScanCallback) & disk_directory_scan,
+ ectx,
+ anonymity,
+ priority,
+ !do_insert,
+ YES,
+ !do_no_direct_references,
+ start_time + 2 * cronYEARS,
+ meta, gloKeywords, topKeywords);
if (gloKeywords != NULL)
- ECRS_freeUri(gloKeywords);
+ ECRS_freeUri (gloKeywords);
if (topKeywords != NULL)
- ECRS_freeUri(topKeywords);
- FREE(tmp);
- if (ul != NULL) {
- GNUNET_SHUTDOWN_WAITFOR();
- if (errorCode == 1)
- FSUI_abortUpload(ctx, ul);
- FSUI_stopUpload(ctx, ul);
- }
- ECRS_freeMetaData(meta);
- FSUI_stop(ctx);
+ ECRS_freeUri (topKeywords);
+ FREE (tmp);
+ if (ul != NULL)
+ {
+ GNUNET_SHUTDOWN_WAITFOR ();
+ if (errorCode == 1)
+ FSUI_abortUpload (ctx, ul);
+ FSUI_stopUpload (ctx, ul);
+ }
+ ECRS_freeMetaData (meta);
+ FSUI_stop (ctx);
quit:
- GNUNET_fini(ectx, cfg);
+ GNUNET_fini (ectx, cfg);
return errorCode;
}
Modified: GNUnet/src/applications/fs/tools/gnunet-pseudonym.c
===================================================================
--- GNUnet/src/applications/fs/tools/gnunet-pseudonym.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/tools/gnunet-pseudonym.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -31,9 +31,9 @@
#include "gnunet_util_boot.h"
#include "gnunet_util_crypto.h"
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
static int start_collection;
@@ -43,13 +43,13 @@
static int no_advertisement;
-static char * delete_name;
+static char *delete_name;
-static char * create_name;
+static char *create_name;
-static char * set_rating;
+static char *set_rating;
-static char * root_name;
+static char *root_name;
static unsigned int anonymity;
@@ -57,265 +57,260 @@
static cron_t expiration = 2 * cronYEARS;
-static char * cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
+static char *cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
-static struct ECRS_MetaData * meta;
+static struct ECRS_MetaData *meta;
-static struct ECRS_URI * advertisement;
+static struct ECRS_URI *advertisement;
/**
* All gnunet-pseudonym command line options
*/
static struct CommandLineOption gnunetpseudonymOptions[] = {
- { 'a', "anonymity", "LEVEL",
- gettext_noop("set the desired LEVEL of sender-anonymity"),
- 1, &gnunet_getopt_configure_set_uint, &anonymity },
- { 'A', "automate", NULL,
- gettext_noop("automate creation of a namespace by starting a
collection"),
- 0, &gnunet_getopt_configure_set_one, &start_collection },
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- { 'C', "create", "NICKNAME",
- gettext_noop("create a new pseudonym under the given NICKNAME"),
- 1, &gnunet_getopt_configure_set_string, &create_name },
- { 'D', "delete", "NICKNAME",
- gettext_noop("delete the pseudonym with the given NICKNAME"),
- 1, &gnunet_getopt_configure_set_string, &delete_name },
- { 'E', "end", NULL,
- gettext_noop("end automated building of a namespace (ends collection)"),
- 0, &gnunet_getopt_configure_set_one, &stop_collection },
- COMMAND_LINE_OPTION_HELP(gettext_noop("Create new pseudonyms, delete
pseudonyms or list existing pseudonyms.")), /* -h */
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'k', "keyword", "KEYWORD",
- gettext_noop("use the given keyword to advertise the namespace (use when
creating a new pseudonym)"),
- 1, &gnunet_getopt_configure_set_keywords, &advertisement },
- { 'm', "meta", "TYPE=VALUE",
- gettext_noop("specify metadata describing the namespace or collection"),
- 1, &gnunet_getopt_configure_set_metadata, &meta },
- { 'n', "no-advertisement", NULL,
- gettext_noop("do not generate an advertisement for this namespace (use
when creating a new pseudonym)"),
- 0, &gnunet_getopt_configure_set_one, &no_advertisement },
- { 'q', "quiet", NULL,
- gettext_noop("do not list the pseudonyms from the pseudonym database"),
- 0, &gnunet_getopt_configure_set_one, &be_quiet },
- { 'R', "root", "IDENTIFIER",
- gettext_noop("specify IDENTIFIER to be the address of the entrypoint to
content in the namespace (use when creating a new pseudonym)"),
- 1, &gnunet_getopt_configure_set_string, &root_name },
- { 's', "set-rating", "ID:VALUE",
- gettext_noop("set the rating of a namespace"),
- 0, &gnunet_getopt_configure_set_string, &set_rating },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ {'a', "anonymity", "LEVEL",
+ gettext_noop ("set the desired LEVEL of sender-anonymity"),
+ 1, &gnunet_getopt_configure_set_uint, &anonymity},
+ {'A', "automate", NULL,
+ gettext_noop ("automate creation of a namespace by starting a collection"),
+ 0, &gnunet_getopt_configure_set_one, &start_collection},
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ {'C', "create", "NICKNAME",
+ gettext_noop ("create a new pseudonym under the given NICKNAME"),
+ 1, &gnunet_getopt_configure_set_string, &create_name},
+ {'D', "delete", "NICKNAME",
+ gettext_noop ("delete the pseudonym with the given NICKNAME"),
+ 1, &gnunet_getopt_configure_set_string, &delete_name},
+ {'E', "end", NULL,
+ gettext_noop ("end automated building of a namespace (ends collection)"),
+ 0, &gnunet_getopt_configure_set_one, &stop_collection},
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Create new pseudonyms, delete
pseudonyms or list existing pseudonyms.")), /* -h */
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'k', "keyword", "KEYWORD",
+ gettext_noop
+ ("use the given keyword to advertise the namespace (use when creating a new
pseudonym)"),
+ 1, &gnunet_getopt_configure_set_keywords, &advertisement},
+ {'m', "meta", "TYPE=VALUE",
+ gettext_noop ("specify metadata describing the namespace or collection"),
+ 1, &gnunet_getopt_configure_set_metadata, &meta},
+ {'n', "no-advertisement", NULL,
+ gettext_noop
+ ("do not generate an advertisement for this namespace (use when creating a
new pseudonym)"),
+ 0, &gnunet_getopt_configure_set_one, &no_advertisement},
+ {'q', "quiet", NULL,
+ gettext_noop ("do not list the pseudonyms from the pseudonym database"),
+ 0, &gnunet_getopt_configure_set_one, &be_quiet},
+ {'R', "root", "IDENTIFIER",
+ gettext_noop
+ ("specify IDENTIFIER to be the address of the entrypoint to content in the
namespace (use when creating a new pseudonym)"),
+ 1, &gnunet_getopt_configure_set_string, &root_name},
+ {'s', "set-rating", "ID:VALUE",
+ gettext_noop ("set the rating of a namespace"),
+ 0, &gnunet_getopt_configure_set_string, &set_rating},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_VERBOSE,
COMMAND_LINE_OPTION_END,
};
-static int itemPrinter(EXTRACTOR_KeywordType type,
- const char * data,
- void * closure) {
- printf("\t%20s: %s\n",
- dgettext("libextractor",
- EXTRACTOR_getKeywordTypeAsString(type)),
- data);
+static int
+itemPrinter (EXTRACTOR_KeywordType type, const char *data, void *closure)
+{
+ printf ("\t%20s: %s\n",
+ dgettext ("libextractor",
+ EXTRACTOR_getKeywordTypeAsString (type)), data);
return OK;
}
-static void printMeta(const struct ECRS_MetaData * m) {
- ECRS_getMetaData(m,
- &itemPrinter,
- NULL);
+static void
+printMeta (const struct ECRS_MetaData *m)
+{
+ ECRS_getMetaData (m, &itemPrinter, NULL);
}
-static int namespacePrinter(void * unused,
- const char * namespaceName,
- const HashCode512 * id,
- const struct ECRS_MetaData * md,
- int rating) {
+static int
+namespacePrinter (void *unused,
+ const char *namespaceName,
+ const HashCode512 * id,
+ const struct ECRS_MetaData *md, int rating)
+{
EncName enc;
int cpos;
- hash2enc(id,
- &enc);
- if (0 == strcmp(namespaceName, (char*)&enc))
- printf(_("Namespace `%s' has rating %d.\n"),
- namespaceName,
- rating);
+ hash2enc (id, &enc);
+ if (0 == strcmp (namespaceName, (char *) &enc))
+ printf (_("Namespace `%s' has rating %d.\n"), namespaceName, rating);
else
- printf(_("Namespace `%s' (%s) has rating %d.\n"),
- namespaceName,
- (char*) &enc,
- rating);
- printMeta(md);
+ printf (_("Namespace `%s' (%s) has rating %d.\n"),
+ namespaceName, (char *) &enc, rating);
+ printMeta (md);
- if (set_rating != NULL) {
- int delta;
- char * set;
+ if (set_rating != NULL)
+ {
+ int delta;
+ char *set;
- set = set_rating;
- delta = 0;
- cpos = 0;
- while ( (set[cpos] != '\0') &&
- (set[cpos] != ':') )
- cpos++;
- if ( ( ( ( (strlen((char*)&enc)+1 == cpos) &&
- (0 == strncmp(set,
- (char*)&enc,
- cpos)) ) ) ||
- ( (namespaceName != NULL) &&
- (strlen(namespaceName) == cpos) &&
- (0 == strncmp(set,
- namespaceName,
- cpos)) ) ) &&
- (set[cpos] == ':') ) {
- delta = strtol(&set[cpos+1],
- NULL, /* no error handling yet */
- 10);
- }
+ set = set_rating;
+ delta = 0;
+ cpos = 0;
+ while ((set[cpos] != '\0') && (set[cpos] != ':'))
+ cpos++;
+ if (((((strlen ((char *) &enc) + 1 == cpos) &&
+ (0 == strncmp (set,
+ (char *) &enc,
+ cpos)))) ||
+ ((namespaceName != NULL) &&
+ (strlen (namespaceName) == cpos) &&
+ (0 == strncmp (set, namespaceName, cpos)))) && (set[cpos] == ':'))
+ {
+ delta = strtol (&set[cpos + 1], NULL, /* no error handling yet */
+ 10);
+ }
- if (delta != 0) {
- rating = NS_rankNamespace(ectx,
- cfg,
- namespaceName,
- delta);
- printf(_("\tRating (after update): %d\n"),
- rating);
+ if (delta != 0)
+ {
+ rating = NS_rankNamespace (ectx, cfg, namespaceName, delta);
+ printf (_("\tRating (after update): %d\n"), rating);
+ }
}
- }
- printf("\n");
+ printf ("\n");
return OK;
}
-int main(int argc,
- char * const * argv) {
+int
+main (int argc, char *const *argv)
+{
int cnt;
int success;
int i;
HashCode512 hc;
- meta = ECRS_createMetaData();
- i = GNUNET_init(argc,
- argv,
- "gnunet-pseudonym [OPTIONS]",
- &cfgFilename,
- gnunetpseudonymOptions,
- &ectx,
- &cfg);
- if (i == -1) {
- ECRS_freeMetaData(meta);
- GNUNET_fini(ectx, cfg);
- return -1;
- }
- success = 0; /* no errors */
- CO_init(ectx, cfg);
+ meta = ECRS_createMetaData ();
+ i = GNUNET_init (argc,
+ argv,
+ "gnunet-pseudonym [OPTIONS]",
+ &cfgFilename, gnunetpseudonymOptions, &ectx, &cfg);
+ if (i == -1)
+ {
+ ECRS_freeMetaData (meta);
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
+ success = 0; /* no errors */
+ CO_init (ectx, cfg);
/* stop collections */
- if (stop_collection && (! start_collection)) {
- if (OK == CO_stopCollection())
- printf(_("Collection stopped.\n"));
- else
- printf(_("Failed to stop collection (not active?).\n"));
- }
+ if (stop_collection && (!start_collection))
+ {
+ if (OK == CO_stopCollection ())
+ printf (_("Collection stopped.\n"));
+ else
+ printf (_("Failed to stop collection (not active?).\n"));
+ }
/* delete pseudonyms */
- if (delete_name != NULL) {
- if (OK == NS_deleteNamespace(ectx,
- cfg,
- delete_name)) {
- printf(_("Pseudonym `%s' deleted.\n"),
- delete_name);
- } else {
- success += 2;
- printf(_("Error deleting pseudonym `%s' (does not exist?).\n"),
- delete_name);
+ if (delete_name != NULL)
+ {
+ if (OK == NS_deleteNamespace (ectx, cfg, delete_name))
+ {
+ printf (_("Pseudonym `%s' deleted.\n"), delete_name);
+ }
+ else
+ {
+ success += 2;
+ printf (_("Error deleting pseudonym `%s' (does not exist?).\n"),
+ delete_name);
+ }
+ FREE (delete_name);
}
- FREE(delete_name);
- }
/* create collections / namespace */
- if (create_name != NULL) {
- if (start_collection) {
- ECRS_addToMetaData(meta,
- EXTRACTOR_OWNER,
- create_name);
- if (OK == CO_startCollection(anonymity,
- priority,
- ECRS_SBLOCK_UPDATE_SPORADIC, /* FIXME: allow other
update policies */
- create_name,
- meta)) {
- printf(_("Started collection `%s'.\n"),
- create_name);
- } else {
- printf(_("Failed to start collection.\n"));
- success++;
- }
+ if (create_name != NULL)
+ {
+ if (start_collection)
+ {
+ ECRS_addToMetaData (meta, EXTRACTOR_OWNER, create_name);
+ if (OK == CO_startCollection (anonymity, priority,
ECRS_SBLOCK_UPDATE_SPORADIC, /* FIXME: allow other update policies */
+ create_name, meta))
+ {
+ printf (_("Started collection `%s'.\n"), create_name);
+ }
+ else
+ {
+ printf (_("Failed to start collection.\n"));
+ success++;
+ }
- ECRS_delFromMetaData(meta,
- EXTRACTOR_OWNER,
- create_name);
- } else { /* no collection */
- HashCode512 rootEntry;
- struct ECRS_URI * rootURI;
- char * root;
+ ECRS_delFromMetaData (meta, EXTRACTOR_OWNER, create_name);
+ }
+ else
+ { /* no collection */
+ HashCode512 rootEntry;
+ struct ECRS_URI *rootURI;
+ char *root;
- if (root_name == NULL) {
- memset(&rootEntry, 0, sizeof(HashCode512));
- } else {
- if (SYSERR == enc2hash(root_name,
- &hc))
- hash(root_name,
- strlen(root_name),
- &hc);
- }
- if (no_advertisement) {
- if (advertisement != NULL)
- ECRS_freeUri(advertisement);
- advertisement = NULL;
- } else {
- if (advertisement == NULL)
- advertisement = ECRS_parseCharKeywordURI(ectx,
- "namespace");
- }
- rootURI = NS_createNamespace(ectx,
- cfg,
- anonymity,
- priority,
- expiration + get_time(),
- create_name,
- meta,
- advertisement,
- &rootEntry);
- if (rootURI == NULL) {
- printf(_("Could not create namespace `%s' (exists?).\n"),
- create_name);
- success += 1;
- } else {
- root = ECRS_uriToString(rootURI);
- printf(_("Namespace `%s' created (root: %s).\n"),
- create_name,
- root);
- FREE(root);
- ECRS_freeUri(rootURI);
- }
- if (NULL != advertisement)
- ECRS_freeUri(advertisement);
+ if (root_name == NULL)
+ {
+ memset (&rootEntry, 0, sizeof (HashCode512));
+ }
+ else
+ {
+ if (SYSERR == enc2hash (root_name, &hc))
+ hash (root_name, strlen (root_name), &hc);
+ }
+ if (no_advertisement)
+ {
+ if (advertisement != NULL)
+ ECRS_freeUri (advertisement);
+ advertisement = NULL;
+ }
+ else
+ {
+ if (advertisement == NULL)
+ advertisement = ECRS_parseCharKeywordURI (ectx, "namespace");
+ }
+ rootURI = NS_createNamespace (ectx,
+ cfg,
+ anonymity,
+ priority,
+ expiration + get_time (),
+ create_name,
+ meta, advertisement, &rootEntry);
+ if (rootURI == NULL)
+ {
+ printf (_("Could not create namespace `%s' (exists?).\n"),
+ create_name);
+ success += 1;
+ }
+ else
+ {
+ root = ECRS_uriToString (rootURI);
+ printf (_("Namespace `%s' created (root: %s).\n"),
+ create_name, root);
+ FREE (root);
+ ECRS_freeUri (rootURI);
+ }
+ if (NULL != advertisement)
+ ECRS_freeUri (advertisement);
+ }
+ FREE (create_name);
+ create_name = NULL;
}
- FREE(create_name);
- create_name = NULL;
- } else {
- if (start_collection)
- printf(_("You must specify a name for the collection (`%s' option).\n"),
- "-C");
- }
- if (0 == be_quiet) {
- /* print information about pseudonyms */
- cnt = NS_listNamespaces(ectx,
- cfg,
- &namespacePrinter,
- NULL);
- if (cnt == -1)
- printf(_("Could not access namespace information.\n"));
- }
- ECRS_freeMetaData(meta);
- CO_done();
- GNUNET_fini(ectx, cfg);
+ else
+ {
+ if (start_collection)
+ printf (_
+ ("You must specify a name for the collection (`%s'
option).\n"),
+ "-C");
+ }
+ if (0 == be_quiet)
+ {
+ /* print information about pseudonyms */
+ cnt = NS_listNamespaces (ectx, cfg, &namespacePrinter, NULL);
+ if (cnt == -1)
+ printf (_("Could not access namespace information.\n"));
+ }
+ ECRS_freeMetaData (meta);
+ CO_done ();
+ GNUNET_fini (ectx, cfg);
return success;
}
Modified: GNUnet/src/applications/fs/tools/gnunet-search.c
===================================================================
--- GNUnet/src/applications/fs/tools/gnunet-search.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/tools/gnunet-search.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -31,9 +31,9 @@
#include "gnunet_util_boot.h"
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
static unsigned int anonymity = 1;
@@ -41,94 +41,89 @@
static unsigned int max_results;
-static char * cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
+static char *cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
-static char * output_filename;
+static char *output_filename;
static int errorCode;
-static ECRS_FileInfo * fis;
+static ECRS_FileInfo *fis;
static unsigned int fiCount;
-static int itemPrinter(EXTRACTOR_KeywordType type,
- const char * data,
- void * closure) {
- printf("\t%20s: %s\n",
- dgettext("libextractor",
- EXTRACTOR_getKeywordTypeAsString(type)),
- data);
+static int
+itemPrinter (EXTRACTOR_KeywordType type, const char *data, void *closure)
+{
+ printf ("\t%20s: %s\n",
+ dgettext ("libextractor",
+ EXTRACTOR_getKeywordTypeAsString (type)), data);
return OK;
}
-static void printMeta(const struct ECRS_MetaData * meta) {
- ECRS_getMetaData(meta,
- &itemPrinter,
- NULL);
+static void
+printMeta (const struct ECRS_MetaData *meta)
+{
+ ECRS_getMetaData (meta, &itemPrinter, NULL);
}
/**
* Handle the search result.
*/
-static void * eventCallback(void * cls,
- const FSUI_Event * event) {
- char * uri;
- char * filename;
+static void *
+eventCallback (void *cls, const FSUI_Event * event)
+{
+ char *uri;
+ char *filename;
- switch (event->type) {
- case FSUI_search_error:
- errorCode = 3;
- GNUNET_SHUTDOWN_INITIATE();
- break;
- case FSUI_search_aborted:
- errorCode = 4;
- GNUNET_SHUTDOWN_INITIATE();
- break;
- case FSUI_search_completed:
- errorCode = 0;
- GNUNET_SHUTDOWN_INITIATE();
- break;
- case FSUI_search_result:
- /* retain URIs for possible directory dump later */
- GROW(fis,
- fiCount,
- fiCount+1);
- fis[fiCount-1].uri
- = ECRS_dupUri(event->data.SearchResult.fi.uri);
- fis[fiCount-1].meta
- = ECRS_dupMetaData(event->data.SearchResult.fi.meta);
+ switch (event->type)
+ {
+ case FSUI_search_error:
+ errorCode = 3;
+ GNUNET_SHUTDOWN_INITIATE ();
+ break;
+ case FSUI_search_aborted:
+ errorCode = 4;
+ GNUNET_SHUTDOWN_INITIATE ();
+ break;
+ case FSUI_search_completed:
+ errorCode = 0;
+ GNUNET_SHUTDOWN_INITIATE ();
+ break;
+ case FSUI_search_result:
+ /* retain URIs for possible directory dump later */
+ GROW (fis, fiCount, fiCount + 1);
+ fis[fiCount - 1].uri = ECRS_dupUri (event->data.SearchResult.fi.uri);
+ fis[fiCount - 1].meta
+ = ECRS_dupMetaData (event->data.SearchResult.fi.meta);
- uri = ECRS_uriToString(event->data.SearchResult.fi.uri);
- printf("%s:\n",
- uri);
- filename = ECRS_getFromMetaData(event->data.SearchResult.fi.meta,
- EXTRACTOR_FILENAME);
- if (filename != NULL) {
- char * dotdot;
+ uri = ECRS_uriToString (event->data.SearchResult.fi.uri);
+ printf ("%s:\n", uri);
+ filename = ECRS_getFromMetaData (event->data.SearchResult.fi.meta,
+ EXTRACTOR_FILENAME);
+ if (filename != NULL)
+ {
+ char *dotdot;
- while (NULL != (dotdot = strstr(filename, "..")))
- dotdot[0] = dotdot[1] = '_';
+ while (NULL != (dotdot = strstr (filename, "..")))
+ dotdot[0] = dotdot[1] = '_';
- printf("gnunet-download -o \"%s\" %s\n",
- filename,
- uri);
+ printf ("gnunet-download -o \"%s\" %s\n", filename, uri);
+ }
+ else
+ printf ("gnunet-download %s\n", uri);
+ printMeta (event->data.SearchResult.fi.meta);
+ printf ("\n");
+ FREENONNULL (filename);
+ FREE (uri);
+ break;
+ case FSUI_search_started:
+ case FSUI_search_stopped:
+ break;
+ default:
+ GE_BREAK (NULL, 0);
+ break;
}
- else
- printf("gnunet-download %s\n",
- uri);
- printMeta(event->data.SearchResult.fi.meta);
- printf("\n");
- FREENONNULL(filename);
- FREE(uri);
- break;
- case FSUI_search_started:
- case FSUI_search_stopped:
- break;
- default:
- GE_BREAK(NULL, 0);
- break;
- }
return NULL;
}
@@ -136,23 +131,23 @@
* All gnunet-search command line options
*/
static struct CommandLineOption gnunetsearchOptions[] = {
- { 'a', "anonymity", "LEVEL",
- gettext_noop("set the desired LEVEL of sender-anonymity"),
- 1, &gnunet_getopt_configure_set_uint, &anonymity },
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- COMMAND_LINE_OPTION_HELP(gettext_noop("Search GNUnet for files.")), /* -h */
+ {'a', "anonymity", "LEVEL",
+ gettext_noop ("set the desired LEVEL of sender-anonymity"),
+ 1, &gnunet_getopt_configure_set_uint, &anonymity},
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Search GNUnet for files.")), /* -h
*/
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'm', "max", "LIMIT",
- gettext_noop("exit after receiving LIMIT results"),
- 1, &gnunet_getopt_configure_set_uint, &max_results },
- { 'o', "output", "FILENAME",
- gettext_noop("write encountered (decrypted) search results to FILENAME"),
- 1, &gnunet_getopt_configure_set_string, &output_filename },
- { 't', "timeout", "DELAY",
- gettext_noop("wait DELAY seconds for search results before aborting"),
- 1, &gnunet_getopt_configure_set_uint, &delay },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'m', "max", "LIMIT",
+ gettext_noop ("exit after receiving LIMIT results"),
+ 1, &gnunet_getopt_configure_set_uint, &max_results},
+ {'o', "output", "FILENAME",
+ gettext_noop ("write encountered (decrypted) search results to FILENAME"),
+ 1, &gnunet_getopt_configure_set_string, &output_filename},
+ {'t', "timeout", "DELAY",
+ gettext_noop ("wait DELAY seconds for search results before aborting"),
+ 1, &gnunet_getopt_configure_set_uint, &delay},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_VERBOSE,
COMMAND_LINE_OPTION_END,
};
@@ -164,103 +159,82 @@
* @param argv command line arguments
* @return return value from gnunet-search: 0: ok, -1: error
*/
-int main(int argc,
- char * const * argv) {
- struct ECRS_URI * uri;
+int
+main (int argc, char *const *argv)
+{
+ struct ECRS_URI *uri;
int i;
- struct FSUI_Context * ctx;
- struct FSUI_SearchList * s;
+ struct FSUI_Context *ctx;
+ struct FSUI_SearchList *s;
- i = GNUNET_init(argc,
- argv,
- "gnunet-search [OPTIONS] [KEYWORDS]",
- &cfgFilename,
- gnunetsearchOptions,
- &ectx,
- &cfg);
- if (i == SYSERR) {
- GNUNET_fini(ectx,
- cfg);
- return -1;
- }
+ i = GNUNET_init (argc,
+ argv,
+ "gnunet-search [OPTIONS] [KEYWORDS]",
+ &cfgFilename, gnunetsearchOptions, &ectx, &cfg);
+ if (i == SYSERR)
+ {
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
/* convert args to URI */
- uri = ECRS_parseArgvKeywordURI(ectx,
- argc - i,
- (const char**) &argv[i]);
- if (uri == NULL) {
- printf(_("Error converting arguments to URI!\n"));
- errorCode = -1;
- goto quit;
- }
+ uri = ECRS_parseArgvKeywordURI (ectx, argc - i, (const char **) &argv[i]);
+ if (uri == NULL)
+ {
+ printf (_("Error converting arguments to URI!\n"));
+ errorCode = -1;
+ goto quit;
+ }
if (max_results == 0)
- max_results = (unsigned int)-1; /* infty */
- ctx = FSUI_start(ectx,
- cfg,
- "gnunet-search",
- 4,
- NO,
- &eventCallback,
- NULL);
- if (ctx == NULL) {
- ECRS_freeUri(uri);
- GNUNET_fini(ectx, cfg);
- return SYSERR;
- }
+ max_results = (unsigned int) -1; /* infty */
+ ctx = FSUI_start (ectx, cfg, "gnunet-search", 4, NO, &eventCallback, NULL);
+ if (ctx == NULL)
+ {
+ ECRS_freeUri (uri);
+ GNUNET_fini (ectx, cfg);
+ return SYSERR;
+ }
errorCode = 1;
- s = FSUI_startSearch(ctx,
- anonymity,
- max_results,
- delay * cronSECONDS,
- uri);
- ECRS_freeUri(uri);
- if (s == NULL) {
- errorCode = 2;
- FSUI_stop(ctx);
- goto quit;
- }
- GNUNET_SHUTDOWN_WAITFOR();
+ s = FSUI_startSearch (ctx,
+ anonymity, max_results, delay * cronSECONDS, uri);
+ ECRS_freeUri (uri);
+ if (s == NULL)
+ {
+ errorCode = 2;
+ FSUI_stop (ctx);
+ goto quit;
+ }
+ GNUNET_SHUTDOWN_WAITFOR ();
if (errorCode == 1)
- FSUI_abortSearch(ctx,
- s);
- FSUI_stopSearch(ctx,
- s);
- FSUI_stop(ctx);
+ FSUI_abortSearch (ctx, s);
+ FSUI_stopSearch (ctx, s);
+ FSUI_stop (ctx);
- if (output_filename != NULL) {
- char * outfile;
- unsigned long long n;
- char * data;
- struct ECRS_MetaData * meta;
+ if (output_filename != NULL)
+ {
+ char *outfile;
+ unsigned long long n;
+ char *data;
+ struct ECRS_MetaData *meta;
- meta = ECRS_createMetaData();
- /* ?: anything here to put into meta? */
- if (OK == ECRS_createDirectory(ectx,
- &data,
- &n,
- fiCount,
- fis,
- meta)) {
- outfile = string_expandFileName(ectx,
- output_filename);
- disk_file_write(ectx,
- outfile,
- data,
- n,
- "600");
- FREE(outfile);
- FREE(data);
+ meta = ECRS_createMetaData ();
+ /* ?: anything here to put into meta? */
+ if (OK == ECRS_createDirectory (ectx, &data, &n, fiCount, fis, meta))
+ {
+ outfile = string_expandFileName (ectx, output_filename);
+ disk_file_write (ectx, outfile, data, n, "600");
+ FREE (outfile);
+ FREE (data);
+ }
+ FREE (output_filename);
}
- FREE(output_filename);
- }
- for (i=0;i<fiCount;i++) {
- ECRS_freeUri(fis[i].uri);
- ECRS_freeMetaData(fis[i].meta);
- }
- GROW(fis,
- fiCount,
- 0);
- quit:
- GNUNET_fini(ectx, cfg);
+ for (i = 0; i < fiCount; i++)
+ {
+ ECRS_freeUri (fis[i].uri);
+ ECRS_freeMetaData (fis[i].meta);
+ }
+ GROW (fis, fiCount, 0);
+quit:
+ GNUNET_fini (ectx, cfg);
return errorCode;
}
Modified: GNUnet/src/applications/fs/tools/gnunet-unindex.c
===================================================================
--- GNUnet/src/applications/fs/tools/gnunet-unindex.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/tools/gnunet-unindex.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -32,63 +32,68 @@
#include "gnunet_fsui_lib.h"
#include "gnunet_util_boot.h"
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
static cron_t start_time;
static int errorCode;
-static char * cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
+static char *cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
/**
* Print progess message.
*/
-static void * printstatus(void * cls,
- const FSUI_Event * event) {
- unsigned long long * verboselevel = cls;
+static void *
+printstatus (void *cls, const FSUI_Event * event)
+{
+ unsigned long long *verboselevel = cls;
unsigned long long delta;
- switch(event->type) {
- case FSUI_unindex_progress:
- if (*verboselevel) {
- delta = event->data.UnindexProgress.eta - get_time();
- PRINTF(_("%16llu of %16llu bytes unindexed (estimating %llu seconds to
completion) "),
- event->data.UnindexProgress.completed,
- event->data.UnindexProgress.total,
- delta / cronSECONDS);
- printf("\r");
+ switch (event->type)
+ {
+ case FSUI_unindex_progress:
+ if (*verboselevel)
+ {
+ delta = event->data.UnindexProgress.eta - get_time ();
+ PRINTF (_
+ ("%16llu of %16llu bytes unindexed (estimating %llu seconds
to completion) "),
+ event->data.UnindexProgress.completed,
+ event->data.UnindexProgress.total, delta / cronSECONDS);
+ printf ("\r");
+ }
+ break;
+ case FSUI_unindex_completed:
+ if (*verboselevel)
+ {
+ delta = get_time () - start_time;
+ PRINTF (_
+ ("\nUnindexing of `%s' complete, %llu bytes took %llu
seconds (%8.3f KiB/s).\n"),
+ event->data.UnindexCompleted.filename,
+ event->data.UnindexCompleted.total, delta / cronSECONDS,
+ (delta ==
+ 0) ? (double) (-1.0) : (double) (event->data.
+ UnindexCompleted.total /
+ 1024.0 * cronSECONDS /
+ delta));
+ }
+ errorCode = 0;
+ GNUNET_SHUTDOWN_INITIATE ();
+ break;
+ case FSUI_unindex_error:
+ printf (_("\nError unindexing file: %s\n"),
+ event->data.UnindexError.message);
+ errorCode = 3;
+ GNUNET_SHUTDOWN_INITIATE ();
+ break;
+ case FSUI_unindex_started:
+ case FSUI_unindex_stopped:
+ break;
+ default:
+ GE_BREAK (ectx, 0);
+ break;
}
- break;
- case FSUI_unindex_completed:
- if (*verboselevel) {
- delta = get_time() - start_time;
- PRINTF(
- _("\nUnindexing of `%s' complete, %llu bytes took %llu seconds (%8.3f
KiB/s).\n"),
- event->data.UnindexCompleted.filename,
- event->data.UnindexCompleted.total,
- delta / cronSECONDS,
- (delta == 0)
- ? (double) (-1.0)
- : (double) (event->data.UnindexCompleted.total / 1024.0 * cronSECONDS /
delta));
- }
- errorCode = 0;
- GNUNET_SHUTDOWN_INITIATE();
- break;
- case FSUI_unindex_error:
- printf(_("\nError unindexing file: %s\n"),
- event->data.UnindexError.message);
- errorCode = 3;
- GNUNET_SHUTDOWN_INITIATE();
- break;
- case FSUI_unindex_started:
- case FSUI_unindex_stopped:
- break;
- default:
- GE_BREAK(ectx, 0);
- break;
- }
return NULL;
}
@@ -96,11 +101,11 @@
* All gnunet-unindex command line options
*/
static struct CommandLineOption gnunetunindexOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- COMMAND_LINE_OPTION_HELP(gettext_noop("Unindex files.")), /* -h */
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Unindex files.")), /* -h */
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_VERBOSE,
COMMAND_LINE_OPTION_END,
};
@@ -112,68 +117,57 @@
* @param argv command line arguments
* @return return 0 for ok, -1 on error
*/
-int main(int argc,
- char * const * argv) {
- static struct FSUI_Context * ctx;
- char * filename;
+int
+main (int argc, char *const *argv)
+{
+ static struct FSUI_Context *ctx;
+ char *filename;
int i;
unsigned long long verbose;
- struct FSUI_UnindexList * ul;
+ struct FSUI_UnindexList *ul;
- i = GNUNET_init(argc,
- argv,
- "gnunet-unindex [OPTIONS] FILENAME",
- &cfgFilename,
- gnunetunindexOptions,
- &ectx,
- &cfg);
- if (i == -1) {
- GNUNET_fini(ectx, cfg);
- return -1;
- }
- if (i == argc) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Not enough arguments. "
- "You must specify a filename.\n"));
- GNUNET_fini(ectx, cfg);
- return -1;
- }
- GC_get_configuration_value_number(cfg,
- "GNUNET",
- "VERBOSE",
- 0,
- 9999,
- 0,
- &verbose);
+ i = GNUNET_init (argc,
+ argv,
+ "gnunet-unindex [OPTIONS] FILENAME",
+ &cfgFilename, gnunetunindexOptions, &ectx, &cfg);
+ if (i == -1)
+ {
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
+ if (i == argc)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Not enough arguments. " "You must specify a filename.\n"));
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
+ GC_get_configuration_value_number (cfg,
+ "GNUNET",
+ "VERBOSE", 0, 9999, 0, &verbose);
/* fundamental init */
- ctx = FSUI_start(ectx,
- cfg,
- "gnunet-unindex",
- 2,
- NO,
- &printstatus,
- &verbose);
+ ctx = FSUI_start (ectx,
+ cfg, "gnunet-unindex", 2, NO, &printstatus, &verbose);
errorCode = 1;
- start_time = get_time();
- filename = string_expandFileName(ectx,
- argv[i]);
- ul = FSUI_startUnindex(ctx,
- filename);
- if (ul == NULL) {
- printf(_("`%s' failed. Is `%s' a file?\n"),
- "FSUI_unindex",
- filename);
- errorCode = 2;
- } else {
- GNUNET_SHUTDOWN_WAITFOR();
- if (errorCode == 1)
- FSUI_abortUnindex(ctx, ul);
- FSUI_stopUnindex(ctx, ul);
- }
- FREE(filename);
- FSUI_stop(ctx);
- GNUNET_fini(ectx, cfg);
+ start_time = get_time ();
+ filename = string_expandFileName (ectx, argv[i]);
+ ul = FSUI_startUnindex (ctx, filename);
+ if (ul == NULL)
+ {
+ printf (_("`%s' failed. Is `%s' a file?\n"), "FSUI_unindex", filename);
+ errorCode = 2;
+ }
+ else
+ {
+ GNUNET_SHUTDOWN_WAITFOR ();
+ if (errorCode == 1)
+ FSUI_abortUnindex (ctx, ul);
+ FSUI_stopUnindex (ctx, ul);
+ }
+ FREE (filename);
+ FSUI_stop (ctx);
+ GNUNET_fini (ectx, cfg);
return errorCode;
}
Modified: GNUnet/src/applications/fs/uritrack/callbacks.c
===================================================================
--- GNUnet/src/applications/fs/uritrack/callbacks.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/uritrack/callbacks.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -32,48 +32,44 @@
/**
* @brief Struct for URITRACK callback.
*/
-typedef struct {
- struct GE_Context * ectx;
+typedef struct
+{
+ struct GE_Context *ectx;
- struct GC_Configuration * cfg;
-
+ struct GC_Configuration *cfg;
+
ECRS_SearchProgressCallback iterator;
- void * closure;
+ void *closure;
- struct PTHREAD * init;
+ struct PTHREAD *init;
int abort_init;
} Callback;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-static Callback ** callbacks;
+static Callback **callbacks;
static unsigned int callbacks_size;
-static int init_iterator(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * closure) {
- Callback * c = closure;
+static int
+init_iterator (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *closure)
+{
+ Callback *c = closure;
- c->iterator(fi,
- key,
- isRoot,
- c->closure);
- if (c->abort_init)
- return SYSERR;
- return OK;
+ c->iterator (fi, key, isRoot, c->closure);
+ if (c->abort_init)
+ return SYSERR;
+ return OK;
}
-static void * init_thread(void * arg) {
- Callback * c = arg;
- URITRACK_listURIs(c->ectx,
- c->cfg,
- YES,
- &init_iterator,
- arg);
+static void *
+init_thread (void *arg)
+{
+ Callback *c = arg;
+ URITRACK_listURIs (c->ectx, c->cfg, YES, &init_iterator, arg);
return NULL;
}
@@ -83,80 +79,80 @@
* the database, the callback will be called
* for all existing URIs as well.
*/
-int URITRACK_registerTrackCallback(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- ECRS_SearchProgressCallback iterator,
- void * closure) {
- Callback * c;
+int
+URITRACK_registerTrackCallback (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ ECRS_SearchProgressCallback iterator,
+ void *closure)
+{
+ Callback *c;
- c = MALLOC(sizeof(Callback));
+ c = MALLOC (sizeof (Callback));
c->ectx = ectx;
c->cfg = cfg;
c->iterator = iterator;
c->closure = closure;
c->abort_init = NO;
- c->init = PTHREAD_CREATE(&init_thread,
- c,
- 16 * 1024);
- MUTEX_LOCK(lock);
- GROW(callbacks,
- callbacks_size,
- callbacks_size + 1);
- callbacks[callbacks_size-1] = c;
- MUTEX_UNLOCK(lock);
+ c->init = PTHREAD_CREATE (&init_thread, c, 16 * 1024);
+ MUTEX_LOCK (lock);
+ GROW (callbacks, callbacks_size, callbacks_size + 1);
+ callbacks[callbacks_size - 1] = c;
+ MUTEX_UNLOCK (lock);
return OK;
}
/**
* Unregister a URI callback.
*/
-int URITRACK_unregisterTrackCallback(ECRS_SearchProgressCallback iterator,
- void * closure) {
+int
+URITRACK_unregisterTrackCallback (ECRS_SearchProgressCallback iterator,
+ void *closure)
+{
int i;
- void * unused;
- Callback * c;
+ void *unused;
+ Callback *c;
- MUTEX_LOCK(lock);
- for (i=0;i<callbacks_size;i++) {
- c = callbacks[i];
- if ( (c->iterator == iterator) &&
- (c->closure == closure) ) {
- c->abort_init = YES;
- PTHREAD_JOIN(c->init, &unused);
- callbacks[i] = callbacks[callbacks_size-1];
- GROW(callbacks,
- callbacks_size,
- callbacks_size - 1);
- FREE(c);
- MUTEX_UNLOCK(lock);
- return OK;
+ MUTEX_LOCK (lock);
+ for (i = 0; i < callbacks_size; i++)
+ {
+ c = callbacks[i];
+ if ((c->iterator == iterator) && (c->closure == closure))
+ {
+ c->abort_init = YES;
+ PTHREAD_JOIN (c->init, &unused);
+ callbacks[i] = callbacks[callbacks_size - 1];
+ GROW (callbacks, callbacks_size, callbacks_size - 1);
+ FREE (c);
+ MUTEX_UNLOCK (lock);
+ return OK;
+ }
}
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return SYSERR;
}
/**
* Internal notification about new tracked URI.
*/
-void URITRACK_internal_notify(const ECRS_FileInfo * fi) {
+void
+URITRACK_internal_notify (const ECRS_FileInfo * fi)
+{
int i;
- MUTEX_LOCK(lock);
- for (i=0;i<callbacks_size;i++)
- callbacks[i]->iterator(fi,
- NULL,
- NO,
- callbacks[i]->closure);
- MUTEX_UNLOCK(lock);
+ MUTEX_LOCK (lock);
+ for (i = 0; i < callbacks_size; i++)
+ callbacks[i]->iterator (fi, NULL, NO, callbacks[i]->closure);
+ MUTEX_UNLOCK (lock);
}
-void __attribute__ ((constructor)) gnunet_uritrack_ltdl_init() {
- lock = MUTEX_CREATE(NO);
+void __attribute__ ((constructor)) gnunet_uritrack_ltdl_init ()
+{
+ lock = MUTEX_CREATE (NO);
}
-void __attribute__ ((destructor)) gnunet_uritrack_ltdl_fini() {
- MUTEX_DESTROY(lock);
+void __attribute__ ((destructor)) gnunet_uritrack_ltdl_fini ()
+{
+ MUTEX_DESTROY (lock);
lock = NULL;
}
Modified: GNUnet/src/applications/fs/uritrack/callbacks.h
===================================================================
--- GNUnet/src/applications/fs/uritrack/callbacks.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/uritrack/callbacks.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -30,6 +30,6 @@
/**
* Internal notification about new tracked URI.
*/
-void URITRACK_internal_notify(const ECRS_FileInfo * fi);
+void URITRACK_internal_notify (const ECRS_FileInfo * fi);
#endif
Modified: GNUnet/src/applications/fs/uritrack/file_info.c
===================================================================
--- GNUnet/src/applications/fs/uritrack/file_info.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/uritrack/file_info.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -39,66 +39,61 @@
#define TRACK_OPTION "fs_uridb_status"
static struct IPC_SEMAPHORE *
-createIPC(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- char * basename;
- char * ipcName;
- struct IPC_SEMAPHORE * sem;
+createIPC (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ char *basename;
+ char *ipcName;
+ struct IPC_SEMAPHORE *sem;
size_t n;
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &basename);
- n = strlen(basename) + 512;
- ipcName = MALLOC(n);
- SNPRINTF(ipcName, n, "%s/directory_ipc_lock", basename);
- FREE(basename);
- sem = IPC_SEMAPHORE_CREATE(ectx, ipcName, 1);
- FREE(ipcName);
- return sem;
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &basename);
+ n = strlen (basename) + 512;
+ ipcName = MALLOC (n);
+ SNPRINTF (ipcName, n, "%s/directory_ipc_lock", basename);
+ FREE (basename);
+ sem = IPC_SEMAPHORE_CREATE (ectx, ipcName, 1);
+ FREE (ipcName);
+ return sem;
}
static char *
-getUriDbName(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- char * nw;
- char * pfx;
+getUriDbName (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ char *nw;
+ char *pfx;
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &pfx);
- nw = MALLOC(strlen(pfx) + strlen(STATE_NAME) + 2);
- strcpy(nw, pfx);
- strcat(nw, DIR_SEPARATOR_STR);
- strcat(nw, STATE_NAME);
- FREE(pfx);
- disk_directory_create_for_file(ectx,
- nw);
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &pfx);
+ nw = MALLOC (strlen (pfx) + strlen (STATE_NAME) + 2);
+ strcpy (nw, pfx);
+ strcat (nw, DIR_SEPARATOR_STR);
+ strcat (nw, STATE_NAME);
+ FREE (pfx);
+ disk_directory_create_for_file (ectx, nw);
return nw;
}
static char *
-getToggleName(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- char * nw;
- char * pfx;
+getToggleName (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ char *nw;
+ char *pfx;
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &pfx);
- nw = MALLOC(strlen(pfx) + strlen(TRACK_OPTION) + 2);
- strcpy(nw, pfx);
- strcat(nw, DIR_SEPARATOR_STR);
- strcat(nw, TRACK_OPTION);
- FREE(pfx);
- disk_directory_create_for_file(ectx,
- nw);
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &pfx);
+ nw = MALLOC (strlen (pfx) + strlen (TRACK_OPTION) + 2);
+ strcpy (nw, pfx);
+ strcat (nw, DIR_SEPARATOR_STR);
+ strcat (nw, TRACK_OPTION);
+ FREE (pfx);
+ disk_directory_create_for_file (ectx, nw);
return nw;
}
@@ -107,134 +102,138 @@
*
* @return YES of tracking is enabled, NO if not
*/
-int URITRACK_trackStatus(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
+int
+URITRACK_trackStatus (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
int status;
- char * tn;
+ char *tn;
- tn = getToggleName(ectx,
- cfg);
- if (YES != disk_file_test(ectx,
- tn)) {
- FREE(tn);
- return NO; /* default: off */
- }
- if ( (sizeof(int) != disk_file_read(ectx,
- tn,
- sizeof(int),
- &status)) ||
- (ntohl(status) != YES) ) {
- FREE(tn);
+ tn = getToggleName (ectx, cfg);
+ if (YES != disk_file_test (ectx, tn))
+ {
+ FREE (tn);
+ return NO; /* default: off */
+ }
+ if ((sizeof (int) != disk_file_read (ectx,
+ tn,
+ sizeof (int),
+ &status)) || (ntohl (status) != YES))
+ {
+ FREE (tn);
#if DEBUG_FILE_INFO
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _("Collecting file identifiers disabled.\n"));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ _("Collecting file identifiers disabled.\n"));
#endif
- return NO;
- } else {
- FREE(tn);
- return YES;
- }
+ return NO;
+ }
+ else
+ {
+ FREE (tn);
+ return YES;
+ }
}
-struct CheckPresentClosure {
- const ECRS_FileInfo * fi;
+struct CheckPresentClosure
+{
+ const ECRS_FileInfo *fi;
int present;
};
-static int checkPresent(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * closure) {
- struct CheckPresentClosure * cpc = closure;
- if (ECRS_equalsUri(fi->uri,
- cpc->fi->uri)) {
- cpc->present = 1;
- return SYSERR;
- }
+static int
+checkPresent (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *closure)
+{
+ struct CheckPresentClosure *cpc = closure;
+ if (ECRS_equalsUri (fi->uri, cpc->fi->uri))
+ {
+ cpc->present = 1;
+ return SYSERR;
+ }
return OK;
}
/**
* Makes a URI available for directory building.
*/
-void URITRACK_trackURI(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const ECRS_FileInfo * fi) {
- struct IPC_SEMAPHORE * sem;
- char * data;
+void
+URITRACK_trackURI (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, const ECRS_FileInfo * fi)
+{
+ struct IPC_SEMAPHORE *sem;
+ char *data;
unsigned int size;
- char * suri;
+ char *suri;
int fh;
- char * fn;
+ char *fn;
struct CheckPresentClosure cpc;
- if (NO == URITRACK_trackStatus(ectx, cfg))
+ if (NO == URITRACK_trackStatus (ectx, cfg))
return;
cpc.present = 0;
cpc.fi = fi;
- URITRACK_listURIs(ectx,
- cfg,
- NO,
- &checkPresent,
- &cpc);
+ URITRACK_listURIs (ectx, cfg, NO, &checkPresent, &cpc);
if (cpc.present == 1)
return;
- size = ECRS_sizeofMetaData(fi->meta,
- ECRS_SERIALIZE_FULL | ECRS_SERIALIZE_NO_COMPRESS);
- data = MALLOC(size);
- GE_ASSERT(ectx,
- size == ECRS_serializeMetaData(ectx,
- fi->meta,
- data,
- size,
- ECRS_SERIALIZE_FULL |
ECRS_SERIALIZE_NO_COMPRESS));
- size = htonl(size);
- suri = ECRS_uriToString(fi->uri);
- sem = createIPC(ectx, cfg);
- IPC_SEMAPHORE_DOWN(sem, YES);
- fn = getUriDbName(ectx, cfg);
- fh = disk_file_open(ectx,
- fn,
- O_WRONLY|O_APPEND|O_CREAT|O_LARGEFILE,
- S_IRUSR|S_IWUSR);
- if (fh != -1) {
- WRITE(fh, suri, strlen(suri) + 1);
- WRITE(fh, &size, sizeof(unsigned int));
- WRITE(fh, data, ntohl(size));
- CLOSE(fh);
- }
- FREE(fn);
- IPC_SEMAPHORE_UP(sem);
- IPC_SEMAPHORE_DESTROY(sem);
- FREE(data);
- FREE(suri);
- URITRACK_internal_notify(fi);
+ size = ECRS_sizeofMetaData (fi->meta,
+ ECRS_SERIALIZE_FULL |
+ ECRS_SERIALIZE_NO_COMPRESS);
+ data = MALLOC (size);
+ GE_ASSERT (ectx,
+ size == ECRS_serializeMetaData (ectx,
+ fi->meta,
+ data,
+ size,
+ ECRS_SERIALIZE_FULL |
+ ECRS_SERIALIZE_NO_COMPRESS));
+ size = htonl (size);
+ suri = ECRS_uriToString (fi->uri);
+ sem = createIPC (ectx, cfg);
+ IPC_SEMAPHORE_DOWN (sem, YES);
+ fn = getUriDbName (ectx, cfg);
+ fh = disk_file_open (ectx,
+ fn,
+ O_WRONLY | O_APPEND | O_CREAT | O_LARGEFILE,
+ S_IRUSR | S_IWUSR);
+ if (fh != -1)
+ {
+ WRITE (fh, suri, strlen (suri) + 1);
+ WRITE (fh, &size, sizeof (unsigned int));
+ WRITE (fh, data, ntohl (size));
+ CLOSE (fh);
+ }
+ FREE (fn);
+ IPC_SEMAPHORE_UP (sem);
+ IPC_SEMAPHORE_DESTROY (sem);
+ FREE (data);
+ FREE (suri);
+ URITRACK_internal_notify (fi);
}
/**
* Remove all of the root-nodes of a particular type
* from the tracking database.
*/
-void URITRACK_clearTrackedURIS(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- struct IPC_SEMAPHORE * sem;
- char * fn;
+void
+URITRACK_clearTrackedURIS (struct GE_Context *ectx,
+ struct GC_Configuration *cfg)
+{
+ struct IPC_SEMAPHORE *sem;
+ char *fn;
- sem = createIPC(ectx, cfg);
- IPC_SEMAPHORE_DOWN(sem, YES);
- fn = getUriDbName(ectx, cfg);
- if (YES == disk_file_test(ectx,
- fn)) {
- if (0 != UNLINK(fn))
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "unlink",
- fn);
- }
- FREE(fn);
- IPC_SEMAPHORE_UP(sem);
- IPC_SEMAPHORE_DESTROY(sem);
+ sem = createIPC (ectx, cfg);
+ IPC_SEMAPHORE_DOWN (sem, YES);
+ fn = getUriDbName (ectx, cfg);
+ if (YES == disk_file_test (ectx, fn))
+ {
+ if (0 != UNLINK (fn))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "unlink", fn);
+ }
+ FREE (fn);
+ IPC_SEMAPHORE_UP (sem);
+ IPC_SEMAPHORE_DESTROY (sem);
}
/**
@@ -243,20 +242,16 @@
* @param onOff YES to enable tracking, NO to disable
* disabling tracking
*/
-void URITRACK_trackURIS(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- int onOff) {
- int o = htonl(onOff);
- char * tn;
+void
+URITRACK_trackURIS (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, int onOff)
+{
+ int o = htonl (onOff);
+ char *tn;
- tn = getToggleName(ectx,
- cfg);
- disk_file_write(ectx,
- tn,
- &o,
- sizeof(int),
- "600");
- FREE(tn);
+ tn = getToggleName (ectx, cfg);
+ disk_file_write (ectx, tn, &o, sizeof (int), "600");
+ FREE (tn);
}
/**
@@ -269,11 +264,12 @@
* provided, NO if metadata is not needed (faster)
* @return number of entries found
*/
-int URITRACK_listURIs(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- int need_metadata,
- ECRS_SearchProgressCallback iterator,
- void *closure) {
+int
+URITRACK_listURIs (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ int need_metadata,
+ ECRS_SearchProgressCallback iterator, void *closure)
+{
struct IPC_SEMAPHORE *sem;
int rval;
char *result;
@@ -286,131 +282,124 @@
char *fn;
struct stat buf;
- fn = getUriDbName(ectx, cfg);
- sem = createIPC(ectx, cfg);
- IPC_SEMAPHORE_DOWN(sem, YES);
- if ( (0 != STAT(fn, &buf)) ||
- (buf.st_size == 0) ) {
- IPC_SEMAPHORE_UP(sem);
- IPC_SEMAPHORE_DESTROY(sem);
- FREE(fn);
- return 0; /* no URI db */
- }
- fd = disk_file_open(ectx,
- fn,
- O_LARGEFILE | O_RDONLY);
- if (fd == -1) {
- IPC_SEMAPHORE_UP(sem);
- IPC_SEMAPHORE_DESTROY(sem);
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "open",
- fn);
- FREE(fn);
- return SYSERR; /* error opening URI db */
- }
- result = MMAP(NULL,
- buf.st_size,
- PROT_READ,
- MAP_SHARED,
- fd,
- 0);
- if (result == MAP_FAILED) {
- CLOSE(fd);
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "mmap",
- fn);
- FREE(fn);
- IPC_SEMAPHORE_UP(sem);
- IPC_SEMAPHORE_DESTROY(sem);
- return SYSERR;
- }
+ fn = getUriDbName (ectx, cfg);
+ sem = createIPC (ectx, cfg);
+ IPC_SEMAPHORE_DOWN (sem, YES);
+ if ((0 != STAT (fn, &buf)) || (buf.st_size == 0))
+ {
+ IPC_SEMAPHORE_UP (sem);
+ IPC_SEMAPHORE_DESTROY (sem);
+ FREE (fn);
+ return 0; /* no URI db */
+ }
+ fd = disk_file_open (ectx, fn, O_LARGEFILE | O_RDONLY);
+ if (fd == -1)
+ {
+ IPC_SEMAPHORE_UP (sem);
+ IPC_SEMAPHORE_DESTROY (sem);
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "open", fn);
+ FREE (fn);
+ return SYSERR; /* error opening URI db */
+ }
+ result = MMAP (NULL, buf.st_size, PROT_READ, MAP_SHARED, fd, 0);
+ if (result == MAP_FAILED)
+ {
+ CLOSE (fd);
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "mmap", fn);
+ FREE (fn);
+ IPC_SEMAPHORE_UP (sem);
+ IPC_SEMAPHORE_DESTROY (sem);
+ return SYSERR;
+ }
ret = buf.st_size;
pos = 0;
rval = 0;
- while(pos < ret) {
- spos = pos;
- while((spos < ret) && (result[spos] != '\0'))
- spos++;
- spos++; /* skip '\0' */
- if((spos + sizeof(int) >= ret) || (spos + sizeof(int) < spos)) {
- GE_BREAK(ectx, 0);
- goto FORMATERROR;
+ while (pos < ret)
+ {
+ spos = pos;
+ while ((spos < ret) && (result[spos] != '\0'))
+ spos++;
+ spos++; /* skip '\0' */
+ if ((spos + sizeof (int) >= ret) || (spos + sizeof (int) < spos))
+ {
+ GE_BREAK (ectx, 0);
+ goto FORMATERROR;
+ }
+ fi.uri = ECRS_stringToUri (ectx, &result[pos]);
+ if (fi.uri == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ goto FORMATERROR;
+ }
+ memcpy (&msize, &result[spos], sizeof (int));
+ msize = ntohl (msize);
+ spos += sizeof (int);
+ if ((spos + msize > ret) || (spos + msize < spos))
+ {
+ GE_BREAK (ectx, 0);
+ ECRS_freeUri (fi.uri);
+ goto FORMATERROR;
+ }
+ if (need_metadata == YES)
+ {
+ fi.meta = ECRS_deserializeMetaData (ectx, &result[spos], msize);
+ if (fi.meta == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ ECRS_freeUri (fi.uri);
+ goto FORMATERROR;
+ }
+ }
+ else
+ {
+ fi.meta = NULL;
+ }
+ pos = spos + msize;
+ if (iterator != NULL)
+ {
+ if (OK != iterator (&fi, NULL, NO, closure))
+ {
+ if (fi.meta != NULL)
+ ECRS_freeMetaData (fi.meta);
+ ECRS_freeUri (fi.uri);
+ if (0 != MUNMAP (result, buf.st_size))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK,
+ "munmap", fn);
+ CLOSE (fd);
+ FREE (fn);
+ IPC_SEMAPHORE_UP (sem);
+ IPC_SEMAPHORE_DESTROY (sem);
+ return SYSERR; /* iteration aborted */
+ }
+ }
+ rval++;
+ if (fi.meta != NULL)
+ ECRS_freeMetaData (fi.meta);
+ ECRS_freeUri (fi.uri);
}
- fi.uri = ECRS_stringToUri(ectx,
- &result[pos]);
- if(fi.uri == NULL) {
- GE_BREAK(ectx, 0);
- goto FORMATERROR;
- }
- memcpy(&msize, &result[spos], sizeof(int));
- msize = ntohl(msize);
- spos += sizeof(int);
- if((spos + msize > ret) || (spos + msize < spos)) {
- GE_BREAK(ectx, 0);
- ECRS_freeUri(fi.uri);
- goto FORMATERROR;
- }
- if (need_metadata == YES) {
- fi.meta = ECRS_deserializeMetaData(ectx,
- &result[spos], msize);
- if(fi.meta == NULL) {
- GE_BREAK(ectx, 0);
- ECRS_freeUri(fi.uri);
- goto FORMATERROR;
- }
- } else {
- fi.meta = NULL;
- }
- pos = spos + msize;
- if(iterator != NULL) {
- if (OK != iterator(&fi, NULL, NO, closure)) {
- if (fi.meta != NULL)
- ECRS_freeMetaData(fi.meta);
- ECRS_freeUri(fi.uri);
- if (0 != MUNMAP(result, buf.st_size))
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "munmap",
- fn);
- CLOSE(fd);
- FREE(fn);
- IPC_SEMAPHORE_UP(sem);
- IPC_SEMAPHORE_DESTROY(sem);
- return SYSERR; /* iteration aborted */
- }
- }
- rval++;
- if (fi.meta != NULL)
- ECRS_freeMetaData(fi.meta);
- ECRS_freeUri(fi.uri);
- }
- if(0 != MUNMAP(result, buf.st_size))
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "munmap",
- fn);
- CLOSE(fd);
- FREE(fn);
- IPC_SEMAPHORE_UP(sem);
- IPC_SEMAPHORE_DESTROY(sem);
+ if (0 != MUNMAP (result, buf.st_size))
+ GE_LOG_STRERROR_FILE (ectx, GE_ERROR | GE_ADMIN | GE_BULK, "munmap", fn);
+ CLOSE (fd);
+ FREE (fn);
+ IPC_SEMAPHORE_UP (sem);
+ IPC_SEMAPHORE_DESTROY (sem);
return rval;
FORMATERROR:
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Deleted corrupt URI database in `%s'."),
- STATE_NAME);
- if(0 != MUNMAP(result, buf.st_size))
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "munmap",
- fn);
- CLOSE(fd);
- FREE(fn);
- IPC_SEMAPHORE_UP(sem);
- IPC_SEMAPHORE_DESTROY(sem);
- URITRACK_clearTrackedURIS(ectx, cfg);
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Deleted corrupt URI database in `%s'."), STATE_NAME);
+ if (0 != MUNMAP (result, buf.st_size))
+ GE_LOG_STRERROR_FILE (ectx, GE_ERROR | GE_ADMIN | GE_BULK, "munmap", fn);
+ CLOSE (fd);
+ FREE (fn);
+ IPC_SEMAPHORE_UP (sem);
+ IPC_SEMAPHORE_DESTROY (sem);
+ URITRACK_clearTrackedURIS (ectx, cfg);
return SYSERR;
}
Modified: GNUnet/src/applications/fs/uritrack/tracktest.c
===================================================================
--- GNUnet/src/applications/fs/uritrack/tracktest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/uritrack/tracktest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -32,7 +32,7 @@
#define CHECK(a) { if (! (a)) { fprintf(stderr, "Error at %s:%d\n", __FILE__,
__LINE__); return 1; } }
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
static ECRS_FileInfo fi1;
@@ -40,159 +40,114 @@
static unsigned int notifications;
-static int notified(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * cls) {
- if ( (fi1.meta != NULL) &&
- (fi1.uri != NULL) &&
- (ECRS_equalsMetaData(fi->meta,
- fi1.meta)) &&
- (ECRS_equalsUri(fi->uri,
- fi1.uri)) ) {
- notifications++;
- return OK;
- }
- if ( (fi2.meta != NULL) &&
- (fi2.uri != NULL) &&
- (ECRS_equalsMetaData(fi->meta,
- fi2.meta)) &&
- (ECRS_equalsUri(fi->uri,
- fi2.uri)) ) {
- notifications++;
- return OK;
- }
+static int
+notified (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *cls)
+{
+ if ((fi1.meta != NULL) &&
+ (fi1.uri != NULL) &&
+ (ECRS_equalsMetaData (fi->meta,
+ fi1.meta)) && (ECRS_equalsUri (fi->uri, fi1.uri)))
+ {
+ notifications++;
+ return OK;
+ }
+ if ((fi2.meta != NULL) &&
+ (fi2.uri != NULL) &&
+ (ECRS_equalsMetaData (fi->meta,
+ fi2.meta)) && (ECRS_equalsUri (fi->uri, fi2.uri)))
+ {
+ notifications++;
+ return OK;
+ }
return OK;
}
-static int processor(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * cls) {
- if ( (fi1.meta != NULL) &&
- (fi1.uri != NULL) &&
- (ECRS_equalsMetaData(fi->meta,
- fi1.meta)) &&
- (ECRS_equalsUri(fi->uri,
- fi1.uri)) ) {
- ECRS_freeUri(fi1.uri);
- fi1.uri = NULL;
- ECRS_freeMetaData(fi1.meta);
- fi1.meta = NULL;
- return OK;
- }
- if ( (fi2.meta != NULL) &&
- (fi2.uri != NULL) &&
- (ECRS_equalsMetaData(fi->meta,
- fi2.meta)) &&
- (ECRS_equalsUri(fi->uri,
- fi2.uri)) ) {
- ECRS_freeUri(fi2.uri);
- fi2.uri = NULL;
- ECRS_freeMetaData(fi2.meta);
- fi2.meta = NULL;
- return OK;
- }
+static int
+processor (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *cls)
+{
+ if ((fi1.meta != NULL) &&
+ (fi1.uri != NULL) &&
+ (ECRS_equalsMetaData (fi->meta,
+ fi1.meta)) && (ECRS_equalsUri (fi->uri, fi1.uri)))
+ {
+ ECRS_freeUri (fi1.uri);
+ fi1.uri = NULL;
+ ECRS_freeMetaData (fi1.meta);
+ fi1.meta = NULL;
+ return OK;
+ }
+ if ((fi2.meta != NULL) &&
+ (fi2.uri != NULL) &&
+ (ECRS_equalsMetaData (fi->meta,
+ fi2.meta)) && (ECRS_equalsUri (fi->uri, fi2.uri)))
+ {
+ ECRS_freeUri (fi2.uri);
+ fi2.uri = NULL;
+ ECRS_freeMetaData (fi2.meta);
+ fi2.meta = NULL;
+ return OK;
+ }
return SYSERR;
}
-static int testTracking() {
- static const char * k1[] = {
+static int
+testTracking ()
+{
+ static const char *k1[] = {
"foo",
NULL,
};
- static const char * k2[] = {
+ static const char *k2[] = {
"foot",
NULL,
};
- fi1.uri = ECRS_keywordsToUri(k1);
- fi1.meta = ECRS_createMetaData();
- ECRS_addToMetaData(fi1.meta,
- EXTRACTOR_MIMETYPE,
- "foo/bar");
- fi2.uri = ECRS_keywordsToUri(k2);
- fi2.meta = ECRS_createMetaData();
- ECRS_addToMetaData(fi2.meta,
- EXTRACTOR_MIMETYPE,
- "foo/bar");
+ fi1.uri = ECRS_keywordsToUri (k1);
+ fi1.meta = ECRS_createMetaData ();
+ ECRS_addToMetaData (fi1.meta, EXTRACTOR_MIMETYPE, "foo/bar");
+ fi2.uri = ECRS_keywordsToUri (k2);
+ fi2.meta = ECRS_createMetaData ();
+ ECRS_addToMetaData (fi2.meta, EXTRACTOR_MIMETYPE, "foo/bar");
- URITRACK_clearTrackedURIS(NULL,
- cfg);
- URITRACK_registerTrackCallback(NULL,
- cfg,
- ¬ified,
- NULL);
- URITRACK_trackURIS(NULL,
- cfg,
- NO);
- URITRACK_clearTrackedURIS(NULL,
- cfg);
+ URITRACK_clearTrackedURIS (NULL, cfg);
+ URITRACK_registerTrackCallback (NULL, cfg, ¬ified, NULL);
+ URITRACK_trackURIS (NULL, cfg, NO);
+ URITRACK_clearTrackedURIS (NULL, cfg);
/* test non-tracking */
- URITRACK_trackURI(NULL,
- cfg,
- &fi1);
- CHECK(0 == URITRACK_listURIs(NULL,
- cfg,
- NO,
- NULL,
- NULL));
- CHECK(NO == URITRACK_trackStatus(NULL,
- cfg));
- URITRACK_clearTrackedURIS(NULL,
- cfg);
- URITRACK_trackURIS(NULL,
- cfg,
- YES);
- URITRACK_clearTrackedURIS(NULL,
- cfg);
- CHECK(0 == URITRACK_listURIs(NULL,
- cfg,
- NO,
- NULL,
- NULL));
- CHECK(YES == URITRACK_trackStatus(NULL,
- cfg));
- URITRACK_trackURI(NULL,
- cfg,
- &fi1);
- CHECK(1 == URITRACK_listURIs(NULL,
- cfg,
- NO,
- NULL,
- NULL));
- URITRACK_trackURI(NULL,
- cfg,
- &fi2);
- CHECK(2 == URITRACK_listURIs(NULL,
- cfg,
- YES,
- &processor,
- NULL));
- URITRACK_trackURIS(NULL,
- cfg,
- NO);
- CHECK(NO == URITRACK_trackStatus(NULL,
- cfg));
- URITRACK_clearTrackedURIS(NULL,
- cfg);
- CHECK(notifications == 2);
- URITRACK_unregisterTrackCallback(¬ified,
- NULL);
+ URITRACK_trackURI (NULL, cfg, &fi1);
+ CHECK (0 == URITRACK_listURIs (NULL, cfg, NO, NULL, NULL));
+ CHECK (NO == URITRACK_trackStatus (NULL, cfg));
+ URITRACK_clearTrackedURIS (NULL, cfg);
+ URITRACK_trackURIS (NULL, cfg, YES);
+ URITRACK_clearTrackedURIS (NULL, cfg);
+ CHECK (0 == URITRACK_listURIs (NULL, cfg, NO, NULL, NULL));
+ CHECK (YES == URITRACK_trackStatus (NULL, cfg));
+ URITRACK_trackURI (NULL, cfg, &fi1);
+ CHECK (1 == URITRACK_listURIs (NULL, cfg, NO, NULL, NULL));
+ URITRACK_trackURI (NULL, cfg, &fi2);
+ CHECK (2 == URITRACK_listURIs (NULL, cfg, YES, &processor, NULL));
+ URITRACK_trackURIS (NULL, cfg, NO);
+ CHECK (NO == URITRACK_trackStatus (NULL, cfg));
+ URITRACK_clearTrackedURIS (NULL, cfg);
+ CHECK (notifications == 2);
+ URITRACK_unregisterTrackCallback (¬ified, NULL);
return 0;
}
-int main(int argc,
- char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- failureCount += testTracking();
- GC_free(cfg);
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ failureCount += testTracking ();
+ GC_free (cfg);
if (failureCount != 0)
return 1;
return 0;
Modified: GNUnet/src/applications/fs/uritrack/uri_info.c
===================================================================
--- GNUnet/src/applications/fs/uritrack/uri_info.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/fs/uritrack/uri_info.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -34,38 +34,34 @@
#include "platform.h"
static char *
-getDBName(struct GC_Configuration * cfg) {
- char * basename;
- char * ipcName;
+getDBName (struct GC_Configuration *cfg)
+{
+ char *basename;
+ char *ipcName;
size_t n;
- GC_get_configuration_value_filename(cfg,
- "GNUNET",
- "GNUNET_HOME",
- GNUNET_HOME_DIRECTORY,
- &basename);
- n = strlen(basename) + 512;
- ipcName = MALLOC(n);
- SNPRINTF(ipcName,
- n,
- "%s/uri_info.db",
- basename);
- FREE(basename);
+ GC_get_configuration_value_filename (cfg,
+ "GNUNET",
+ "GNUNET_HOME",
+ GNUNET_HOME_DIRECTORY, &basename);
+ n = strlen (basename) + 512;
+ ipcName = MALLOC (n);
+ SNPRINTF (ipcName, n, "%s/uri_info.db", basename);
+ FREE (basename);
return ipcName;
}
static unsigned long long
-getDBSize(struct GC_Configuration * cfg) {
+getDBSize (struct GC_Configuration *cfg)
+{
unsigned long long value;
value = 1024 * 1024;
- GC_get_configuration_value_number(cfg,
- "FS",
- "URI_DB_SIZE",
- 1,
- 1024 * 1024 * 1024,
- 1024 * 1024,
- &value);
+ GC_get_configuration_value_number (cfg,
+ "FS",
+ "URI_DB_SIZE",
+ 1,
+ 1024 * 1024 * 1024, 1024 * 1024, &value);
return value;
}
@@ -79,44 +75,42 @@
* return information from the wrong URI without detecting it).
*/
enum URITRACK_STATE
-URITRACK_getState(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri) {
- char * s;
+URITRACK_getState (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, const struct ECRS_URI *uri)
+{
+ char *s;
int crc;
int fd;
unsigned long long size;
unsigned char io[2];
off_t o;
- s = ECRS_uriToString(uri);
- crc = crc32N(s, strlen(s));
- FREE(s);
- s = getDBName(cfg);
- if (NO == disk_file_test(ectx,
- s))
- return URITRACK_FRESH;
- size = getDBSize(cfg);
- fd = disk_file_open(ectx,
- s,
- O_RDONLY);
- FREE(s);
+ s = ECRS_uriToString (uri);
+ crc = crc32N (s, strlen (s));
+ FREE (s);
+ s = getDBName (cfg);
+ if (NO == disk_file_test (ectx, s))
+ return URITRACK_FRESH;
+ size = getDBSize (cfg);
+ fd = disk_file_open (ectx, s, O_RDONLY);
+ FREE (s);
if (fd == -1)
return URITRACK_FRESH;
o = 2 * (crc % size);
- if (o != lseek(fd, o, SEEK_SET)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- "lseek",
- s);
- CLOSE(fd);
- return URITRACK_FRESH;
- }
- if (2 != read(fd, io, 2)) {
- CLOSE(fd);
- return URITRACK_FRESH;
- }
- CLOSE(fd);
+ if (o != lseek (fd, o, SEEK_SET))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
+ "lseek", s);
+ CLOSE (fd);
+ return URITRACK_FRESH;
+ }
+ if (2 != read (fd, io, 2))
+ {
+ CLOSE (fd);
+ return URITRACK_FRESH;
+ }
+ CLOSE (fd);
if (io[0] == (unsigned char) crc)
return (enum URITRACK_STATE) io[1];
return URITRACK_FRESH;
@@ -125,64 +119,65 @@
/**
* Add additional information about a given URI's past.
*/
-void URITRACK_addState(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri,
- enum URITRACK_STATE state) {
- char * s;
+void
+URITRACK_addState (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const struct ECRS_URI *uri, enum URITRACK_STATE state)
+{
+ char *s;
int crc;
int fd;
unsigned long long size;
unsigned char io[2];
off_t o;
- s = ECRS_uriToString(uri);
- crc = crc32N(s, strlen(s));
- FREE(s);
- s = getDBName(cfg);
- size = getDBSize(cfg);
- fd = disk_file_open(ectx,
- s,
- O_RDWR | O_CREAT,
- S_IRUSR | S_IWUSR);
- if (fd == -1) {
- FREE(s);
- return;
- }
+ s = ECRS_uriToString (uri);
+ crc = crc32N (s, strlen (s));
+ FREE (s);
+ s = getDBName (cfg);
+ size = getDBSize (cfg);
+ fd = disk_file_open (ectx, s, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
+ if (fd == -1)
+ {
+ FREE (s);
+ return;
+ }
o = 2 * (crc % size);
- if (o != lseek(fd, o, SEEK_SET)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- "lseek",
- s);
- CLOSE(fd);
- FREE(s);
- return;
- }
- if (2 != read(fd, io, 2)) {
- io[0] = crc;
- io[1] = URITRACK_FRESH;
- } else if (io[0] != (unsigned char) crc) {
- io[0] = (unsigned char) crc;
- io[1] = URITRACK_FRESH;
- }
+ if (o != lseek (fd, o, SEEK_SET))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
+ "lseek", s);
+ CLOSE (fd);
+ FREE (s);
+ return;
+ }
+ if (2 != read (fd, io, 2))
+ {
+ io[0] = crc;
+ io[1] = URITRACK_FRESH;
+ }
+ else if (io[0] != (unsigned char) crc)
+ {
+ io[0] = (unsigned char) crc;
+ io[1] = URITRACK_FRESH;
+ }
io[1] |= state;
- if (o != lseek(fd, o, SEEK_SET)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- "lseek",
- s);
- CLOSE(fd);
- FREE(s);
- return;
- }
- if (2 != write(fd, io, 2))
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- "write",
- s);
- disk_file_close(ectx, s, fd);
- FREE(s);
+ if (o != lseek (fd, o, SEEK_SET))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
+ "lseek", s);
+ CLOSE (fd);
+ FREE (s);
+ return;
+ }
+ if (2 != write (fd, io, 2))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
+ "write", s);
+ disk_file_close (ectx, s, fd);
+ FREE (s);
}
/* end of uri_info.c */
Modified: GNUnet/src/applications/gap/gap.c
===================================================================
--- GNUnet/src/applications/gap/gap.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/gap/gap.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -48,22 +48,22 @@
* Avoiding concurrent lookups for the same ITE: lock to grant
* access to peers to perform a lookup that matches this ITE entry.
*/
-static struct MUTEX * lookup_exclusion;
+static struct MUTEX *lookup_exclusion;
/**
* GNUnet core.
*/
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
/**
* Identity service.
*/
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
/**
* Statistics service.
*/
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static int stat_routing_collisions;
@@ -106,18 +106,18 @@
/**
* Topology service.
*/
-static Topology_ServiceAPI * topology;
+static Topology_ServiceAPI *topology;
/**
* Traffic service.
*/
-static Traffic_ServiceAPI * traffic;
+static Traffic_ServiceAPI *traffic;
/**
* For migration / local stores, local lookup and
* content verification.
*/
-static Blockstore * bs;
+static Blockstore *bs;
/**
* Function that can be used to identify unique
@@ -133,7 +133,7 @@
* GNUnet to route the replies back to the respective
* sender.
*/
-static IndirectionTableEntry * ROUTING_indTable_;
+static IndirectionTableEntry *ROUTING_indTable_;
/**
* Size of the indirection table specified in gnunet.conf
@@ -155,15 +155,15 @@
/**
* Mutex for all gap structures.
*/
-static struct MUTEX * lock;
+static struct MUTEX *lock;
/**
* Linked list tracking reply statistics. Synchronize access using
* the lock!
*/
-static ReplyTrackData * rtdList;
+static ReplyTrackData *rtdList;
-static RewardEntry * rewards;
+static RewardEntry *rewards;
static unsigned int rewardSize;
@@ -184,19 +184,20 @@
static int hist_total;
#endif
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
/* ****************** helper functions ***************** */
/**
* Adjust the TTL (priority limitation heuristic)
*/
-static int adjustTTL(int ttl, unsigned int prio) {
- if ( (ttl > 0) &&
- (ttl > (int)(prio+3)*TTL_DECREMENT) )
- ttl = (int) (prio+3)*TTL_DECREMENT; /* bound! */
+static int
+adjustTTL (int ttl, unsigned int prio)
+{
+ if ((ttl > 0) && (ttl > (int) (prio + 3) * TTL_DECREMENT))
+ ttl = (int) (prio + 3) * TTL_DECREMENT; /* bound! */
return ttl;
}
@@ -213,18 +214,18 @@
* @return binary encoding: QUERY_XXXX constants
*/
static QUERY_POLICY
-evaluateQuery(const PeerIdentity * sender,
- unsigned int * priority) {
- unsigned int netLoad = os_network_monitor_get_load(coreAPI->load_monitor,
- Upload);
+evaluateQuery (const PeerIdentity * sender, unsigned int *priority)
+{
+ unsigned int netLoad = os_network_monitor_get_load (coreAPI->load_monitor,
+ Upload);
- if ( (netLoad == (unsigned int) -1) ||
- (netLoad < IDLE_LOAD_THRESHOLD) ) {
- *priority = 0; /* minimum priority, no charge! */
- return QUERY_ANSWER | QUERY_FORWARD | QUERY_INDIRECT;
- }
+ if ((netLoad == (unsigned int) -1) || (netLoad < IDLE_LOAD_THRESHOLD))
+ {
+ *priority = 0; /* minimum priority, no charge! */
+ return QUERY_ANSWER | QUERY_FORWARD | QUERY_INDIRECT;
+ }
/* charge! */
- (*priority) = - identity->changeHostTrust(sender, -(*priority));
+ (*priority) = -identity->changeHostTrust (sender, -(*priority));
if (netLoad < IDLE_LOAD_THRESHOLD + (*priority))
return QUERY_ANSWER | QUERY_FORWARD | QUERY_INDIRECT;
else if (netLoad < 90 + 10 * (*priority))
@@ -232,26 +233,30 @@
else if (netLoad < 100)
return QUERY_ANSWER;
else
- return 0; /* drop entirely */
+ return 0; /* drop entirely */
}
/**
* Map the id to an index into the bitmap array.
*/
-static unsigned int getIndex(const PeerIdentity * peer) {
- return ((unsigned int*)peer)[0] % (8*BITMAP_SIZE);
+static unsigned int
+getIndex (const PeerIdentity * peer)
+{
+ return ((unsigned int *) peer)[0] % (8 * BITMAP_SIZE);
}
-static void setBit(QueryRecord * qr,
- int bit) {
+static void
+setBit (QueryRecord * qr, int bit)
+{
unsigned char theBit = (1 << (bit & 7));
- qr->bitmap[bit>>3] |= theBit;
+ qr->bitmap[bit >> 3] |= theBit;
}
-static int getBit(const QueryRecord * qr,
- int bit) {
+static int
+getBit (const QueryRecord * qr, int bit)
+{
unsigned char theBit = (1 << (bit & 7));
- return (qr->bitmap[bit>>3] & theBit) > 0;
+ return (qr->bitmap[bit >> 3] & theBit) > 0;
}
@@ -261,67 +266,75 @@
* Cron job that ages the RTD data and that frees
* memory for entries that reach 0.
*/
-static void ageRTD(void * unused) {
- ReplyTrackData * pos;
- ReplyTrackData * prev;
- ResponseList * rpos;
- ResponseList * rprev;
+static void
+ageRTD (void *unused)
+{
+ ReplyTrackData *pos;
+ ReplyTrackData *prev;
+ ResponseList *rpos;
+ ResponseList *rprev;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
prev = NULL;
pos = rtdList;
- while (pos != NULL) {
- /* after 10 minutes, always discard everything */
- if (pos->lastReplyReceived < TIME(NULL) - 600) {
- while (pos->responseList != NULL) {
- rpos = pos->responseList;
- pos->responseList = rpos->next;
- change_pid_rc(rpos->responder, -1);
- FREE(rpos);
- }
+ while (pos != NULL)
+ {
+ /* after 10 minutes, always discard everything */
+ if (pos->lastReplyReceived < TIME (NULL) - 600)
+ {
+ while (pos->responseList != NULL)
+ {
+ rpos = pos->responseList;
+ pos->responseList = rpos->next;
+ change_pid_rc (rpos->responder, -1);
+ FREE (rpos);
+ }
+ }
+ /* otherwise, age reply counts */
+ rprev = NULL;
+ rpos = pos->responseList;
+ while (rpos != NULL)
+ {
+ if (stats != NULL)
+ stats->change (stat_response_count, rpos->responseCount / 2);
+ rpos->responseCount = rpos->responseCount / 2;
+ if (rpos->responseCount == 0)
+ {
+ if (rprev == NULL)
+ pos->responseList = rpos->next;
+ else
+ rprev->next = rpos->next;
+ change_pid_rc (rpos->responder, -1);
+ FREE (rpos);
+ if (rprev == NULL)
+ rpos = pos->responseList;
+ else
+ rpos = rprev->next;
+ continue;
+ }
+ rprev = rpos;
+ rpos = rprev->next;
+ }
+ /* if we have no counts for a peer anymore,
+ free pos entry */
+ if (pos->responseList == NULL)
+ {
+ if (prev == NULL)
+ rtdList = pos->next;
+ else
+ prev->next = pos->next;
+ change_pid_rc (pos->queryOrigin, -1);
+ FREE (pos);
+ if (prev == NULL)
+ pos = rtdList;
+ else
+ pos = prev->next;
+ continue;
+ }
+ prev = pos;
+ pos = pos->next;
}
- /* otherwise, age reply counts */
- rprev = NULL;
- rpos = pos->responseList;
- while (rpos != NULL) {
- if (stats != NULL)
- stats->change(stat_response_count, rpos->responseCount / 2);
- rpos->responseCount = rpos->responseCount / 2;
- if (rpos->responseCount == 0) {
- if (rprev == NULL)
- pos->responseList = rpos->next;
- else
- rprev->next = rpos->next;
- change_pid_rc(rpos->responder, -1);
- FREE(rpos);
- if (rprev == NULL)
- rpos = pos->responseList;
- else
- rpos = rprev->next;
- continue;
- }
- rprev = rpos;
- rpos = rprev->next;
- }
- /* if we have no counts for a peer anymore,
- free pos entry */
- if (pos->responseList == NULL) {
- if (prev == NULL)
- rtdList = pos->next;
- else
- prev->next = pos->next;
- change_pid_rc(pos->queryOrigin, -1);
- FREE(pos);
- if (prev == NULL)
- pos = rtdList;
- else
- pos = prev->next;
- continue;
- }
- prev = pos;
- pos = pos->next;
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
/**
@@ -331,61 +344,66 @@
* @param origin
* @param responder peer that send the reply
*/
-static void updateResponseData(PID_INDEX origin,
- PID_INDEX responder) {
- ReplyTrackData * pos;
- ReplyTrackData * prev;
- ResponseList * rpos;
- ResponseList * rprev;
+static void
+updateResponseData (PID_INDEX origin, PID_INDEX responder)
+{
+ ReplyTrackData *pos;
+ ReplyTrackData *prev;
+ ResponseList *rpos;
+ ResponseList *rprev;
if (responder == 0)
- return; /* we don't track local responses */
- MUTEX_LOCK(lock);
+ return; /* we don't track local responses */
+ MUTEX_LOCK (lock);
pos = rtdList;
prev = NULL;
- while (pos != NULL) {
- if (origin == pos->queryOrigin)
- break; /* found */
- prev = pos;
- pos = pos->next;
- }
- if (pos == NULL) {
- pos = MALLOC(sizeof(ReplyTrackData));
- pos->next = NULL;
- pos->responseList = NULL;
- pos->queryOrigin = origin;
- change_pid_rc(origin, 1);
- if (prev == NULL)
- rtdList = pos;
- else
- prev->next = pos;
- }
- TIME(&pos->lastReplyReceived);
+ while (pos != NULL)
+ {
+ if (origin == pos->queryOrigin)
+ break; /* found */
+ prev = pos;
+ pos = pos->next;
+ }
+ if (pos == NULL)
+ {
+ pos = MALLOC (sizeof (ReplyTrackData));
+ pos->next = NULL;
+ pos->responseList = NULL;
+ pos->queryOrigin = origin;
+ change_pid_rc (origin, 1);
+ if (prev == NULL)
+ rtdList = pos;
+ else
+ prev->next = pos;
+ }
+ TIME (&pos->lastReplyReceived);
rpos = pos->responseList;
rprev = NULL;
- while (rpos != NULL) {
- if (responder == rpos->responder) {
- rpos->responseCount++;
- if (stats != NULL)
- stats->change(stat_response_count, 1);
- MUTEX_UNLOCK(lock);
- return;
+ while (rpos != NULL)
+ {
+ if (responder == rpos->responder)
+ {
+ rpos->responseCount++;
+ if (stats != NULL)
+ stats->change (stat_response_count, 1);
+ MUTEX_UNLOCK (lock);
+ return;
+ }
+ rprev = rpos;
+ rpos = rpos->next;
}
- rprev = rpos;
- rpos = rpos->next;
- }
- rpos = MALLOC(sizeof(ResponseList));
+ rpos = MALLOC (sizeof (ResponseList));
rpos->responseCount = 1;
if (stats != NULL)
- stats->change(stat_response_count, 1);
+ stats->change (stat_response_count, 1);
rpos->responder = responder;
- change_pid_rc(responder, 1);
+ change_pid_rc (responder, 1);
rpos->next = NULL;
if (rprev == NULL)
pos->responseList = rpos;
else
rprev->next = rpos;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
/**
@@ -406,45 +424,45 @@
* that buffer (must be a positive number).
*/
static unsigned int
-fillInQuery(const PeerIdentity * receiver,
- void * position,
- unsigned int padding) {
+fillInQuery (const PeerIdentity * receiver,
+ void *position, unsigned int padding)
+{
static unsigned int pos = 0;
unsigned int start;
unsigned int delta;
cron_t now;
- QueryRecord * qr;
+ QueryRecord *qr;
PID_INDEX receiverId;
- now = get_time();
- receiverId = intern_pid(receiver);
- MUTEX_LOCK(lock);
+ now = get_time ();
+ receiverId = intern_pid (receiver);
+ MUTEX_LOCK (lock);
start = pos;
delta = 0;
- while (padding - delta > sizeof(P2P_gap_query_MESSAGE)) {
- qr = &queries[pos];
- if ( (qr->expires > now) &&
- (0 == getBit(qr, getIndex(receiver))) &&
- (receiverId != qr->noTarget) &&
- (! (equalsHashCode512(&receiver->hashPubKey,
- &qr->msg->returnTo.hashPubKey)) ) &&
- (padding - delta >= ntohs(qr->msg->header.size) ) ) {
- setBit(&queries[pos],
- getIndex(receiver));
- memcpy(&((char*)position)[delta],
- qr->msg,
- ntohs(qr->msg->header.size));
- qr->sendCount++;
- delta += ntohs(qr->msg->header.size);
+ while (padding - delta > sizeof (P2P_gap_query_MESSAGE))
+ {
+ qr = &queries[pos];
+ if ((qr->expires > now) &&
+ (0 == getBit (qr, getIndex (receiver))) &&
+ (receiverId != qr->noTarget) &&
+ (!(equalsHashCode512 (&receiver->hashPubKey,
+ &qr->msg->returnTo.hashPubKey))) &&
+ (padding - delta >= ntohs (qr->msg->header.size)))
+ {
+ setBit (&queries[pos], getIndex (receiver));
+ memcpy (&((char *) position)[delta],
+ qr->msg, ntohs (qr->msg->header.size));
+ qr->sendCount++;
+ delta += ntohs (qr->msg->header.size);
+ }
+ pos++;
+ if (pos >= QUERY_RECORD_COUNT)
+ pos = 0;
+ if (pos == start)
+ break;
}
- pos++;
- if (pos >= QUERY_RECORD_COUNT)
- pos = 0;
- if (pos == start)
- break;
- }
- MUTEX_UNLOCK(lock);
- change_pid_rc(receiverId, -1);
+ MUTEX_UNLOCK (lock);
+ change_pid_rc (receiverId, -1);
return delta;
}
@@ -452,11 +470,12 @@
* Select a subset of the peers for forwarding. Called
* on each connected node by the core.
*/
-static void hotpathSelectionCode(const PeerIdentity * peer,
- void * cls) {
- QueryRecord * qr = cls;
- ReplyTrackData * pos;
- ResponseList * rp;
+static void
+hotpathSelectionCode (const PeerIdentity * peer, void *cls)
+{
+ QueryRecord *qr = cls;
+ ReplyTrackData *pos;
+ ResponseList *rp;
unsigned int ranking = 0;
int distance;
PID_INDEX id;
@@ -466,135 +485,134 @@
EncName enc2;
#endif
- id = intern_pid(peer);
+ id = intern_pid (peer);
/* compute some basic ranking based on historical
queries from the same origin */
pos = rtdList;
- while (pos != NULL) {
- if (pos->queryOrigin == qr->noTarget)
- break;
- pos = pos->next;
- }
+ while (pos != NULL)
+ {
+ if (pos->queryOrigin == qr->noTarget)
+ break;
+ pos = pos->next;
+ }
rp = NULL;
- if (pos != NULL) {
- rp = pos->responseList;
- while (rp != NULL) {
- if (rp->responder == id)
- break;
- rp = rp->next;
+ if (pos != NULL)
+ {
+ rp = pos->responseList;
+ while (rp != NULL)
+ {
+ if (rp->responder == id)
+ break;
+ rp = rp->next;
+ }
+ if (rp != NULL)
+ {
+ if (rp->responseCount < 0xFFFF)
+ ranking = 0x7FFF * rp->responseCount;
+ else
+ ranking = 0x7FFFFFF;
+ }
}
- if (rp != NULL) {
- if (rp->responseCount < 0xFFFF)
- ranking = 0x7FFF * rp->responseCount;
- else
- ranking = 0x7FFFFFF;
- }
- }
- distance
- = distanceHashCode512(&qr->msg->queries[0],
- &peer->hashPubKey) >> 10; /* change to value in [0:63] */
+ distance = distanceHashCode512 (&qr->msg->queries[0], &peer->hashPubKey) >>
10; /* change to value in [0:63] */
if (distance <= 0)
distance = 1;
- ranking += weak_randomi(1 + 0xFFFF * 10 / (1 + distance)); /* 0 to 20
"response equivalents" for proximity */
- ranking += weak_randomi(0xFFFF); /* 2 "response equivalents" random chance
for everyone */
+ ranking += weak_randomi (1 + 0xFFFF * 10 / (1 + distance)); /* 0 to 20
"response equivalents" for proximity */
+ ranking += weak_randomi (0xFFFF); /* 2 "response equivalents" random
chance for everyone */
if (id == qr->noTarget)
- ranking = 0; /* no chance for blocked peers */
- idx = getIndex(peer);
+ ranking = 0; /* no chance for blocked peers */
+ idx = getIndex (peer);
#if DEBUG_GAP
- hash2enc(&qr->msg->queries[0],
- &enc);
- ((char*)&enc)[6] = '\0';
- hash2enc(&peer->hashPubKey,
- &enc2);
- ((char*)&enc2)[6] = '\0';
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Q %s peer %2u (%s) ranks (responses: %2u, distance %4d): %u%s\n",
- &enc,
- idx,
- &enc2,
- rp == NULL ? 0 : rp->responseCount,
- distance,
- ranking,
- id == qr->noTarget ? " (no target)" : "");
+ hash2enc (&qr->msg->queries[0], &enc);
+ ((char *) &enc)[6] = '\0';
+ hash2enc (&peer->hashPubKey, &enc2);
+ ((char *) &enc2)[6] = '\0';
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Q %s peer %2u (%s) ranks (responses: %2u, distance %4d): %u%s\n",
+ &enc,
+ idx,
+ &enc2,
+ rp == NULL ? 0 : rp->responseCount,
+ distance, ranking, id == qr->noTarget ? " (no target)" : "");
#endif
qr->rankings[idx] = ranking;
- change_pid_rc(id, -1);
+ change_pid_rc (id, -1);
}
/**
* Return 1 if the current network (upstream) or CPU load is
* too high, 0 if the load is ok.
*/
-static int loadTooHigh() {
- return ( (hardCPULimit > 0) &&
- (os_cpu_get_load(ectx,
- coreAPI->cfg) >= hardCPULimit) ) ||
- ( (hardUpLimit > 0) &&
- (os_network_monitor_get_load(coreAPI->load_monitor,
- Upload) >= hardUpLimit) );
+static int
+loadTooHigh ()
+{
+ return ((hardCPULimit > 0) &&
+ (os_cpu_get_load (ectx,
+ coreAPI->cfg) >= hardCPULimit)) ||
+ ((hardUpLimit > 0) &&
+ (os_network_monitor_get_load (coreAPI->load_monitor,
+ Upload) >= hardUpLimit));
}
/**
* A "PerNodeCallback" method that forwards the query to the selected
* nodes.
*/
-static void sendToSelected(const PeerIdentity * peer,
- void * cls) {
- const QueryRecord * qr = cls;
+static void
+sendToSelected (const PeerIdentity * peer, void *cls)
+{
+ const QueryRecord *qr = cls;
PID_INDEX id;
#if DEBUG_GAP
EncName encq;
EncName encp;
#endif
- if (equalsHashCode512(&peer->hashPubKey,
- &qr->msg->returnTo.hashPubKey))
- return; /* never send back to source */
+ if (equalsHashCode512 (&peer->hashPubKey, &qr->msg->returnTo.hashPubKey))
+ return; /* never send back to source */
/* Load above hard limit? */
- if (loadTooHigh())
+ if (loadTooHigh ())
return;
- id = intern_pid(peer);
- if (id == qr->noTarget) {
- change_pid_rc(id, -1);
- return; /* never send back to source */
- }
+ id = intern_pid (peer);
+ if (id == qr->noTarget)
+ {
+ change_pid_rc (id, -1);
+ return; /* never send back to source */
+ }
- if (getBit(qr, getIndex(peer)) == 1) {
+ if (getBit (qr, getIndex (peer)) == 1)
+ {
#if DEBUG_GAP
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&peer->hashPubKey,
- &encp);
- hash2enc(&qr->msg->queries[0],
- &encq));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Sending query `%s' to `%s'\n",
- &encq,
- &encp);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&peer->hashPubKey, &encp);
+ hash2enc (&qr->msg->queries[0], &encq));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Sending query `%s' to `%s'\n", &encq, &encp);
#endif
- if (stats != NULL)
- stats->change(stat_routing_forwards, 1);
- coreAPI->unicast(peer,
- &qr->msg->header,
- BASE_QUERY_PRIORITY * ntohl(qr->msg->priority) * 2,
- TTL_DECREMENT);
- }
- change_pid_rc(id, -1);
+ if (stats != NULL)
+ stats->change (stat_routing_forwards, 1);
+ coreAPI->unicast (peer,
+ &qr->msg->header,
+ BASE_QUERY_PRIORITY * ntohl (qr->msg->priority) * 2,
+ TTL_DECREMENT);
+ }
+ change_pid_rc (id, -1);
}
/**
* Take a query and forward it to the appropriate number of nodes
* (depending on load, queue, etc).
*/
-static void forwardQuery(const P2P_gap_query_MESSAGE * msg,
- const PeerIdentity * target,
- const PeerIdentity * excludePeer) {
+static void
+forwardQuery (const P2P_gap_query_MESSAGE * msg,
+ const PeerIdentity * target, const PeerIdentity * excludePeer)
+{
cron_t now;
- QueryRecord * qr;
+ QueryRecord *qr;
QueryRecord dummy;
cron_t oldestTime;
cron_t expirationTime;
@@ -607,159 +625,164 @@
unsigned long long pos;
PID_INDEX tpid;
- if (target != NULL) {
- /* connect to target host -- if known */
- coreAPI->unicast(target,
- NULL,
- ntohl(msg->priority),
- 0);
- }
- now = get_time();
- MUTEX_LOCK(lock);
+ if (target != NULL)
+ {
+ /* connect to target host -- if known */
+ coreAPI->unicast (target, NULL, ntohl (msg->priority), 0);
+ }
+ now = get_time ();
+ MUTEX_LOCK (lock);
oldestIndex = -1;
- expirationTime = now + ntohl(msg->ttl);
+ expirationTime = now + ntohl (msg->ttl);
oldestTime = expirationTime;
- for (i=0;i<QUERY_RECORD_COUNT;i++) {
- if (queries[i].expires < oldestTime) {
- oldestTime = queries[i].expires;
- oldestIndex = i;
- }
- if (queries[i].msg == NULL)
- continue;
- if ( (queries[i].msg->header.size == msg->header.size) &&
- (0 == memcmp(&queries[i].msg->queries[0],
- &msg->queries[0],
- ntohs(msg->header.size)
- - sizeof(P2P_gap_query_MESSAGE)
- + sizeof(HashCode512))) ) {
- /* We have exactly this query pending already.
- Replace existing query! */
- oldestIndex = i;
- if ( (queries[i].expires > now - 4 * TTL_DECREMENT) && /* not long
expired */
- (weak_randomi(4) != 0) ) {
- /* do not clear the bitmap describing which peers we have
- forwarded the query to already; but do this only with high
- probability since we may want to try again if the query is
- retransmitted lots (this can happen if this is the only
- query; we may forward it to all connected peers and get no
- reply. If the initiator keeps retrying, we want to
- eventually forward it again.
+ for (i = 0; i < QUERY_RECORD_COUNT; i++)
+ {
+ if (queries[i].expires < oldestTime)
+ {
+ oldestTime = queries[i].expires;
+ oldestIndex = i;
+ }
+ if (queries[i].msg == NULL)
+ continue;
+ if ((queries[i].msg->header.size == msg->header.size) &&
+ (0 == memcmp (&queries[i].msg->queries[0],
+ &msg->queries[0],
+ ntohs (msg->header.size)
+ - sizeof (P2P_gap_query_MESSAGE)
+ + sizeof (HashCode512))))
+ {
+ /* We have exactly this query pending already.
+ Replace existing query! */
+ oldestIndex = i;
+ if ((queries[i].expires > now - 4 * TTL_DECREMENT) && /* not long
expired */
+ (weak_randomi (4) != 0))
+ {
+ /* do not clear the bitmap describing which peers we have
+ forwarded the query to already; but do this only with high
+ probability since we may want to try again if the query is
+ retransmitted lots (this can happen if this is the only
+ query; we may forward it to all connected peers and get no
+ reply. If the initiator keeps retrying, we want to
+ eventually forward it again.
- Note that the initial probability here (0.6.0/0.6.1) was
- very low (1:64), which is far too low considering that the
- clients do an exponential back-off. The rule is a pure
- optimization, and as such the probability that we
- eventually forward must be significant. 25% seems to work
- better... (extra-note: in small testbeds, the problem
- is bigger than in a larger network where the case that
- a query stays in the QM indefinitely might be much more
- rare; so don't just trust a micro-scale benchmark when
- trying to figure out an 'optimal' threshold). */
- noclear = YES;
- }
- break; /* this is it, do not scan for other
- 'oldest' entries */
+ Note that the initial probability here (0.6.0/0.6.1) was
+ very low (1:64), which is far too low considering that the
+ clients do an exponential back-off. The rule is a pure
+ optimization, and as such the probability that we
+ eventually forward must be significant. 25% seems to work
+ better... (extra-note: in small testbeds, the problem
+ is bigger than in a larger network where the case that
+ a query stays in the QM indefinitely might be much more
+ rare; so don't just trust a micro-scale benchmark when
+ trying to figure out an 'optimal' threshold). */
+ noclear = YES;
+ }
+ break; /* this is it, do not scan for other
+ 'oldest' entries */
+ }
}
- }
- if (oldestIndex == -1) {
- memset(&dummy,
- 0,
- sizeof(QueryRecord));
- qr = &dummy;
- } else {
- qr = &queries[oldestIndex];
- FREENONNULL(qr->msg);
- qr->msg = NULL;
- }
+ if (oldestIndex == -1)
+ {
+ memset (&dummy, 0, sizeof (QueryRecord));
+ qr = &dummy;
+ }
+ else
+ {
+ qr = &queries[oldestIndex];
+ FREENONNULL (qr->msg);
+ qr->msg = NULL;
+ }
qr->expires = expirationTime;
qr->transmissionCount = 0;
- qr->msg = MALLOC(ntohs(msg->header.size));
- memcpy(qr->msg,
- msg,
- ntohs(msg->header.size));
+ qr->msg = MALLOC (ntohs (msg->header.size));
+ memcpy (qr->msg, msg, ntohs (msg->header.size));
if (noclear == NO)
- memset(&qr->bitmap[0],
- 0,
- BITMAP_SIZE);
+ memset (&qr->bitmap[0], 0, BITMAP_SIZE);
if (qr->noTarget != 0)
- change_pid_rc(qr->noTarget, -1);
+ change_pid_rc (qr->noTarget, -1);
if (excludePeer != NULL)
- qr->noTarget = intern_pid(excludePeer);
+ qr->noTarget = intern_pid (excludePeer);
else
- qr->noTarget = intern_pid(coreAPI->myIdentity);
+ qr->noTarget = intern_pid (coreAPI->myIdentity);
qr->totalDistance = 0;
- qr->rankings = MALLOC(sizeof(int)*8*BITMAP_SIZE);
+ qr->rankings = MALLOC (sizeof (int) * 8 * BITMAP_SIZE);
qr->activeConnections
- = coreAPI->forAllConnectedNodes
- (&hotpathSelectionCode,
- qr);
+ = coreAPI->forAllConnectedNodes (&hotpathSelectionCode, qr);
/* actual selection, proportional to rankings
assigned by hotpathSelectionCode ... */
rankingSum = 0;
- for (i=0;i<8*BITMAP_SIZE;i++)
+ for (i = 0; i < 8 * BITMAP_SIZE; i++)
rankingSum += qr->rankings[i];
- if (qr->activeConnections > 0) {
- /* select 4 peers for forwarding */
- for (i=0;i<4;i++) {
- if (rankingSum == 0)
- break;
- sel = weak_randomi64(rankingSum);
- pos = 0;
- for (j=0;j<8*BITMAP_SIZE;j++) {
- pos += qr->rankings[j];
- if (pos > sel) {
- setBit(qr, j);
- GE_ASSERT(ectx, rankingSum >= qr->rankings[j]);
- rankingSum -= qr->rankings[j];
- qr->rankings[j] = 0;
- break;
- }
- }
+ if (qr->activeConnections > 0)
+ {
+ /* select 4 peers for forwarding */
+ for (i = 0; i < 4; i++)
+ {
+ if (rankingSum == 0)
+ break;
+ sel = weak_randomi64 (rankingSum);
+ pos = 0;
+ for (j = 0; j < 8 * BITMAP_SIZE; j++)
+ {
+ pos += qr->rankings[j];
+ if (pos > sel)
+ {
+ setBit (qr, j);
+ GE_ASSERT (ectx, rankingSum >= qr->rankings[j]);
+ rankingSum -= qr->rankings[j];
+ qr->rankings[j] = 0;
+ break;
+ }
+ }
+ }
}
- }
- FREE(qr->rankings);
+ FREE (qr->rankings);
qr->rankings = NULL;
- if (target != NULL) {
- tpid = intern_pid(target);
- setBit(qr, tpid);
- change_pid_rc(tpid, -1);
- }
+ if (target != NULL)
+ {
+ tpid = intern_pid (target);
+ setBit (qr, tpid);
+ change_pid_rc (tpid, -1);
+ }
/* now forward to a couple of selected nodes */
- coreAPI->forAllConnectedNodes
- (&sendToSelected,
- qr);
- if (qr == &dummy) {
- change_pid_rc(dummy.noTarget, -1);
- FREE(dummy.msg);
- }
- MUTEX_UNLOCK(lock);
+ coreAPI->forAllConnectedNodes (&sendToSelected, qr);
+ if (qr == &dummy)
+ {
+ change_pid_rc (dummy.noTarget, -1);
+ FREE (dummy.msg);
+ }
+ MUTEX_UNLOCK (lock);
}
/**
* Stop transmitting a certain query (we don't route it anymore or
* we have learned the answer).
*/
-static int dequeueQuery(const HashCode512 * query) {
+static int
+dequeueQuery (const HashCode512 * query)
+{
int i;
int ret;
- QueryRecord * qr;
+ QueryRecord *qr;
ret = SYSERR;
- MUTEX_LOCK(lock);
- for (i=0;i<QUERY_RECORD_COUNT;i++) {
- qr = &queries[i];
- if( qr->msg != NULL ) {
- if (equalsHashCode512(query,
- &qr->msg->queries[0])) {
- qr->expires = 0; /* expire NOW! */
- ret = OK;
- break;
- }
+ MUTEX_LOCK (lock);
+ for (i = 0; i < QUERY_RECORD_COUNT; i++)
+ {
+ qr = &queries[i];
+ if (qr->msg != NULL)
+ {
+ if (equalsHashCode512 (query, &qr->msg->queries[0]))
+ {
+ qr->expires = 0; /* expire NOW! */
+ ret = OK;
+ break;
+ }
+ }
}
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return ret;
}
@@ -769,22 +792,24 @@
* Compute the hashtable index of a host id.
*/
static unsigned int
-computeRoutingIndex(const HashCode512 * query) {
+computeRoutingIndex (const HashCode512 * query)
+{
unsigned int res
- = (((unsigned int*)query)[0] ^
- ((unsigned int*)query)[1] / (1 + random_qsel))
+ = (((unsigned int *) query)[0] ^
+ ((unsigned int *) query)[1] / (1 + random_qsel))
% indirectionTableSize;
- GE_ASSERT(ectx, res < indirectionTableSize);
+ GE_ASSERT (ectx, res < indirectionTableSize);
#if DO_HISTOGRAM
histogram[res % 65536]++;
- if (++hist_total % 10000 == 0) {
- int i;
- for (i=0;i<65536;i++)
- if (histogram[i] != 0) {
- printf("%d: %d\n",
- i, histogram[i]);
- }
- }
+ if (++hist_total % 10000 == 0)
+ {
+ int i;
+ for (i = 0; i < 65536; i++)
+ if (histogram[i] != 0)
+ {
+ printf ("%d: %d\n", i, histogram[i]);
+ }
+ }
#endif
return res;
}
@@ -794,17 +819,18 @@
* @param hostId the peer from where the content came,
* NULL for the local peer
*/
-static int useContent(const PeerIdentity * hostId,
- const MESSAGE_HEADER * pmsg);
+static int useContent (const PeerIdentity * hostId,
+ const MESSAGE_HEADER * pmsg);
/**
* Call useContent "later" and then free the pmsg.
*/
-static void useContentLater(void * data) {
- MESSAGE_HEADER * pmsg = data;
- useContent(NULL,
- pmsg);
- FREE(pmsg);
+static void
+useContentLater (void *data)
+{
+ MESSAGE_HEADER *pmsg = data;
+ useContent (NULL, pmsg);
+ FREE (pmsg);
}
/**
@@ -820,131 +846,123 @@
* which in turn wraps the DBlock (including
* the type ID).
*/
-static int queueReply(const PeerIdentity * sender,
- const HashCode512 * primaryKey,
- const DataContainer * data) {
- P2P_gap_reply_MESSAGE * pmsg;
- IndirectionTableEntry * ite;
+static int
+queueReply (const PeerIdentity * sender,
+ const HashCode512 * primaryKey, const DataContainer * data)
+{
+ P2P_gap_reply_MESSAGE *pmsg;
+ IndirectionTableEntry *ite;
unsigned int size;
#if DEBUG_GAP
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(primaryKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Gap queues reply to query `%s' for later use.\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (primaryKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Gap queues reply to query `%s' for later use.\n", &enc);
#endif
#if EXTRA_CHECKS
/* verify data is valid */
- uri(data,
- ANY_BLOCK,
- YES,
- primaryKey);
+ uri (data, ANY_BLOCK, YES, primaryKey);
#endif
- ite = &ROUTING_indTable_[computeRoutingIndex(primaryKey)];
- if (! equalsHashCode512(&ite->primaryKey,
- primaryKey) ) {
+ ite = &ROUTING_indTable_[computeRoutingIndex (primaryKey)];
+ if (!equalsHashCode512 (&ite->primaryKey, primaryKey))
+ {
#if DEBUG_GAP
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "GAP: Dropping reply, routing table has no query associated with it
(anymore)\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "GAP: Dropping reply, routing table has no query associated with
it (anymore)\n");
#endif
- return NO; /* we don't care for the reply (anymore) */
- }
- if (YES == ite->successful_local_lookup_in_delay_loop) {
+ return NO; /* we don't care for the reply (anymore) */
+ }
+ if (YES == ite->successful_local_lookup_in_delay_loop)
+ {
#if DEBUG_GAP
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "GAP: Dropping reply, found reply locally during delay\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "GAP: Dropping reply, found reply locally during delay\n");
#endif
- return NO; /* wow, really bad concurrent DB lookup and processing for
- the same query. Well, at least we should not also
- queue the delayed reply twice... */
- }
- size = sizeof(P2P_gap_reply_MESSAGE) + ntohl(data->size) -
sizeof(DataContainer);
- if (size >= MAX_BUFFER_SIZE) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ return NO; /* wow, really bad concurrent DB lookup and
processing for
+ the same query. Well, at least we should
not also
+ queue the delayed reply twice... */
+ }
+ size =
+ sizeof (P2P_gap_reply_MESSAGE) + ntohl (data->size) -
+ sizeof (DataContainer);
+ if (size >= MAX_BUFFER_SIZE)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
ite->successful_local_lookup_in_delay_loop = YES;
- pmsg = MALLOC(size);
- pmsg->header.size
- = htons(size);
- pmsg->header.type
- = htons(P2P_PROTO_gap_RESULT);
- pmsg->primaryKey
- = *primaryKey;
- memcpy(&pmsg[1],
- &data[1],
- size - sizeof(P2P_gap_reply_MESSAGE));
+ pmsg = MALLOC (size);
+ pmsg->header.size = htons (size);
+ pmsg->header.type = htons (P2P_PROTO_gap_RESULT);
+ pmsg->primaryKey = *primaryKey;
+ memcpy (&pmsg[1], &data[1], size - sizeof (P2P_gap_reply_MESSAGE));
/* delay reply, delay longer if we are busy (makes it harder
to predict / analyze, too). */
- cron_add_job(coreAPI->cron,
- &useContentLater,
- weak_randomi(TTL_DECREMENT),
- 0,
- pmsg);
+ cron_add_job (coreAPI->cron,
+ &useContentLater, weak_randomi (TTL_DECREMENT), 0, pmsg);
return YES;
}
-static void addReward(const HashCode512 * query,
- unsigned int prio) {
+static void
+addReward (const HashCode512 * query, unsigned int prio)
+{
if (prio == 0)
return;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
rewards[rewardPos].query = *query;
if (stats != NULL)
- stats->change(stat_pending_rewards,
- prio - rewards[rewardPos].prio);
+ stats->change (stat_pending_rewards, prio - rewards[rewardPos].prio);
rewards[rewardPos].prio = prio;
rewardPos++;
if (rewardPos == rewardSize)
rewardPos = 0;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
-static unsigned int claimReward(const HashCode512 * query) {
+static unsigned int
+claimReward (const HashCode512 * query)
+{
int i;
unsigned int ret;
ret = 0;
- MUTEX_LOCK(lock);
- for (i=0;i<rewardSize;i++) {
- if (equalsHashCode512(query,
- &rewards[i].query)) {
- ret += rewards[i].prio;
- if (stats != NULL)
- stats->change(stat_pending_rewards,
- - rewards[i].prio);
- rewards[i].prio = 0;
+ MUTEX_LOCK (lock);
+ for (i = 0; i < rewardSize; i++)
+ {
+ if (equalsHashCode512 (query, &rewards[i].query))
+ {
+ ret += rewards[i].prio;
+ if (stats != NULL)
+ stats->change (stat_pending_rewards, -rewards[i].prio);
+ rewards[i].prio = 0;
+ }
}
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return ret;
}
-static void resetSeen(IndirectionTableEntry * ite) {
+static void
+resetSeen (IndirectionTableEntry * ite)
+{
if (stats != NULL)
- stats->change(stat_memory_seen, - ite->seenIndex);
- GROW(ite->seen,
- ite->seenIndex,
- 0);
+ stats->change (stat_memory_seen, -ite->seenIndex);
+ GROW (ite->seen, ite->seenIndex, 0);
}
-static void resetDestinations(IndirectionTableEntry * ite) {
- decrement_pid_rcs(ite->destination,
- ite->hostsWaiting);
+static void
+resetDestinations (IndirectionTableEntry * ite)
+{
+ decrement_pid_rcs (ite->destination, ite->hostsWaiting);
if (stats != NULL)
- stats->change(stat_memory_destinations, - ite->hostsWaiting);
- GROW(ite->destination,
- ite->hostsWaiting,
- 0);
+ stats->change (stat_memory_destinations, -ite->hostsWaiting);
+ GROW (ite->destination, ite->hostsWaiting, 0);
}
/**
@@ -960,75 +978,70 @@
* @return OK if sender was added, SYSERR if existed already
* in the queue
*/
-static int addToSlot(int mode,
- IndirectionTableEntry * ite,
- const HashCode512 * query,
- int ttl,
- unsigned int priority,
- PID_INDEX sender) {
+static int
+addToSlot (int mode,
+ IndirectionTableEntry * ite,
+ const HashCode512 * query,
+ int ttl, unsigned int priority, PID_INDEX sender)
+{
unsigned int i;
cron_t now;
#if DEBUG__GAP
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(query,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "GAP: Queueing query '%s' in slot %p\n",
- &enc,
- ite);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (query, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "GAP: Queueing query '%s' in slot %p\n", &enc, ite);
#endif
- GE_ASSERT(ectx, sender != 0); /* do NOT add to RT for local clients! */
- now = get_time();
- if ( (stats != NULL) &&
- (ite->ttl == 0) )
- stats->change(stat_routing_slots_used, 1);
+ GE_ASSERT (ectx, sender != 0); /* do NOT add to RT for local clients!
*/
+ now = get_time ();
+ if ((stats != NULL) && (ite->ttl == 0))
+ stats->change (stat_routing_slots_used, 1);
- if (mode == ITE_REPLACE) {
- resetSeen(ite);
- ite->seenReplyWasUnique = NO;
- if (equalsHashCode512(query,
- &ite->primaryKey)) {
- ite->ttl = now + ttl;
+ if (mode == ITE_REPLACE)
+ {
+ resetSeen (ite);
+ ite->seenReplyWasUnique = NO;
+ if (equalsHashCode512 (query, &ite->primaryKey))
+ {
+ ite->ttl = now + ttl;
+ ite->priority += priority;
+ for (i = 0; i < ite->hostsWaiting; i++)
+ if (ite->destination[i] == sender)
+ return SYSERR;
+ if (ite->hostsWaiting >= MAX_HOSTS_WAITING)
+ resetDestinations (ite);
+ }
+ else
+ {
+ ite->successful_local_lookup_in_delay_loop = NO;
+ /* different request, flush pending queues */
+ dequeueQuery (&ite->primaryKey);
+ ite->primaryKey = *query;
+ resetDestinations (ite);
+ ite->ttl = now + ttl;
+ ite->priority = priority;
+ }
+ }
+ else
+ { /* GROW mode */
+ GE_ASSERT (ectx, equalsHashCode512 (query, &ite->primaryKey));
+ /* extend lifetime */
+ if (ite->ttl < now + ttl)
+ ite->ttl = now + ttl;
ite->priority += priority;
- for (i=0;i<ite->hostsWaiting;i++)
- if (ite->destination[i] == sender)
- return SYSERR;
- if (ite->hostsWaiting >= MAX_HOSTS_WAITING)
- resetDestinations(ite);
- } else {
- ite->successful_local_lookup_in_delay_loop = NO;
- /* different request, flush pending queues */
- dequeueQuery(&ite->primaryKey);
- ite->primaryKey = *query;
- resetDestinations(ite);
- ite->ttl = now + ttl;
- ite->priority = priority;
+ for (i = 0; i < ite->hostsWaiting; i++)
+ if (sender == ite->destination[i])
+ return SYSERR; /* already there! */
}
- } else { /* GROW mode */
- GE_ASSERT(ectx,
- equalsHashCode512(query,
- &ite->primaryKey));
- /* extend lifetime */
- if (ite->ttl < now + ttl)
- ite->ttl = now + ttl;
- ite->priority += priority;
- for (i=0;i<ite->hostsWaiting;i++)
- if (sender == ite->destination[i])
- return SYSERR; /* already there! */
- }
if (stats != NULL)
- stats->change(stat_memory_destinations, 1);
- GROW(ite->destination,
- ite->hostsWaiting,
- ite->hostsWaiting+1);
- ite->destination[ite->hostsWaiting-1] = sender;
- change_pid_rc(sender, 1);
+ stats->change (stat_memory_destinations, 1);
+ GROW (ite->destination, ite->hostsWaiting, ite->hostsWaiting + 1);
+ ite->destination[ite->hostsWaiting - 1] = sender;
+ change_pid_rc (sender, 1);
/* again: new listener, flush seen list */
- resetSeen(ite);
+ resetSeen (ite);
ite->seenReplyWasUnique = NO;
return OK;
}
@@ -1059,223 +1072,273 @@
* forward the query, SYSERR if not
* @return a case ID for debugging
*/
-static int needsForwarding(const HashCode512 * query,
- int ttl,
- unsigned int priority,
- PID_INDEX sender,
- int * isRouted,
- int * doForward) {
- IndirectionTableEntry * ite;
+static int
+needsForwarding (const HashCode512 * query,
+ int ttl,
+ unsigned int priority,
+ PID_INDEX sender, int *isRouted, int *doForward)
+{
+ IndirectionTableEntry *ite;
cron_t now;
cron_t new_ttl;
int equal_to_pending;
- now = get_time();
- ite = &ROUTING_indTable_[computeRoutingIndex(query)];
- equal_to_pending = equalsHashCode512(query, &ite->primaryKey);
- if ( (stats != NULL) &&
- (equal_to_pending) )
- stats->change(stat_routing_request_duplicates, 1);
+ now = get_time ();
+ ite = &ROUTING_indTable_[computeRoutingIndex (query)];
+ equal_to_pending = equalsHashCode512 (query, &ite->primaryKey);
+ if ((stats != NULL) && (equal_to_pending))
+ stats->change (stat_routing_request_duplicates, 1);
new_ttl = now + ttl;
- if ( (ite->ttl < now) &&
- (ite->ttl < now - (cron_t) (TTL_DECREMENT * 10L)) &&
- (ttl > - TTL_DECREMENT * 5) ) {
- addToSlot(ITE_REPLACE, ite, query, ttl, priority, sender);
- *isRouted = YES;
- *doForward = YES;
- return 21;
- }
- if ( ( ttl < 0) &&
- (equal_to_pending) ) {
- /* if ttl is "expired" and we have
- the exact query pending, route
- replies but do NOT forward _again_! */
- addToSlot(ITE_GROW, ite, query, ttl, priority, sender);
- *isRouted = NO;
- /* don't go again, we are not even going to reset the seen
- list, so why bother looking locally again, if we would find
- something, the seen list would block sending the reply anyway
- since we're not resetting that (ttl too small!)! */
- *doForward = NO;
- return 0;
- }
-
- if ( (ite->ttl < new_ttl) &&
- (ite->ttl + (cron_t) (TTL_DECREMENT * topology->estimateNetworkSize())
< new_ttl) &&
- (ite->ttl + (cron_t) (TTL_DECREMENT * 10L) < new_ttl) &&
- (ite->ttl < now) ) {
- /* expired AND is significantly (!)
- longer expired than new query */
- /* previous entry relatively expired, start using the slot --
- and kill the old seen list!*/
- resetSeen(ite);
- ite->seenReplyWasUnique = NO;
- if ( (equal_to_pending) &&
- (YES == ite-> successful_local_lookup_in_delay_loop) ) {
- *isRouted = NO;
- *doForward = NO;
- addToSlot(ITE_GROW, ite, query, ttl, priority, sender);
- return 1;
- } else {
+ if ((ite->ttl < now) &&
+ (ite->ttl < now - (cron_t) (TTL_DECREMENT * 10L)) &&
+ (ttl > -TTL_DECREMENT * 5))
+ {
+ addToSlot (ITE_REPLACE, ite, query, ttl, priority, sender);
*isRouted = YES;
*doForward = YES;
- if ( (stats != NULL) &&
- (equal_to_pending) ) {
- stats->change(stat_routing_request_repeat, 1);
- if (ite->ttl != 0) {
- stats->change(stat_routing_request_repeat_dttl, new_ttl - ite->ttl);
- }
- }
- addToSlot(ITE_REPLACE, ite, query, ttl, priority, sender);
- return 2;
+ return 21;
}
- }
- if (equal_to_pending) {
- if (ite->seenIndex == 0) {
- if ( (ite->ttl < new_ttl) &&
- (ite->ttl + (cron_t) TTL_DECREMENT < new_ttl) ) {
- /* ttl of new is SIGNIFICANTLY longer? */
- /* query again */
- if (YES == ite->successful_local_lookup_in_delay_loop) {
- *isRouted = NO; /* don't go again, we are already
- processing a local lookup! */
- *doForward = NO;
- addToSlot(ITE_REPLACE, ite, query, ttl, priority, sender);
- return 3;
- } else {
- *isRouted = YES;
- *doForward = YES;
- if (stats != NULL) {
- stats->change(stat_routing_request_repeat, 1);
- if (ite->ttl != 0) {
- stats->change(stat_routing_request_repeat_dttl, new_ttl - ite->ttl);
- }
- }
- addToSlot(ITE_REPLACE, ite, query, ttl, priority, sender);
- return 4;
- }
- } else {
- /* new TTL is lower than the old one, thus
- just wait for the reply that may come back */
- if (OK == addToSlot(ITE_GROW, ite, query, ttl, priority, sender)) {
- if (YES == ite->successful_local_lookup_in_delay_loop) {
+ if ((ttl < 0) && (equal_to_pending))
+ {
+ /* if ttl is "expired" and we have
+ the exact query pending, route
+ replies but do NOT forward _again_! */
+ addToSlot (ITE_GROW, ite, query, ttl, priority, sender);
*isRouted = NO;
- /* don't go again, we are already processing a
- local lookup! */
+ /* don't go again, we are not even going to reset the seen
+ list, so why bother looking locally again, if we would find
+ something, the seen list would block sending the reply anyway
+ since we're not resetting that (ttl too small!)! */
*doForward = NO;
- return 5;
- } else {
- *isRouted = YES;
- *doForward = NO;
- return 6;
+ return 0;
}
- } else {
- *isRouted = NO; /* same query with _higher_ TTL has already been
- processed FOR THE SAME recipient! Do NOT do
- the lookup *again*. */
- *doForward = NO;
- return 7;
- }
- }
+
+ if ((ite->ttl < new_ttl) &&
+ (ite->ttl +
+ (cron_t) (TTL_DECREMENT * topology->estimateNetworkSize ()) < new_ttl)
+ && (ite->ttl + (cron_t) (TTL_DECREMENT * 10L) < new_ttl)
+ && (ite->ttl < now))
+ {
+ /* expired AND is significantly (!)
+ longer expired than new query */
+ /* previous entry relatively expired, start using the slot --
+ and kill the old seen list! */
+ resetSeen (ite);
+ ite->seenReplyWasUnique = NO;
+ if ((equal_to_pending) &&
+ (YES == ite->successful_local_lookup_in_delay_loop))
+ {
+ *isRouted = NO;
+ *doForward = NO;
+ addToSlot (ITE_GROW, ite, query, ttl, priority, sender);
+ return 1;
+ }
+ else
+ {
+ *isRouted = YES;
+ *doForward = YES;
+ if ((stats != NULL) && (equal_to_pending))
+ {
+ stats->change (stat_routing_request_repeat, 1);
+ if (ite->ttl != 0)
+ {
+ stats->change (stat_routing_request_repeat_dttl,
+ new_ttl - ite->ttl);
+ }
+ }
+ addToSlot (ITE_REPLACE, ite, query, ttl, priority, sender);
+ return 2;
+ }
}
- /* ok, we've seen at least one reply before, replace
- more agressively */
+ if (equal_to_pending)
+ {
+ if (ite->seenIndex == 0)
+ {
+ if ((ite->ttl < new_ttl) &&
+ (ite->ttl + (cron_t) TTL_DECREMENT < new_ttl))
+ {
+ /* ttl of new is SIGNIFICANTLY longer? */
+ /* query again */
+ if (YES == ite->successful_local_lookup_in_delay_loop)
+ {
+ *isRouted = NO; /* don't go again, we are already
+ processing a local lookup! */
+ *doForward = NO;
+ addToSlot (ITE_REPLACE, ite, query, ttl, priority, sender);
+ return 3;
+ }
+ else
+ {
+ *isRouted = YES;
+ *doForward = YES;
+ if (stats != NULL)
+ {
+ stats->change (stat_routing_request_repeat, 1);
+ if (ite->ttl != 0)
+ {
+ stats->change (stat_routing_request_repeat_dttl,
+ new_ttl - ite->ttl);
+ }
+ }
+ addToSlot (ITE_REPLACE, ite, query, ttl, priority, sender);
+ return 4;
+ }
+ }
+ else
+ {
+ /* new TTL is lower than the old one, thus
+ just wait for the reply that may come back */
+ if (OK ==
+ addToSlot (ITE_GROW, ite, query, ttl, priority, sender))
+ {
+ if (YES == ite->successful_local_lookup_in_delay_loop)
+ {
+ *isRouted = NO;
+ /* don't go again, we are already processing a
+ local lookup! */
+ *doForward = NO;
+ return 5;
+ }
+ else
+ {
+ *isRouted = YES;
+ *doForward = NO;
+ return 6;
+ }
+ }
+ else
+ {
+ *isRouted = NO; /* same query with _higher_ TTL has
already been
+ processed FOR THE SAME recipient!
Do NOT do
+ the lookup *again*. */
+ *doForward = NO;
+ return 7;
+ }
+ }
+ }
+ /* ok, we've seen at least one reply before, replace
+ more agressively */
- /* pending == new! */
- if (ite->seenReplyWasUnique) {
- if (ite->ttl < new_ttl) { /* ttl of new is longer? */
- /* go again */
- resetSeen(ite);
- ite->seenReplyWasUnique = NO;
- if (YES == ite->successful_local_lookup_in_delay_loop) {
- *isRouted = NO;
- /* don't go again, we are already processing a local lookup! */
- *doForward = NO;
- addToSlot(ITE_REPLACE, ite, query, ttl, priority, sender);
- return 8;
- } else {
- *isRouted = YES;
- /* only forward if new TTL is significantly higher */
- if (ite->ttl + TTL_DECREMENT < new_ttl) {
- *doForward = YES;
- if (stats != NULL) {
- stats->change(stat_routing_request_repeat, 1);
- if (ite->ttl != 0) {
- stats->change(stat_routing_request_repeat_dttl, new_ttl - ite->ttl);
+ /* pending == new! */
+ if (ite->seenReplyWasUnique)
+ {
+ if (ite->ttl < new_ttl)
+ { /* ttl of new is longer? */
+ /* go again */
+ resetSeen (ite);
+ ite->seenReplyWasUnique = NO;
+ if (YES == ite->successful_local_lookup_in_delay_loop)
+ {
+ *isRouted = NO;
+ /* don't go again, we are already processing a local lookup!
*/
+ *doForward = NO;
+ addToSlot (ITE_REPLACE, ite, query, ttl, priority, sender);
+ return 8;
+ }
+ else
+ {
+ *isRouted = YES;
+ /* only forward if new TTL is significantly higher */
+ if (ite->ttl + TTL_DECREMENT < new_ttl)
+ {
+ *doForward = YES;
+ if (stats != NULL)
+ {
+ stats->change (stat_routing_request_repeat, 1);
+ if (ite->ttl != 0)
+ {
+ stats->change (stat_routing_request_repeat_dttl,
+ new_ttl - ite->ttl);
+ }
+ }
+ }
+ else
+ *doForward = NO;
+ addToSlot (ITE_REPLACE, ite, query, ttl, priority, sender);
+ return 9;
+ }
+ }
+ else
+ {
+ /* new TTL is lower than the old one, thus
+ just wait for the reply that may come back */
+ if (OK ==
+ addToSlot (ITE_GROW, ite, query, ttl, priority, sender))
+ {
+ if (YES == ite->successful_local_lookup_in_delay_loop)
+ {
+ *isRouted = NO;
+ *doForward = NO;
+ return 10;
+ }
+ else
+ {
+ *isRouted = YES;
+ *doForward = NO;
+ return 11;
+ }
+ }
+ else
+ {
+ *isRouted = NO;
+ *doForward = NO;
+ return 12;
+ }
+ }
}
- }
- } else
- *doForward = NO;
- addToSlot(ITE_REPLACE, ite, query, ttl, priority, sender);
- return 9;
- }
- } else {
- /* new TTL is lower than the old one, thus
- just wait for the reply that may come back */
- if (OK == addToSlot(ITE_GROW, ite, query, ttl, priority, sender)) {
- if (YES == ite->successful_local_lookup_in_delay_loop) {
- *isRouted = NO;
- *doForward = NO;
- return 10;
- } else {
- *isRouted = YES;
- *doForward = NO;
- return 11;
- }
- } else {
- *isRouted = NO;
- *doForward = NO;
- return 12;
- }
- }
- } else { /* KSK or SKS, multiple results possible! */
- /* It's a pending KSK or SKS that can have multiple
- replies. Do not re-send, just forward the
- answers that we get from now on to this additional
- receiver */
- int isttlHigher;
- if (ite->ttl < new_ttl)
- isttlHigher = NO;
else
- isttlHigher = YES;
- if (OK == addToSlot(ITE_GROW, ite, query, ttl, priority, sender)) {
- *isRouted = YES;
- *doForward = NO;
- return 13;
- } else {
- *isRouted = isttlHigher;
- /* receiver is the same as the one that already got the
- answer, do not bother to do this again, IF
- the TTL is not higher! */
- *doForward = NO;
- return 14;
- }
+ { /* KSK or SKS, multiple results possible! */
+ /* It's a pending KSK or SKS that can have multiple
+ replies. Do not re-send, just forward the
+ answers that we get from now on to this additional
+ receiver */
+ int isttlHigher;
+ if (ite->ttl < new_ttl)
+ isttlHigher = NO;
+ else
+ isttlHigher = YES;
+ if (OK == addToSlot (ITE_GROW, ite, query, ttl, priority, sender))
+ {
+ *isRouted = YES;
+ *doForward = NO;
+ return 13;
+ }
+ else
+ {
+ *isRouted = isttlHigher;
+ /* receiver is the same as the one that already got the
+ answer, do not bother to do this again, IF
+ the TTL is not higher! */
+ *doForward = NO;
+ return 14;
+ }
+ }
}
- }
/* a different query that is expired a bit longer is using
the slot; but if it is a query that has received
a unique response already, we can eagerly throw it out
anyway, since the request has been satisfied
completely */
- if ( (ite->ttl + TTL_DECREMENT < new_ttl) &&
- (ite->ttl < now) &&
- (ite->seenReplyWasUnique) ) {
- /* we have seen the unique answer, get rid of it early */
- addToSlot(ITE_REPLACE, ite, query, ttl, priority, sender);
- *isRouted = YES;
- *doForward = YES;
- return 15;
- }
+ if ((ite->ttl + TTL_DECREMENT < new_ttl) &&
+ (ite->ttl < now) && (ite->seenReplyWasUnique))
+ {
+ /* we have seen the unique answer, get rid of it early */
+ addToSlot (ITE_REPLACE, ite, query, ttl, priority, sender);
+ *isRouted = YES;
+ *doForward = YES;
+ return 15;
+ }
/* Another still valid query is using the slot. Now we need a _really_
good reason to discard it... */
- if (ttl < 0) {
- *isRouted = NO;
- *doForward = NO;
- if (stats != NULL)
- stats->change(stat_routing_collisions, 1);
- return 16; /* if new ttl is "expired", don't bother with priorities */
- }
+ if (ttl < 0)
+ {
+ *isRouted = NO;
+ *doForward = NO;
+ if (stats != NULL)
+ stats->change (stat_routing_collisions, 1);
+ return 16; /* if new ttl is "expired", don't bother with
priorities */
+ }
/* Finally try to find a _strong_ reason looking at priority/ttl
relationships to replace the existing query. A low ttl with high
@@ -1286,26 +1349,28 @@
the routing table, otherwise it might happen that query A
replaces query B which replaces query A which could happen so
quickly that no response to either query ever makes it through...
- */
- if ( (long long)((ite->ttl - now) * priority) >
- (long long) 10 * (ttl * ite->priority) ) {
- addToSlot(ITE_REPLACE, ite, query, ttl, priority, sender);
- *isRouted = YES;
- *doForward = YES;
- return 17;
- }
- if (weak_randomi(TIE_BREAKER_CHANCE) == 0) {
- addToSlot(ITE_REPLACE, ite, query, ttl, priority, sender);
- *isRouted = YES;
- *doForward = YES;
- return 20;
- }
+ */
+ if ((long long) ((ite->ttl - now) * priority) >
+ (long long) 10 * (ttl * ite->priority))
+ {
+ addToSlot (ITE_REPLACE, ite, query, ttl, priority, sender);
+ *isRouted = YES;
+ *doForward = YES;
+ return 17;
+ }
+ if (weak_randomi (TIE_BREAKER_CHANCE) == 0)
+ {
+ addToSlot (ITE_REPLACE, ite, query, ttl, priority, sender);
+ *isRouted = YES;
+ *doForward = YES;
+ return 20;
+ }
/* sadly, the slot is busy with something else; we can
not even add ourselves to the reply set */
*isRouted = NO;
*doForward = NO;
if (stats != NULL)
- stats->change(stat_routing_collisions, 1);
+ stats->change (stat_routing_collisions, 1);
return 18;
}
@@ -1316,8 +1381,9 @@
* @param ite the matching slot in the indirection table
* @param msg the message to route
*/
-static void sendReply(IndirectionTableEntry * ite,
- const MESSAGE_HEADER * msg) {
+static void
+sendReply (IndirectionTableEntry * ite, const MESSAGE_HEADER * msg)
+{
unsigned int j;
unsigned int maxDelay;
cron_t now;
@@ -1327,38 +1393,33 @@
#endif
if (stats != NULL)
- stats->change(stat_routing_successes,
- 1);
- now = get_time();
+ stats->change (stat_routing_successes, 1);
+ now = get_time ();
if (now < ite->ttl)
maxDelay = ite->ttl - now;
else
- maxDelay = TTL_DECREMENT; /* for expired queries */
+ maxDelay = TTL_DECREMENT; /* for expired queries */
/* send to peers */
- for (j=0;j<ite->hostsWaiting;j++) {
- resolve_pid(ite->destination[j],
- &recv);
+ for (j = 0; j < ite->hostsWaiting; j++)
+ {
+ resolve_pid (ite->destination[j], &recv);
#if DEBUG_GAP
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&recv.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "GAP sending reply to `%s'\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&recv.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "GAP sending reply to `%s'\n", &enc);
#endif
- coreAPI->unicast(&recv,
- msg,
- BASE_REPLY_PRIORITY *
- (ite->priority+5),
- /* weigh priority */
- maxDelay);
- }
+ coreAPI->unicast (&recv, msg, BASE_REPLY_PRIORITY * (ite->priority + 5),
+ /* weigh priority */
+ maxDelay);
+ }
}
-struct qLRC {
- DataContainer ** values;
+struct qLRC
+{
+ DataContainer **values;
unsigned int valueCount;
HashCode512 query;
};
@@ -1376,36 +1437,26 @@
* the type ID).
*/
static int
-queryLocalResultCallback(const HashCode512 * primaryKey,
- const DataContainer * value,
- void * closure) {
- struct qLRC * cls = closure;
+queryLocalResultCallback (const HashCode512 * primaryKey,
+ const DataContainer * value, void *closure)
+{
+ struct qLRC *cls = closure;
int i;
#if EXTRA_CHECKS
/* verify data is valid */
- uri(value,
- ANY_BLOCK,
- YES,
- primaryKey);
+ uri (value, ANY_BLOCK, YES, primaryKey);
#endif
/* check seen */
- if ( (cls->valueCount > MAX_SEEN_VALUES) &&
- (weak_randomi(cls->valueCount) > 8) )
- return OK; /* statistical drop, too many replies to keep in memory */
- for (i=0;i<cls->valueCount;i++)
- if (0 == memcmp(value,
- cls->values[i],
- ntohl(value->size)))
- return OK; /* drop, duplicate entry in DB! */
- GROW(cls->values,
- cls->valueCount,
- cls->valueCount+1);
- cls->values[cls->valueCount-1]
- = MALLOC(ntohl(value->size));
- memcpy(cls->values[cls->valueCount-1],
- value,
- ntohl(value->size));
+ if ((cls->valueCount > MAX_SEEN_VALUES) &&
+ (weak_randomi (cls->valueCount) > 8))
+ return OK; /* statistical drop, too many replies to keep
in memory */
+ for (i = 0; i < cls->valueCount; i++)
+ if (0 == memcmp (value, cls->values[i], ntohl (value->size)))
+ return OK; /* drop, duplicate entry in DB! */
+ GROW (cls->values, cls->valueCount, cls->valueCount + 1);
+ cls->values[cls->valueCount - 1] = MALLOC (ntohl (value->size));
+ memcpy (cls->values[cls->valueCount - 1], value, ntohl (value->size));
return OK;
}
@@ -1426,18 +1477,18 @@
* NO if we already found the one and only response,
* SYSERR if not (out of resources)
*/
-static int execQuery(const PeerIdentity * sender,
- const PeerIdentity * target,
- unsigned int prio,
- QUERY_POLICY policy,
- int ttl,
- const P2P_gap_query_MESSAGE * query) {
- IndirectionTableEntry * ite;
+static int
+execQuery (const PeerIdentity * sender,
+ const PeerIdentity * target,
+ unsigned int prio,
+ QUERY_POLICY policy, int ttl, const P2P_gap_query_MESSAGE * query)
+{
+ IndirectionTableEntry *ite;
int isRouted;
struct qLRC cls;
int i;
int max;
- int * perm;
+ int *perm;
int doForward;
PID_INDEX senderID;
#if DEBUG_GAP
@@ -1445,131 +1496,122 @@
#endif
/* Load above hard limit? */
- if (loadTooHigh())
+ if (loadTooHigh ())
return SYSERR;
if (rhf == NULL)
- return SYSERR; /* not fully initialized */
+ return SYSERR; /* not fully initialized */
- senderID = intern_pid(sender);
- GE_ASSERT(ectx, (senderID != 0) || (sender == NULL) );
- ite = &ROUTING_indTable_[computeRoutingIndex(&query->queries[0])];
- MUTEX_LOCK(lookup_exclusion);
+ senderID = intern_pid (sender);
+ GE_ASSERT (ectx, (senderID != 0) || (sender == NULL));
+ ite = &ROUTING_indTable_[computeRoutingIndex (&query->queries[0])];
+ MUTEX_LOCK (lookup_exclusion);
i = -1;
- if (sender != NULL) {
- if ( ( (policy & QUERY_ANSWER) > 0) &&
- ( ((policy & QUERY_INDIRECT) > 0) ||
- (bs->fast_get(&query->queries[0])) ) ) {
- i = needsForwarding(&query->queries[0],
- ttl,
- prio,
- senderID,
- &isRouted,
- &doForward);
- } else {
- isRouted = NO;
- doForward = NO;
- if (stats != NULL) {
- if ((policy & QUERY_ANSWER) > 0)
- stats->change(stat_routing_no_route_policy, 1);
+ if (sender != NULL)
+ {
+ if (((policy & QUERY_ANSWER) > 0) &&
+ (((policy & QUERY_INDIRECT) > 0) ||
+ (bs->fast_get (&query->queries[0]))))
+ {
+ i = needsForwarding (&query->queries[0],
+ ttl, prio, senderID, &isRouted, &doForward);
+ }
+ else
+ {
+ isRouted = NO;
+ doForward = NO;
+ if (stats != NULL)
+ {
+ if ((policy & QUERY_ANSWER) > 0)
+ stats->change (stat_routing_no_route_policy, 1);
+ else
+ stats->change (stat_routing_no_answer_policy, 1);
+ }
+ }
+ }
else
- stats->change(stat_routing_no_answer_policy, 1);
- }
+ {
+ addReward (&query->queries[0], prio);
+ isRouted = YES;
+ doForward = YES;
}
- } else {
- addReward(&query->queries[0],
- prio);
- isRouted = YES;
- doForward = YES;
- }
- if ( (policy & QUERY_FORWARD) == 0)
+ if ((policy & QUERY_FORWARD) == 0)
doForward = NO;
#if DEBUG_GAP
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&query->queries[0],
- &enc));
- ((char*)&enc)[6] = '\0';
- GE_LOG(ectx,
- GE_INFO | GE_IMMEDIATE | GE_USER,
- "GAP is executing request for `%s':%s%s (%d)\n",
- &enc,
- doForward ? " forwarding" : "",
- isRouted ? " routing" : "",
- i);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&query->queries[0], &enc));
+ ((char *) &enc)[6] = '\0';
+ GE_LOG (ectx,
+ GE_INFO | GE_IMMEDIATE | GE_USER,
+ "GAP is executing request for `%s':%s%s (%d)\n",
+ &enc,
+ doForward ? " forwarding" : "", isRouted ? " routing" : "", i);
#endif
- if ( (stats != NULL) &&
- (isRouted || doForward) )
- stats->change(stat_routing_processed, 1);
+ if ((stats != NULL) && (isRouted || doForward))
+ stats->change (stat_routing_processed, 1);
cls.values = NULL;
cls.valueCount = 0;
cls.query = query->queries[0];
- if ( (isRouted == YES) && /* if we can't route, lookup useless! */
- ( (policy & QUERY_ANSWER) > 0) ) {
- bs->get(bs->closure,
- ntohl(query->type),
- prio,
- 1 + ( ntohs(query->header.size)
- - sizeof(P2P_gap_query_MESSAGE)) / sizeof(HashCode512),
- &query->queries[0],
- &queryLocalResultCallback,
- &cls);
- }
+ if ((isRouted == YES) && /* if we can't route, lookup useless! */
+ ((policy & QUERY_ANSWER) > 0))
+ {
+ bs->get (bs->closure,
+ ntohl (query->type),
+ prio,
+ 1 + (ntohs (query->header.size)
+ - sizeof (P2P_gap_query_MESSAGE)) / sizeof (HashCode512),
+ &query->queries[0], &queryLocalResultCallback, &cls);
+ }
- if (cls.valueCount > 0) {
- perm = permute(WEAK, cls.valueCount);
- max = os_network_monitor_get_load(coreAPI->load_monitor,
- Download);
- if (max > 100)
- max = 100;
- if (max == -1)
- max = 50; /* we don't know the load, assume middle-of-the-road */
- max = max / 10; /* 1 reply per 10% free capacity */
- max = 1 + (10 - max);
- if (max > cls.valueCount)
- max = cls.valueCount; /* can't send more back then
- what we have */
+ if (cls.valueCount > 0)
+ {
+ perm = permute (WEAK, cls.valueCount);
+ max = os_network_monitor_get_load (coreAPI->load_monitor, Download);
+ if (max > 100)
+ max = 100;
+ if (max == -1)
+ max = 50; /* we don't know the load, assume
middle-of-the-road */
+ max = max / 10; /* 1 reply per 10% free capacity */
+ max = 1 + (10 - max);
+ if (max > cls.valueCount)
+ max = cls.valueCount; /* can't send more back then
+ what we have */
- for (i=0;i<cls.valueCount;i++) {
- if ( (i == 0) &&
- (SYSERR == bs->put(bs->closure,
- &query->queries[0],
- cls.values[perm[i]],
- ite->priority)) ) {
- GE_BREAK(NULL, 0);
- FREE(cls.values[perm[i]]);
- continue;
- }
- if ( (i < max) &&
- (sender != NULL) &&
- (YES == queueReply(sender,
- &query->queries[0],
- cls.values[perm[i]])) &&
- (stats != NULL) )
- stats->change(stat_routing_local_results, 1);
- /* even for local results, always do 'put'
- (at least to give back results to local client &
- to update priority; but only do this for
- the first result */
- if (uri(cls.values[perm[i]],
- ite->type,
- NO, /* no need to verify local results! */
- &query->queries[0]))
- doForward = NO; /* we have the one and only answer,
- do not bother to forward... */
- FREE(cls.values[perm[i]]);
+ for (i = 0; i < cls.valueCount; i++)
+ {
+ if ((i == 0) &&
+ (SYSERR == bs->put (bs->closure,
+ &query->queries[0],
+ cls.values[perm[i]], ite->priority)))
+ {
+ GE_BREAK (NULL, 0);
+ FREE (cls.values[perm[i]]);
+ continue;
+ }
+ if ((i < max) &&
+ (sender != NULL) &&
+ (YES == queueReply (sender,
+ &query->queries[0],
+ cls.values[perm[i]])) && (stats != NULL))
+ stats->change (stat_routing_local_results, 1);
+ /* even for local results, always do 'put'
+ (at least to give back results to local client &
+ to update priority; but only do this for
+ the first result */
+ if (uri (cls.values[perm[i]], ite->type, NO, /* no need to verify
local results! */
+ &query->queries[0]))
+ doForward = NO; /* we have the one and only answer,
+ do not bother to forward... */
+ FREE (cls.values[perm[i]]);
+ }
+ FREE (perm);
}
- FREE(perm);
- }
- GROW(cls.values,
- cls.valueCount,
- 0);
- MUTEX_UNLOCK(lookup_exclusion);
+ GROW (cls.values, cls.valueCount, 0);
+ MUTEX_UNLOCK (lookup_exclusion);
if (doForward)
- forwardQuery(query,
- target,
- sender);
- change_pid_rc(senderID, -1);
+ forwardQuery (query, target, sender);
+ change_pid_rc (senderID, -1);
return doForward;
}
@@ -1587,16 +1629,17 @@
* @return how good this content was (effective
* priority of the original request)
*/
-static int useContent(const PeerIdentity * host,
- const MESSAGE_HEADER * pmsg) {
- const P2P_gap_reply_MESSAGE * msg;
+static int
+useContent (const PeerIdentity * host, const MESSAGE_HEADER * pmsg)
+{
+ const P2P_gap_reply_MESSAGE *msg;
unsigned int i;
HashCode512 contentHC;
- IndirectionTableEntry * ite;
+ IndirectionTableEntry *ite;
unsigned int size;
int ret;
unsigned int prio;
- DataContainer * value;
+ DataContainer *value;
double preference;
PID_INDEX hostId;
#if DEBUG_GAP
@@ -1604,173 +1647,163 @@
EncName enc2;
#endif
- if (ntohs(pmsg->size) < sizeof(P2P_gap_reply_MESSAGE)) {
- GE_BREAK_OP(ectx, 0);
- return SYSERR; /* invalid! */
- }
+ if (ntohs (pmsg->size) < sizeof (P2P_gap_reply_MESSAGE))
+ {
+ GE_BREAK_OP (ectx, 0);
+ return SYSERR; /* invalid! */
+ }
msg = (const P2P_gap_reply_MESSAGE *) pmsg;
#if DEBUG_GAP
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- if (host != NULL)
- hash2enc(&host->hashPubKey,
- &enc));
- hash2enc(&msg->primaryKey,
- &enc2);
- ((char*)&enc2)[6] = '\0';
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "GAP received content `%s' from `%s'\n",
- &enc2,
- (host != NULL) ? (const char*)&enc : "myself");
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ if (host != NULL) hash2enc (&host->hashPubKey, &enc));
+ hash2enc (&msg->primaryKey, &enc2);
+ ((char *) &enc2)[6] = '\0';
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "GAP received content `%s' from `%s'\n",
+ &enc2, (host != NULL) ? (const char *) &enc : "myself");
#endif
- ite = &ROUTING_indTable_[computeRoutingIndex(&msg->primaryKey)];
+ ite = &ROUTING_indTable_[computeRoutingIndex (&msg->primaryKey)];
ite->successful_local_lookup_in_delay_loop = NO;
- size = ntohs(msg->header.size) - sizeof(P2P_gap_reply_MESSAGE);
+ size = ntohs (msg->header.size) - sizeof (P2P_gap_reply_MESSAGE);
prio = 0;
- if (rhf == NULL) {
- if (stats != NULL)
- stats->change(stat_routing_reply_drops, 1);
- return OK; /* not fully initialized! */
- }
- value = MALLOC(size + sizeof(DataContainer));
- value->size = htonl(size + sizeof(DataContainer));
- memcpy(&value[1],
- &msg[1],
- size);
- rhf(value,
- &contentHC);
+ if (rhf == NULL)
+ {
+ if (stats != NULL)
+ stats->change (stat_routing_reply_drops, 1);
+ return OK; /* not fully initialized! */
+ }
+ value = MALLOC (size + sizeof (DataContainer));
+ value->size = htonl (size + sizeof (DataContainer));
+ memcpy (&value[1], &msg[1], size);
+ rhf (value, &contentHC);
/* FIRST: check if valid */
- ret = bs->put(bs->closure,
- &msg->primaryKey,
- value,
- 0);
- if (ret == SYSERR) {
- EncName enc;
+ ret = bs->put (bs->closure, &msg->primaryKey, value, 0);
+ if (ret == SYSERR)
+ {
+ EncName enc;
- IF_GELOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- if (host != NULL)
- hash2enc(&host->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("GAP received invalid content from `%s'\n"),
- (host != NULL) ? (const char*)&enc : _("myself"));
- GE_BREAK_OP(ectx, 0);
- FREE(value);
- return SYSERR; /* invalid */
- }
+ IF_GELOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ if (host != NULL) hash2enc (&host->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("GAP received invalid content from `%s'\n"),
+ (host != NULL) ? (const char *) &enc : _("myself"));
+ GE_BREAK_OP (ectx, 0);
+ FREE (value);
+ return SYSERR; /* invalid */
+ }
/* SECOND: check if seen */
- MUTEX_LOCK(lookup_exclusion);
- for (i=0;i<ite->seenIndex;i++) {
- if (equalsHashCode512(&contentHC,
- &ite->seen[i])) {
- MUTEX_UNLOCK(lookup_exclusion);
- FREE(value);
- if (stats != NULL)
- stats->change(stat_routing_reply_dups, 1);
- return 0; /* seen before, useless */
+ MUTEX_LOCK (lookup_exclusion);
+ for (i = 0; i < ite->seenIndex; i++)
+ {
+ if (equalsHashCode512 (&contentHC, &ite->seen[i]))
+ {
+ MUTEX_UNLOCK (lookup_exclusion);
+ FREE (value);
+ if (stats != NULL)
+ stats->change (stat_routing_reply_dups, 1);
+ return 0; /* seen before, useless */
+ }
}
- }
- MUTEX_UNLOCK(lookup_exclusion);
+ MUTEX_UNLOCK (lookup_exclusion);
/* THIRD: compute content priority/value and
send remote reply (ITE processing) */
- hostId = intern_pid(host);
- MUTEX_LOCK(lookup_exclusion);
- if (equalsHashCode512(&ite->primaryKey,
- &msg->primaryKey) ) {
- prio = ite->priority;
- ite->priority = 0;
- /* remove the sender from the waiting list
- (if the sender was waiting for a response) */
- if (host != NULL) {
- for (i=0;i<ite->hostsWaiting;i++) {
- if (hostId == ite->destination[i]) {
- change_pid_rc(ite->destination[i], -1);
- ite->destination[i] = ite->destination[ite->hostsWaiting-1];
- if (stats != NULL)
- stats->change(stat_memory_destinations, - 1);
- GROW(ite->destination,
- ite->hostsWaiting,
- ite->hostsWaiting - 1);
- }
- }
- }
- if (stats != NULL)
- stats->change(stat_memory_seen, 1);
- GROW(ite->seen,
- ite->seenIndex,
- ite->seenIndex+1);
- ite->seen[ite->seenIndex-1] = contentHC;
- if (ite->seenIndex == 1) {
- ite->seenReplyWasUnique
- = uri(value,
- ite->type,
- NO, /* already verified */
- &ite->primaryKey);
- } else {
- ite->seenReplyWasUnique = NO;
- }
- sendReply(ite,
- &msg->header);
- if (ite->seenIndex > MAX_SEEN_VALUES * 2) {
- /* kill routing entry -- we have seen so many different
- replies already that we cannot afford to continue
- to keep track of all of the responses seen (#1014) */
- resetDestinations(ite);
- resetSeen(ite);
+ hostId = intern_pid (host);
+ MUTEX_LOCK (lookup_exclusion);
+ if (equalsHashCode512 (&ite->primaryKey, &msg->primaryKey))
+ {
+ prio = ite->priority;
ite->priority = 0;
- ite->type = 0;
- ite->ttl = 0;
+ /* remove the sender from the waiting list
+ (if the sender was waiting for a response) */
+ if (host != NULL)
+ {
+ for (i = 0; i < ite->hostsWaiting; i++)
+ {
+ if (hostId == ite->destination[i])
+ {
+ change_pid_rc (ite->destination[i], -1);
+ ite->destination[i] =
+ ite->destination[ite->hostsWaiting - 1];
+ if (stats != NULL)
+ stats->change (stat_memory_destinations, -1);
+ GROW (ite->destination,
+ ite->hostsWaiting, ite->hostsWaiting - 1);
+ }
+ }
+ }
if (stats != NULL)
- stats->change(stat_routing_slots_used, -1);
+ stats->change (stat_memory_seen, 1);
+ GROW (ite->seen, ite->seenIndex, ite->seenIndex + 1);
+ ite->seen[ite->seenIndex - 1] = contentHC;
+ if (ite->seenIndex == 1)
+ {
+ ite->seenReplyWasUnique = uri (value, ite->type, NO, /* already
verified */
+ &ite->primaryKey);
+ }
+ else
+ {
+ ite->seenReplyWasUnique = NO;
+ }
+ sendReply (ite, &msg->header);
+ if (ite->seenIndex > MAX_SEEN_VALUES * 2)
+ {
+ /* kill routing entry -- we have seen so many different
+ replies already that we cannot afford to continue
+ to keep track of all of the responses seen (#1014) */
+ resetDestinations (ite);
+ resetSeen (ite);
+ ite->priority = 0;
+ ite->type = 0;
+ ite->ttl = 0;
+ if (stats != NULL)
+ stats->change (stat_routing_slots_used, -1);
+ }
}
- } else {
- if (stats != NULL)
- stats->change(stat_routing_reply_drops, 1);
- }
- MUTEX_UNLOCK(lookup_exclusion);
- prio += claimReward(&msg->primaryKey);
+ else
+ {
+ if (stats != NULL)
+ stats->change (stat_routing_reply_drops, 1);
+ }
+ MUTEX_UNLOCK (lookup_exclusion);
+ prio += claimReward (&msg->primaryKey);
/* FOURTH: update content priority in local datastore */
- if (prio > 0) {
- bs->put(bs->closure,
- &msg->primaryKey,
- value,
- prio);
- }
+ if (prio > 0)
+ {
+ bs->put (bs->closure, &msg->primaryKey, value, prio);
+ }
/* FIFTH: if unique reply, stop querying */
- if (uri(value,
- ite->type,
- NO, /* already verified */
- &ite->primaryKey)) {
- /* unique reply, stop forwarding! */
- dequeueQuery(&ite->primaryKey);
- }
- FREE(value);
+ if (uri (value, ite->type, NO, /* already verified */
+ &ite->primaryKey))
+ {
+ /* unique reply, stop forwarding! */
+ dequeueQuery (&ite->primaryKey);
+ }
+ FREE (value);
/* SIXTH: adjust traffic preferences */
- if (host != NULL) { /* if we are the sender, hostId will be NULL */
- preference = (double) prio;
- identity->changeHostTrust(host,
- prio);
- for (i=0;i<ite->hostsWaiting;i++)
- updateResponseData(ite->destination[i],
- hostId);
- if (preference < CONTENT_BANDWIDTH_VALUE)
- preference = CONTENT_BANDWIDTH_VALUE;
- coreAPI->preferTrafficFrom(host,
- preference);
- }
- change_pid_rc(hostId, -1);
+ if (host != NULL)
+ { /* if we are the sender, hostId will be NULL */
+ preference = (double) prio;
+ identity->changeHostTrust (host, prio);
+ for (i = 0; i < ite->hostsWaiting; i++)
+ updateResponseData (ite->destination[i], hostId);
+ if (preference < CONTENT_BANDWIDTH_VALUE)
+ preference = CONTENT_BANDWIDTH_VALUE;
+ coreAPI->preferTrafficFrom (host, preference);
+ }
+ change_pid_rc (hostId, -1);
return OK;
}
@@ -1782,13 +1815,14 @@
* @param datastore the storage callbacks to use for storing data
* @return SYSERR on error, OK on success
*/
-static int init(Blockstore * datastore,
- UniqueReplyIdentifier uid,
- ReplyHashFunction rh) {
- if (bs != NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+static int
+init (Blockstore * datastore, UniqueReplyIdentifier uid, ReplyHashFunction rh)
+{
+ if (bs != NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
bs = datastore;
uri = uid;
rhf = rh;
@@ -1812,98 +1846,99 @@
* buffers are full or other error, NO if we already
* returned the one and only reply (local hit)
*/
-static int get_start(const PeerIdentity * target,
- unsigned int type,
- unsigned int anonymityLevel,
- unsigned int keyCount,
- const HashCode512 * keys,
- cron_t timeout,
- unsigned int prio) {
- P2P_gap_query_MESSAGE * msg;
+static int
+get_start (const PeerIdentity * target,
+ unsigned int type,
+ unsigned int anonymityLevel,
+ unsigned int keyCount,
+ const HashCode512 * keys, cron_t timeout, unsigned int prio)
+{
+ P2P_gap_query_MESSAGE *msg;
unsigned int size;
int ret;
- size = sizeof(P2P_gap_query_MESSAGE) + (keyCount-1) * sizeof(HashCode512);
- if (size >= MAX_BUFFER_SIZE) {
- GE_BREAK(ectx, 0);
- return SYSERR; /* too many keys! */
- }
+ size =
+ sizeof (P2P_gap_query_MESSAGE) + (keyCount - 1) * sizeof (HashCode512);
+ if (size >= MAX_BUFFER_SIZE)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR; /* too many keys! */
+ }
/* anonymity level considerations:
check cover traffic availability! */
- if (anonymityLevel > 0) {
- unsigned int count;
- unsigned int peers;
- unsigned int sizes;
- unsigned int timevect;
+ if (anonymityLevel > 0)
+ {
+ unsigned int count;
+ unsigned int peers;
+ unsigned int sizes;
+ unsigned int timevect;
- anonymityLevel--;
- if (traffic == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Cover traffic requested but traffic service not loaded. Rejecting
request.\n"));
- return SYSERR;
+ anonymityLevel--;
+ if (traffic == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("Cover traffic requested but traffic service not loaded.
Rejecting request.\n"));
+ return SYSERR;
+ }
+ if (OK != traffic->get ((TTL_DECREMENT + timeout) / TRAFFIC_TIME_UNIT,
+ P2P_PROTO_gap_QUERY,
+ TC_RECEIVED, &count, &peers, &sizes, &timevect))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Failed to get traffic stats.\n"));
+ return SYSERR;
+ }
+ if (anonymityLevel > 1000)
+ {
+ if (peers < anonymityLevel / 1000)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("Cannot satisfy desired level of anonymity, ignoring
request.\n"));
+ return SYSERR;
+ }
+ if (count < anonymityLevel % 1000)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("Cannot satisfy desired level of anonymity, ignoring
request.\n"));
+ return SYSERR;
+ }
+ }
+ else
+ {
+ if (count < anonymityLevel)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("Cannot satisfy desired level of anonymity, ignoring
request.\n"));
+ return SYSERR;
+ }
+ }
}
- if (OK != traffic->get((TTL_DECREMENT + timeout) / TRAFFIC_TIME_UNIT,
- P2P_PROTO_gap_QUERY,
- TC_RECEIVED,
- &count,
- &peers,
- &sizes,
- &timevect)) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Failed to get traffic stats.\n"));
- return SYSERR;
- }
- if (anonymityLevel > 1000) {
- if (peers < anonymityLevel / 1000) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Cannot satisfy desired level of anonymity, ignoring request.\n"));
- return SYSERR;
- }
- if (count < anonymityLevel % 1000) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Cannot satisfy desired level of anonymity, ignoring request.\n"));
- return SYSERR;
- }
- } else {
- if (count < anonymityLevel) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Cannot satisfy desired level of anonymity, ignoring request.\n"));
- return SYSERR;
- }
- }
- }
- msg = MALLOC(size);
- msg->header.size
- = htons(size);
- msg->header.type
- = htons(P2P_PROTO_gap_QUERY);
- msg->type
- = htonl(type);
- msg->priority
- = htonl(prio);
- msg->ttl
- = htonl(adjustTTL((int)timeout - get_time(),
- prio));
- memcpy(&msg->queries[0],
- keys,
- sizeof(HashCode512) * keyCount);
- msg->returnTo
- = *coreAPI->myIdentity;
- ret = execQuery(NULL,
- target,
- prio,
- QUERY_ANSWER|QUERY_FORWARD|QUERY_INDIRECT,
- timeout - get_time(),
- msg);
- FREE(msg);
+ msg = MALLOC (size);
+ msg->header.size = htons (size);
+ msg->header.type = htons (P2P_PROTO_gap_QUERY);
+ msg->type = htonl (type);
+ msg->priority = htonl (prio);
+ msg->ttl = htonl (adjustTTL ((int) timeout - get_time (), prio));
+ memcpy (&msg->queries[0], keys, sizeof (HashCode512) * keyCount);
+ msg->returnTo = *coreAPI->myIdentity;
+ ret = execQuery (NULL,
+ target,
+ prio,
+ QUERY_ANSWER | QUERY_FORWARD | QUERY_INDIRECT,
+ timeout - get_time (), msg);
+ FREE (msg);
return ret;
}
@@ -1912,12 +1947,12 @@
* stop sending queries at some point, but this method can be used to
* stop it earlier.
*/
-static int get_stop(unsigned int type,
- unsigned int keyCount,
- const HashCode512 * keys) {
+static int
+get_stop (unsigned int type, unsigned int keyCount, const HashCode512 * keys)
+{
if (keyCount < 1)
return SYSERR;
- return dequeueQuery(&keys[0]);
+ return dequeueQuery (&keys[0]);
}
/**
@@ -1930,27 +1965,23 @@
* that buffer (must be a positive number).
*/
static unsigned int
-tryMigrate(const DataContainer * data,
- const HashCode512 * primaryKey,
- char * position,
- unsigned int padding) {
- P2P_gap_reply_MESSAGE * reply;
+tryMigrate (const DataContainer * data,
+ const HashCode512 * primaryKey,
+ char *position, unsigned int padding)
+{
+ P2P_gap_reply_MESSAGE *reply;
unsigned int size;
- size = sizeof(P2P_gap_reply_MESSAGE) + ntohl(data->size) -
sizeof(DataContainer);
- if ( (size > padding) ||
- (size >= MAX_BUFFER_SIZE) )
+ size =
+ sizeof (P2P_gap_reply_MESSAGE) + ntohl (data->size) -
+ sizeof (DataContainer);
+ if ((size > padding) || (size >= MAX_BUFFER_SIZE))
return 0;
- reply = (P2P_gap_reply_MESSAGE*) position;
- reply->header.type
- = htons(P2P_PROTO_gap_RESULT);
- reply->header.size
- = htons(size);
- reply->primaryKey
- = *primaryKey;
- memcpy(&reply[1],
- &data[1],
- size - sizeof(P2P_gap_reply_MESSAGE));
+ reply = (P2P_gap_reply_MESSAGE *) position;
+ reply->header.type = htons (P2P_PROTO_gap_RESULT);
+ reply->header.size = htons (size);
+ reply->primaryKey = *primaryKey;
+ memcpy (&reply[1], &data[1], size - sizeof (P2P_gap_reply_MESSAGE));
return size;
}
@@ -1958,10 +1989,11 @@
* Handle query for content. Depending on how we like the sender,
* lookup, forward or even indirect.
*/
-static int handleQuery(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg) {
+static int
+handleQuery (const PeerIdentity * sender, const MESSAGE_HEADER * msg)
+{
QUERY_POLICY policy;
- P2P_gap_query_MESSAGE * qmsg;
+ P2P_gap_query_MESSAGE *qmsg;
unsigned int queries;
int ttl;
unsigned int prio;
@@ -1970,146 +2002,149 @@
EncName enc;
#endif
- if (bs == NULL) {
- GE_BREAK(ectx, 0);
- return 0;
- }
+ if (bs == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return 0;
+ }
/* Load above hard limit? */
- if (loadTooHigh()) {
+ if (loadTooHigh ())
+ {
#if DEBUG_GAP
- if (sender != NULL) {
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&sender->hashPubKey,
- &enc));
+ if (sender != NULL)
+ {
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&sender->hashPubKey, &enc));
+ }
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Dropping query from %s, this peer is too busy.\n",
+ sender == NULL ? "localhost" : (char *) &enc);
+#endif
+ return OK;
}
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Dropping query from %s, this peer is too busy.\n",
- sender == NULL ? "localhost" : (char*)&enc);
-#endif
- return OK;
- }
- queries = 1 + (ntohs(msg->size) - sizeof(P2P_gap_query_MESSAGE))
- / sizeof(HashCode512);
- if ( (queries <= 0) ||
- (ntohs(msg->size) < sizeof(P2P_gap_query_MESSAGE)) ||
- (ntohs(msg->size) != sizeof(P2P_gap_query_MESSAGE) +
- (queries-1) * sizeof(HashCode512)) ) {
- GE_BREAK_OP(ectx, 0);
- return SYSERR; /* malformed query */
- }
+ queries = 1 + (ntohs (msg->size) - sizeof (P2P_gap_query_MESSAGE))
+ / sizeof (HashCode512);
+ if ((queries <= 0) ||
+ (ntohs (msg->size) < sizeof (P2P_gap_query_MESSAGE)) ||
+ (ntohs (msg->size) != sizeof (P2P_gap_query_MESSAGE) +
+ (queries - 1) * sizeof (HashCode512)))
+ {
+ GE_BREAK_OP (ectx, 0);
+ return SYSERR; /* malformed query */
+ }
- qmsg = MALLOC(ntohs(msg->size));
- memcpy(qmsg, msg, ntohs(msg->size));
- if (equalsHashCode512(&qmsg->returnTo.hashPubKey,
- &coreAPI->myIdentity->hashPubKey)) {
- /* A to B, B sends to C without source rewriting,
- C sends back to A again without source rewriting;
- (or B directly back to A; also should not happen)
- in this case, A must just drop; however, this
- should not happen (peers should check). */
- GE_BREAK_OP(ectx, 0);
- FREE(qmsg);
- return OK;
- }
+ qmsg = MALLOC (ntohs (msg->size));
+ memcpy (qmsg, msg, ntohs (msg->size));
+ if (equalsHashCode512 (&qmsg->returnTo.hashPubKey,
+ &coreAPI->myIdentity->hashPubKey))
+ {
+ /* A to B, B sends to C without source rewriting,
+ C sends back to A again without source rewriting;
+ (or B directly back to A; also should not happen)
+ in this case, A must just drop; however, this
+ should not happen (peers should check). */
+ GE_BREAK_OP (ectx, 0);
+ FREE (qmsg);
+ return OK;
+ }
if (stats != NULL)
- stats->change(stat_routing_totals, 1);
+ stats->change (stat_routing_totals, 1);
/* decrement ttl (always) */
- ttl = ntohl(qmsg->ttl);
- if (ttl < 0) {
- ttl = ttl - 2*TTL_DECREMENT - weak_randomi(TTL_DECREMENT);
- if (ttl > 0) { /* integer underflow => drop (should be very rare)! */
- FREE(qmsg);
- if (stats != NULL)
- stats->change(stat_routing_direct_drops, 1);
- return OK; /* just abort */
+ ttl = ntohl (qmsg->ttl);
+ if (ttl < 0)
+ {
+ ttl = ttl - 2 * TTL_DECREMENT - weak_randomi (TTL_DECREMENT);
+ if (ttl > 0)
+ { /* integer underflow => drop (should be very
rare)! */
+ FREE (qmsg);
+ if (stats != NULL)
+ stats->change (stat_routing_direct_drops, 1);
+ return OK; /* just abort */
+ }
}
- } else {
- ttl = ttl - 2*TTL_DECREMENT - weak_randomi(TTL_DECREMENT);
- }
- prio = ntohl(qmsg->priority);
- policy = evaluateQuery(sender,
- &prio);
+ else
+ {
+ ttl = ttl - 2 * TTL_DECREMENT - weak_randomi (TTL_DECREMENT);
+ }
+ prio = ntohl (qmsg->priority);
+ policy = evaluateQuery (sender, &prio);
#if DEBUG_GAP
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&qmsg->queries[0],
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received GAP query `%s'.\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&qmsg->queries[0], &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received GAP query `%s'.\n", &enc);
#endif
- if ((policy & QUERY_DROPMASK) == 0) {
- /* policy says no answer/forward/indirect => direct drop;
- this happens if the peer is too busy (netload-up >= 100%). */
- FREE(qmsg);
+ if ((policy & QUERY_DROPMASK) == 0)
+ {
+ /* policy says no answer/forward/indirect => direct drop;
+ this happens if the peer is too busy (netload-up >= 100%). */
+ FREE (qmsg);
#if DEBUG_GAP
- if (sender != NULL) {
- IF_GELOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&sender->hashPubKey,
- &enc));
+ if (sender != NULL)
+ {
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&sender->hashPubKey, &enc));
+ }
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Dropping query from %s, policy decided that this peer is too
busy.\n",
+ sender == NULL ? "localhost" : (const char *) &enc);
+#endif
+ if (stats != NULL)
+ stats->change (stat_routing_direct_drops, 1);
+ return OK; /* straight drop. */
}
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Dropping query from %s, policy decided that this peer is too busy.\n",
- sender == NULL ? "localhost" : (const char*) &enc);
-#endif
- if (stats != NULL)
- stats->change(stat_routing_direct_drops, 1);
- return OK; /* straight drop. */
- }
preference = (double) prio;
- if ((policy & QUERY_INDIRECT) > 0) {
- qmsg->returnTo
- = *coreAPI->myIdentity;
- } else {
- /* otherwise we preserve the original sender
- and kill the priority (since we cannot benefit) */
- prio = 0;
- }
+ if ((policy & QUERY_INDIRECT) > 0)
+ {
+ qmsg->returnTo = *coreAPI->myIdentity;
+ }
+ else
+ {
+ /* otherwise we preserve the original sender
+ and kill the priority (since we cannot benefit) */
+ prio = 0;
+ }
if (preference < QUERY_BANDWIDTH_VALUE)
preference = QUERY_BANDWIDTH_VALUE;
- coreAPI->preferTrafficFrom(sender,
- preference);
+ coreAPI->preferTrafficFrom (sender, preference);
/* adjust priority */
- qmsg->priority
- = htonl(prio);
- qmsg->ttl
- = htonl(adjustTTL(ttl, prio));
+ qmsg->priority = htonl (prio);
+ qmsg->ttl = htonl (adjustTTL (ttl, prio));
- ttl = ntohl(qmsg->ttl);
+ ttl = ntohl (qmsg->ttl);
if (ttl < 0)
ttl = 0;
- execQuery(sender,
- NULL,
- prio,
- policy,
- ttl,
- qmsg);
- FREE(qmsg);
+ execQuery (sender, NULL, prio, policy, ttl, qmsg);
+ FREE (qmsg);
return OK;
}
-static unsigned int getAvgPriority() {
- IndirectionTableEntry * ite;
+static unsigned int
+getAvgPriority ()
+{
+ IndirectionTableEntry *ite;
unsigned long long tot;
int i;
unsigned int active;
tot = 0;
active = 0;
- for (i=indirectionTableSize-1;i>=0;i--) {
- ite = &ROUTING_indTable_[i];
- if ( (ite->hostsWaiting > 0) &&
- (ite->seenIndex == 0) ) {
- tot += ite->priority;
- active++;
+ for (i = indirectionTableSize - 1; i >= 0; i--)
+ {
+ ite = &ROUTING_indTable_[i];
+ if ((ite->hostsWaiting > 0) && (ite->seenIndex == 0))
+ {
+ tot += ite->priority;
+ active++;
+ }
}
- }
if (active == 0)
return 0;
else
@@ -2118,112 +2153,125 @@
GAP_ServiceAPI *
-provide_module_gap(CoreAPIForApplication * capi) {
+provide_module_gap (CoreAPIForApplication * capi)
+{
static GAP_ServiceAPI api;
unsigned int i;
ectx = capi->ectx;
cfg = capi->cfg;
coreAPI = capi;
- if ( (-1 == GC_get_configuration_value_number(cfg,
- "LOAD",
- "HARDCPULIMIT",
- 0,
- 100000, /* 1000 CPUs!? */
- 0, /* 0 == no limit */
- &hardCPULimit)) ||
- (-1 == GC_get_configuration_value_number(cfg,
- "LOAD",
- "HARDUPLIMIT",
- 0,
- 999999999,
- 0, /* 0 == no limit */
- &hardUpLimit)) ||
- (-1 == GC_get_configuration_value_number(cfg,
- "GAP",
- "TABLESIZE",
- MIN_INDIRECTION_TABLE_SIZE,
- MAX_MALLOC_CHECKED /
sizeof(IndirectionTableEntry),
- MIN_INDIRECTION_TABLE_SIZE,
- &indirectionTableSize)) )
+ if ((-1 == GC_get_configuration_value_number (cfg, "LOAD", "HARDCPULIMIT",
0, 100000, /* 1000 CPUs!? */
+ 0, /* 0 == no limit */
+ &hardCPULimit)) || (-1 ==
GC_get_configuration_value_number (cfg, "LOAD", "HARDUPLIMIT", 0, 999999999, 0,
/* 0 == no limit */
+
&hardUpLimit))
+ || (-1 ==
+ GC_get_configuration_value_number (cfg, "GAP", "TABLESIZE",
+ MIN_INDIRECTION_TABLE_SIZE,
+ MAX_MALLOC_CHECKED /
+ sizeof (IndirectionTableEntry),
+ MIN_INDIRECTION_TABLE_SIZE,
+ &indirectionTableSize)))
return NULL;
- GE_ASSERT(ectx, sizeof(P2P_gap_reply_MESSAGE) == 68);
- GE_ASSERT(ectx, sizeof(P2P_gap_query_MESSAGE) == 144);
+ GE_ASSERT (ectx, sizeof (P2P_gap_reply_MESSAGE) == 68);
+ GE_ASSERT (ectx, sizeof (P2P_gap_query_MESSAGE) == 144);
- stats = capi->requestService("stats");
- if (stats != NULL) {
- stat_routing_totals = stats->create(gettext_noop("# gap
requests total received"));
- stat_routing_direct_drops = stats->create(gettext_noop("# gap
requests policy: immediate drop"));
- stat_routing_no_route_policy = stats->create(gettext_noop("# gap
requests policy: not routed"));
- stat_routing_no_answer_policy = stats->create(gettext_noop("# gap
requests policy: not answered"));
- stat_routing_processed = stats->create(gettext_noop("# gap
requests processed: attempted add to RT"));
- stat_routing_local_results = stats->create(gettext_noop("# gap
requests processed: local result"));
- stat_routing_successes = stats->create(gettext_noop("# gap
routing successes (total)"));
- stat_routing_collisions = stats->create(gettext_noop("# gap
requests dropped: collision in RT"));
- stat_routing_forwards = stats->create(gettext_noop("# gap
requests forwarded (counting each peer)"));
- stat_routing_request_duplicates = stats->create(gettext_noop("# gap
duplicate requests (pending)"));
- stat_routing_request_repeat = stats->create(gettext_noop("# gap
duplicate requests that were re-tried"));
- stat_routing_request_repeat_dttl= stats->create(gettext_noop("# gap re-try
ttl difference (cummulative)"));
- stat_routing_reply_dups = stats->create(gettext_noop("# gap reply
duplicates"));
- stat_routing_reply_drops = stats->create(gettext_noop("# gap
spurious replies (dropped)"));
- stat_routing_slots_used = stats->create(gettext_noop("# gap
routing slots currently in use"));
- stat_memory_seen = stats->create(gettext_noop("# gap memory
used for tracking seen content"));
- stat_memory_destinations = stats->create(gettext_noop("# gap memory
used for tracking routing destinations"));
- stat_pending_rewards = stats->create(gettext_noop("# gap
rewards pending"));
- stat_response_count = stats->create(gettext_noop("# gap
response weights"));
- }
- init_pid_table(ectx,
- stats);
- GROW(rewards,
- rewardSize,
- MAX_REWARD_TRACKS);
+ stats = capi->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_routing_totals =
+ stats->create (gettext_noop ("# gap requests total received"));
+ stat_routing_direct_drops =
+ stats->
+ create (gettext_noop ("# gap requests policy: immediate drop"));
+ stat_routing_no_route_policy =
+ stats->create (gettext_noop ("# gap requests policy: not routed"));
+ stat_routing_no_answer_policy =
+ stats->create (gettext_noop ("# gap requests policy: not answered"));
+ stat_routing_processed =
+ stats->
+ create (gettext_noop
+ ("# gap requests processed: attempted add to RT"));
+ stat_routing_local_results =
+ stats->
+ create (gettext_noop ("# gap requests processed: local result"));
+ stat_routing_successes =
+ stats->create (gettext_noop ("# gap routing successes (total)"));
+ stat_routing_collisions =
+ stats->
+ create (gettext_noop ("# gap requests dropped: collision in RT"));
+ stat_routing_forwards =
+ stats->
+ create (gettext_noop
+ ("# gap requests forwarded (counting each peer)"));
+ stat_routing_request_duplicates =
+ stats->create (gettext_noop ("# gap duplicate requests (pending)"));
+ stat_routing_request_repeat =
+ stats->
+ create (gettext_noop ("# gap duplicate requests that were re-tried"));
+ stat_routing_request_repeat_dttl =
+ stats->
+ create (gettext_noop ("# gap re-try ttl difference (cummulative)"));
+ stat_routing_reply_dups =
+ stats->create (gettext_noop ("# gap reply duplicates"));
+ stat_routing_reply_drops =
+ stats->create (gettext_noop ("# gap spurious replies (dropped)"));
+ stat_routing_slots_used =
+ stats->create (gettext_noop ("# gap routing slots currently in use"));
+ stat_memory_seen =
+ stats->
+ create (gettext_noop ("# gap memory used for tracking seen content"));
+ stat_memory_destinations =
+ stats->
+ create (gettext_noop
+ ("# gap memory used for tracking routing destinations"));
+ stat_pending_rewards =
+ stats->create (gettext_noop ("# gap rewards pending"));
+ stat_response_count =
+ stats->create (gettext_noop ("# gap response weights"));
+ }
+ init_pid_table (ectx, stats);
+ GROW (rewards, rewardSize, MAX_REWARD_TRACKS);
- identity = coreAPI->requestService("identity");
- GE_ASSERT(ectx, identity != NULL);
- topology = coreAPI->requestService("topology");
- GE_ASSERT(ectx, topology != NULL);
- traffic = coreAPI->requestService("traffic");
- if (traffic == NULL) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Traffic service failed to load; gap cannot ensure cover-traffic
availability.\n"));
- }
- random_qsel = weak_randomi(0xFFFF);
- lookup_exclusion = MUTEX_CREATE(NO);
+ identity = coreAPI->requestService ("identity");
+ GE_ASSERT (ectx, identity != NULL);
+ topology = coreAPI->requestService ("topology");
+ GE_ASSERT (ectx, topology != NULL);
+ traffic = coreAPI->requestService ("traffic");
+ if (traffic == NULL)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("Traffic service failed to load; gap cannot ensure
cover-traffic availability.\n"));
+ }
+ random_qsel = weak_randomi (0xFFFF);
+ lookup_exclusion = MUTEX_CREATE (NO);
ROUTING_indTable_
- = MALLOC(sizeof(IndirectionTableEntry)
- * indirectionTableSize);
- memset(ROUTING_indTable_,
- 0,
- sizeof(IndirectionTableEntry)
- * indirectionTableSize);
- for (i=0;i<indirectionTableSize;i++) {
- ROUTING_indTable_[i].successful_local_lookup_in_delay_loop = NO;
- }
+ = MALLOC (sizeof (IndirectionTableEntry) * indirectionTableSize);
+ memset (ROUTING_indTable_,
+ 0, sizeof (IndirectionTableEntry) * indirectionTableSize);
+ for (i = 0; i < indirectionTableSize; i++)
+ {
+ ROUTING_indTable_[i].successful_local_lookup_in_delay_loop = NO;
+ }
- for (i=0;i<QUERY_RECORD_COUNT;i++) {
- queries[i].expires = 0; /* all expired */
- queries[i].msg = NULL;
- }
- lock = coreAPI->getConnectionModuleLock();
- cron_add_job(capi->cron,
- &ageRTD,
- 2 * cronMINUTES,
- 2 * cronMINUTES,
- NULL);
+ for (i = 0; i < QUERY_RECORD_COUNT; i++)
+ {
+ queries[i].expires = 0; /* all expired */
+ queries[i].msg = NULL;
+ }
+ lock = coreAPI->getConnectionModuleLock ();
+ cron_add_job (capi->cron, &ageRTD, 2 * cronMINUTES, 2 * cronMINUTES, NULL);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _("`%s' registering handlers %d %d\n"),
- "gap",
- P2P_PROTO_gap_QUERY,
- P2P_PROTO_gap_RESULT);
- capi->registerHandler(P2P_PROTO_gap_QUERY,
- &handleQuery);
- capi->registerHandler(P2P_PROTO_gap_RESULT,
- &useContent);
- coreAPI->registerSendCallback(sizeof(P2P_gap_query_MESSAGE),
- &fillInQuery);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ _("`%s' registering handlers %d %d\n"),
+ "gap", P2P_PROTO_gap_QUERY, P2P_PROTO_gap_RESULT);
+ capi->registerHandler (P2P_PROTO_gap_QUERY, &handleQuery);
+ capi->registerHandler (P2P_PROTO_gap_RESULT, &useContent);
+ coreAPI->registerSendCallback (sizeof (P2P_gap_query_MESSAGE),
+ &fillInQuery);
api.init = &init;
api.get_start = &get_start;
@@ -2233,64 +2281,64 @@
return &api;
}
-void release_module_gap() {
+void
+release_module_gap ()
+{
unsigned int i;
- ResponseList * rpos;
- ReplyTrackData * pos;
- IndirectionTableEntry * ite;
+ ResponseList *rpos;
+ ReplyTrackData *pos;
+ IndirectionTableEntry *ite;
- coreAPI->unregisterHandler(P2P_PROTO_gap_QUERY,
- &handleQuery);
- coreAPI->unregisterHandler(P2P_PROTO_gap_RESULT,
- &useContent);
- coreAPI->unregisterSendCallback(sizeof(P2P_gap_query_MESSAGE),
- &fillInQuery);
+ coreAPI->unregisterHandler (P2P_PROTO_gap_QUERY, &handleQuery);
+ coreAPI->unregisterHandler (P2P_PROTO_gap_RESULT, &useContent);
+ coreAPI->unregisterSendCallback (sizeof (P2P_gap_query_MESSAGE),
+ &fillInQuery);
- cron_del_job(coreAPI->cron,
- &ageRTD,
- 2 * cronMINUTES,
- NULL);
+ cron_del_job (coreAPI->cron, &ageRTD, 2 * cronMINUTES, NULL);
- for (i=0;i<indirectionTableSize;i++) {
- ite = &ROUTING_indTable_[i];
- resetSeen(ite);
- ite->seenReplyWasUnique = NO;
- resetDestinations(ite);
- }
+ for (i = 0; i < indirectionTableSize; i++)
+ {
+ ite = &ROUTING_indTable_[i];
+ resetSeen (ite);
+ ite->seenReplyWasUnique = NO;
+ resetDestinations (ite);
+ }
- MUTEX_DESTROY(lookup_exclusion);
+ MUTEX_DESTROY (lookup_exclusion);
lookup_exclusion = NULL;
- while (rtdList != NULL) {
- pos = rtdList;
- rtdList = rtdList->next;
- while (pos->responseList != NULL) {
- rpos = pos->responseList;
- pos->responseList = rpos->next;
- FREE(rpos);
+ while (rtdList != NULL)
+ {
+ pos = rtdList;
+ rtdList = rtdList->next;
+ while (pos->responseList != NULL)
+ {
+ rpos = pos->responseList;
+ pos->responseList = rpos->next;
+ FREE (rpos);
+ }
+ FREE (pos);
}
- FREE(pos);
- }
- for (i=0;i<QUERY_RECORD_COUNT;i++)
- FREENONNULL(queries[i].msg);
+ for (i = 0; i < QUERY_RECORD_COUNT; i++)
+ FREENONNULL (queries[i].msg);
- coreAPI->releaseService(identity);
+ coreAPI->releaseService (identity);
identity = NULL;
- coreAPI->releaseService(topology);
+ coreAPI->releaseService (topology);
topology = NULL;
- if (traffic != NULL) {
- coreAPI->releaseService(traffic);
- traffic = NULL;
- }
- FREE(ROUTING_indTable_);
- GROW(rewards,
- rewardSize,
- 0);
- done_pid_table();
- if (stats != NULL) {
- stats->set(stat_pending_rewards, 0);
- coreAPI->releaseService(stats);
- stats = NULL;
- }
+ if (traffic != NULL)
+ {
+ coreAPI->releaseService (traffic);
+ traffic = NULL;
+ }
+ FREE (ROUTING_indTable_);
+ GROW (rewards, rewardSize, 0);
+ done_pid_table ();
+ if (stats != NULL)
+ {
+ stats->set (stat_pending_rewards, 0);
+ coreAPI->releaseService (stats);
+ stats = NULL;
+ }
lock = NULL;
coreAPI = NULL;
bs = NULL;
Modified: GNUnet/src/applications/gap/gap.h
===================================================================
--- GNUnet/src/applications/gap/gap.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/gap/gap.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -203,7 +203,8 @@
* Request for content. The number of queries can
* be determined from the header size.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -237,7 +238,8 @@
/**
* Return message for search result.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
HashCode512 primaryKey;
@@ -249,7 +251,8 @@
* query that is being send from the local node to
* optimize the sending strategy.
*/
-typedef struct {
+typedef struct
+{
/**
* How often did we send this query so far?
@@ -270,13 +273,13 @@
/**
* The message that we are sending.
*/
- P2P_gap_query_MESSAGE * msg;
+ P2P_gap_query_MESSAGE *msg;
/**
* How important would it be to send the message to all peers in
* this bucket?
*/
- int * rankings;
+ int *rankings;
/**
* When do we stop forwarding (!) this query?
@@ -314,7 +317,8 @@
* that the entries point to can easily use another 8 MB at this
* point [see Mantis #1058])
*/
-typedef struct {
+typedef struct
+{
/**
* What are we waiting for?
*/
@@ -343,17 +347,17 @@
*/
unsigned int seenIndex;
- int seenReplyWasUnique; /* YES/NO, only valid if seenIndex == 1 */
+ int seenReplyWasUnique; /* YES/NO, only valid if seenIndex == 1 */
/**
* Hashcodes of the encrypted (!) replies that we have forwarded so far
*/
- HashCode512 * seen;
+ HashCode512 *seen;
/**
* Who are these hosts?
*/
- PID_INDEX * destination;
+ PID_INDEX *destination;
/**
* How many hosts are waiting for an answer to this query (length of
@@ -380,8 +384,9 @@
* to queries from a certain peer at the moment
* Linked list of peer ids with number of replies received.
*/
-typedef struct RL_ {
- struct RL_ * next;
+typedef struct RL_
+{
+ struct RL_ *next;
PID_INDEX responder;
unsigned int responseCount;
} ResponseList;
@@ -390,12 +395,13 @@
* Structure for tracking from which peer we got valueable replies for
* which clients / other peers.
*/
-typedef struct RTD_ {
+typedef struct RTD_
+{
/**
* This is a linked list.
*/
- struct RTD_ * next;
+ struct RTD_ *next;
/**
* For which client does this entry track replies?
@@ -406,7 +412,7 @@
* Linked list of peers that responded, with
* number of responses.
*/
- ResponseList * responseList;
+ ResponseList *responseList;
/**
* Time at which we received the last reply
@@ -420,10 +426,8 @@
* Tracking of just reward data (how much trust a peer
* can gain for a particular reply).
*/
-typedef struct {
+typedef struct
+{
HashCode512 query;
unsigned int prio;
} RewardEntry;
-
-
-
Modified: GNUnet/src/applications/gap/gaptest.c
===================================================================
--- GNUnet/src/applications/gap/gaptest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/gap/gaptest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -34,226 +34,203 @@
#include "gnunet_util_network_client.h"
#include "gnunet_stats_lib.h"
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static int testTerminate(void * unused) {
+static int
+testTerminate (void *unused)
+{
return OK;
}
-static void uprogress(unsigned long long totalBytes,
- unsigned long long completedBytes,
- cron_t eta,
- void * closure) {
- fprintf(stderr,
- totalBytes == completedBytes ? "\n" : ".");
+static void
+uprogress (unsigned long long totalBytes,
+ unsigned long long completedBytes, cron_t eta, void *closure)
+{
+ fprintf (stderr, totalBytes == completedBytes ? "\n" : ".");
}
-static void dprogress(unsigned long long totalBytes,
- unsigned long long completedBytes,
- cron_t eta,
- unsigned long long lastBlockOffset,
- const char * lastBlock,
- unsigned int lastBlockSize,
- void * closure) {
- fprintf(stderr,
- totalBytes == completedBytes ? "\n" : ".");
+static void
+dprogress (unsigned long long totalBytes,
+ unsigned long long completedBytes,
+ cron_t eta,
+ unsigned long long lastBlockOffset,
+ const char *lastBlock, unsigned int lastBlockSize, void *closure)
+{
+ fprintf (stderr, totalBytes == completedBytes ? "\n" : ".");
}
-static char * makeName(unsigned int i) {
- char * fn;
+static char *
+makeName (unsigned int i)
+{
+ char *fn;
- fn = MALLOC(strlen("/tmp/gnunet-gaptest/GAPTEST") + 14);
- SNPRINTF(fn,
- strlen("/tmp/gnunet-gaptest/GAPTEST") + 14,
- "/tmp/gnunet-gaptest/GAPTEST%u",
- i);
- disk_directory_create_for_file(NULL, fn);
+ fn = MALLOC (strlen ("/tmp/gnunet-gaptest/GAPTEST") + 14);
+ SNPRINTF (fn,
+ strlen ("/tmp/gnunet-gaptest/GAPTEST") + 14,
+ "/tmp/gnunet-gaptest/GAPTEST%u", i);
+ disk_directory_create_for_file (NULL, fn);
return fn;
}
-static struct ECRS_URI * uploadFile(unsigned int size) {
+static struct ECRS_URI *
+uploadFile (unsigned int size)
+{
int ret;
- char * name;
+ char *name;
int fd;
- char * buf;
- struct ECRS_URI * uri;
+ char *buf;
+ struct ECRS_URI *uri;
int i;
- name = makeName(size);
- fd = disk_file_open(ectx,
- name,
- O_WRONLY|O_CREAT, S_IWUSR|S_IRUSR);
- buf = MALLOC(size);
- memset(buf, size + size / 253, size);
- for (i=0;i<(int) (size - 42 - sizeof(HashCode512));i+=sizeof(HashCode512))
- hash(&buf[i+sizeof(HashCode512)],
- 42,
- (HashCode512*) &buf[i]);
- WRITE(fd, buf, size);
- FREE(buf);
- disk_file_close(ectx, name, fd);
- ret = ECRS_uploadFile(ectx,
- cfg,
- name,
- YES, /* index */
- 0, /* anon */
- 0, /* prio */
- get_time() + 10 * cronMINUTES, /* expire */
- &uprogress,
- NULL,
- &testTerminate,
- NULL,
- &uri);
- if (ret != SYSERR) {
- struct ECRS_MetaData * meta;
- struct ECRS_URI * key;
- const char * keywords[2];
+ name = makeName (size);
+ fd = disk_file_open (ectx, name, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR);
+ buf = MALLOC (size);
+ memset (buf, size + size / 253, size);
+ for (i = 0; i < (int) (size - 42 - sizeof (HashCode512));
+ i += sizeof (HashCode512))
+ hash (&buf[i + sizeof (HashCode512)], 42, (HashCode512 *) & buf[i]);
+ WRITE (fd, buf, size);
+ FREE (buf);
+ disk_file_close (ectx, name, fd);
+ ret = ECRS_uploadFile (ectx, cfg, name, YES, /* index */
+ 0, /* anon */
+ 0, /* prio */
+ get_time () + 10 * cronMINUTES, /* expire */
+ &uprogress, NULL, &testTerminate, NULL, &uri);
+ if (ret != SYSERR)
+ {
+ struct ECRS_MetaData *meta;
+ struct ECRS_URI *key;
+ const char *keywords[2];
- keywords[0] = name;
- keywords[1] = NULL;
+ keywords[0] = name;
+ keywords[1] = NULL;
- meta = ECRS_createMetaData();
- key = ECRS_keywordsToUri(keywords);
- ret = ECRS_addToKeyspace(ectx,
- cfg,
- key,
- 0,
- 0,
- get_time() + 10 * cronMINUTES, /* expire */
- uri,
- meta);
- ECRS_freeMetaData(meta);
- ECRS_freeUri(uri);
- FREE(name);
- if (ret == OK) {
- return key;
- } else {
- ECRS_freeUri(key);
+ meta = ECRS_createMetaData ();
+ key = ECRS_keywordsToUri (keywords);
+ ret = ECRS_addToKeyspace (ectx, cfg, key, 0, 0, get_time () + 10 *
cronMINUTES, /* expire */
+ uri, meta);
+ ECRS_freeMetaData (meta);
+ ECRS_freeUri (uri);
+ FREE (name);
+ if (ret == OK)
+ {
+ return key;
+ }
+ else
+ {
+ ECRS_freeUri (key);
+ return NULL;
+ }
+ }
+ else
+ {
+ FREE (name);
return NULL;
}
- } else {
- FREE(name);
- return NULL;
- }
}
-static int searchCB(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * closure) {
- struct ECRS_URI ** my = closure;
- char * tmp;
+static int
+searchCB (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *closure)
+{
+ struct ECRS_URI **my = closure;
+ char *tmp;
- tmp = ECRS_uriToString(fi->uri);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Search found URI `%s'\n",
- tmp);
- FREE(tmp);
- GE_ASSERT(ectx, NULL == *my);
- *my = ECRS_dupUri(fi->uri);
- return SYSERR; /* abort search */
+ tmp = ECRS_uriToString (fi->uri);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "Search found URI `%s'\n", tmp);
+ FREE (tmp);
+ GE_ASSERT (ectx, NULL == *my);
+ *my = ECRS_dupUri (fi->uri);
+ return SYSERR; /* abort search */
}
/**
* @param *uri In: keyword URI, out: file URI
* @return OK on success
*/
-static int searchFile(struct ECRS_URI ** uri) {
+static int
+searchFile (struct ECRS_URI **uri)
+{
int ret;
- struct ECRS_URI * myURI;
+ struct ECRS_URI *myURI;
myURI = NULL;
- ret = ECRS_search(ectx,
- cfg,
- *uri,
- 0,
- 15 * cronSECONDS,
- &searchCB,
- &myURI,
- &testTerminate,
- NULL);
- ECRS_freeUri(*uri);
+ ret = ECRS_search (ectx,
+ cfg,
+ *uri,
+ 0,
+ 15 * cronSECONDS,
+ &searchCB, &myURI, &testTerminate, NULL);
+ ECRS_freeUri (*uri);
*uri = myURI;
- if ( (ret != SYSERR) &&
- (myURI != NULL) )
+ if ((ret != SYSERR) && (myURI != NULL))
return OK;
else
return SYSERR;
}
-static int downloadFile(unsigned int size,
- const struct ECRS_URI * uri) {
+static int
+downloadFile (unsigned int size, const struct ECRS_URI *uri)
+{
int ret;
- char * tmpName;
+ char *tmpName;
int fd;
- char * buf;
- char * in;
+ char *buf;
+ char *in;
int i;
- char * tmp;
+ char *tmp;
- tmp = ECRS_uriToString(uri);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Starting download of `%s'\n",
- tmp);
- FREE(tmp);
- tmpName = makeName(0);
+ tmp = ECRS_uriToString (uri);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Starting download of `%s'\n", tmp);
+ FREE (tmp);
+ tmpName = makeName (0);
ret = SYSERR;
- if (OK == ECRS_downloadFile(ectx,
- cfg,
- uri,
- tmpName,
- 0,
- &dprogress,
- NULL,
- &testTerminate,
- NULL)) {
+ if (OK == ECRS_downloadFile (ectx,
+ cfg,
+ uri,
+ tmpName,
+ 0, &dprogress, NULL, &testTerminate, NULL))
+ {
- fd = disk_file_open(ectx,
- tmpName,
- O_RDONLY);
- buf = MALLOC(size);
- in = MALLOC(size);
- memset(buf, size + size / 253, size);
- for (i=0;i<(int) (size - 42 - sizeof(HashCode512));i+=sizeof(HashCode512))
- hash(&buf[i+sizeof(HashCode512)],
- 42,
- (HashCode512*) &buf[i]);
- if (size != READ(fd, in, size))
- ret = SYSERR;
- else if (0 == memcmp(buf,
- in,
- size))
- ret = OK;
- FREE(buf);
- FREE(in);
- disk_file_close(ectx, tmpName, fd);
- }
- UNLINK(tmpName);
- FREE(tmpName);
+ fd = disk_file_open (ectx, tmpName, O_RDONLY);
+ buf = MALLOC (size);
+ in = MALLOC (size);
+ memset (buf, size + size / 253, size);
+ for (i = 0; i < (int) (size - 42 - sizeof (HashCode512));
+ i += sizeof (HashCode512))
+ hash (&buf[i + sizeof (HashCode512)], 42, (HashCode512 *) & buf[i]);
+ if (size != READ (fd, in, size))
+ ret = SYSERR;
+ else if (0 == memcmp (buf, in, size))
+ ret = OK;
+ FREE (buf);
+ FREE (in);
+ disk_file_close (ectx, tmpName, fd);
+ }
+ UNLINK (tmpName);
+ FREE (tmpName);
return ret;
}
-static int unindexFile(unsigned int size) {
+static int
+unindexFile (unsigned int size)
+{
int ret;
- char * name;
+ char *name;
- name = makeName(size);
- ret = ECRS_unindexFile(ectx,
- cfg,
- name,
- NULL,
- NULL,
- &testTerminate,
- NULL);
- if (0 != UNLINK(name))
+ name = makeName (size);
+ ret = ECRS_unindexFile (ectx, cfg, name, NULL, NULL, &testTerminate, NULL);
+ if (0 != UNLINK (name))
ret = SYSERR;
- FREE(name);
+ FREE (name);
return ret;
}
@@ -265,64 +242,59 @@
* Testcase to test gap routing (2 peers only).
* @return 0: ok, -1: error
*/
-int main(int argc, char ** argv) {
- struct DaemonContext * peers;
+int
+main (int argc, char **argv)
+{
+ struct DaemonContext *peers;
int ret;
- struct ECRS_URI * uri;
+ struct ECRS_URI *uri;
ret = 0;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_PEERS
- peers = gnunet_testing_start_daemons("tcp",
- "advertising topology fs stats",
- "/tmp/gnunet-gap-test",
- 2087,
- 10000,
- 2);
- if (peers == NULL) {
- fprintf(stderr,
- "Failed to start the gnunetd daemons!\n");
- GC_free(cfg);
- return -1;
- }
+ peers = gnunet_testing_start_daemons ("tcp",
+ "advertising topology fs stats",
+ "/tmp/gnunet-gap-test",
+ 2087, 10000, 2);
+ if (peers == NULL)
+ {
+ fprintf (stderr, "Failed to start the gnunetd daemons!\n");
+ GC_free (cfg);
+ return -1;
+ }
#endif
- if (OK != gnunet_testing_connect_daemons(2087,
- 12087)) {
- gnunet_testing_stop_daemons(peers);
- fprintf(stderr,
- "Failed to connect the peers!\n");
- GC_free(cfg);
- return -1;
- }
+ if (OK != gnunet_testing_connect_daemons (2087, 12087))
+ {
+ gnunet_testing_stop_daemons (peers);
+ fprintf (stderr, "Failed to connect the peers!\n");
+ GC_free (cfg);
+ return -1;
+ }
- uri = uploadFile(12345);
- CHECK(NULL != uri);
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- "localhost:12087");
- CHECK(OK == searchFile(&uri));
- CHECK(OK == downloadFile(12345, uri));
- ECRS_freeUri(uri);
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- "localhost:2087");
- CHECK(OK == unindexFile(12345));
+ uri = uploadFile (12345);
+ CHECK (NULL != uri);
+ GC_set_configuration_value_string (cfg,
+ ectx,
+ "NETWORK", "HOST", "localhost:12087");
+ CHECK (OK == searchFile (&uri));
+ CHECK (OK == downloadFile (12345, uri));
+ ECRS_freeUri (uri);
+ GC_set_configuration_value_string (cfg,
+ ectx,
+ "NETWORK", "HOST", "localhost:2087");
+ CHECK (OK == unindexFile (12345));
- FAILURE:
+FAILURE:
#if START_PEERS
- gnunet_testing_stop_daemons(peers);
+ gnunet_testing_stop_daemons (peers);
#endif
- GC_free(cfg);
+ GC_free (cfg);
return ret;
}
Modified: GNUnet/src/applications/gap/gaptest2.c
===================================================================
--- GNUnet/src/applications/gap/gaptest2.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/gap/gaptest2.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -41,223 +41,204 @@
#define SIZE 1024 * 1024 * 2
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static int testTerminate(void * unused) {
+static int
+testTerminate (void *unused)
+{
return OK;
}
-static void uprogress(unsigned long long totalBytes,
- unsigned long long completedBytes,
- cron_t eta,
- void * closure) {
- fprintf(stderr,
- totalBytes == completedBytes ? "\n" : ".");
+static void
+uprogress (unsigned long long totalBytes,
+ unsigned long long completedBytes, cron_t eta, void *closure)
+{
+ fprintf (stderr, totalBytes == completedBytes ? "\n" : ".");
}
-static void dprogress(unsigned long long totalBytes,
- unsigned long long completedBytes,
- cron_t eta,
- unsigned long long lastBlockOffset,
- const char * lastBlock,
- unsigned int lastBlockSize,
- void * closure) {
- fprintf(stderr,
- totalBytes == completedBytes ? "\n" : ".");
+static void
+dprogress (unsigned long long totalBytes,
+ unsigned long long completedBytes,
+ cron_t eta,
+ unsigned long long lastBlockOffset,
+ const char *lastBlock, unsigned int lastBlockSize, void *closure)
+{
+ fprintf (stderr, totalBytes == completedBytes ? "\n" : ".");
}
-static char * makeName(unsigned int i) {
- char * fn;
+static char *
+makeName (unsigned int i)
+{
+ char *fn;
- fn = MALLOC(strlen("/tmp/gnunet-gaptest/GAPTEST") + 14);
- SNPRINTF(fn,
- strlen("/tmp/gnunet-gaptest/GAPTEST") + 14,
- "/tmp/gnunet-gaptest/GAPTEST%u",
- i);
- disk_directory_create_for_file(NULL, fn);
+ fn = MALLOC (strlen ("/tmp/gnunet-gaptest/GAPTEST") + 14);
+ SNPRINTF (fn,
+ strlen ("/tmp/gnunet-gaptest/GAPTEST") + 14,
+ "/tmp/gnunet-gaptest/GAPTEST%u", i);
+ disk_directory_create_for_file (NULL, fn);
return fn;
}
-static struct ECRS_URI * uploadFile(unsigned int size) {
+static struct ECRS_URI *
+uploadFile (unsigned int size)
+{
int ret;
- char * name;
+ char *name;
int fd;
- char * buf;
- struct ECRS_URI * uri;
+ char *buf;
+ struct ECRS_URI *uri;
int i;
- name = makeName(size);
- fd = disk_file_open(ectx,
- name,
- O_WRONLY|O_CREAT, S_IWUSR|S_IRUSR);
- buf = MALLOC(size);
- memset(buf, size / 253, sizeof(HashCode512));
- for (i=0;i<size - sizeof(HashCode512);i+=sizeof(HashCode512))
- hash(&buf[i],
- sizeof(HashCode512),
- (HashCode512*) &buf[i+sizeof(HashCode512)]);
- WRITE(fd, buf, size);
- FREE(buf);
- disk_file_close(ectx, name, fd);
- ret = ECRS_uploadFile(ectx,
- cfg,
- name,
- YES, /* index */
- 1, /* anon */
- 0, /* prio */
- get_time() + 100 * cronMINUTES, /* expire */
- &uprogress, /* progress */
- NULL,
- &testTerminate,
- NULL,
- &uri);
- if (ret != SYSERR) {
- struct ECRS_MetaData * meta;
- struct ECRS_URI * key;
- const char * keywords[2];
+ name = makeName (size);
+ fd = disk_file_open (ectx, name, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR);
+ buf = MALLOC (size);
+ memset (buf, size / 253, sizeof (HashCode512));
+ for (i = 0; i < size - sizeof (HashCode512); i += sizeof (HashCode512))
+ hash (&buf[i],
+ sizeof (HashCode512),
+ (HashCode512 *) & buf[i + sizeof (HashCode512)]);
+ WRITE (fd, buf, size);
+ FREE (buf);
+ disk_file_close (ectx, name, fd);
+ ret = ECRS_uploadFile (ectx, cfg, name, YES, /* index */
+ 1, /* anon */
+ 0, /* prio */
+ get_time () + 100 * cronMINUTES, /* expire */
+ &uprogress, /* progress */
+ NULL, &testTerminate, NULL, &uri);
+ if (ret != SYSERR)
+ {
+ struct ECRS_MetaData *meta;
+ struct ECRS_URI *key;
+ const char *keywords[2];
- keywords[0] = name;
- keywords[1] = NULL;
+ keywords[0] = name;
+ keywords[1] = NULL;
- meta = ECRS_createMetaData();
- key = ECRS_keywordsToUri(keywords);
- ret = ECRS_addToKeyspace(ectx,
- cfg,
- key,
- 0,
- 0,
- get_time() + 100 * cronMINUTES, /* expire */
- uri,
- meta);
- ECRS_freeMetaData(meta);
- ECRS_freeUri(uri);
- FREE(name);
- if (ret == OK) {
- return key;
- } else {
- ECRS_freeUri(key);
+ meta = ECRS_createMetaData ();
+ key = ECRS_keywordsToUri (keywords);
+ ret = ECRS_addToKeyspace (ectx, cfg, key, 0, 0, get_time () + 100 *
cronMINUTES, /* expire */
+ uri, meta);
+ ECRS_freeMetaData (meta);
+ ECRS_freeUri (uri);
+ FREE (name);
+ if (ret == OK)
+ {
+ return key;
+ }
+ else
+ {
+ ECRS_freeUri (key);
+ return NULL;
+ }
+ }
+ else
+ {
+ FREE (name);
return NULL;
}
- } else {
- FREE(name);
- return NULL;
- }
}
-static int searchCB(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * closure) {
- struct ECRS_URI ** my = closure;
- char * tmp;
+static int
+searchCB (const ECRS_FileInfo * fi,
+ const HashCode512 * key, int isRoot, void *closure)
+{
+ struct ECRS_URI **my = closure;
+ char *tmp;
- tmp = ECRS_uriToString(fi->uri);
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Search found URI `%s'\n",
- tmp);
- FREE(tmp);
- GE_ASSERT(ectx, NULL == *my);
- *my = ECRS_dupUri(fi->uri);
- return SYSERR; /* abort search */
+ tmp = ECRS_uriToString (fi->uri);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Search found URI `%s'\n", tmp);
+ FREE (tmp);
+ GE_ASSERT (ectx, NULL == *my);
+ *my = ECRS_dupUri (fi->uri);
+ return SYSERR; /* abort search */
}
/**
* @param *uri In: keyword URI, out: file URI
* @return OK on success
*/
-static int searchFile(struct ECRS_URI ** uri) {
+static int
+searchFile (struct ECRS_URI **uri)
+{
int ret;
- struct ECRS_URI * myURI;
+ struct ECRS_URI *myURI;
myURI = NULL;
- ret = ECRS_search(ectx,
- cfg,
- *uri,
- 1,
- 1450 * cronSECONDS,
- &searchCB,
- &myURI,
- &testTerminate,
- NULL);
- ECRS_freeUri(*uri);
+ ret = ECRS_search (ectx,
+ cfg,
+ *uri,
+ 1,
+ 1450 * cronSECONDS,
+ &searchCB, &myURI, &testTerminate, NULL);
+ ECRS_freeUri (*uri);
*uri = myURI;
- if ( (ret != SYSERR) &&
- (myURI != NULL) )
+ if ((ret != SYSERR) && (myURI != NULL))
return OK;
else
return SYSERR;
}
-static int downloadFile(unsigned int size,
- const struct ECRS_URI * uri) {
+static int
+downloadFile (unsigned int size, const struct ECRS_URI *uri)
+{
int ret;
- char * tmpName;
+ char *tmpName;
int fd;
- char * buf;
- char * in;
+ char *buf;
+ char *in;
int i;
- char * tmp;
+ char *tmp;
- tmp = ECRS_uriToString(uri);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Starting download of `%s'\n",
- tmp);
- FREE(tmp);
- tmpName = makeName(0);
+ tmp = ECRS_uriToString (uri);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Starting download of `%s'\n", tmp);
+ FREE (tmp);
+ tmpName = makeName (0);
ret = SYSERR;
- if (OK == ECRS_downloadFile(ectx,
- cfg,
- uri,
- tmpName,
- 1,
- &dprogress,
- NULL,
- &testTerminate,
- NULL)) {
+ if (OK == ECRS_downloadFile (ectx,
+ cfg,
+ uri,
+ tmpName,
+ 1, &dprogress, NULL, &testTerminate, NULL))
+ {
- fd = disk_file_open(ectx,
- tmpName,
- O_RDONLY);
- buf = MALLOC(size);
- in = MALLOC(size);
- memset(buf, size / 253, sizeof(HashCode512));
- for (i=0;i<size - sizeof(HashCode512);i+=sizeof(HashCode512))
- hash(&buf[i],
- sizeof(HashCode512),
- (HashCode512*) &buf[i+sizeof(HashCode512)]);
- if (size != READ(fd, in, size))
- ret = SYSERR;
- else if (0 == memcmp(buf,
- in,
- size))
- ret = OK;
- FREE(buf);
- FREE(in);
- disk_file_close(ectx, tmpName, fd);
- }
- UNLINK(tmpName);
- FREE(tmpName);
+ fd = disk_file_open (ectx, tmpName, O_RDONLY);
+ buf = MALLOC (size);
+ in = MALLOC (size);
+ memset (buf, size / 253, sizeof (HashCode512));
+ for (i = 0; i < size - sizeof (HashCode512); i += sizeof (HashCode512))
+ hash (&buf[i],
+ sizeof (HashCode512),
+ (HashCode512 *) & buf[i + sizeof (HashCode512)]);
+ if (size != READ (fd, in, size))
+ ret = SYSERR;
+ else if (0 == memcmp (buf, in, size))
+ ret = OK;
+ FREE (buf);
+ FREE (in);
+ disk_file_close (ectx, tmpName, fd);
+ }
+ UNLINK (tmpName);
+ FREE (tmpName);
return ret;
}
-static int unindexFile(unsigned int size) {
+static int
+unindexFile (unsigned int size)
+{
int ret;
- char * name;
+ char *name;
- name = makeName(size);
- ret = ECRS_unindexFile(ectx,
- cfg,
- name,
- NULL,
- NULL,
- &testTerminate,
- NULL);
- if (0 != UNLINK(name))
+ name = makeName (size);
+ ret = ECRS_unindexFile (ectx, cfg, name, NULL, NULL, &testTerminate, NULL);
+ if (0 != UNLINK (name))
ret = SYSERR;
- FREE(name);
+ FREE (name);
return ret;
}
@@ -267,79 +248,71 @@
* Testcase to test gap routing (2 peers only).
* @return 0: ok, -1: error
*/
-int main(int argc, char ** argv) {
- struct DaemonContext * peers;
+int
+main (int argc, char **argv)
+{
+ struct DaemonContext *peers;
int ret;
- struct ECRS_URI * uri;
+ struct ECRS_URI *uri;
int i;
char buf[128];
cron_t start;
ret = 0;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_PEERS
- peers = gnunet_testing_start_daemons("tcp",
- "advertising topology fs stats",
- "/tmp/gnunet-gap-test2",
- 2087,
- 10,
- PEER_COUNT);
- if (peers == NULL) {
- fprintf(stderr,
- "Failed to start the gnunetd daemons!\n");
- GC_free(cfg);
- return -1;
- }
-#endif
- for (i=1;i<PEER_COUNT;i++) {
- if (OK != gnunet_testing_connect_daemons(2077 + (10*i),
- 2087 + (10*i))) {
- gnunet_testing_stop_daemons(peers);
- fprintf(stderr,
- "Failed to connect the peers!\n");
- GC_free(cfg);
+ peers = gnunet_testing_start_daemons ("tcp",
+ "advertising topology fs stats",
+ "/tmp/gnunet-gap-test2",
+ 2087, 10, PEER_COUNT);
+ if (peers == NULL)
+ {
+ fprintf (stderr, "Failed to start the gnunetd daemons!\n");
+ GC_free (cfg);
return -1;
}
- }
+#endif
+ for (i = 1; i < PEER_COUNT; i++)
+ {
+ if (OK != gnunet_testing_connect_daemons (2077 + (10 * i),
+ 2087 + (10 * i)))
+ {
+ gnunet_testing_stop_daemons (peers);
+ fprintf (stderr, "Failed to connect the peers!\n");
+ GC_free (cfg);
+ return -1;
+ }
+ }
- printf("Uploading...\n");
- uri = uploadFile(SIZE);
- CHECK(NULL != uri);
- SNPRINTF(buf,
- 128,
- "localhost:%u",
- 2077 + PEER_COUNT * 10);
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- buf);
- CHECK(OK == searchFile(&uri));
- printf("Search successful!\n");
- start = get_time();
- printf("Downloading...\n");
- CHECK(OK == downloadFile(SIZE, uri));
- printf("Download successful at %llu kbps!\n",
- (SIZE / 1024) / ((get_time() - start) / cronSECONDS));
- ECRS_freeUri(uri);
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- "localhost:2087");
- CHECK(OK == unindexFile(SIZE));
+ printf ("Uploading...\n");
+ uri = uploadFile (SIZE);
+ CHECK (NULL != uri);
+ SNPRINTF (buf, 128, "localhost:%u", 2077 + PEER_COUNT * 10);
+ GC_set_configuration_value_string (cfg, ectx, "NETWORK", "HOST", buf);
+ CHECK (OK == searchFile (&uri));
+ printf ("Search successful!\n");
+ start = get_time ();
+ printf ("Downloading...\n");
+ CHECK (OK == downloadFile (SIZE, uri));
+ printf ("Download successful at %llu kbps!\n",
+ (SIZE / 1024) / ((get_time () - start) / cronSECONDS));
+ ECRS_freeUri (uri);
+ GC_set_configuration_value_string (cfg,
+ ectx,
+ "NETWORK", "HOST", "localhost:2087");
+ CHECK (OK == unindexFile (SIZE));
- FAILURE:
+FAILURE:
#if START_PEERS
- gnunet_testing_stop_daemons(peers);
+ gnunet_testing_stop_daemons (peers);
#endif
- GC_free(cfg);
+ GC_free (cfg);
return ret;
}
Modified: GNUnet/src/applications/gap/gaptest3.c
===================================================================
--- GNUnet/src/applications/gap/gaptest3.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/gap/gaptest3.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -41,134 +41,119 @@
#define SIZE 1024*1024*2
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static int testTerminate(void * unused) {
+static int
+testTerminate (void *unused)
+{
return OK;
}
-static void uprogress(unsigned long long totalBytes,
- unsigned long long completedBytes,
- cron_t eta,
- void * closure) {
- fprintf(stderr,
- totalBytes == completedBytes ? "\n" : ".");
+static void
+uprogress (unsigned long long totalBytes,
+ unsigned long long completedBytes, cron_t eta, void *closure)
+{
+ fprintf (stderr, totalBytes == completedBytes ? "\n" : ".");
}
-static void dprogress(unsigned long long totalBytes,
- unsigned long long completedBytes,
- cron_t eta,
- unsigned long long lastBlockOffset,
- const char * lastBlock,
- unsigned int lastBlockSize,
- void * closure) {
- fprintf(stderr,
- totalBytes == completedBytes ? "\n" : ".");
+static void
+dprogress (unsigned long long totalBytes,
+ unsigned long long completedBytes,
+ cron_t eta,
+ unsigned long long lastBlockOffset,
+ const char *lastBlock, unsigned int lastBlockSize, void *closure)
+{
+ fprintf (stderr, totalBytes == completedBytes ? "\n" : ".");
}
-static char * makeName(unsigned int i) {
- char * fn;
+static char *
+makeName (unsigned int i)
+{
+ char *fn;
- fn = MALLOC(strlen("/tmp/gnunet-gaptest/GAPTEST") + 14);
- SNPRINTF(fn,
- strlen("/tmp/gnunet-gaptest/GAPTEST") + 14,
- "/tmp/gnunet-gaptest/GAPTEST%u",
- i);
- disk_directory_create_for_file(NULL, fn);
+ fn = MALLOC (strlen ("/tmp/gnunet-gaptest/GAPTEST") + 14);
+ SNPRINTF (fn,
+ strlen ("/tmp/gnunet-gaptest/GAPTEST") + 14,
+ "/tmp/gnunet-gaptest/GAPTEST%u", i);
+ disk_directory_create_for_file (NULL, fn);
return fn;
}
-static struct ECRS_URI * uploadFile(unsigned int size) {
+static struct ECRS_URI *
+uploadFile (unsigned int size)
+{
int ret;
- char * name;
+ char *name;
int fd;
- char * buf;
- struct ECRS_URI * uri;
+ char *buf;
+ struct ECRS_URI *uri;
int i;
- name = makeName(size);
- fd = disk_file_open(ectx,
- name,
- O_WRONLY|O_CREAT, S_IWUSR|S_IRUSR);
- buf = MALLOC_LARGE(size);
- memset(buf, size + size / 253, size);
- for (i=0;i<(int) (size - 42 - sizeof(HashCode512));i+=sizeof(HashCode512))
- hash(&buf[i+sizeof(HashCode512)],
- 42,
- (HashCode512*) &buf[i]);
- WRITE(fd, buf, size);
- FREE(buf);
- disk_file_close(ectx, name, fd);
- ret = ECRS_uploadFile(ectx,
- cfg,
- name,
- YES, /* index */
- 1, /* anon */
- 0, /* prio */
- get_time() + 100 * cronMINUTES, /* expire */
- &uprogress,
- NULL,
- &testTerminate,
- NULL,
- &uri);
- FREE(name);
+ name = makeName (size);
+ fd = disk_file_open (ectx, name, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR);
+ buf = MALLOC_LARGE (size);
+ memset (buf, size + size / 253, size);
+ for (i = 0; i < (int) (size - 42 - sizeof (HashCode512));
+ i += sizeof (HashCode512))
+ hash (&buf[i + sizeof (HashCode512)], 42, (HashCode512 *) & buf[i]);
+ WRITE (fd, buf, size);
+ FREE (buf);
+ disk_file_close (ectx, name, fd);
+ ret = ECRS_uploadFile (ectx, cfg, name, YES, /* index */
+ 1, /* anon */
+ 0, /* prio */
+ get_time () + 100 * cronMINUTES, /* expire */
+ &uprogress, NULL, &testTerminate, NULL, &uri);
+ FREE (name);
if (ret != SYSERR)
return uri;
return NULL;
}
-static int downloadFile(unsigned int size,
- const struct ECRS_URI * uri) {
+static int
+downloadFile (unsigned int size, const struct ECRS_URI *uri)
+{
int ret;
- char * tmpName;
+ char *tmpName;
int fd;
- char * buf;
- char * in;
+ char *buf;
+ char *in;
int i;
- char * tmp;
+ char *tmp;
- tmp = ECRS_uriToString(uri);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Starting download of `%s'\n",
- tmp);
- FREE(tmp);
- tmpName = makeName(0);
+ tmp = ECRS_uriToString (uri);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Starting download of `%s'\n", tmp);
+ FREE (tmp);
+ tmpName = makeName (0);
ret = SYSERR;
- if (OK == ECRS_downloadFile(ectx,
- cfg,
- uri,
- tmpName,
- 1,
- &dprogress,
- NULL,
- &testTerminate,
- NULL)) {
+ if (OK == ECRS_downloadFile (ectx,
+ cfg,
+ uri,
+ tmpName,
+ 1, &dprogress, NULL, &testTerminate, NULL))
+ {
- fd = disk_file_open(ectx,
- tmpName,
- O_RDONLY);
- buf = MALLOC(size);
- in = MALLOC(size);
- memset(buf, size + size / 253, size);
- for (i=0;i<(int) (size - 42 - sizeof(HashCode512));i+=sizeof(HashCode512))
- hash(&buf[i+sizeof(HashCode512)],
- 42,
- (HashCode512*) &buf[i]);
- if (size != READ(fd, in, size))
- ret = SYSERR;
- else if (0 == memcmp(buf,
- in,
- size))
- ret = OK;
- FREE(buf);
- FREE(in);
- disk_file_close(ectx, tmpName, fd);
- }
- UNLINK(tmpName);
- FREE(tmpName);
+ fd = disk_file_open (ectx, tmpName, O_RDONLY);
+ buf = MALLOC (size);
+ in = MALLOC (size);
+ memset (buf, size + size / 253, size);
+ for (i = 0; i < (int) (size - 42 - sizeof (HashCode512));
+ i += sizeof (HashCode512))
+ hash (&buf[i + sizeof (HashCode512)], 42, (HashCode512 *) & buf[i]);
+ if (size != READ (fd, in, size))
+ ret = SYSERR;
+ else if (0 == memcmp (buf, in, size))
+ ret = OK;
+ FREE (buf);
+ FREE (in);
+ disk_file_close (ectx, tmpName, fd);
+ }
+ UNLINK (tmpName);
+ FREE (tmpName);
return ret;
}
@@ -177,35 +162,28 @@
static PeerIdentity goodPeers[PEER_COUNT];
static unsigned int goodPeerPos;
-static int infoCallback(void * data,
- const PeerIdentity * identity,
- const void * address,
- unsigned int addr_len,
- cron_t last_seen,
- unsigned int trust,
- unsigned int bpmFromPeer) {
+static int
+infoCallback (void *data,
+ const PeerIdentity * identity,
+ const void *address,
+ unsigned int addr_len,
+ cron_t last_seen, unsigned int trust, unsigned int bpmFromPeer)
+{
int i;
int good;
EncName enc;
good = 0;
- for (i=0;i<goodPeerPos;i++)
- if (0 == memcmp(&goodPeers[i],
- identity,
- sizeof(PeerIdentity)))
+ for (i = 0; i < goodPeerPos; i++)
+ if (0 == memcmp (&goodPeers[i], identity, sizeof (PeerIdentity)))
good = 1;
- hash2enc(&identity->hashPubKey,
- &enc);
+ hash2enc (&identity->hashPubKey, &enc);
if (good)
- printf("Good peer `%8s' has trust %u and bandwidth %u\n",
- (const char*) &enc,
- trust,
- bpmFromPeer);
+ printf ("Good peer `%8s' has trust %u and bandwidth %u\n",
+ (const char *) &enc, trust, bpmFromPeer);
else
- printf("Poor peer `%8s' has trust %u and bandwidth %u\n",
- (const char*) &enc,
- trust,
- bpmFromPeer);
+ printf ("Poor peer `%8s' has trust %u and bandwidth %u\n",
+ (const char *) &enc, trust, bpmFromPeer);
return OK;
}
@@ -213,108 +191,94 @@
* Testcase to test gap routing (2 peers only).
* @return 0: ok, -1: error
*/
-int main(int argc, char ** argv) {
- struct DaemonContext * peers;
+int
+main (int argc, char **argv)
+{
+ struct DaemonContext *peers;
int ret;
- struct ECRS_URI * uri;
+ struct ECRS_URI *uri;
int i;
char buf[128];
- P2P_hello_MESSAGE * hello;
- struct ClientServerConnection * sock;
+ P2P_hello_MESSAGE *hello;
+ struct ClientServerConnection *sock;
cron_t start;
EncName enc;
ret = 0;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_PEERS
- peers = gnunet_testing_start_daemons("tcp",
- "advertising topology fs stats",
- "/tmp/gnunet-gap-test3",
- 2087,
- 10,
- PEER_COUNT);
- if (peers == NULL) {
- fprintf(stderr,
- "Failed to start the gnunetd daemons!\n");
- GC_free(cfg);
- return -1;
- }
+ peers = gnunet_testing_start_daemons ("tcp",
+ "advertising topology fs stats",
+ "/tmp/gnunet-gap-test3",
+ 2087, 10, PEER_COUNT);
+ if (peers == NULL)
+ {
+ fprintf (stderr, "Failed to start the gnunetd daemons!\n");
+ GC_free (cfg);
+ return -1;
+ }
#endif
/* connect as star-topology */
- for (i=1;i<PEER_COUNT;i++) {
- if (OK != gnunet_testing_connect_daemons(2087,
- 2087 + 10*i)) {
- gnunet_testing_stop_daemons(peers);
- fprintf(stderr,
- "Failed to connect the peers!\n");
- GC_free(cfg);
- return -1;
+ for (i = 1; i < PEER_COUNT; i++)
+ {
+ if (OK != gnunet_testing_connect_daemons (2087, 2087 + 10 * i))
+ {
+ gnunet_testing_stop_daemons (peers);
+ fprintf (stderr, "Failed to connect the peers!\n");
+ GC_free (cfg);
+ return -1;
+ }
}
- }
uri = NULL;
goodPeerPos = 0;
- for (i=1;i<PEER_COUNT;i+=2) {
- SNPRINTF(buf,
- 128,
- "localhost:%u",
- 2087 + i * 10);
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- buf);
- sock = client_connection_create(NULL,
- cfg);
- if (OK != gnunet_identity_get_self(sock,
- &hello)) {
- connection_destroy(sock);
- GE_BREAK(NULL, 0);
- break;
- }
- connection_destroy(sock);
- if (uri != NULL)
- ECRS_freeUri(uri);
- hash2enc(&hello->senderIdentity.hashPubKey,
- &enc);
- printf("Uploading to peer `%8s'\n",
- (const char*)&enc);
- uri = uploadFile(SIZE);
- CHECK(NULL != uri);
+ for (i = 1; i < PEER_COUNT; i += 2)
+ {
+ SNPRINTF (buf, 128, "localhost:%u", 2087 + i * 10);
+ GC_set_configuration_value_string (cfg, ectx, "NETWORK", "HOST", buf);
+ sock = client_connection_create (NULL, cfg);
+ if (OK != gnunet_identity_get_self (sock, &hello))
+ {
+ connection_destroy (sock);
+ GE_BREAK (NULL, 0);
+ break;
+ }
+ connection_destroy (sock);
+ if (uri != NULL)
+ ECRS_freeUri (uri);
+ hash2enc (&hello->senderIdentity.hashPubKey, &enc);
+ printf ("Uploading to peer `%8s'\n", (const char *) &enc);
+ uri = uploadFile (SIZE);
+ CHECK (NULL != uri);
- goodPeers[goodPeerPos++] = hello->senderIdentity;
- FREE(hello);
+ goodPeers[goodPeerPos++] = hello->senderIdentity;
+ FREE (hello);
- }
- GC_set_configuration_value_string(cfg,
- ectx,
- "NETWORK",
- "HOST",
- "localhost:2087");
- printf("Downloading...\n");
- start = get_time();
- CHECK(OK == downloadFile(SIZE, uri));
- printf("Download complete - %f kbps.\n",
- SIZE/1024 * 1.0 * cronSECONDS / (1 + get_time() - start));
+ }
+ GC_set_configuration_value_string (cfg,
+ ectx,
+ "NETWORK", "HOST", "localhost:2087");
+ printf ("Downloading...\n");
+ start = get_time ();
+ CHECK (OK == downloadFile (SIZE, uri));
+ printf ("Download complete - %f kbps.\n",
+ SIZE / 1024 * 1.0 * cronSECONDS / (1 + get_time () - start));
/* verify trust values have developed as expected */
- sock = client_connection_create(NULL,
- cfg);
- gnunet_identity_request_peer_infos(sock,
- &infoCallback,
- NULL);
- connection_destroy(sock);
+ sock = client_connection_create (NULL, cfg);
+ gnunet_identity_request_peer_infos (sock, &infoCallback, NULL);
+ connection_destroy (sock);
- FAILURE:
+FAILURE:
#if START_PEERS
- gnunet_testing_stop_daemons(peers);
+ gnunet_testing_stop_daemons (peers);
#endif
- GC_free(cfg);
+ GC_free (cfg);
return ret;
}
Modified: GNUnet/src/applications/gap/pid_table.c
===================================================================
--- GNUnet/src/applications/gap/pid_table.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/gap/pid_table.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,15 +30,16 @@
/**
* Statistics service.
*/
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static int stat_pid_entries;
static int stat_pid_rc;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-typedef struct {
+typedef struct
+{
/**
* the identifier itself
*/
@@ -52,126 +53,143 @@
static unsigned int size;
-static PID_Entry * table;
+static PID_Entry *table;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-PID_INDEX intern_pid(const PeerIdentity * pid) {
+PID_INDEX
+intern_pid (const PeerIdentity * pid)
+{
PID_INDEX ret;
PID_INDEX zero;
if (pid == NULL)
return 0;
zero = size;
- MUTEX_LOCK(lock);
- for (ret=1;ret<size;ret++) {
- if (0 == memcmp(&pid->hashPubKey,
- &table[ret].id,
- sizeof(HashCode512))) {
- table[ret].rc++;
- if (stats != NULL) {
- stats->change(stat_pid_rc, 1);
- if (table[ret].rc == 1)
- stats->change(stat_pid_entries, 1);
- }
- MUTEX_UNLOCK(lock);
- return ret;
- } else if ( (zero == size) &&
- (table[ret].rc == 0) ) {
- zero = ret;
+ MUTEX_LOCK (lock);
+ for (ret = 1; ret < size; ret++)
+ {
+ if (0 == memcmp (&pid->hashPubKey,
+ &table[ret].id, sizeof (HashCode512)))
+ {
+ table[ret].rc++;
+ if (stats != NULL)
+ {
+ stats->change (stat_pid_rc, 1);
+ if (table[ret].rc == 1)
+ stats->change (stat_pid_entries, 1);
+ }
+ MUTEX_UNLOCK (lock);
+ return ret;
+ }
+ else if ((zero == size) && (table[ret].rc == 0))
+ {
+ zero = ret;
+ }
}
- }
ret = zero;
- if (ret == size) {
- GROW(table,
- size,
- size + 16);
- }
+ if (ret == size)
+ {
+ GROW (table, size, size + 16);
+ }
if (ret == 0)
ret = 1;
- GE_ASSERT(ectx, ret < size);
+ GE_ASSERT (ectx, ret < size);
table[ret].id = pid->hashPubKey;
table[ret].rc = 1;
- MUTEX_UNLOCK(lock);
- if (stats != NULL) {
- stats->change(stat_pid_rc, 1);
- stats->change(stat_pid_entries, 1);
- }
+ MUTEX_UNLOCK (lock);
+ if (stats != NULL)
+ {
+ stats->change (stat_pid_rc, 1);
+ stats->change (stat_pid_entries, 1);
+ }
return ret;
}
-void decrement_pid_rcs(const PID_INDEX * ids,
- unsigned int count) {
+void
+decrement_pid_rcs (const PID_INDEX * ids, unsigned int count)
+{
int i;
PID_INDEX id;
if (count == 0)
return;
- MUTEX_LOCK(lock);
- for (i=count-1;i>=0;i--) {
- id = ids[i];
- GE_ASSERT(ectx, id < size);
- GE_ASSERT(ectx, table[id].rc > 0);
- table[id].rc--;
- if ( (table[id].rc == 0) &&
- (stats != NULL) )
- stats->change(stat_pid_entries, -1);
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_LOCK (lock);
+ for (i = count - 1; i >= 0; i--)
+ {
+ id = ids[i];
+ GE_ASSERT (ectx, id < size);
+ GE_ASSERT (ectx, table[id].rc > 0);
+ table[id].rc--;
+ if ((table[id].rc == 0) && (stats != NULL))
+ stats->change (stat_pid_entries, -1);
+ }
+ MUTEX_UNLOCK (lock);
if (stats != NULL)
- stats->change(stat_pid_rc, - count);
+ stats->change (stat_pid_rc, -count);
}
-void change_pid_rc(PID_INDEX id, int delta) {
+void
+change_pid_rc (PID_INDEX id, int delta)
+{
if (id == 0)
return;
- MUTEX_LOCK(lock);
- GE_ASSERT(ectx, id < size);
- GE_ASSERT(ectx, table[id].rc > 0);
+ MUTEX_LOCK (lock);
+ GE_ASSERT (ectx, id < size);
+ GE_ASSERT (ectx, table[id].rc > 0);
table[id].rc += delta;
- if (stats != NULL) {
- stats->change(stat_pid_rc, delta);
- if (table[id].rc == 0)
- stats->change(stat_pid_entries, -1);
- }
- MUTEX_UNLOCK(lock);
+ if (stats != NULL)
+ {
+ stats->change (stat_pid_rc, delta);
+ if (table[id].rc == 0)
+ stats->change (stat_pid_entries, -1);
+ }
+ MUTEX_UNLOCK (lock);
}
-void resolve_pid(PID_INDEX id,
- PeerIdentity * pid) {
- if (id == 0) {
- memset(pid, 0, sizeof(PeerIdentity));
- GE_BREAK(ectx, 0);
- return;
- }
- MUTEX_LOCK(lock);
- GE_ASSERT(ectx, id < size);
- GE_ASSERT(ectx, table[id].rc > 0);
+void
+resolve_pid (PID_INDEX id, PeerIdentity * pid)
+{
+ if (id == 0)
+ {
+ memset (pid, 0, sizeof (PeerIdentity));
+ GE_BREAK (ectx, 0);
+ return;
+ }
+ MUTEX_LOCK (lock);
+ GE_ASSERT (ectx, id < size);
+ GE_ASSERT (ectx, table[id].rc > 0);
pid->hashPubKey = table[id].id;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
-void init_pid_table(struct GE_Context * e,
- Stats_ServiceAPI * s) {
+void
+init_pid_table (struct GE_Context *e, Stats_ServiceAPI * s)
+{
ectx = e;
stats = s;
- if (stats != NULL) {
- stat_pid_entries
- = stats->create(gettext_noop("# distinct interned peer IDs in pid
table"));
- stat_pid_rc
- = stats->create(gettext_noop("# total RC of interned peer IDs in pid
table"));
- }
- lock = MUTEX_CREATE(NO);
+ if (stats != NULL)
+ {
+ stat_pid_entries
+ =
+ stats->
+ create (gettext_noop ("# distinct interned peer IDs in pid table"));
+ stat_pid_rc =
+ stats->
+ create (gettext_noop
+ ("# total RC of interned peer IDs in pid table"));
+ }
+ lock = MUTEX_CREATE (NO);
}
-void done_pid_table() {
- GROW(table,
- size,
- 0);
+void
+done_pid_table ()
+{
+ GROW (table, size, 0);
stats = NULL;
- MUTEX_DESTROY(lock);
+ MUTEX_DESTROY (lock);
lock = NULL;
ectx = NULL;
}
Modified: GNUnet/src/applications/gap/pid_table.h
===================================================================
--- GNUnet/src/applications/gap/pid_table.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/gap/pid_table.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -27,20 +27,16 @@
#include "gnunet_util.h"
#include "gnunet_stats_service.h"
-void init_pid_table(struct GE_Context * ectx,
- Stats_ServiceAPI * s);
+void init_pid_table (struct GE_Context *ectx, Stats_ServiceAPI * s);
-void done_pid_table(void);
+void done_pid_table (void);
typedef unsigned int PID_INDEX;
-PID_INDEX intern_pid(const PeerIdentity * pid);
+PID_INDEX intern_pid (const PeerIdentity * pid);
-void change_pid_rc(PID_INDEX id, int delta);
+void change_pid_rc (PID_INDEX id, int delta);
-void decrement_pid_rcs(const PID_INDEX * ids,
- unsigned int count);
+void decrement_pid_rcs (const PID_INDEX * ids, unsigned int count);
-void resolve_pid(PID_INDEX id,
- PeerIdentity * pid);
-
+void resolve_pid (PID_INDEX id, PeerIdentity * pid);
Modified: GNUnet/src/applications/getoption/clientapi.c
===================================================================
--- GNUnet/src/applications/getoption/clientapi.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/getoption/clientapi.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -37,40 +37,35 @@
*
* @return NULL on error (for both option not set and internal errors)
*/
-char * getConfigurationOptionValue(struct ClientServerConnection * sock,
- const char * section,
- const char * option) {
+char *
+getConfigurationOptionValue (struct ClientServerConnection *sock,
+ const char *section, const char *option)
+{
CS_getoption_request_MESSAGE req;
- CS_getoption_reply_MESSAGE * reply;
+ CS_getoption_reply_MESSAGE *reply;
int res;
- char * ret;
+ char *ret;
- memset(&req,
- 0,
- sizeof(CS_getoption_request_MESSAGE));
- req.header.type = htons(CS_PROTO_GET_OPTION_REQUEST);
- req.header.size = htons(sizeof(CS_getoption_request_MESSAGE));
- if ( (strlen(section) >= CS_getoption_request_MESSAGE_OPT_LEN) ||
- (strlen(option) >= CS_getoption_request_MESSAGE_OPT_LEN) )
+ memset (&req, 0, sizeof (CS_getoption_request_MESSAGE));
+ req.header.type = htons (CS_PROTO_GET_OPTION_REQUEST);
+ req.header.size = htons (sizeof (CS_getoption_request_MESSAGE));
+ if ((strlen (section) >= CS_getoption_request_MESSAGE_OPT_LEN) ||
+ (strlen (option) >= CS_getoption_request_MESSAGE_OPT_LEN))
return NULL;
- strcpy(&req.section[0],
- section);
- strcpy(&req.option[0],
- option);
- res = connection_write(sock,
- &req.header);
+ strcpy (&req.section[0], section);
+ strcpy (&req.option[0], option);
+ res = connection_write (sock, &req.header);
if (res != OK)
return NULL;
reply = NULL;
- res = connection_read(sock,
- (MESSAGE_HEADER**)&reply);
+ res = connection_read (sock, (MESSAGE_HEADER **) & reply);
if (res != OK)
return NULL;
- ret = MALLOC(ntohs(reply->header.size) - sizeof(MESSAGE_HEADER) + 1);
- memcpy(ret,
- &reply->value[0],
- ntohs(reply->header.size) - sizeof(MESSAGE_HEADER));
- ret[ntohs(reply->header.size) - sizeof(MESSAGE_HEADER)] = '\0';
- FREE(reply);
+ ret = MALLOC (ntohs (reply->header.size) - sizeof (MESSAGE_HEADER) + 1);
+ memcpy (ret,
+ &reply->value[0],
+ ntohs (reply->header.size) - sizeof (MESSAGE_HEADER));
+ ret[ntohs (reply->header.size) - sizeof (MESSAGE_HEADER)] = '\0';
+ FREE (reply);
return ret;
}
Modified: GNUnet/src/applications/getoption/getoption.c
===================================================================
--- GNUnet/src/applications/getoption/getoption.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/getoption/getoption.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -1,22 +1,22 @@
/*
- This file is part of GNUnet
- (C) 2005, 2006 Christian Grothoff (and other contributing authors)
+ This file is part of GNUnet
+ (C) 2005, 2006 Christian Grothoff (and other contributing authors)
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 2, or (at your
- option) any later version.
+ GNUnet is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published
+ by the Free Software Foundation; either version 2, or (at your
+ option) any later version.
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
+ GNUnet is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA.
- */
+ You should have received a copy of the GNU General Public License
+ along with GNUnet; see the file COPYING. If not, write to the
+ Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ Boston, MA 02111-1307, USA.
+ */
#include "platform.h"
#include "gnunet_util.h"
@@ -31,67 +31,65 @@
* @author Christian Grothoff
*/
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static int handleGetOption(struct ClientHandle * sock,
- const MESSAGE_HEADER * message) {
- CS_getoption_request_MESSAGE * req;
- CS_getoption_reply_MESSAGE * rep;
- char * val;
+static int
+handleGetOption (struct ClientHandle *sock, const MESSAGE_HEADER * message)
+{
+ CS_getoption_request_MESSAGE *req;
+ CS_getoption_reply_MESSAGE *rep;
+ char *val;
int ret;
- if (ntohs(message->size) != sizeof(CS_getoption_request_MESSAGE))
+ if (ntohs (message->size) != sizeof (CS_getoption_request_MESSAGE))
return SYSERR;
- req = (CS_getoption_request_MESSAGE*)message;
- req->section[CS_getoption_request_MESSAGE_OPT_LEN-1] = '\0';
- req->option[CS_getoption_request_MESSAGE_OPT_LEN-1] = '\0';
+ req = (CS_getoption_request_MESSAGE *) message;
+ req->section[CS_getoption_request_MESSAGE_OPT_LEN - 1] = '\0';
+ req->option[CS_getoption_request_MESSAGE_OPT_LEN - 1] = '\0';
val = NULL;
- if (NO == GC_have_configuration_value(coreAPI->cfg,
- req->section,
- req->option))
- return SYSERR; /* signal error: option not set */
- if ( (0 != GC_get_configuration_value_string(coreAPI->cfg,
- req->section,
- req->option,
- NULL,
- &val)) ||
- (val == NULL) )
- return SYSERR; /* signal error: option not set */
+ if (NO == GC_have_configuration_value (coreAPI->cfg,
+ req->section, req->option))
+ return SYSERR; /* signal error: option not set */
+ if ((0 != GC_get_configuration_value_string (coreAPI->cfg,
+ req->section,
+ req->option,
+ NULL, &val)) || (val == NULL))
+ return SYSERR; /* signal error: option not set */
- rep = MALLOC(sizeof(MESSAGE_HEADER) + strlen(val) + 1);
- rep->header.size = htons(sizeof(MESSAGE_HEADER) + strlen(val) + 1);
- memcpy(rep->value,
- val,
- strlen(val)+1);
- rep->header.type = htons(CS_PROTO_GET_OPTION_REPLY);
- ret = coreAPI->sendToClient(sock,
- &rep->header);
- FREE(rep);
- FREE(val);
+ rep = MALLOC (sizeof (MESSAGE_HEADER) + strlen (val) + 1);
+ rep->header.size = htons (sizeof (MESSAGE_HEADER) + strlen (val) + 1);
+ memcpy (rep->value, val, strlen (val) + 1);
+ rep->header.type = htons (CS_PROTO_GET_OPTION_REPLY);
+ ret = coreAPI->sendToClient (sock, &rep->header);
+ FREE (rep);
+ FREE (val);
return ret;
}
-int initialize_module_getoption(CoreAPIForApplication * capi) {
+int
+initialize_module_getoption (CoreAPIForApplication * capi)
+{
coreAPI = capi;
- GE_LOG(capi->ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- _("`%s' registering client handler %d\n"),
- "getoption",
- CS_PROTO_GET_OPTION_REQUEST);
- capi->registerClientHandler(CS_PROTO_GET_OPTION_REQUEST,
- &handleGetOption);
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "getoption",
- _("allows clients to determine
gnunetd's"
- " configuration")));
+ GE_LOG (capi->ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ _("`%s' registering client handler %d\n"),
+ "getoption", CS_PROTO_GET_OPTION_REQUEST);
+ capi->registerClientHandler (CS_PROTO_GET_OPTION_REQUEST, &handleGetOption);
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "getoption",
+ _
+ ("allows clients to
determine gnunetd's"
+ " configuration")));
return OK;
}
-void done_module_getoption() {
- coreAPI->unregisterClientHandler(CS_PROTO_GET_OPTION_REQUEST,
- &handleGetOption);
+void
+done_module_getoption ()
+{
+ coreAPI->unregisterClientHandler (CS_PROTO_GET_OPTION_REQUEST,
+ &handleGetOption);
coreAPI = NULL;
}
Modified: GNUnet/src/applications/getoption/getoption.h
===================================================================
--- GNUnet/src/applications/getoption/getoption.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/getoption/getoption.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -1,22 +1,22 @@
/*
- This file is part of GNUnet
- (C) 2005, 2006 Christian Grothoff (and other contributing authors)
+ This file is part of GNUnet
+ (C) 2005, 2006 Christian Grothoff (and other contributing authors)
- GNUnet is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published
- by the Free Software Foundation; either version 2, or (at your
- option) any later version.
+ GNUnet is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published
+ by the Free Software Foundation; either version 2, or (at your
+ option) any later version.
- GNUnet is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
+ GNUnet is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with GNUnet; see the file COPYING. If not, write to the
- Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA.
- */
+ You should have received a copy of the GNU General Public License
+ along with GNUnet; see the file COPYING. If not, write to the
+ Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ Boston, MA 02111-1307, USA.
+ */
#ifndef GETOPTION_H
#define GETOPTION_H
@@ -26,7 +26,8 @@
/**
* Request for option value.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
char section[CS_getoption_request_MESSAGE_OPT_LEN];
char option[CS_getoption_request_MESSAGE_OPT_LEN];
@@ -36,7 +37,8 @@
* Reply with option value (variable size,
* value is 0-terminated).
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
char value[1];
} CS_getoption_reply_MESSAGE;
Modified: GNUnet/src/applications/identity/clientapi.c
===================================================================
--- GNUnet/src/applications/identity/clientapi.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/identity/clientapi.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -35,34 +35,34 @@
* @param sock socket to talk to gnunetd over
* @return OK on success, SYSERR on error
*/
-int gnunet_identity_peer_add(struct ClientServerConnection * sock,
- const P2P_hello_MESSAGE * hello) {
- P2P_hello_MESSAGE * msg;
+int
+gnunet_identity_peer_add (struct ClientServerConnection *sock,
+ const P2P_hello_MESSAGE * hello)
+{
+ P2P_hello_MESSAGE *msg;
- msg = MALLOC(P2P_hello_MESSAGE_size(hello));
- memcpy(msg,
- hello,
- P2P_hello_MESSAGE_size(hello));
- msg->header.type = htons(CS_PROTO_identity_HELLO);
+ msg = MALLOC (P2P_hello_MESSAGE_size (hello));
+ memcpy (msg, hello, P2P_hello_MESSAGE_size (hello));
+ msg->header.type = htons (CS_PROTO_identity_HELLO);
/* check that signature is valid -- internal
sanity check... */
- if (SYSERR == verifySig(&msg->senderIdentity,
- P2P_hello_MESSAGE_size(msg)
- - sizeof(Signature)
- - sizeof(PublicKey)
- - sizeof(MESSAGE_HEADER),
- &msg->signature,
- &msg->publicKey)) {
- GE_BREAK(NULL, 0);
- FREE(msg);
- return SYSERR;
- }
- if (SYSERR == connection_write(sock,
- &msg->header)) {
- FREE(msg);
- return SYSERR;
- }
- FREE(msg);
+ if (SYSERR == verifySig (&msg->senderIdentity,
+ P2P_hello_MESSAGE_size (msg)
+ - sizeof (Signature)
+ - sizeof (PublicKey)
+ - sizeof (MESSAGE_HEADER),
+ &msg->signature, &msg->publicKey))
+ {
+ GE_BREAK (NULL, 0);
+ FREE (msg);
+ return SYSERR;
+ }
+ if (SYSERR == connection_write (sock, &msg->header))
+ {
+ FREE (msg);
+ return SYSERR;
+ }
+ FREE (msg);
return OK;
}
@@ -71,37 +71,37 @@
* Function to request the peer to sign something
* with the private key of the peer.
*/
-int gnunet_identity_sign_function(struct ClientServerConnection * sock,
- unsigned short size,
- const void * data,
- Signature * result) {
- MESSAGE_HEADER * req;
- CS_identity_signature_MESSAGE * reply;
+int
+gnunet_identity_sign_function (struct ClientServerConnection *sock,
+ unsigned short size,
+ const void *data, Signature * result)
+{
+ MESSAGE_HEADER *req;
+ CS_identity_signature_MESSAGE *reply;
- req = MALLOC(sizeof(MESSAGE_HEADER) + size);
- req->size = htons(sizeof(MESSAGE_HEADER) + size);
- req->type = htons(CS_PROTO_identity_request_SIGN);
- memcpy(&req[1],
- data,
- size);
- if (SYSERR == connection_write(sock,
- req)) {
- FREE(req);
- return SYSERR;
- }
- FREE(req);
- if (OK != connection_read(sock,
- (MESSAGE_HEADER**)&reply)) {
- connection_close_temporarily(sock);
- return SYSERR;
- }
- if ( (ntohs(reply->header.size) != sizeof(CS_identity_signature_MESSAGE)) ||
- (ntohs(reply->header.type) != CS_PROTO_identity_SIGNATURE) ) {
- FREE(reply);
- return SYSERR;
- }
+ req = MALLOC (sizeof (MESSAGE_HEADER) + size);
+ req->size = htons (sizeof (MESSAGE_HEADER) + size);
+ req->type = htons (CS_PROTO_identity_request_SIGN);
+ memcpy (&req[1], data, size);
+ if (SYSERR == connection_write (sock, req))
+ {
+ FREE (req);
+ return SYSERR;
+ }
+ FREE (req);
+ if (OK != connection_read (sock, (MESSAGE_HEADER **) & reply))
+ {
+ connection_close_temporarily (sock);
+ return SYSERR;
+ }
+ if ((ntohs (reply->header.size) != sizeof (CS_identity_signature_MESSAGE))
+ || (ntohs (reply->header.type) != CS_PROTO_identity_SIGNATURE))
+ {
+ FREE (reply);
+ return SYSERR;
+ }
*result = reply->sig;
- FREE(reply);
+ FREE (reply);
return OK;
}
@@ -112,28 +112,30 @@
* set by the function.
* @return SYSERR on error, OK on success
*/
-int gnunet_identity_get_self(struct ClientServerConnection * sock,
- P2P_hello_MESSAGE ** msg) {
+int
+gnunet_identity_get_self (struct ClientServerConnection *sock,
+ P2P_hello_MESSAGE ** msg)
+{
MESSAGE_HEADER req;
- P2P_hello_MESSAGE * reply;
+ P2P_hello_MESSAGE *reply;
- req.size = htons(sizeof(MESSAGE_HEADER));
- req.type = htons(CS_PROTO_identity_request_HELLO);
- if (SYSERR == connection_write(sock,
- &req))
+ req.size = htons (sizeof (MESSAGE_HEADER));
+ req.type = htons (CS_PROTO_identity_request_HELLO);
+ if (SYSERR == connection_write (sock, &req))
return SYSERR;
- if (OK != connection_read(sock,
- (MESSAGE_HEADER**)&reply)) {
- connection_close_temporarily(sock);
- return SYSERR;
- }
- if ( (ntohs(reply->header.size) < sizeof(P2P_hello_MESSAGE)) ||
- (ntohs(reply->header.type) != CS_PROTO_identity_HELLO) ||
- (ntohs(reply->header.size) != P2P_hello_MESSAGE_size(reply)) ) {
- FREE(reply);
- return SYSERR;
- }
- reply->header.type = htons(p2p_PROTO_hello);
+ if (OK != connection_read (sock, (MESSAGE_HEADER **) & reply))
+ {
+ connection_close_temporarily (sock);
+ return SYSERR;
+ }
+ if ((ntohs (reply->header.size) < sizeof (P2P_hello_MESSAGE)) ||
+ (ntohs (reply->header.type) != CS_PROTO_identity_HELLO) ||
+ (ntohs (reply->header.size) != P2P_hello_MESSAGE_size (reply)))
+ {
+ FREE (reply);
+ return SYSERR;
+ }
+ reply->header.type = htons (p2p_PROTO_hello);
*msg = reply;
return OK;
}
@@ -144,23 +146,20 @@
* @return SYSERR on error, YES if connection is now there
* NO if connection is not yet present
*/
-int gnunet_identity_request_connect(struct ClientServerConnection * sock,
- const PeerIdentity * peer) {
+int
+gnunet_identity_request_connect (struct ClientServerConnection *sock,
+ const PeerIdentity * peer)
+{
CS_identity_connect_MESSAGE msg;
int result;
- msg.header.type
- = htons(CS_PROTO_identity_CONNECT);
- msg.header.size
- = htons(sizeof(CS_identity_connect_MESSAGE));
- msg.other
- = *peer;
- if (SYSERR == connection_write(sock,
- &msg.header))
+ msg.header.type = htons (CS_PROTO_identity_CONNECT);
+ msg.header.size = htons (sizeof (CS_identity_connect_MESSAGE));
+ msg.other = *peer;
+ if (SYSERR == connection_write (sock, &msg.header))
return SYSERR;
- if (SYSERR == connection_read_result(sock,
- &result))
+ if (SYSERR == connection_read_result (sock, &result))
return SYSERR;
return result;
}
@@ -171,54 +170,60 @@
* @return SYSERR if iteration was aborted,
* otherwise number of peers known
*/
-int gnunet_identity_request_peer_infos(struct ClientServerConnection * sock,
- GNUnetIdentityPeerInfoCallback callback,
- void * cls) {
+int
+gnunet_identity_request_peer_infos (struct ClientServerConnection *sock,
+ GNUnetIdentityPeerInfoCallback callback,
+ void *cls)
+{
MESSAGE_HEADER req;
- MESSAGE_HEADER * reply;
- CS_identity_peer_info_MESSAGE * info;
+ MESSAGE_HEADER *reply;
+ CS_identity_peer_info_MESSAGE *info;
unsigned int count;
- req.size = htons(sizeof(MESSAGE_HEADER));
- req.type = htons(CS_PROTO_identity_request_INFO);
- if (SYSERR == connection_write(sock,
- &req))
+ req.size = htons (sizeof (MESSAGE_HEADER));
+ req.type = htons (CS_PROTO_identity_request_INFO);
+ if (SYSERR == connection_write (sock, &req))
return SYSERR;
count = 0;
- while (OK == connection_read(sock,
- &reply)) {
- if (ntohs(reply->size) < sizeof(MESSAGE_HEADER)) {
- GE_BREAK(NULL, 0);
- FREE(reply);
- return SYSERR;
+ while (OK == connection_read (sock, &reply))
+ {
+ if (ntohs (reply->size) < sizeof (MESSAGE_HEADER))
+ {
+ GE_BREAK (NULL, 0);
+ FREE (reply);
+ return SYSERR;
+ }
+ if (ntohs (reply->type) == CS_PROTO_RETURN_VALUE)
+ {
+ FREE (reply);
+ return count;
+ }
+ count++;
+ if ((ntohs (reply->type) != CS_PROTO_identity_INFO) ||
+ (ntohs (reply->size) < sizeof (CS_identity_peer_info_MESSAGE)))
+ {
+ GE_BREAK (NULL, 0);
+ FREE (reply);
+ return SYSERR;
+ }
+ if (callback != NULL)
+ {
+ info = (CS_identity_peer_info_MESSAGE *) reply;
+ if (OK != callback (cls,
+ &info->peer,
+ &info[1],
+ ntohs (reply->size) -
+ sizeof (CS_identity_peer_info_MESSAGE),
+ ntohll (info->last_message),
+ ntohl (info->trust), ntohl (info->bpm)))
+ {
+ FREE (reply);
+ return SYSERR;
+ }
+ }
+ FREE (reply);
}
- if (ntohs(reply->type) == CS_PROTO_RETURN_VALUE) {
- FREE(reply);
- return count;
- }
- count++;
- if ( (ntohs(reply->type) != CS_PROTO_identity_INFO) ||
- (ntohs(reply->size) < sizeof(CS_identity_peer_info_MESSAGE)) ) {
- GE_BREAK(NULL, 0);
- FREE(reply);
- return SYSERR;
- }
- if (callback != NULL) {
- info = (CS_identity_peer_info_MESSAGE *) reply;
- if (OK != callback(cls,
- &info->peer,
- &info[1],
- ntohs(reply->size) - sizeof(CS_identity_peer_info_MESSAGE),
- ntohll(info->last_message),
- ntohl(info->trust),
- ntohl(info->bpm))) {
- FREE(reply);
return SYSERR;
- }
- }
- FREE(reply);
- }
- return SYSERR;
}
Modified: GNUnet/src/applications/identity/hostkey.c
===================================================================
--- GNUnet/src/applications/identity/hostkey.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/identity/hostkey.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -40,7 +40,7 @@
* The SECRET hostkey. Keep local, never export outside of this
* module!
*/
-static struct PrivateKey * hostkey;
+static struct PrivateKey *hostkey;
/**
* The public hostkey
@@ -52,7 +52,9 @@
*
* @return reference to the public key. Do not free it!
*/
-const PublicKey * getPublicPrivateKey() {
+const PublicKey *
+getPublicPrivateKey ()
+{
return &publicKey;
}
@@ -61,23 +63,17 @@
* entirely!
* @return SYSERR on error, OK on success
*/
-int signData(const void * data,
- unsigned short size,
- Signature * result) {
+int
+signData (const void *data, unsigned short size, Signature * result)
+{
int ret;
- ret = sign(hostkey,
- size,
- data,
- result);
+ ret = sign (hostkey, size, data, result);
#if EXTRA_CHECKS
- if (ret == OK) {
- GE_ASSERT(NULL,
- OK == verifySig(data,
- size,
- result,
- &publicKey));
- }
+ if (ret == OK)
+ {
+ GE_ASSERT (NULL, OK == verifySig (data, size, result, &publicKey));
+ }
#endif
return ret;
}
@@ -91,102 +87,96 @@
* the decrypted block is bigger, an error is returned
* @returns the size of the decrypted block, -1 on error
*/
-int decryptData(const RSAEncryptedData * block,
- void * result,
- unsigned int max) {
- return decryptPrivateKey(hostkey,
- block,
- result,
- max);
+int
+decryptData (const RSAEncryptedData * block, void *result, unsigned int max)
+{
+ return decryptPrivateKey (hostkey, block, result, max);
}
-void initPrivateKey(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- char * gnHome;
- char * hostkeyfile;
- PrivateKeyEncoded * encPrivateKey;
+void
+initPrivateKey (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ char *gnHome;
+ char *hostkeyfile;
+ PrivateKeyEncoded *encPrivateKey;
unsigned short len;
int res;
- GE_ASSERT(ectx,
- -1 != GC_get_configuration_value_filename(cfg,
- "GNUNETD",
- "GNUNETD_HOME",
- VAR_DAEMON_DIRECTORY,
- &gnHome));
- disk_directory_create(ectx,
- gnHome);
- if (YES != disk_directory_test(ectx,
- gnHome)) {
- GE_LOG(ectx,
- GE_FATAL | GE_ADMIN | GE_USER | GE_IMMEDIATE,
- _("Failed to access GNUnet home directory `%s'\n"),
- gnHome);
- abort();
- }
+ GE_ASSERT (ectx,
+ -1 != GC_get_configuration_value_filename (cfg,
+ "GNUNETD",
+ "GNUNETD_HOME",
+ VAR_DAEMON_DIRECTORY,
+ &gnHome));
+ disk_directory_create (ectx, gnHome);
+ if (YES != disk_directory_test (ectx, gnHome))
+ {
+ GE_LOG (ectx,
+ GE_FATAL | GE_ADMIN | GE_USER | GE_IMMEDIATE,
+ _("Failed to access GNUnet home directory `%s'\n"), gnHome);
+ abort ();
+ }
/* read or create public key */
- hostkeyfile = MALLOC(strlen(gnHome) + strlen(HOSTKEYFILE)+2);
- strcpy(hostkeyfile, gnHome);
- FREE(gnHome);
- if (hostkeyfile[strlen(hostkeyfile)-1] != DIR_SEPARATOR)
- strcat(hostkeyfile, DIR_SEPARATOR_STR);
- strcat(hostkeyfile, HOSTKEYFILE);
+ hostkeyfile = MALLOC (strlen (gnHome) + strlen (HOSTKEYFILE) + 2);
+ strcpy (hostkeyfile, gnHome);
+ FREE (gnHome);
+ if (hostkeyfile[strlen (hostkeyfile) - 1] != DIR_SEPARATOR)
+ strcat (hostkeyfile, DIR_SEPARATOR_STR);
+ strcat (hostkeyfile, HOSTKEYFILE);
res = 0;
- if (YES == disk_file_test(ectx,
- hostkeyfile)) {
- res = disk_file_read(ectx,
- hostkeyfile,
- sizeof(unsigned short),
- &len);
- }
+ if (YES == disk_file_test (ectx, hostkeyfile))
+ {
+ res = disk_file_read (ectx, hostkeyfile, sizeof (unsigned short), &len);
+ }
encPrivateKey = NULL;
- if (res == sizeof(unsigned short)) {
- encPrivateKey = (PrivateKeyEncoded*) MALLOC(ntohs(len));
- if (ntohs(len) !=
- disk_file_read(ectx,
- hostkeyfile,
- ntohs(len),
- encPrivateKey)) {
- FREE(encPrivateKey);
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_IMMEDIATE | GE_ADMIN,
- _("Existing hostkey in file `%s' failed format check, creating new
hostkey.\n"),
- hostkeyfile);
- encPrivateKey = NULL;
+ if (res == sizeof (unsigned short))
+ {
+ encPrivateKey = (PrivateKeyEncoded *) MALLOC (ntohs (len));
+ if (ntohs (len) !=
+ disk_file_read (ectx, hostkeyfile, ntohs (len), encPrivateKey))
+ {
+ FREE (encPrivateKey);
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_IMMEDIATE | GE_ADMIN,
+ _
+ ("Existing hostkey in file `%s' failed format check,
creating new hostkey.\n"),
+ hostkeyfile);
+ encPrivateKey = NULL;
+ }
}
- }
- if (encPrivateKey == NULL) { /* make new hostkey */
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- _("Creating new hostkey (this may take a while).\n"));
- hostkey = makePrivateKey();
- GE_ASSERT(ectx, hostkey != NULL);
- encPrivateKey = encodePrivateKey(hostkey);
- GE_ASSERT(ectx, encPrivateKey != NULL);
- disk_file_write(ectx,
- hostkeyfile,
- encPrivateKey,
- ntohs(encPrivateKey->len),
- "600");
- FREE(encPrivateKey);
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- _("Done creating hostkey.\n"));
- } else {
- hostkey = decodePrivateKey(encPrivateKey);
- FREE(encPrivateKey);
- }
- FREE(hostkeyfile);
- GE_ASSERT(ectx, hostkey != NULL);
- getPublicKey(hostkey,
- &publicKey);
+ if (encPrivateKey == NULL)
+ { /* make new hostkey */
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ _("Creating new hostkey (this may take a while).\n"));
+ hostkey = makePrivateKey ();
+ GE_ASSERT (ectx, hostkey != NULL);
+ encPrivateKey = encodePrivateKey (hostkey);
+ GE_ASSERT (ectx, encPrivateKey != NULL);
+ disk_file_write (ectx,
+ hostkeyfile,
+ encPrivateKey, ntohs (encPrivateKey->len), "600");
+ FREE (encPrivateKey);
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK, _("Done creating hostkey.\n"));
+ }
+ else
+ {
+ hostkey = decodePrivateKey (encPrivateKey);
+ FREE (encPrivateKey);
+ }
+ FREE (hostkeyfile);
+ GE_ASSERT (ectx, hostkey != NULL);
+ getPublicKey (hostkey, &publicKey);
}
-void donePrivateKey() {
- GE_ASSERT(NULL, hostkey != NULL);
- freePrivateKey(hostkey);
+void
+donePrivateKey ()
+{
+ GE_ASSERT (NULL, hostkey != NULL);
+ freePrivateKey (hostkey);
hostkey = NULL;
}
Modified: GNUnet/src/applications/identity/hostkey.h
===================================================================
--- GNUnet/src/applications/identity/hostkey.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/identity/hostkey.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,16 +35,14 @@
* Get the public key of the host
* @return reference to the public key. Do not free it!
*/
-const PublicKey * getPublicPrivateKey(void);
+const PublicKey *getPublicPrivateKey (void);
/**
* Sign arbitrary data. ALWAYS use only on data we generated
* entirely!
* @return SYSERR on error, OK on success
*/
-int signData(const void * data,
- unsigned short size,
- Signature * result);
+int signData (const void *data, unsigned short size, Signature * result);
/**
* Decrypt a given block with the hostkey.
@@ -54,16 +52,14 @@
* the decrypted block is bigger, an error is returned
* @returns the size of the decrypted block, -1 on error
*/
-int decryptData(const RSAEncryptedData * block,
- void * result,
- unsigned int max);
+int decryptData (const RSAEncryptedData * block,
+ void *result, unsigned int max);
-void initPrivateKey(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+void initPrivateKey (struct GE_Context *ectx, struct GC_Configuration *cfg);
-void donePrivateKey(void);
+void donePrivateKey (void);
#endif
Modified: GNUnet/src/applications/identity/identity.c
===================================================================
--- GNUnet/src/applications/identity/identity.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/identity/identity.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -65,7 +65,8 @@
#define CRON_DISCARDS_HOSTS_AFTER (3 * cronMONTHS)
-typedef struct {
+typedef struct
+{
PeerIdentity identity;
@@ -82,14 +83,14 @@
/**
* hellos for the peer (maybe NULL)!
*/
- P2P_hello_MESSAGE ** hellos;
+ P2P_hello_MESSAGE **hellos;
unsigned int helloCount;
/**
* for which protocols is this host known?
*/
- unsigned short * protocols;
+ unsigned short *protocols;
unsigned int protocolCount;
@@ -108,7 +109,7 @@
/**
* The list of known hosts.
*/
-static HostEntry ** hosts_ = NULL;
+static HostEntry **hosts_ = NULL;
/**
* The current (allocated) size of knownHosts
@@ -123,17 +124,17 @@
/**
* A lock for accessing knownHosts
*/
-static struct MUTEX * lock_;
+static struct MUTEX *lock_;
/**
* Directory where the hellos are stored in (data/hosts)
*/
-static char * networkIdDirectory;
+static char *networkIdDirectory;
/**
* Where do we store trust information?
*/
-static char * trustDirectory;
+static char *trustDirectory;
/**
* The list of temporarily known hosts
@@ -142,31 +143,26 @@
static PeerIdentity myIdentity;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
/**
* Get the filename under which we would store the P2P_hello_MESSAGE
* for the given host and protocol.
* @return filename of the form DIRECTORY/HOSTID.PROTOCOL
*/
-static char * getHostFileName(const PeerIdentity * id,
- unsigned short protocol) {
+static char *
+getHostFileName (const PeerIdentity * id, unsigned short protocol)
+{
EncName fil;
- char * fn;
+ char *fn;
size_t n;
- hash2enc(&id->hashPubKey,
- &fil);
- n = strlen(networkIdDirectory) + sizeof(EncName) + 1 + 5 + 1;
- fn = MALLOC(n);
- SNPRINTF(fn,
- n,
- "%s%s.%u",
- networkIdDirectory,
- (char*) &fil,
- protocol);
+ hash2enc (&id->hashPubKey, &fil);
+ n = strlen (networkIdDirectory) + sizeof (EncName) + 1 + 5 + 1;
+ fn = MALLOC (n);
+ SNPRINTF (fn, n, "%s%s.%u", networkIdDirectory, (char *) &fil, protocol);
return fn;
}
@@ -175,14 +171,14 @@
* only when synchronized!
* @return NULL if not found
*/
-static HostEntry * findHost(const PeerIdentity * id) {
+static HostEntry *
+findHost (const PeerIdentity * id)
+{
int i;
- GE_ASSERT(ectx, numberOfHosts_ <= sizeOfHosts_);
- for (i=0;i<numberOfHosts_;i++)
- if ( (0 == memcmp(id,
- &hosts_[i]->identity,
- sizeof(PeerIdentity))) )
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
+ for (i = 0; i < numberOfHosts_; i++)
+ if ((0 == memcmp (id, &hosts_[i]->identity, sizeof (PeerIdentity))))
return hosts_[i];
return NULL;
}
@@ -193,64 +189,62 @@
* @param identity the identity of the host
* @param protocol the protocol for the host
*/
-static void addHostToKnown(const PeerIdentity * identity,
- unsigned short protocol) {
- HostEntry * entry;
+static void
+addHostToKnown (const PeerIdentity * identity, unsigned short protocol)
+{
+ HostEntry *entry;
int i;
EncName fil;
- char * fn;
+ char *fn;
unsigned int trust;
- GE_ASSERT(ectx, numberOfHosts_ <= sizeOfHosts_);
- MUTEX_LOCK(lock_);
- entry = findHost(identity);
- if (entry == NULL) {
- entry = MALLOC(sizeof(HostEntry));
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
+ MUTEX_LOCK (lock_);
+ entry = findHost (identity);
+ if (entry == NULL)
+ {
+ entry = MALLOC (sizeof (HostEntry));
- entry->identity = *identity;
- entry->until = 0;
- entry->delta = 30 * cronSECONDS;
- entry->protocols = NULL;
- entry->protocolCount = 0;
- entry->strict = NO;
- entry->hellos = NULL;
- entry->helloCount = 0;
- hash2enc(&identity->hashPubKey,
- &fil);
- fn = MALLOC(strlen(trustDirectory)+sizeof(EncName)+1);
- strcpy(fn, trustDirectory);
- strcat(fn, (char*) &fil);
- if ( (disk_file_test(ectx,
- fn) == YES) &&
- (sizeof(unsigned int) ==
- disk_file_read(ectx,
- fn,
- sizeof(unsigned int),
- &trust)) ) {
- entry->trust = ntohl(trust);
- } else {
- entry->trust = 0;
- }
- FREE(fn);
+ entry->identity = *identity;
+ entry->until = 0;
+ entry->delta = 30 * cronSECONDS;
+ entry->protocols = NULL;
+ entry->protocolCount = 0;
+ entry->strict = NO;
+ entry->hellos = NULL;
+ entry->helloCount = 0;
+ hash2enc (&identity->hashPubKey, &fil);
+ fn = MALLOC (strlen (trustDirectory) + sizeof (EncName) + 1);
+ strcpy (fn, trustDirectory);
+ strcat (fn, (char *) &fil);
+ if ((disk_file_test (ectx,
+ fn) == YES) &&
+ (sizeof (unsigned int) ==
+ disk_file_read (ectx, fn, sizeof (unsigned int), &trust)))
+ {
+ entry->trust = ntohl (trust);
+ }
+ else
+ {
+ entry->trust = 0;
+ }
+ FREE (fn);
- if (numberOfHosts_ == sizeOfHosts_)
- GROW(hosts_,
- sizeOfHosts_,
- sizeOfHosts_+32);
- hosts_[numberOfHosts_++] = entry;
- }
- for (i=0;i<entry->protocolCount;i++) {
- if (entry->protocols[i] == protocol) {
- MUTEX_UNLOCK(lock_);
- return; /* already there */
+ if (numberOfHosts_ == sizeOfHosts_)
+ GROW (hosts_, sizeOfHosts_, sizeOfHosts_ + 32);
+ hosts_[numberOfHosts_++] = entry;
}
- }
- GROW(entry->protocols,
- entry->protocolCount,
- entry->protocolCount+1);
- entry->protocols[entry->protocolCount-1]
- = protocol;
- MUTEX_UNLOCK(lock_);
+ for (i = 0; i < entry->protocolCount; i++)
+ {
+ if (entry->protocols[i] == protocol)
+ {
+ MUTEX_UNLOCK (lock_);
+ return; /* already there */
+ }
+ }
+ GROW (entry->protocols, entry->protocolCount, entry->protocolCount + 1);
+ entry->protocols[entry->protocolCount - 1] = protocol;
+ MUTEX_UNLOCK (lock_);
}
/**
@@ -261,34 +255,38 @@
* host credit is to be increased or decreased
* @returns the actual change in trust (positive or negative)
*/
-static int changeHostTrust(const PeerIdentity * hostId,
- int value){
- HostEntry * host;
+static int
+changeHostTrust (const PeerIdentity * hostId, int value)
+{
+ HostEntry *host;
if (value == 0)
return 0;
- MUTEX_LOCK(lock_);
- host = findHost(hostId);
- if (host == NULL) {
- addHostToKnown(hostId,
- NAT_PROTOCOL_NUMBER);
- host = findHost(hostId);
- if (host == NULL) {
- GE_BREAK(ectx, 0);
- MUTEX_UNLOCK(lock_);
- return 0;
+ MUTEX_LOCK (lock_);
+ host = findHost (hostId);
+ if (host == NULL)
+ {
+ addHostToKnown (hostId, NAT_PROTOCOL_NUMBER);
+ host = findHost (hostId);
+ if (host == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ MUTEX_UNLOCK (lock_);
+ return 0;
+ }
}
- }
- if ( ((int) (host->trust & TRUST_ACTUAL_MASK)) + value < 0) {
- value = - (host->trust & TRUST_ACTUAL_MASK);
- host->trust = 0
- | TRUST_REFRESH_MASK; /* 0 remaining */
- } else {
- host->trust = ( (host->trust & TRUST_ACTUAL_MASK) + value)
- | TRUST_REFRESH_MASK;
- }
- MUTEX_UNLOCK(lock_);
+ if (((int) (host->trust & TRUST_ACTUAL_MASK)) + value < 0)
+ {
+ value = -(host->trust & TRUST_ACTUAL_MASK);
+ host->trust = 0 | TRUST_REFRESH_MASK; /* 0 remaining */
+ }
+ else
+ {
+ host->trust = ((host->trust & TRUST_ACTUAL_MASK) + value)
+ | TRUST_REFRESH_MASK;
+ }
+ MUTEX_UNLOCK (lock_);
return value;
}
@@ -298,107 +296,104 @@
* @param hostId the identity of the peer
* @return the amount of trust we currently have in that peer
*/
-static unsigned int getHostTrust(const PeerIdentity * hostId) {
- HostEntry * host;
+static unsigned int
+getHostTrust (const PeerIdentity * hostId)
+{
+ HostEntry *host;
unsigned int trust;
- MUTEX_LOCK(lock_);
- host = findHost(hostId);
+ MUTEX_LOCK (lock_);
+ host = findHost (hostId);
if (host == NULL)
trust = 0;
else
trust = host->trust & TRUST_ACTUAL_MASK;
- MUTEX_UNLOCK(lock_);
+ MUTEX_UNLOCK (lock_);
return trust;
}
-static int cronHelper(const char * filename,
- const char * dirname,
- void * unused) {
+static int
+cronHelper (const char *filename, const char *dirname, void *unused)
+{
PeerIdentity identity;
EncName id;
unsigned int protoNumber;
- char * fullname;
+ char *fullname;
- GE_ASSERT(ectx, numberOfHosts_ <= sizeOfHosts_);
- GE_ASSERT(ectx, sizeof(EncName) == 104);
- if (2 == sscanf(filename,
- "%103c.%u",
- (char*)&id,
- &protoNumber)) {
- id.encoding[sizeof(EncName)-1] = '\0';
- if (OK == enc2hash((char*)&id,
- &identity.hashPubKey)) {
- addHostToKnown(&identity,
- (unsigned short) protoNumber);
- return OK;
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
+ GE_ASSERT (ectx, sizeof (EncName) == 104);
+ if (2 == sscanf (filename, "%103c.%u", (char *) &id, &protoNumber))
+ {
+ id.encoding[sizeof (EncName) - 1] = '\0';
+ if (OK == enc2hash ((char *) &id, &identity.hashPubKey))
+ {
+ addHostToKnown (&identity, (unsigned short) protoNumber);
+ return OK;
+ }
}
- }
- fullname = MALLOC(strlen(filename) +
- strlen(networkIdDirectory) + 1);
- strcpy(fullname, networkIdDirectory);
- strcat(fullname, filename);
- if (disk_file_test(ectx, fullname) == YES) {
- if (0 == UNLINK(fullname))
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- _("File `%s' in directory `%s' does not match naming convention. "
- "Removed.\n"),
- filename,
- networkIdDirectory);
- else
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- "unlink",
- fullname);
- } else if (disk_directory_test(ectx, fullname) == YES) {
- if (0 == RMDIR(fullname))
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- _("Directory `%s' in directory `%s' does not match naming convention. "
- "Removed.\n"),
- filename,
- networkIdDirectory);
- else
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- "rmdir",
- fullname);
- }
- FREE(fullname);
+ fullname = MALLOC (strlen (filename) + strlen (networkIdDirectory) + 1);
+ strcpy (fullname, networkIdDirectory);
+ strcat (fullname, filename);
+ if (disk_file_test (ectx, fullname) == YES)
+ {
+ if (0 == UNLINK (fullname))
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
+ _
+ ("File `%s' in directory `%s' does not match naming
convention. "
+ "Removed.\n"), filename, networkIdDirectory);
+ else
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ "unlink", fullname);
+ }
+ else if (disk_directory_test (ectx, fullname) == YES)
+ {
+ if (0 == RMDIR (fullname))
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
+ _
+ ("Directory `%s' in directory `%s' does not match naming
convention. "
+ "Removed.\n"), filename, networkIdDirectory);
+ else
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ "rmdir", fullname);
+ }
+ FREE (fullname);
return OK;
}
/**
* Call this method periodically to scan data/hosts for new hosts.
*/
-static void cronScanDirectoryDataHosts(void * unused) {
+static void
+cronScanDirectoryDataHosts (void *unused)
+{
static cron_t lastRun;
static int retries;
int count;
cron_t now;
- now = get_time();
+ now = get_time ();
if (lastRun + MAX_DATA_HOST_FREQ > now)
- return; /* prevent scanning more than
- once every 5 min */
+ return; /* prevent scanning more than
+ once every 5 min */
lastRun = now;
- count = disk_directory_scan(ectx,
- networkIdDirectory,
- &cronHelper,
- NULL);
- if (count <= 0) {
- retries++;
- if ((retries & 32) > 0) {
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Still no peers found in `%s'!\n"),
- networkIdDirectory);
+ count = disk_directory_scan (ectx, networkIdDirectory, &cronHelper, NULL);
+ if (count <= 0)
+ {
+ retries++;
+ if ((retries & 32) > 0)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Still no peers found in `%s'!\n"), networkIdDirectory);
+ }
}
- }
- GE_ASSERT(ectx, numberOfHosts_ <= sizeOfHosts_);
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
}
@@ -407,225 +402,207 @@
* @param pubKey the public key of the host
* @param result address where to write the identity of the node
*/
-static void getPeerIdentity(const PublicKey * pubKey,
- PeerIdentity * result) {
- if (pubKey == NULL) {
- memset(&result,
- 0,
- sizeof(PeerIdentity));
- } else {
- hash(pubKey,
- sizeof(PublicKey),
- &result->hashPubKey);
- }
+static void
+getPeerIdentity (const PublicKey * pubKey, PeerIdentity * result)
+{
+ if (pubKey == NULL)
+ {
+ memset (&result, 0, sizeof (PeerIdentity));
+ }
+ else
+ {
+ hash (pubKey, sizeof (PublicKey), &result->hashPubKey);
+ }
}
/**
* Add a host to the temporary list.
*/
-static void addHostTemporarily(const P2P_hello_MESSAGE * tmp) {
+static void
+addHostTemporarily (const P2P_hello_MESSAGE * tmp)
+{
static int tempHostsNextSlot;
- P2P_hello_MESSAGE * msg;
- HostEntry * entry;
+ P2P_hello_MESSAGE *msg;
+ HostEntry *entry;
int i;
int slot;
PeerIdentity have;
- getPeerIdentity(&tmp->publicKey,
- &have);
- if (0 != memcmp(&have,
- &tmp->senderIdentity,
- sizeof(PeerIdentity))) {
- GE_BREAK(NULL, 0);
- return;
- }
- MUTEX_LOCK(lock_);
- entry = findHost(&tmp->senderIdentity);
- if ( (entry != NULL) &&
- (entry->helloCount > 0) ) {
- MUTEX_UNLOCK(lock_);
- return;
- }
- msg = MALLOC(P2P_hello_MESSAGE_size(tmp));
- memcpy(msg,
- tmp,
- P2P_hello_MESSAGE_size(tmp));
+ getPeerIdentity (&tmp->publicKey, &have);
+ if (0 != memcmp (&have, &tmp->senderIdentity, sizeof (PeerIdentity)))
+ {
+ GE_BREAK (NULL, 0);
+ return;
+ }
+ MUTEX_LOCK (lock_);
+ entry = findHost (&tmp->senderIdentity);
+ if ((entry != NULL) && (entry->helloCount > 0))
+ {
+ MUTEX_UNLOCK (lock_);
+ return;
+ }
+ msg = MALLOC (P2P_hello_MESSAGE_size (tmp));
+ memcpy (msg, tmp, P2P_hello_MESSAGE_size (tmp));
slot = tempHostsNextSlot;
- for (i=0;i<MAX_TEMP_HOSTS;i++)
- if (0 == memcmp(&tmp->senderIdentity,
- &tempHosts[i].identity,
- sizeof(PeerIdentity)))
+ for (i = 0; i < MAX_TEMP_HOSTS; i++)
+ if (0 == memcmp (&tmp->senderIdentity,
+ &tempHosts[i].identity, sizeof (PeerIdentity)))
slot = i;
- if (slot == tempHostsNextSlot) {
- tempHostsNextSlot++;
- if (tempHostsNextSlot >= MAX_TEMP_HOSTS)
- tempHostsNextSlot = 0;
- }
+ if (slot == tempHostsNextSlot)
+ {
+ tempHostsNextSlot++;
+ if (tempHostsNextSlot >= MAX_TEMP_HOSTS)
+ tempHostsNextSlot = 0;
+ }
entry = &tempHosts[slot];
entry->identity = msg->senderIdentity;
entry->until = 0;
entry->delta = 0;
- for (i=0;i<entry->helloCount;i++)
- FREE(entry->hellos[i]);
- GROW(entry->hellos,
- entry->helloCount,
- 1);
- GROW(entry->protocols,
- entry->protocolCount,
- 1);
+ for (i = 0; i < entry->helloCount; i++)
+ FREE (entry->hellos[i]);
+ GROW (entry->hellos, entry->helloCount, 1);
+ GROW (entry->protocols, entry->protocolCount, 1);
entry->hellos[0] = msg;
- entry->protocols[0] = ntohs(msg->protocol);
+ entry->protocols[0] = ntohs (msg->protocol);
entry->strict = NO;
entry->trust = 0;
- MUTEX_UNLOCK(lock_);
+ MUTEX_UNLOCK (lock_);
}
/**
* Delete a host from the list.
*/
-static void delHostFromKnown(const PeerIdentity * identity,
- unsigned short protocol) {
- HostEntry * entry;
- char * fn;
+static void
+delHostFromKnown (const PeerIdentity * identity, unsigned short protocol)
+{
+ HostEntry *entry;
+ char *fn;
int i;
int j;
- GE_ASSERT(ectx, numberOfHosts_ <= sizeOfHosts_);
- GE_ASSERT(ectx, protocol != ANY_PROTOCOL_NUMBER);
- MUTEX_LOCK(lock_);
- for (i=0;i<numberOfHosts_;i++) {
- if ( (0 == memcmp(identity,
- &hosts_[i]->identity,
- sizeof(PeerIdentity))) ) {
- entry = hosts_[i];
- for (j=0;j<entry->protocolCount;j++) {
- if (protocol == entry->protocols[j]) {
- entry->protocols[j]
- = entry->protocols[entry->protocolCount-1];
- GROW(entry->protocols,
- entry->protocolCount,
- entry->protocolCount-1);
- }
- }
- for (j=0;j<entry->helloCount;j++) {
- if (protocol == ntohs(entry->hellos[j]->protocol)) {
- FREE(entry->hellos[j]);
- entry->hellos[j]
- = entry->hellos[entry->helloCount-1];
- GROW(entry->hellos,
- entry->helloCount,
- entry->helloCount-1);
- }
- }
- /* also remove hello file itself */
- fn = getHostFileName(identity,
- protocol);
- if (0 != UNLINK(fn))
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "unlink",
- fn);
- FREE(fn);
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
+ GE_ASSERT (ectx, protocol != ANY_PROTOCOL_NUMBER);
+ MUTEX_LOCK (lock_);
+ for (i = 0; i < numberOfHosts_; i++)
+ {
+ if ((0 == memcmp (identity,
+ &hosts_[i]->identity, sizeof (PeerIdentity))))
+ {
+ entry = hosts_[i];
+ for (j = 0; j < entry->protocolCount; j++)
+ {
+ if (protocol == entry->protocols[j])
+ {
+ entry->protocols[j]
+ = entry->protocols[entry->protocolCount - 1];
+ GROW (entry->protocols,
+ entry->protocolCount, entry->protocolCount - 1);
+ }
+ }
+ for (j = 0; j < entry->helloCount; j++)
+ {
+ if (protocol == ntohs (entry->hellos[j]->protocol))
+ {
+ FREE (entry->hellos[j]);
+ entry->hellos[j] = entry->hellos[entry->helloCount - 1];
+ GROW (entry->hellos,
+ entry->helloCount, entry->helloCount - 1);
+ }
+ }
+ /* also remove hello file itself */
+ fn = getHostFileName (identity, protocol);
+ if (0 != UNLINK (fn))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ "unlink", fn);
+ FREE (fn);
- if (entry->protocolCount == 0) {
- if (entry->helloCount > 0) {
- for (j=0;j<entry->helloCount;j++)
- FREE(entry->hellos[j]);
- GROW(entry->hellos,
- entry->helloCount,
- 0);
- }
- hosts_[i] = hosts_[--numberOfHosts_];
- FREE(entry);
- }
- MUTEX_UNLOCK(lock_);
- GE_ASSERT(ectx,
- numberOfHosts_ <= sizeOfHosts_);
- return; /* deleted */
+ if (entry->protocolCount == 0)
+ {
+ if (entry->helloCount > 0)
+ {
+ for (j = 0; j < entry->helloCount; j++)
+ FREE (entry->hellos[j]);
+ GROW (entry->hellos, entry->helloCount, 0);
+ }
+ hosts_[i] = hosts_[--numberOfHosts_];
+ FREE (entry);
+ }
+ MUTEX_UNLOCK (lock_);
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
+ return; /* deleted */
+ }
}
- }
- MUTEX_UNLOCK(lock_);
+ MUTEX_UNLOCK (lock_);
}
/**
* Bind a host address (hello) to a hostId.
* @param msg the verified (!) hello message
*/
-static void bindAddress(const P2P_hello_MESSAGE * msg) {
- char * fn;
- char * buffer;
- P2P_hello_MESSAGE * oldMsg;
+static void
+bindAddress (const P2P_hello_MESSAGE * msg)
+{
+ char *fn;
+ char *buffer;
+ P2P_hello_MESSAGE *oldMsg;
int size;
- HostEntry * host;
+ HostEntry *host;
int i;
PeerIdentity have;
- getPeerIdentity(&msg->publicKey,
- &have);
- if (0 != memcmp(&have,
- &msg->senderIdentity,
- sizeof(PeerIdentity))) {
- GE_BREAK(NULL, 0);
- return;
- }
- GE_ASSERT(ectx,
- numberOfHosts_ <= sizeOfHosts_);
- GE_ASSERT(ectx,
- msg != NULL);
- fn = getHostFileName(&msg->senderIdentity,
- ntohs(msg->protocol));
- buffer = MALLOC(MAX_BUFFER_SIZE);
- if (disk_file_test(ectx,
- fn) == YES) {
- size = disk_file_read(ectx,
- fn,
- MAX_BUFFER_SIZE,
- buffer);
- if (size >= sizeof(P2P_hello_MESSAGE)) {
- oldMsg = (P2P_hello_MESSAGE*) buffer;
- if ((unsigned int)size == P2P_hello_MESSAGE_size(oldMsg)) {
- if (ntohl(oldMsg->expirationTime) > ntohl(msg->expirationTime)) {
- FREE(fn);
- FREE(buffer);
- return; /* have more recent hello in stock */
- }
- }
+ getPeerIdentity (&msg->publicKey, &have);
+ if (0 != memcmp (&have, &msg->senderIdentity, sizeof (PeerIdentity)))
+ {
+ GE_BREAK (NULL, 0);
+ return;
}
- }
- disk_file_write(ectx,
- fn,
- msg,
- P2P_hello_MESSAGE_size(msg),
- "644");
- FREE(fn);
- FREE(buffer);
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
+ GE_ASSERT (ectx, msg != NULL);
+ fn = getHostFileName (&msg->senderIdentity, ntohs (msg->protocol));
+ buffer = MALLOC (MAX_BUFFER_SIZE);
+ if (disk_file_test (ectx, fn) == YES)
+ {
+ size = disk_file_read (ectx, fn, MAX_BUFFER_SIZE, buffer);
+ if (size >= sizeof (P2P_hello_MESSAGE))
+ {
+ oldMsg = (P2P_hello_MESSAGE *) buffer;
+ if ((unsigned int) size == P2P_hello_MESSAGE_size (oldMsg))
+ {
+ if (ntohl (oldMsg->expirationTime) >
+ ntohl (msg->expirationTime))
+ {
+ FREE (fn);
+ FREE (buffer);
+ return; /* have more recent hello in stock */
+ }
+ }
+ }
+ }
+ disk_file_write (ectx, fn, msg, P2P_hello_MESSAGE_size (msg), "644");
+ FREE (fn);
+ FREE (buffer);
- MUTEX_LOCK(lock_);
- addHostToKnown(&msg->senderIdentity,
- ntohs(msg->protocol));
- host = findHost(&msg->senderIdentity);
- GE_ASSERT(ectx,
- host != NULL);
+ MUTEX_LOCK (lock_);
+ addHostToKnown (&msg->senderIdentity, ntohs (msg->protocol));
+ host = findHost (&msg->senderIdentity);
+ GE_ASSERT (ectx, host != NULL);
- for (i=0;i<host->helloCount;i++) {
- if (msg->protocol == host->hellos[i]->protocol) {
- FREE(host->hellos[i]);
- host->hellos[i] = NULL;
- break;
+ for (i = 0; i < host->helloCount; i++)
+ {
+ if (msg->protocol == host->hellos[i]->protocol)
+ {
+ FREE (host->hellos[i]);
+ host->hellos[i] = NULL;
+ break;
+ }
}
- }
if (i == host->helloCount)
- GROW(host->hellos,
- host->helloCount,
- host->helloCount+1);
- host->hellos[i]
- = MALLOC(P2P_hello_MESSAGE_size(msg));
- memcpy(host->hellos[i],
- msg,
- P2P_hello_MESSAGE_size(msg));
- MUTEX_UNLOCK(lock_);
- GE_ASSERT(ectx,
- numberOfHosts_ <= sizeOfHosts_);
+ GROW (host->hellos, host->helloCount, host->helloCount + 1);
+ host->hellos[i] = MALLOC (P2P_hello_MESSAGE_size (msg));
+ memcpy (host->hellos[i], msg, P2P_hello_MESSAGE_size (msg));
+ MUTEX_UNLOCK (lock_);
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
}
/**
@@ -641,142 +618,131 @@
* @returns SYSERR on failure, OK on success
*/
static P2P_hello_MESSAGE *
-identity2Hello(const PeerIdentity * hostId,
- unsigned short protocol,
- int tryTemporaryList) {
- P2P_hello_MESSAGE * result;
- HostEntry * host;
- char * fn;
+identity2Hello (const PeerIdentity * hostId,
+ unsigned short protocol, int tryTemporaryList)
+{
+ P2P_hello_MESSAGE *result;
+ HostEntry *host;
+ char *fn;
P2P_hello_MESSAGE buffer;
PeerIdentity have;
int size;
int i;
int j;
- GE_ASSERT(ectx,
- numberOfHosts_ <= sizeOfHosts_);
- MUTEX_LOCK(lock_);
- if (YES == tryTemporaryList) {
- /* ok, then first try temporary hosts
- (in memory, cheapest!) */
- for (i=0;i<MAX_TEMP_HOSTS;i++) {
- host = &tempHosts[i];
- if ( (host->helloCount > 0) &&
- (0 == memcmp(hostId,
- &host->identity,
- sizeof(PeerIdentity))) ) {
- if (protocol == ANY_PROTOCOL_NUMBER) {
- j = weak_randomi(host->helloCount);
- } else {
- j = 0;
- while ( (j < host->helloCount) &&
- (host->protocols[j] != protocol) )
- j++;
- }
- if (j == host->helloCount) {
- /* not found */
- MUTEX_UNLOCK(lock_);
- return NULL;
- }
- result = MALLOC(P2P_hello_MESSAGE_size(host->hellos[j]));
- memcpy(result,
- host->hellos[j],
- P2P_hello_MESSAGE_size(host->hellos[j]));
- MUTEX_UNLOCK(lock_);
- return result;
- }
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
+ MUTEX_LOCK (lock_);
+ if (YES == tryTemporaryList)
+ {
+ /* ok, then first try temporary hosts
+ (in memory, cheapest!) */
+ for (i = 0; i < MAX_TEMP_HOSTS; i++)
+ {
+ host = &tempHosts[i];
+ if ((host->helloCount > 0) &&
+ (0 == memcmp (hostId, &host->identity, sizeof (PeerIdentity))))
+ {
+ if (protocol == ANY_PROTOCOL_NUMBER)
+ {
+ j = weak_randomi (host->helloCount);
+ }
+ else
+ {
+ j = 0;
+ while ((j < host->helloCount) &&
+ (host->protocols[j] != protocol))
+ j++;
+ }
+ if (j == host->helloCount)
+ {
+ /* not found */
+ MUTEX_UNLOCK (lock_);
+ return NULL;
+ }
+ result = MALLOC (P2P_hello_MESSAGE_size (host->hellos[j]));
+ memcpy (result,
+ host->hellos[j],
+ P2P_hello_MESSAGE_size (host->hellos[j]));
+ MUTEX_UNLOCK (lock_);
+ return result;
+ }
+ }
}
- }
- host = findHost(hostId);
- if ( (host == NULL) ||
- (host->protocolCount == 0) ) {
- MUTEX_UNLOCK(lock_);
- return NULL;
- }
+ host = findHost (hostId);
+ if ((host == NULL) || (host->protocolCount == 0))
+ {
+ MUTEX_UNLOCK (lock_);
+ return NULL;
+ }
if (protocol == ANY_PROTOCOL_NUMBER)
- protocol = host->protocols[weak_randomi(host->protocolCount)];
+ protocol = host->protocols[weak_randomi (host->protocolCount)];
- for (i=0;i<host->helloCount;i++) {
- if (ntohs(host->hellos[i]->protocol) == protocol) {
- result
- = MALLOC(P2P_hello_MESSAGE_size(host->hellos[i]));
- memcpy(result,
- host->hellos[i],
- P2P_hello_MESSAGE_size(host->hellos[i]));
- MUTEX_UNLOCK(lock_);
- return result;
+ for (i = 0; i < host->helloCount; i++)
+ {
+ if (ntohs (host->hellos[i]->protocol) == protocol)
+ {
+ result = MALLOC (P2P_hello_MESSAGE_size (host->hellos[i]));
+ memcpy (result,
+ host->hellos[i], P2P_hello_MESSAGE_size (host->hellos[i]));
+ MUTEX_UNLOCK (lock_);
+ return result;
+ }
}
- }
/* do direct read */
- fn = getHostFileName(hostId,
- protocol);
- if (1 != disk_file_test(ectx,
- fn)) {
- FREE(fn);
- MUTEX_UNLOCK(lock_);
- return NULL;
- }
- size = disk_file_read(ectx,
- fn,
- sizeof(P2P_hello_MESSAGE),
- &buffer);
- if (size != sizeof(P2P_hello_MESSAGE)) {
- if (0 == UNLINK(fn))
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Removed file `%s' containing invalid HELLO data.\n"),
- fn);
- else
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "unlink",
- fn);
- FREE(fn);
- MUTEX_UNLOCK(lock_);
- return NULL;
- }
- result = MALLOC(P2P_hello_MESSAGE_size(&buffer));
- size = disk_file_read(ectx,
- fn,
- P2P_hello_MESSAGE_size(&buffer),
- result);
- getPeerIdentity(&result->publicKey,
- &have);
- if ( ((unsigned int)size != P2P_hello_MESSAGE_size(&buffer)) ||
- (0 != memcmp(&have,
- hostId,
- sizeof(PeerIdentity))) ||
- (0 != memcmp(&have,
- &result->senderIdentity,
- sizeof(PeerIdentity))) ) {
- if (0 == UNLINK(fn))
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Removed file `%s' containing invalid HELLO data.\n"),
- fn);
- else
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "unlink",
- fn);
- FREE(fn);
- FREE(result);
- MUTEX_UNLOCK(lock_);
- return NULL;
- }
- FREE(fn);
- GROW(host->hellos,
- host->helloCount,
- host->helloCount+1);
- host->hellos[host->helloCount-1]
- = MALLOC(P2P_hello_MESSAGE_size(&buffer));
- memcpy(host->hellos[host->helloCount-1],
- result,
- P2P_hello_MESSAGE_size(&buffer));
- MUTEX_UNLOCK(lock_);
+ fn = getHostFileName (hostId, protocol);
+ if (1 != disk_file_test (ectx, fn))
+ {
+ FREE (fn);
+ MUTEX_UNLOCK (lock_);
+ return NULL;
+ }
+ size = disk_file_read (ectx, fn, sizeof (P2P_hello_MESSAGE), &buffer);
+ if (size != sizeof (P2P_hello_MESSAGE))
+ {
+ if (0 == UNLINK (fn))
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Removed file `%s' containing invalid HELLO data.\n"), fn);
+ else
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "unlink", fn);
+ FREE (fn);
+ MUTEX_UNLOCK (lock_);
+ return NULL;
+ }
+ result = MALLOC (P2P_hello_MESSAGE_size (&buffer));
+ size = disk_file_read (ectx, fn, P2P_hello_MESSAGE_size (&buffer), result);
+ getPeerIdentity (&result->publicKey, &have);
+ if (((unsigned int) size != P2P_hello_MESSAGE_size (&buffer)) ||
+ (0 != memcmp (&have,
+ hostId,
+ sizeof (PeerIdentity))) ||
+ (0 != memcmp (&have, &result->senderIdentity, sizeof (PeerIdentity))))
+ {
+ if (0 == UNLINK (fn))
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Removed file `%s' containing invalid HELLO data.\n"), fn);
+ else
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "unlink", fn);
+ FREE (fn);
+ FREE (result);
+ MUTEX_UNLOCK (lock_);
+ return NULL;
+ }
+ FREE (fn);
+ GROW (host->hellos, host->helloCount, host->helloCount + 1);
+ host->hellos[host->helloCount - 1]
+ = MALLOC (P2P_hello_MESSAGE_size (&buffer));
+ memcpy (host->hellos[host->helloCount - 1],
+ result, P2P_hello_MESSAGE_size (&buffer));
+ MUTEX_UNLOCK (lock_);
return result;
}
@@ -789,38 +755,35 @@
* @param sig the signature
* @return OK on success, SYSERR on error (verification failed)
*/
-static int verifyPeerSignature(const PeerIdentity * signer,
- const void * message,
- int size,
- const Signature * sig) {
- P2P_hello_MESSAGE * hello;
+static int
+verifyPeerSignature (const PeerIdentity * signer,
+ const void *message, int size, const Signature * sig)
+{
+ P2P_hello_MESSAGE *hello;
int res;
- hello = identity2Hello(signer,
- ANY_PROTOCOL_NUMBER,
- YES);
- if (hello == NULL) {
+ hello = identity2Hello (signer, ANY_PROTOCOL_NUMBER, YES);
+ if (hello == NULL)
+ {
#if DEBUG_IDENTITY
- EncName enc;
+ EncName enc;
- IF_GELOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- hash2enc(&signer->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- _("Signature failed verification: peer `%s' not known.\n"),
- &enc);
+ IF_GELOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ hash2enc (&signer->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ _("Signature failed verification: peer `%s' not known.\n"),
+ &enc);
#endif
- return SYSERR;
- }
- res = verifySig(message, size, sig,
- &hello->publicKey);
+ return SYSERR;
+ }
+ res = verifySig (message, size, sig, &hello->publicKey);
if (res == SYSERR)
- GE_LOG(ectx,
- GE_ERROR | GE_REQUEST | GE_DEVELOPER | GE_USER,
- _("Signature failed verification: signature invalid.\n"));
- FREE(hello);
+ GE_LOG (ectx,
+ GE_ERROR | GE_REQUEST | GE_DEVELOPER | GE_USER,
+ _("Signature failed verification: signature invalid.\n"));
+ FREE (hello);
return res;
}
@@ -833,66 +796,66 @@
* @param strict should we reject incoming connection attempts as well?
* @return OK on success SYSERR on error
*/
-static int blacklistHost(const PeerIdentity * identity,
- unsigned int desperation,
- int strict) {
+static int
+blacklistHost (const PeerIdentity * identity,
+ unsigned int desperation, int strict)
+{
EncName hn;
- HostEntry * entry;
+ HostEntry *entry;
int i;
cron_t now;
- GE_ASSERT(ectx,
- numberOfHosts_ <= sizeOfHosts_);
- MUTEX_LOCK(lock_);
- entry = findHost(identity);
- if (entry == NULL) {
- for (i=0;i<MAX_TEMP_HOSTS;i++) {
- if (0 == memcmp(identity,
- &tempHosts[i].identity,
- sizeof(PeerIdentity))) {
- entry = &tempHosts[i];
- break;
- }
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
+ MUTEX_LOCK (lock_);
+ entry = findHost (identity);
+ if (entry == NULL)
+ {
+ for (i = 0; i < MAX_TEMP_HOSTS; i++)
+ {
+ if (0 == memcmp (identity,
+ &tempHosts[i].identity, sizeof (PeerIdentity)))
+ {
+ entry = &tempHosts[i];
+ break;
+ }
+ }
}
- }
- if (entry == NULL) {
- MUTEX_UNLOCK(lock_);
- return SYSERR;
- }
- now = get_time();
- if ( (entry->strict == YES) &&
- (strict == NO) ) {
- /* stronger blacklisting in place! */
- MUTEX_UNLOCK(lock_);
- return OK;
- }
- if (strict) {
- entry->delta = desperation * cronSECONDS;
- } else {
- if (entry->until < now)
- entry->delta
- = weak_randomi(1+desperation*cronSECONDS);
- else
- entry->delta
- += weak_randomi(1+desperation*cronSECONDS);
- }
+ if (entry == NULL)
+ {
+ MUTEX_UNLOCK (lock_);
+ return SYSERR;
+ }
+ now = get_time ();
+ if ((entry->strict == YES) && (strict == NO))
+ {
+ /* stronger blacklisting in place! */
+ MUTEX_UNLOCK (lock_);
+ return OK;
+ }
+ if (strict)
+ {
+ entry->delta = desperation * cronSECONDS;
+ }
+ else
+ {
+ if (entry->until < now)
+ entry->delta = weak_randomi (1 + desperation * cronSECONDS);
+ else
+ entry->delta += weak_randomi (1 + desperation * cronSECONDS);
+ }
if (entry->delta > 4 * cronHOURS)
entry->delta = 4 * cronHOURS;
entry->until = now + entry->delta;
entry->strict = strict;
- hash2enc(&identity->hashPubKey,
- &hn);
+ hash2enc (&identity->hashPubKey, &hn);
#if DEBUG_IDENTITY
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_DEVELOPER,
- "Blacklisting host `%s' for %llu seconds"
- " until %llu (strict=%d).\n",
- &hn,
- entry->delta / cronSECONDS,
- entry->until,
- strict);
+ GE_LOG (ectx,
+ GE_INFO | GE_REQUEST | GE_DEVELOPER,
+ "Blacklisting host `%s' for %llu seconds"
+ " until %llu (strict=%d).\n",
+ &hn, entry->delta / cronSECONDS, entry->until, strict);
#endif
- MUTEX_UNLOCK(lock_);
+ MUTEX_UNLOCK (lock_);
return OK;
}
@@ -902,39 +865,43 @@
* @param identity host to check
* @return YES if true, else NO
*/
-static int isBlacklistedStrict(const PeerIdentity * identity) {
+static int
+isBlacklistedStrict (const PeerIdentity * identity)
+{
cron_t now;
- HostEntry * entry;
+ HostEntry *entry;
- GE_ASSERT(ectx, numberOfHosts_ <= sizeOfHosts_);
- MUTEX_LOCK(lock_);
- entry = findHost(identity);
- if (entry == NULL) {
- MUTEX_UNLOCK(lock_);
- return NO;
- }
- now = get_time();
- if ( (now < entry->until) &&
- (entry->strict == YES) ) {
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
+ MUTEX_LOCK (lock_);
+ entry = findHost (identity);
+ if (entry == NULL)
+ {
+ MUTEX_UNLOCK (lock_);
+ return NO;
+ }
+ now = get_time ();
+ if ((now < entry->until) && (entry->strict == YES))
+ {
#if DEBUG_IDENTITY
- EncName enc;
+ EncName enc;
- IF_GELOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- hash2enc(&identity->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- _("Peer `%s' is currently strictly blacklisted (for another %llums).\n"),
- &enc,
- entry->until - now);
+ IF_GELOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ hash2enc (&identity->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ _
+ ("Peer `%s' is currently strictly blacklisted (for another
%llums).\n"),
+ &enc, entry->until - now);
#endif
- MUTEX_UNLOCK(lock_);
- return YES;
- } else {
- MUTEX_UNLOCK(lock_);
- return NO;
- }
+ MUTEX_UNLOCK (lock_);
+ return YES;
+ }
+ else
+ {
+ MUTEX_UNLOCK (lock_);
+ return NO;
+ }
}
/**
@@ -943,31 +910,36 @@
* resets the exponential backoff to the smallest value.
* @return OK on success SYSERR on error
*/
-static int whitelistHost(const PeerIdentity * identity) {
- HostEntry * entry;
+static int
+whitelistHost (const PeerIdentity * identity)
+{
+ HostEntry *entry;
int i;
- GE_ASSERT(ectx, numberOfHosts_ <= sizeOfHosts_);
- MUTEX_LOCK(lock_);
- entry = findHost(identity);
- if (entry == NULL) {
- for (i=0;i<MAX_TEMP_HOSTS;i++) {
- if (0 == memcmp(identity,
- &tempHosts[i].identity,
- sizeof(PeerIdentity))) {
- entry = &tempHosts[i];
- break;
- }
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
+ MUTEX_LOCK (lock_);
+ entry = findHost (identity);
+ if (entry == NULL)
+ {
+ for (i = 0; i < MAX_TEMP_HOSTS; i++)
+ {
+ if (0 == memcmp (identity,
+ &tempHosts[i].identity, sizeof (PeerIdentity)))
+ {
+ entry = &tempHosts[i];
+ break;
+ }
+ }
}
- }
- if (entry == NULL) {
- MUTEX_UNLOCK(lock_);
- return SYSERR;
- }
+ if (entry == NULL)
+ {
+ MUTEX_UNLOCK (lock_);
+ return SYSERR;
+ }
entry->delta = 30 * cronSECONDS;
entry->until = 0;
entry->strict = NO;
- MUTEX_UNLOCK(lock_);
+ MUTEX_UNLOCK (lock_);
return OK;
}
@@ -981,99 +953,97 @@
* @param data an argument to pass to the method
* @return the number of hosts matching
*/
-static int forEachHost(cron_t now,
- HostIterator callback,
- void * data) {
+static int
+forEachHost (cron_t now, HostIterator callback, void *data)
+{
int i;
int j;
int count;
PeerIdentity hi;
unsigned short proto;
- HostEntry * entry;
+ HostEntry *entry;
int ret;
ret = OK;
- GE_ASSERT(ectx,
- numberOfHosts_ <= sizeOfHosts_);
+ GE_ASSERT (ectx, numberOfHosts_ <= sizeOfHosts_);
count = 0;
- MUTEX_LOCK(lock_);
- for (i=0;i<numberOfHosts_;i++) {
- entry = hosts_[i];
- if (0 == memcmp(&entry->identity,
- &myIdentity,
- sizeof(PeerIdentity)))
- continue;
- if ( (now == 0) ||
- (now >= entry->until) ) {
- count++;
- if (callback != NULL) {
- hi = entry->identity;
- for (j=0;j<entry->protocolCount;j++) {
- proto = entry->protocols[j];
- MUTEX_UNLOCK(lock_);
- ret = callback(&hi,
- proto,
- YES,
- data);
- MUTEX_LOCK(lock_);
- if (ret != OK)
- break;
- /* we gave up the lock,
- need to re-acquire entry (if possible)! */
- if (i >= numberOfHosts_)
- break;
- entry = hosts_[i];
- if (0 == memcmp(&entry->identity,
- &myIdentity,
- sizeof(PeerIdentity)))
- break;
- }
- }
- } else {
+ MUTEX_LOCK (lock_);
+ for (i = 0; i < numberOfHosts_; i++)
+ {
+ entry = hosts_[i];
+ if (0 == memcmp (&entry->identity, &myIdentity, sizeof (PeerIdentity)))
+ continue;
+ if ((now == 0) || (now >= entry->until))
+ {
+ count++;
+ if (callback != NULL)
+ {
+ hi = entry->identity;
+ for (j = 0; j < entry->protocolCount; j++)
+ {
+ proto = entry->protocols[j];
+ MUTEX_UNLOCK (lock_);
+ ret = callback (&hi, proto, YES, data);
+ MUTEX_LOCK (lock_);
+ if (ret != OK)
+ break;
+ /* we gave up the lock,
+ need to re-acquire entry (if possible)! */
+ if (i >= numberOfHosts_)
+ break;
+ entry = hosts_[i];
+ if (0 == memcmp (&entry->identity,
+ &myIdentity, sizeof (PeerIdentity)))
+ break;
+ }
+ }
+ }
+ else
+ {
#if 0
#if DEBUG_IDENTITY
- EncName enc;
+ EncName enc;
- IF_GELOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- hash2enc(&entry->identity.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- entry->strict ?
- _("Peer `%s' is currently strictly blacklisted (for another
%llums).\n") :
- _("Peer `%s' is currently blacklisted (for another %llums).\n"),
- &enc,
- entry->until - now);
+ IF_GELOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ hash2enc (&entry->identity.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ entry->strict ?
+ _
+ ("Peer `%s' is currently strictly blacklisted (for another
%llums).\n")
+ :
+ _
+ ("Peer `%s' is currently blacklisted (for another
%llums).\n"),
+ &enc, entry->until - now);
#endif
#endif
- }
- if (ret != OK)
- break;
+ }
+ if (ret != OK)
+ break;
- }
- for (i=0;i<MAX_TEMP_HOSTS;i++) {
- if (ret != OK)
- break;
- entry = &tempHosts[i];
- if (entry->helloCount == 0)
- continue;
- if ( (now == 0) ||
- (now >= entry->until) ) {
- count++;
- if (callback != NULL) {
- hi = entry->identity;
- proto = entry->protocols[0];
- MUTEX_UNLOCK(lock_);
- ret = callback(&hi,
- proto,
- YES,
- data);
- MUTEX_LOCK(lock_);
- }
}
- }
- MUTEX_UNLOCK(lock_);
+ for (i = 0; i < MAX_TEMP_HOSTS; i++)
+ {
+ if (ret != OK)
+ break;
+ entry = &tempHosts[i];
+ if (entry->helloCount == 0)
+ continue;
+ if ((now == 0) || (now >= entry->until))
+ {
+ count++;
+ if (callback != NULL)
+ {
+ hi = entry->identity;
+ proto = entry->protocols[0];
+ MUTEX_UNLOCK (lock_);
+ ret = callback (&hi, proto, YES, data);
+ MUTEX_LOCK (lock_);
+ }
+ }
+ }
+ MUTEX_UNLOCK (lock_);
return count;
}
@@ -1081,76 +1051,72 @@
* Write host-trust information to a file - flush the buffer entry!
* Assumes synchronized access.
*/
-static void flushHostCredit(HostEntry * host) {
+static void
+flushHostCredit (HostEntry * host)
+{
EncName fil;
- char * fn;
+ char *fn;
unsigned int trust;
if ((host->trust & TRUST_REFRESH_MASK) == 0)
- return; /* unchanged */
+ return; /* unchanged */
host->trust = host->trust & TRUST_ACTUAL_MASK;
- hash2enc(&host->identity.hashPubKey,
- &fil);
- fn = MALLOC(strlen(trustDirectory)+sizeof(EncName)+1);
- strcpy(fn, trustDirectory);
- strcat(fn, (char*) &fil);
- if (host->trust == 0) {
- if ( (0 != UNLINK(fn)) &&
- (errno != ENOENT) )
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "unlink",
- fn);
- } else {
- trust = htonl(host->trust);
- disk_file_write(ectx,
- fn,
- &trust,
- sizeof(unsigned int),
- "644");
- }
- FREE(fn);
+ hash2enc (&host->identity.hashPubKey, &fil);
+ fn = MALLOC (strlen (trustDirectory) + sizeof (EncName) + 1);
+ strcpy (fn, trustDirectory);
+ strcat (fn, (char *) &fil);
+ if (host->trust == 0)
+ {
+ if ((0 != UNLINK (fn)) && (errno != ENOENT))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_BULK, "unlink", fn);
+ }
+ else
+ {
+ trust = htonl (host->trust);
+ disk_file_write (ectx, fn, &trust, sizeof (unsigned int), "644");
+ }
+ FREE (fn);
}
/**
* Call once in a while to synchronize trust values with the disk.
*/
-static void cronFlushTrustBuffer(void * unused) {
+static void
+cronFlushTrustBuffer (void *unused)
+{
int i;
- MUTEX_LOCK(lock_);
- for (i=0;i<numberOfHosts_;i++)
- flushHostCredit(hosts_[i]);
- MUTEX_UNLOCK(lock_);
+ MUTEX_LOCK (lock_);
+ for (i = 0; i < numberOfHosts_; i++)
+ flushHostCredit (hosts_[i]);
+ MUTEX_UNLOCK (lock_);
}
/**
* @brief delete expired HELLO entries in data/hosts/
*/
-static int discardHostsHelper(const char *filename,
- const char *dirname,
- void *now) {
+static int
+discardHostsHelper (const char *filename, const char *dirname, void *now)
+{
char *fn;
struct stat hostStat;
int hostFile;
- fn = MALLOC(strlen(filename) + strlen(dirname) + 2);
- sprintf(fn,
- "%s%s%s",
- dirname,
- DIR_SEPARATOR_STR,
- filename);
- hostFile = disk_file_open(ectx,
- fn,
- O_WRONLY);
- if (hostFile != -1) {
- if (FSTAT(hostFile, &hostStat) == 0) {
- CLOSE(hostFile);
+ fn = MALLOC (strlen (filename) + strlen (dirname) + 2);
+ sprintf (fn, "%s%s%s", dirname, DIR_SEPARATOR_STR, filename);
+ hostFile = disk_file_open (ectx, fn, O_WRONLY);
+ if (hostFile != -1)
+ {
+ if (FSTAT (hostFile, &hostStat) == 0)
+ {
+ CLOSE (hostFile);
- if (hostStat.st_mtime + (CRON_DISCARDS_HOSTS_AFTER / cronSECONDS) <
*((time_t *) now))
- UNLINK(fn);
+ if (hostStat.st_mtime + (CRON_DISCARDS_HOSTS_AFTER / cronSECONDS) <
+ *((time_t *) now))
+ UNLINK (fn);
+ }
}
- }
- FREE(fn);
+ FREE (fn);
return OK;
}
@@ -1158,66 +1124,65 @@
/**
* @brief scan host directory for expired entries
*/
-static void cronDiscardHosts(void *unused) {
+static void
+cronDiscardHosts (void *unused)
+{
time_t timeNow;
- timeNow = time(NULL);
- disk_directory_scan(ectx,
- networkIdDirectory,
- &discardHostsHelper,
- (void *) &timeNow);
+ timeNow = time (NULL);
+ disk_directory_scan (ectx,
+ networkIdDirectory,
+ &discardHostsHelper, (void *) &timeNow);
}
-static int identityRequestConnectHandler(struct ClientHandle * sock,
- const MESSAGE_HEADER * message) {
- const CS_identity_connect_MESSAGE * msg;
+static int
+identityRequestConnectHandler (struct ClientHandle *sock,
+ const MESSAGE_HEADER * message)
+{
+ const CS_identity_connect_MESSAGE *msg;
int ret;
- if (sizeof(CS_identity_connect_MESSAGE) != ntohs(message->size))
+ if (sizeof (CS_identity_connect_MESSAGE) != ntohs (message->size))
return SYSERR;
- msg = (const CS_identity_connect_MESSAGE*) message;
- coreAPI->unicast(&msg->other,
- NULL,
- 0,
- 0);
- ret = coreAPI->queryPeerStatus(&msg->other,
- NULL,
- NULL);
- return coreAPI->sendValueToClient(sock,
- ret != OK ? NO : YES);
+ msg = (const CS_identity_connect_MESSAGE *) message;
+ coreAPI->unicast (&msg->other, NULL, 0, 0);
+ ret = coreAPI->queryPeerStatus (&msg->other, NULL, NULL);
+ return coreAPI->sendValueToClient (sock, ret != OK ? NO : YES);
}
-static int identityHelloHandler(struct ClientHandle * sock,
- const MESSAGE_HEADER * message) {
- const P2P_hello_MESSAGE * msg;
- P2P_hello_MESSAGE * hello;
+static int
+identityHelloHandler (struct ClientHandle *sock,
+ const MESSAGE_HEADER * message)
+{
+ const P2P_hello_MESSAGE *msg;
+ P2P_hello_MESSAGE *hello;
- if (sizeof(P2P_hello_MESSAGE) > ntohs(message->size)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- msg = (const P2P_hello_MESSAGE*) message;
- if (P2P_hello_MESSAGE_size(msg) != ntohs(message->size)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- hello = MALLOC(ntohs(msg->header.size));
- memcpy(hello,
- msg,
- ntohs(msg->header.size));
- hello->header.type = htons(p2p_PROTO_hello);
- coreAPI->injectMessage(NULL,
- (const char*) hello,
- ntohs(msg->header.size),
- NO,
- NULL);
- FREE(hello);
+ if (sizeof (P2P_hello_MESSAGE) > ntohs (message->size))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ msg = (const P2P_hello_MESSAGE *) message;
+ if (P2P_hello_MESSAGE_size (msg) != ntohs (message->size))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ hello = MALLOC (ntohs (msg->header.size));
+ memcpy (hello, msg, ntohs (msg->header.size));
+ hello->header.type = htons (p2p_PROTO_hello);
+ coreAPI->injectMessage (NULL,
+ (const char *) hello,
+ ntohs (msg->header.size), NO, NULL);
+ FREE (hello);
return OK;
}
-static int identityRequestHelloHandler(struct ClientHandle * sock,
- const MESSAGE_HEADER * message) {
+static int
+identityRequestHelloHandler (struct ClientHandle *sock,
+ const MESSAGE_HEADER * message)
+{
/* transport types in order of preference
for location URIs (by best guess at what
people are most likely to actually run) */
@@ -1231,57 +1196,56 @@
NAT_PROTOCOL_NUMBER,
0,
};
- Transport_ServiceAPI * tapi;
- P2P_hello_MESSAGE * hello;
+ Transport_ServiceAPI *tapi;
+ P2P_hello_MESSAGE *hello;
int pos;
int ret;
/* we cannot permanently load transport
since that would cause a cyclic dependency;
however, we can request it briefly here */
- tapi = coreAPI->requestService("transport");
+ tapi = coreAPI->requestService ("transport");
if (tapi == NULL)
return SYSERR;
hello = NULL;
pos = 0;
- while ( (hello == NULL) &&
- (types[pos] != 0) )
- hello = tapi->createhello(types[pos++]);
- coreAPI->releaseService(tapi);
+ while ((hello == NULL) && (types[pos] != 0))
+ hello = tapi->createhello (types[pos++]);
+ coreAPI->releaseService (tapi);
if (hello == NULL)
return SYSERR;
- hello->header.type = htons(CS_PROTO_identity_HELLO);
- ret = coreAPI->sendToClient(sock,
- &hello->header);
- FREE(hello);
+ hello->header.type = htons (CS_PROTO_identity_HELLO);
+ ret = coreAPI->sendToClient (sock, &hello->header);
+ FREE (hello);
return ret;
}
-static int identityRequestSignatureHandler(struct ClientHandle * sock,
- const MESSAGE_HEADER * message) {
+static int
+identityRequestSignatureHandler (struct ClientHandle *sock,
+ const MESSAGE_HEADER * message)
+{
CS_identity_signature_MESSAGE reply;
- if (ntohs(message->size) <= sizeof(MESSAGE_HEADER))
+ if (ntohs (message->size) <= sizeof (MESSAGE_HEADER))
return SYSERR;
- reply.header.size = htons(sizeof(CS_identity_signature_MESSAGE));
- reply.header.type = htons(CS_PROTO_identity_SIGNATURE);
- if (OK != signData(&message[1],
- ntohs(message->size) - sizeof(MESSAGE_HEADER),
- &reply.sig))
+ reply.header.size = htons (sizeof (CS_identity_signature_MESSAGE));
+ reply.header.type = htons (CS_PROTO_identity_SIGNATURE);
+ if (OK != signData (&message[1],
+ ntohs (message->size) - sizeof (MESSAGE_HEADER),
+ &reply.sig))
return SYSERR;
- return coreAPI->sendToClient(sock,
- &reply.header);
+ return coreAPI->sendToClient (sock, &reply.header);
}
-static int hostInfoIterator(const PeerIdentity * identity,
- unsigned short protocol,
- int confirmed,
- void * data) {
- struct ClientHandle * sock = data;
- Transport_ServiceAPI * transport;
- CS_identity_peer_info_MESSAGE * reply;
- P2P_hello_MESSAGE * hello;
- void * address;
+static int
+hostInfoIterator (const PeerIdentity * identity,
+ unsigned short protocol, int confirmed, void *data)
+{
+ struct ClientHandle *sock = data;
+ Transport_ServiceAPI *transport;
+ CS_identity_peer_info_MESSAGE *reply;
+ P2P_hello_MESSAGE *hello;
+ void *address;
int ret;
unsigned int len;
unsigned int bpm;
@@ -1289,59 +1253,52 @@
if (confirmed == NO)
return OK;
- hello = identity2Hello(identity,
- protocol,
- YES);
+ hello = identity2Hello (identity, protocol, YES);
if (hello == NULL)
- return OK; /* ignore -- happens if HELLO just expired */
- transport = coreAPI->requestService("transport");
- if (transport == NULL) {
- FREE(hello);
- return OK;
- }
+ return OK; /* ignore -- happens if HELLO just expired */
+ transport = coreAPI->requestService ("transport");
+ if (transport == NULL)
+ {
+ FREE (hello);
+ return OK;
+ }
len = 0;
address = NULL;
- transport->helloToAddress(hello,
- &address,
- &len);
- FREE(hello);
- coreAPI->releaseService(transport);
- if (len >= MAX_BUFFER_SIZE - sizeof(CS_identity_peer_info_MESSAGE) ) {
- FREE(address);
- address = NULL;
- len = 0;
- }
- if (OK != coreAPI->queryPeerStatus(identity,
- &bpm,
- &last)) {
- last = 0;
- bpm = 0;
- }
- reply = MALLOC(sizeof(CS_identity_peer_info_MESSAGE) + len);
- reply->header.size = htons(sizeof(CS_identity_peer_info_MESSAGE) + len);
- reply->header.type = htons(CS_PROTO_identity_INFO);
+ transport->helloToAddress (hello, &address, &len);
+ FREE (hello);
+ coreAPI->releaseService (transport);
+ if (len >= MAX_BUFFER_SIZE - sizeof (CS_identity_peer_info_MESSAGE))
+ {
+ FREE (address);
+ address = NULL;
+ len = 0;
+ }
+ if (OK != coreAPI->queryPeerStatus (identity, &bpm, &last))
+ {
+ last = 0;
+ bpm = 0;
+ }
+ reply = MALLOC (sizeof (CS_identity_peer_info_MESSAGE) + len);
+ reply->header.size = htons (sizeof (CS_identity_peer_info_MESSAGE) + len);
+ reply->header.type = htons (CS_PROTO_identity_INFO);
reply->peer = *identity;
- reply->last_message = htonll(last);
- reply->trust = htonl(getHostTrust(identity));
- reply->bpm = htonl(bpm);
- memcpy(&reply[1],
- address,
- len);
- FREENONNULL(address);
- ret = coreAPI->sendToClient(sock,
- &reply->header);
- FREE(reply);
+ reply->last_message = htonll (last);
+ reply->trust = htonl (getHostTrust (identity));
+ reply->bpm = htonl (bpm);
+ memcpy (&reply[1], address, len);
+ FREENONNULL (address);
+ ret = coreAPI->sendToClient (sock, &reply->header);
+ FREE (reply);
return ret;
}
-static int identityRequestInfoHandler(struct ClientHandle * sock,
- const MESSAGE_HEADER * message) {
- forEachHost(0,
- &hostInfoIterator,
- sock);
- return coreAPI->sendValueToClient(sock,
- OK);
+static int
+identityRequestInfoHandler (struct ClientHandle *sock,
+ const MESSAGE_HEADER * message)
+{
+ forEachHost (0, &hostInfoIterator, sock);
+ return coreAPI->sendValueToClient (sock, OK);
}
@@ -1352,169 +1309,144 @@
* @return NULL on errors, ID_API otherwise
*/
Identity_ServiceAPI *
-provide_module_identity(CoreAPIForApplication * capi) {
+provide_module_identity (CoreAPIForApplication * capi)
+{
static Identity_ServiceAPI id;
- char * gnHome;
- char * tmp;
+ char *gnHome;
+ char *tmp;
int i;
coreAPI = capi;
ectx = coreAPI->ectx;
id.getPublicPrivateKey = &getPublicPrivateKey;
- id.getPeerIdentity = &getPeerIdentity;
- id.signData = &signData;
- id.decryptData = &decryptData;
- id.delHostFromKnown = &delHostFromKnown;
- id.addHostTemporarily = &addHostTemporarily;
- id.addHost = &bindAddress;
- id.forEachHost = &forEachHost;
- id.identity2Hello = &identity2Hello;
+ id.getPeerIdentity = &getPeerIdentity;
+ id.signData = &signData;
+ id.decryptData = &decryptData;
+ id.delHostFromKnown = &delHostFromKnown;
+ id.addHostTemporarily = &addHostTemporarily;
+ id.addHost = &bindAddress;
+ id.forEachHost = &forEachHost;
+ id.identity2Hello = &identity2Hello;
id.verifyPeerSignature = &verifyPeerSignature;
- id.blacklistHost = &blacklistHost;
+ id.blacklistHost = &blacklistHost;
id.isBlacklistedStrict = &isBlacklistedStrict;
- id.whitelistHost = &whitelistHost;
- id.changeHostTrust = &changeHostTrust;
- id.getHostTrust = &getHostTrust;
+ id.whitelistHost = &whitelistHost;
+ id.changeHostTrust = &changeHostTrust;
+ id.getHostTrust = &getHostTrust;
- for (i=0;i<MAX_TEMP_HOSTS;i++)
- memset(&tempHosts[i],
- 0,
- sizeof(HostEntry));
+ for (i = 0; i < MAX_TEMP_HOSTS; i++)
+ memset (&tempHosts[i], 0, sizeof (HostEntry));
numberOfHosts_ = 0;
gnHome = NULL;
- GE_ASSERT(ectx,
- -1 != GC_get_configuration_value_filename(coreAPI->cfg,
- "GNUNETD",
- "GNUNETD_HOME",
- VAR_DAEMON_DIRECTORY,
- &gnHome));
+ GE_ASSERT (ectx,
+ -1 != GC_get_configuration_value_filename (coreAPI->cfg,
+ "GNUNETD",
+ "GNUNETD_HOME",
+ VAR_DAEMON_DIRECTORY,
+ &gnHome));
if (gnHome == NULL)
return NULL;
- disk_directory_create(ectx, gnHome);
- tmp = MALLOC(strlen(gnHome) + strlen(HOST_DIR) + 2);
- strcpy(tmp, gnHome);
- strcat(tmp, DIR_SEPARATOR_STR);
- strcat(tmp, HOST_DIR);
+ disk_directory_create (ectx, gnHome);
+ tmp = MALLOC (strlen (gnHome) + strlen (HOST_DIR) + 2);
+ strcpy (tmp, gnHome);
+ strcat (tmp, DIR_SEPARATOR_STR);
+ strcat (tmp, HOST_DIR);
networkIdDirectory = NULL;
- GE_ASSERT(ectx,
- -1 != GC_get_configuration_value_filename(coreAPI->cfg,
- "GNUNETD",
- "HOSTS",
- tmp,
- &networkIdDirectory));
- FREE(tmp);
- disk_directory_create(ectx,
- networkIdDirectory);
- trustDirectory = MALLOC(strlen(gnHome) +
- strlen(TRUSTDIR)+2);
- strcpy(trustDirectory, gnHome);
- strcat(trustDirectory, DIR_SEPARATOR_STR);
- strcat(trustDirectory, TRUSTDIR);
- disk_directory_create(ectx,
- trustDirectory);
- FREE(gnHome);
+ GE_ASSERT (ectx,
+ -1 != GC_get_configuration_value_filename (coreAPI->cfg,
+ "GNUNETD",
+ "HOSTS",
+ tmp,
+ &networkIdDirectory));
+ FREE (tmp);
+ disk_directory_create (ectx, networkIdDirectory);
+ trustDirectory = MALLOC (strlen (gnHome) + strlen (TRUSTDIR) + 2);
+ strcpy (trustDirectory, gnHome);
+ strcat (trustDirectory, DIR_SEPARATOR_STR);
+ strcat (trustDirectory, TRUSTDIR);
+ disk_directory_create (ectx, trustDirectory);
+ FREE (gnHome);
- lock_ = MUTEX_CREATE(YES);
- initPrivateKey(capi->ectx,
- capi->cfg);
- getPeerIdentity(getPublicPrivateKey(),
- &myIdentity);
- cronScanDirectoryDataHosts(NULL);
- cron_add_job(coreAPI->cron,
- &cronScanDirectoryDataHosts,
- CRON_DATA_HOST_FREQ,
- CRON_DATA_HOST_FREQ,
- NULL);
- cron_add_job(coreAPI->cron,
- &cronFlushTrustBuffer,
- CRON_TRUST_FLUSH_FREQ,
- CRON_TRUST_FLUSH_FREQ,
- NULL);
- cron_add_job(coreAPI->cron,
- &cronDiscardHosts,
- 0,
- CRON_DISCARD_HOSTS_INTERVAL,
- NULL);
- coreAPI->registerClientHandler(CS_PROTO_identity_CONNECT,
- &identityRequestConnectHandler);
- coreAPI->registerClientHandler(CS_PROTO_identity_HELLO,
- &identityHelloHandler);
- coreAPI->registerClientHandler(CS_PROTO_identity_request_HELLO,
- &identityRequestHelloHandler);
- coreAPI->registerClientHandler(CS_PROTO_identity_request_SIGN,
- &identityRequestSignatureHandler);
- coreAPI->registerClientHandler(CS_PROTO_identity_request_INFO,
- &identityRequestInfoHandler);
+ lock_ = MUTEX_CREATE (YES);
+ initPrivateKey (capi->ectx, capi->cfg);
+ getPeerIdentity (getPublicPrivateKey (), &myIdentity);
+ cronScanDirectoryDataHosts (NULL);
+ cron_add_job (coreAPI->cron,
+ &cronScanDirectoryDataHosts,
+ CRON_DATA_HOST_FREQ, CRON_DATA_HOST_FREQ, NULL);
+ cron_add_job (coreAPI->cron,
+ &cronFlushTrustBuffer,
+ CRON_TRUST_FLUSH_FREQ, CRON_TRUST_FLUSH_FREQ, NULL);
+ cron_add_job (coreAPI->cron,
+ &cronDiscardHosts, 0, CRON_DISCARD_HOSTS_INTERVAL, NULL);
+ coreAPI->registerClientHandler (CS_PROTO_identity_CONNECT,
+ &identityRequestConnectHandler);
+ coreAPI->registerClientHandler (CS_PROTO_identity_HELLO,
+ &identityHelloHandler);
+ coreAPI->registerClientHandler (CS_PROTO_identity_request_HELLO,
+ &identityRequestHelloHandler);
+ coreAPI->registerClientHandler (CS_PROTO_identity_request_SIGN,
+ &identityRequestSignatureHandler);
+ coreAPI->registerClientHandler (CS_PROTO_identity_request_INFO,
+ &identityRequestInfoHandler);
return &id;
}
/**
* Shutdown Identity service.
*/
-void release_module_identity() {
+void
+release_module_identity ()
+{
int i;
int j;
- HostEntry * entry;
+ HostEntry *entry;
- coreAPI->unregisterClientHandler(CS_PROTO_identity_CONNECT,
- &identityRequestConnectHandler);
- coreAPI->unregisterClientHandler(CS_PROTO_identity_HELLO,
- &identityHelloHandler);
- coreAPI->unregisterClientHandler(CS_PROTO_identity_request_HELLO,
- &identityRequestHelloHandler);
- coreAPI->unregisterClientHandler(CS_PROTO_identity_request_SIGN,
- &identityRequestSignatureHandler);
- coreAPI->unregisterClientHandler(CS_PROTO_identity_request_INFO,
- &identityRequestInfoHandler);
- for (i=0;i<MAX_TEMP_HOSTS;i++) {
- entry = &tempHosts[i];
- for (j=0;j<entry->helloCount;j++)
- FREE(entry->hellos[j]);
- GROW(entry->hellos,
- entry->helloCount,
- 0);
- GROW(entry->protocols,
- entry->protocolCount,
- 0);
- }
- cron_del_job(coreAPI->cron,
- &cronScanDirectoryDataHosts,
- CRON_DATA_HOST_FREQ,
- NULL);
- cron_del_job(coreAPI->cron,
- &cronFlushTrustBuffer,
- CRON_TRUST_FLUSH_FREQ,
- NULL);
- cron_del_job(coreAPI->cron,
- &cronDiscardHosts,
- CRON_DISCARD_HOSTS_INTERVAL,
- NULL);
- cronFlushTrustBuffer(NULL);
- MUTEX_DESTROY(lock_);
+ coreAPI->unregisterClientHandler (CS_PROTO_identity_CONNECT,
+ &identityRequestConnectHandler);
+ coreAPI->unregisterClientHandler (CS_PROTO_identity_HELLO,
+ &identityHelloHandler);
+ coreAPI->unregisterClientHandler (CS_PROTO_identity_request_HELLO,
+ &identityRequestHelloHandler);
+ coreAPI->unregisterClientHandler (CS_PROTO_identity_request_SIGN,
+ &identityRequestSignatureHandler);
+ coreAPI->unregisterClientHandler (CS_PROTO_identity_request_INFO,
+ &identityRequestInfoHandler);
+ for (i = 0; i < MAX_TEMP_HOSTS; i++)
+ {
+ entry = &tempHosts[i];
+ for (j = 0; j < entry->helloCount; j++)
+ FREE (entry->hellos[j]);
+ GROW (entry->hellos, entry->helloCount, 0);
+ GROW (entry->protocols, entry->protocolCount, 0);
+ }
+ cron_del_job (coreAPI->cron,
+ &cronScanDirectoryDataHosts, CRON_DATA_HOST_FREQ, NULL);
+ cron_del_job (coreAPI->cron,
+ &cronFlushTrustBuffer, CRON_TRUST_FLUSH_FREQ, NULL);
+ cron_del_job (coreAPI->cron,
+ &cronDiscardHosts, CRON_DISCARD_HOSTS_INTERVAL, NULL);
+ cronFlushTrustBuffer (NULL);
+ MUTEX_DESTROY (lock_);
lock_ = NULL;
- for (i=0;i<numberOfHosts_;i++) {
- entry = hosts_[i];
- for (j=0;j<entry->helloCount;j++)
- FREE(entry->hellos[j]);
- GROW(entry->hellos,
- entry->helloCount,
- 0);
- GROW(entry->protocols,
- entry->protocolCount,
- 0);
- FREE(entry);
- }
- GROW(hosts_,
- sizeOfHosts_,
- 0);
+ for (i = 0; i < numberOfHosts_; i++)
+ {
+ entry = hosts_[i];
+ for (j = 0; j < entry->helloCount; j++)
+ FREE (entry->hellos[j]);
+ GROW (entry->hellos, entry->helloCount, 0);
+ GROW (entry->protocols, entry->protocolCount, 0);
+ FREE (entry);
+ }
+ GROW (hosts_, sizeOfHosts_, 0);
numberOfHosts_ = 0;
- FREE(networkIdDirectory);
+ FREE (networkIdDirectory);
networkIdDirectory = NULL;
- FREE(trustDirectory);
+ FREE (trustDirectory);
trustDirectory = NULL;
- donePrivateKey();
+ donePrivateKey ();
}
/* end of identity.c */
Modified: GNUnet/src/applications/identity/identity.h
===================================================================
--- GNUnet/src/applications/identity/identity.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/identity/identity.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -29,7 +29,8 @@
/**
* Format of the signature response.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
Signature sig;
@@ -38,7 +39,8 @@
/**
* Format of the connection request.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
PeerIdentity other;
@@ -51,7 +53,8 @@
* variable-size string with the peer's address as given by the
* transport.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
unsigned int trust;
Modified: GNUnet/src/applications/identity/identitytest.c
===================================================================
--- GNUnet/src/applications/identity/identitytest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/identity/identitytest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -35,9 +35,9 @@
#include "gnunet_util_network_client.h"
#include "core.h"
-static struct CronManager * cron;
+static struct CronManager *cron;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
#define ASSERT(cond) do { \
@@ -51,116 +51,106 @@
} \
} while (0)
-static int runTest() {
- Identity_ServiceAPI * identity;
- Transport_ServiceAPI * transport;
+static int
+runTest ()
+{
+ Identity_ServiceAPI *identity;
+ Transport_ServiceAPI *transport;
PeerIdentity pid;
- const PublicKey * pkey;
+ const PublicKey *pkey;
Signature sig;
- P2P_hello_MESSAGE * hello;
+ P2P_hello_MESSAGE *hello;
- transport = requestService("transport");
- identity = requestService("identity");
- cron_start(cron);
+ transport = requestService ("transport");
+ identity = requestService ("identity");
+ cron_start (cron);
/* give cron job chance to run */
- PTHREAD_SLEEP(5 * cronSECONDS);
- hello = transport->createhello(ANY_PROTOCOL_NUMBER);
- if (NULL == hello) {
- printf("Cannot run test, failed to create any hello.\n");
- cron_stop(cron);
- releaseService(identity);
- releaseService(transport);
- return SYSERR;
- }
- identity->addHost(hello);
+ PTHREAD_SLEEP (5 * cronSECONDS);
+ hello = transport->createhello (ANY_PROTOCOL_NUMBER);
+ if (NULL == hello)
+ {
+ printf ("Cannot run test, failed to create any hello.\n");
+ cron_stop (cron);
+ releaseService (identity);
+ releaseService (transport);
+ return SYSERR;
+ }
+ identity->addHost (hello);
pid = hello->senderIdentity;
- FREE(hello);
+ FREE (hello);
- identity->changeHostTrust
- (&pid,
- -identity->getHostTrust(&pid));
- ASSERT(4 == identity->changeHostTrust
- (&pid, 4));
- releaseService(identity);
+ identity->changeHostTrust (&pid, -identity->getHostTrust (&pid));
+ ASSERT (4 == identity->changeHostTrust (&pid, 4));
+ releaseService (identity);
- identity = requestService("identity");
- ASSERT(4 == identity->getHostTrust(&pid));
- ASSERT(5 == identity->changeHostTrust
- (&pid, 5));
- ASSERT(-2 == identity->changeHostTrust
- (&pid, -2));
- ASSERT(7 == identity->getHostTrust(&pid));
- ASSERT(-7 == identity->changeHostTrust
- (&pid, -40));
- pkey = identity->getPublicPrivateKey();
- identity->getPeerIdentity(pkey,
- &pid);
- ASSERT(0 == identity->getHostTrust(&pid));
+ identity = requestService ("identity");
+ ASSERT (4 == identity->getHostTrust (&pid));
+ ASSERT (5 == identity->changeHostTrust (&pid, 5));
+ ASSERT (-2 == identity->changeHostTrust (&pid, -2));
+ ASSERT (7 == identity->getHostTrust (&pid));
+ ASSERT (-7 == identity->changeHostTrust (&pid, -40));
+ pkey = identity->getPublicPrivateKey ();
+ identity->getPeerIdentity (pkey, &pid);
+ ASSERT (0 == identity->getHostTrust (&pid));
- pkey = identity->getPublicPrivateKey();
- ASSERT(OK == identity->signData("TestData",
- 8,
- &sig));
- ASSERT(OK == verifySig("TestData",
- 8,
- &sig,
- pkey));
+ pkey = identity->getPublicPrivateKey ();
+ ASSERT (OK == identity->signData ("TestData", 8, &sig));
+ ASSERT (OK == verifySig ("TestData", 8, &sig, pkey));
/* to test:
hello verification, temporary storage,
permanent storage, blacklisting, etc. */
- cron_stop(cron);
- releaseService(identity);
- releaseService(transport);
+ cron_stop (cron);
+ releaseService (identity);
+ releaseService (transport);
return OK;
}
-static int hcb(void * data,
- const PeerIdentity * identity,
- const void * address,
- unsigned int addr_len,
- cron_t last_message,
- unsigned int trust,
- unsigned int bpmFromPeer) {
+static int
+hcb (void *data,
+ const PeerIdentity * identity,
+ const void *address,
+ unsigned int addr_len,
+ cron_t last_message, unsigned int trust, unsigned int bpmFromPeer)
+{
/* TODO: do something meaningful */
return OK;
}
-static int runClientTest() {
- struct ClientServerConnection * sock;
+static int
+runClientTest ()
+{
+ struct ClientServerConnection *sock;
int ret;
ret = OK;
- sock = client_connection_create(NULL, cfg);
- gnunet_identity_request_peer_infos(sock,
- &hcb,
- &ret);
- connection_destroy(sock);
+ sock = client_connection_create (NULL, cfg);
+ gnunet_identity_request_peer_infos (sock, &hcb, &ret);
+ connection_destroy (sock);
return ret;
}
-int main(int argc, char *argv[]) {
+int
+main (int argc, char *argv[])
+{
int err;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- cron = cron_create(NULL);
- initCore(NULL,
- cfg,
- cron,
- NULL);
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ cron = cron_create (NULL);
+ initCore (NULL, cfg, cron, NULL);
err = 0;
- if (OK != runTest())
+ if (OK != runTest ())
err = 1;
- if (OK != runClientTest())
+ if (OK != runClientTest ())
err = 1;
- doneCore();
- cron_destroy(cron);
- GC_free(cfg);
+ doneCore ();
+ cron_destroy (cron);
+ GC_free (cfg);
return err;
}
Modified: GNUnet/src/applications/kvstore_sqlite/kv_sqlite.c
===================================================================
--- GNUnet/src/applications/kvstore_sqlite/kv_sqlite.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/kvstore_sqlite/kv_sqlite.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -53,24 +53,26 @@
/**
* @brief Wrapper for SQLite
*/
-typedef struct {
+typedef struct
+{
/**
* Native SQLite database handle - may not be shared between threads!
*/
- sqlite3 * dbh;
+ sqlite3 *dbh;
/**
* Thread ID owning this handle
*/
- struct PTHREAD * tid;
+ struct PTHREAD *tid;
} sqliteHandle;
/**
* @brief Information about the database
*/
-typedef struct {
+typedef struct
+{
/**
* bytes used
@@ -80,17 +82,17 @@
/**
* name of the database
*/
- char * name;
+ char *name;
/**
* filename of this database
*/
- char * fn;
+ char *fn;
/**
* List of open handles
*/
- sqliteHandle ** handles;
+ sqliteHandle **handles;
/**
* Open handles (one per thread)
@@ -101,15 +103,15 @@
} sqliteDatabase;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
static unsigned int databases;
-static sqliteDatabase ** dbs;
+static sqliteDatabase **dbs;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
/**
* @brief Encode a binary buffer "in" of size n bytes so that it contains
@@ -118,26 +120,30 @@
* @param n size of in
* @param out output
*/
-static int sqlite_encode_binary(const unsigned char *in,
- int n,
- unsigned char *out){
+static int
+sqlite_encode_binary (const unsigned char *in, int n, unsigned char *out)
+{
char c;
unsigned char *start = out;
n--;
- for (; n > -1; n--) {
- c = *in;
- in++;
+ for (; n > -1; n--)
+ {
+ c = *in;
+ in++;
- if (c == 0 || c == 1) {
- *out = 1;
+ if (c == 0 || c == 1)
+ {
+ *out = 1;
+ out++;
+ *out = c + 1;
+ }
+ else
+ {
+ *out = c;
+ }
out++;
- *out = c + 1;
- } else {
- *out = c;
}
- out++;
- }
return (int) (out - start);
}
@@ -148,61 +154,62 @@
* @param num size of the output buffer
* @return number of output bytes, -1 on error
*/
-static int sqlite_decode_binary_n(const unsigned char *in,
- unsigned char *out,
- unsigned int num){
+static int
+sqlite_decode_binary_n (const unsigned char *in,
+ unsigned char *out, unsigned int num)
+{
unsigned char *start = out;
unsigned char *stop = (unsigned char *) (in + num);
- while(in != stop) {
- if (*in == 1) {
+ while (in != stop)
+ {
+ if (*in == 1)
+ {
+ in++;
+ *out = *in - 1;
+ }
+ else
+ *out = *in;
in++;
- *out = *in - 1;
- } else
- *out = *in;
- in++;
- out++;
- }
+ out++;
+ }
return (int) (out - start);
}
/**
* @brief Prepare a SQL statement
*/
-static int sq_prepare(sqliteHandle *dbh,
- const char *zSql, /* SQL statement, UTF-8 encoded */
- sqlite3_stmt **ppStmt) { /* OUT: Statement handle */
- char * dummy;
+static int
+sq_prepare (sqliteHandle * dbh, const char *zSql, /* SQL statement,
UTF-8 encoded */
+ sqlite3_stmt ** ppStmt)
+{ /* OUT: Statement handle */
+ char *dummy;
- return sqlite3_prepare(dbh->dbh,
- zSql,
- strlen(zSql),
- ppStmt,
- (const char**) &dummy);
+ return sqlite3_prepare (dbh->dbh,
+ zSql,
+ strlen (zSql), ppStmt, (const char **) &dummy);
}
/**
* Get path to database file
*/
-static char * getDBFileName(const char * name) {
- char * dir;
- char * fn;
+static char *
+getDBFileName (const char *name)
+{
+ char *dir;
+ char *fn;
size_t mem;
- GC_get_configuration_value_filename(coreAPI->cfg,
- "KEYVALUE_DATABASE",
- "DIR",
- VAR_DAEMON_DIRECTORY "/kvstore/",
- &dir);
- disk_directory_create(ectx, dir);
- mem = strlen(dir) + strlen(name) + 6;
- fn = MALLOC(mem);
- SNPRINTF(fn,
- mem,
- "%s/%s.dat",
- dir,
- name);
- FREE(dir);
+ GC_get_configuration_value_filename (coreAPI->cfg,
+ "KEYVALUE_DATABASE",
+ "DIR",
+ VAR_DAEMON_DIRECTORY "/kvstore/",
+ &dir);
+ disk_directory_create (ectx, dir);
+ mem = strlen (dir) + strlen (name) + 6;
+ fn = MALLOC (mem);
+ SNPRINTF (fn, mem, "%s/%s.dat", dir, name);
+ FREE (dir);
return fn;
}
@@ -210,22 +217,20 @@
* @brief Get information about an open database
* @param name the name of the database
*/
-static sqliteDatabase * getDB(const char *name) {
+static sqliteDatabase *
+getDB (const char *name)
+{
unsigned int idx;
- sqliteDatabase * db;
+ sqliteDatabase *db;
for (idx = 0; idx < databases; idx++)
- if (0 == strcmp(dbs[idx]->name, name))
+ if (0 == strcmp (dbs[idx]->name, name))
return dbs[idx];
- db = MALLOC(sizeof(sqliteDatabase));
- memset(db,
- 0,
- sizeof(sqliteDatabase));
- db->fn = getDBFileName(name);
- db->name = STRDUP(name);
- APPEND(dbs,
- databases,
- db);
+ db = MALLOC (sizeof (sqliteDatabase));
+ memset (db, 0, sizeof (sqliteDatabase));
+ db->fn = getDBFileName (name);
+ db->name = STRDUP (name);
+ APPEND (dbs, databases, db);
return db;
}
@@ -236,89 +241,89 @@
* We therefore (re)open the database in each thread.
* @return the native SQLite database handle
*/
-static sqliteHandle * getDBHandle(const char *name) {
+static sqliteHandle *
+getDBHandle (const char *name)
+{
unsigned int idx;
- sqliteHandle * dbh;
- sqliteDatabase * db;
+ sqliteHandle *dbh;
+ sqliteDatabase *db;
- MUTEX_LOCK(lock);
- db = getDB(name);
+ MUTEX_LOCK (lock);
+ db = getDB (name);
for (idx = 0; idx < db->handle_count; idx++)
- if (PTHREAD_TEST_SELF(db->handles[idx]->tid)) {
- sqliteHandle * ret = db->handles[idx];
- MUTEX_UNLOCK(lock);
- return ret;
+ if (PTHREAD_TEST_SELF (db->handles[idx]->tid))
+ {
+ sqliteHandle *ret = db->handles[idx];
+ MUTEX_UNLOCK (lock);
+ return ret;
+ }
+ /* we haven't opened the DB for this thread yet */
+ dbh = MALLOC (sizeof (sqliteHandle));
+ dbh->tid = PTHREAD_GET_SELF ();
+ if (sqlite3_open (db->fn, &dbh->dbh) != SQLITE_OK)
+ {
+ printf ("FN: %s\n", db->fn);
+ LOG_SQLITE (dbh->dbh, GE_ERROR | GE_BULK | GE_USER, "sqlite3_open");
+ sqlite3_close (dbh->dbh);
+ MUTEX_UNLOCK (lock);
+ PTHREAD_REL_SELF (dbh->tid);
+ FREE (dbh);
+ return NULL;
}
- /* we haven't opened the DB for this thread yet */
- dbh = MALLOC(sizeof(sqliteHandle));
- dbh->tid = PTHREAD_GET_SELF();
- if (sqlite3_open(db->fn,
- &dbh->dbh) != SQLITE_OK) {
- printf("FN: %s\n", db->fn);
- LOG_SQLITE(dbh->dbh,
- GE_ERROR | GE_BULK | GE_USER,
- "sqlite3_open");
- sqlite3_close(dbh->dbh);
- MUTEX_UNLOCK(lock);
- PTHREAD_REL_SELF(dbh->tid);
- FREE(dbh);
- return NULL;
- }
- APPEND(db->handles,
- db->handle_count,
- dbh);
- sqlite3_exec(dbh->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL, NULL);
- sqlite3_exec(dbh->dbh, "PRAGMA synchronous=OFF", NULL, NULL, NULL);
- sqlite3_exec(dbh->dbh, "PRAGMA count_changes=OFF", NULL, NULL, NULL);
- sqlite3_exec(dbh->dbh, "PRAGMA page_size=4096", NULL, NULL, NULL);
- MUTEX_UNLOCK(lock);
+ APPEND (db->handles, db->handle_count, dbh);
+ sqlite3_exec (dbh->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL, NULL);
+ sqlite3_exec (dbh->dbh, "PRAGMA synchronous=OFF", NULL, NULL, NULL);
+ sqlite3_exec (dbh->dbh, "PRAGMA count_changes=OFF", NULL, NULL, NULL);
+ sqlite3_exec (dbh->dbh, "PRAGMA page_size=4096", NULL, NULL, NULL);
+ MUTEX_UNLOCK (lock);
return dbh;
}
-static void close_database(sqliteDatabase *db) {
+static void
+close_database (sqliteDatabase * db)
+{
unsigned int idx;
- for (idx = 0; idx < db->handle_count; idx++) {
- sqliteHandle * dbh = db->handles[idx];
- PTHREAD_REL_SELF(dbh->tid);
- if (sqlite3_close(dbh->dbh) != SQLITE_OK)
- LOG_SQLITE(dbh->dbh,
- LOG_ERROR,
- "sqlite_close");
- FREE(dbh);
- }
- GROW(db->handles,
- db->handle_count,
- 0);
- FREE(db->fn);
- FREE(db->name);
- FREE(db);
+ for (idx = 0; idx < db->handle_count; idx++)
+ {
+ sqliteHandle *dbh = db->handles[idx];
+ PTHREAD_REL_SELF (dbh->tid);
+ if (sqlite3_close (dbh->dbh) != SQLITE_OK)
+ LOG_SQLITE (dbh->dbh, LOG_ERROR, "sqlite_close");
+ FREE (dbh);
+ }
+ GROW (db->handles, db->handle_count, 0);
+ FREE (db->fn);
+ FREE (db->name);
+ FREE (db);
}
/**
* @brief Delete the database.
*/
-static void dropDatabase(const char * name) {
- sqliteDatabase * db;
+static void
+dropDatabase (const char *name)
+{
+ sqliteDatabase *db;
unsigned int idx;
- char * fn;
+ char *fn;
- MUTEX_LOCK(lock);
- for (idx = 0; idx < databases; idx++) {
- if (0 == strcmp(dbs[idx]->name, name)) {
- db = dbs[idx];
- close_database(db);
- dbs[idx] = dbs[databases-1];
- GROW(dbs,
- databases,
- databases - 1);
- break;
+ MUTEX_LOCK (lock);
+ for (idx = 0; idx < databases; idx++)
+ {
+ if (0 == strcmp (dbs[idx]->name, name))
+ {
+ db = dbs[idx];
+ close_database (db);
+ dbs[idx] = dbs[databases - 1];
+ GROW (dbs, databases, databases - 1);
+ break;
+ }
}
- }
- fn = getDBFileName(name);
- UNLINK(fn);
- FREE(fn);
- MUTEX_UNLOCK(lock);
+ fn = getDBFileName (name);
+ UNLINK (fn);
+ FREE (fn);
+ MUTEX_UNLOCK (lock);
}
/**
@@ -326,53 +331,49 @@
* @param table the name of the Key/Value-Table
* @return a handle
*/
-static KVHandle *getTable(const char *database,
- const char *table) {
+static KVHandle *
+getTable (const char *database, const char *table)
+{
sqlite3_stmt *stmt;
unsigned int len;
KVHandle *ret;
sqliteHandle *dbh;
- char * idx;
+ char *idx;
- dbh = getDBHandle(database);
+ dbh = getDBHandle (database);
if (dbh == NULL)
return NULL;
- sq_prepare(dbh,
- "Select 1 from sqlite_master where tbl_name = ?",
- &stmt);
- len = strlen(table);
- sqlite3_bind_text(stmt, 1, table, len, SQLITE_STATIC);
- if (sqlite3_step(stmt) == SQLITE_DONE) {
- char * create = MALLOC(len + 58);
+ sq_prepare (dbh, "Select 1 from sqlite_master where tbl_name = ?", &stmt);
+ len = strlen (table);
+ sqlite3_bind_text (stmt, 1, table, len, SQLITE_STATIC);
+ if (sqlite3_step (stmt) == SQLITE_DONE)
+ {
+ char *create = MALLOC (len + 58);
- sprintf(create,
- "CREATE TABLE %s (gn_key BLOB, gn_val BLOB, gn_age BIGINT)",
- table);
+ sprintf (create,
+ "CREATE TABLE %s (gn_key BLOB, gn_val BLOB, gn_age BIGINT)",
+ table);
- if (sqlite3_exec(dbh->dbh, create, NULL, NULL, NULL) != SQLITE_OK)
- {
- LOG_SQLITE(dbh->dbh,
- LOG_ERROR,
- "sqlite_create");
- sqlite3_finalize(stmt);
- FREE(create);
- return NULL;
+ if (sqlite3_exec (dbh->dbh, create, NULL, NULL, NULL) != SQLITE_OK)
+ {
+ LOG_SQLITE (dbh->dbh, LOG_ERROR, "sqlite_create");
+ sqlite3_finalize (stmt);
+ FREE (create);
+ return NULL;
+ }
+
+ FREE (create);
}
+ sqlite3_finalize (stmt);
- FREE(create);
- }
- sqlite3_finalize(stmt);
-
/* FIXME: more indexes */
- idx = MALLOC(len + 34);
- sprintf(idx,
- "CREATE INDEX idx_key ON %s (gn_key)",
- table);
- sqlite3_exec(dbh->dbh, idx, NULL, NULL, NULL);
- FREE(idx);
- ret = MALLOC(sizeof(KVHandle));
- ret->table = STRDUP(table);
- ret->db = STRDUP(database);
+ idx = MALLOC (len + 34);
+ sprintf (idx, "CREATE INDEX idx_key ON %s (gn_key)", table);
+ sqlite3_exec (dbh->dbh, idx, NULL, NULL, NULL);
+ FREE (idx);
+ ret = MALLOC (sizeof (KVHandle));
+ ret->table = STRDUP (table);
+ ret->db = STRDUP (database);
return ret;
}
@@ -387,13 +388,12 @@
* @param handler callback function to be called for every result (may be NULL)
* @param closure optional parameter for handler
*/
-static void *get(KVHandle *kv,
- void *key,
- int keylen,
- unsigned int sort,
- unsigned int limit,
- KVCallback handler,
- void *closure) {
+static void *
+get (KVHandle * kv,
+ void *key,
+ int keylen,
+ unsigned int sort, unsigned int limit, KVCallback handler, void *closure)
+{
unsigned int len, enclen, retlen;
char *sel, *order, *where, limit_spec[30];
sqlite3_stmt *stmt;
@@ -402,30 +402,30 @@
unsigned char *key_enc;
void *ret_dec;
- dbh = getDBHandle(kv->db);
+ dbh = getDBHandle (kv->db);
if (dbh == NULL)
return NULL;
ret = NULL;
ret_dec = NULL;
- len = strlen(kv->table);
- sel = MALLOC(len + 45);
+ len = strlen (kv->table);
+ sel = MALLOC (len + 45);
if (key)
- {
- where = "WHERE gn_key = ?";
- key_enc = MALLOC(keylen * 2 + 1);
- enclen = sqlite_encode_binary(key, keylen, key_enc);
- }
+ {
+ where = "WHERE gn_key = ?";
+ key_enc = MALLOC (keylen * 2 + 1);
+ enclen = sqlite_encode_binary (key, keylen, key_enc);
+ }
else
- {
- where = "";
- key_enc = NULL;
- enclen = 0; /* make gcc happy */
- }
+ {
+ where = "";
+ key_enc = NULL;
+ enclen = 0; /* make gcc happy */
+ }
- switch(sort)
- {
+ switch (sort)
+ {
case 1:
order = "BY RANDOM()";
break;
@@ -435,49 +435,46 @@
default:
order = "";
break;
- }
+ }
if (limit != 0)
- sprintf(limit_spec, "LIMIT %u", limit);
+ sprintf (limit_spec, "LIMIT %u", limit);
else
*limit_spec = 0;
- sprintf(sel,
- "SELECT gn_val FROM %s %s %s %s",
- kv->table,
- where,
- order,
- limit_spec);
+ sprintf (sel,
+ "SELECT gn_val FROM %s %s %s %s",
+ kv->table, where, order, limit_spec);
- sq_prepare(dbh, sel, &stmt);
+ sq_prepare (dbh, sel, &stmt);
if (key)
- sqlite3_bind_blob(stmt, 1, key_enc, enclen, SQLITE_STATIC);
- while(sqlite3_step(stmt) == SQLITE_ROW)
- {
- retlen = sqlite3_column_bytes(stmt, 0);
- ret = (void *) sqlite3_column_blob(stmt, 0);
+ sqlite3_bind_blob (stmt, 1, key_enc, enclen, SQLITE_STATIC);
+ while (sqlite3_step (stmt) == SQLITE_ROW)
+ {
+ retlen = sqlite3_column_bytes (stmt, 0);
+ ret = (void *) sqlite3_column_blob (stmt, 0);
- /* free previous result, only the last in the result set
- is returned to the caller */
- FREENONNULL(ret_dec);
+ /* free previous result, only the last in the result set
+ is returned to the caller */
+ FREENONNULL (ret_dec);
- ret_dec = MALLOC(retlen);
- retlen = sqlite_decode_binary_n(ret, ret_dec, retlen);
+ ret_dec = MALLOC (retlen);
+ retlen = sqlite_decode_binary_n (ret, ret_dec, retlen);
- if (handler)
- if (handler(closure, ret, retlen) != OK)
- {
- FREE(sel);
- FREENONNULL(key_enc);
- FREE(ret_dec);
- sqlite3_finalize(stmt);
+ if (handler)
+ if (handler (closure, ret, retlen) != OK)
+ {
+ FREE (sel);
+ FREENONNULL (key_enc);
+ FREE (ret_dec);
+ sqlite3_finalize (stmt);
- return ret;
- }
- }
- sqlite3_finalize(stmt);
- FREE(sel);
- FREENONNULL(key_enc);
+ return ret;
+ }
+ }
+ sqlite3_finalize (stmt);
+ FREE (sel);
+ FREENONNULL (key_enc);
return ret_dec;
}
@@ -491,8 +488,9 @@
* @param optional creation time
* @return OK on success, SYSERR otherwise
*/
-static int put(KVHandle *kv, void *key, int keylen, void *val, int vallen,
- unsigned long long age)
+static int
+put (KVHandle * kv, void *key, int keylen, void *val, int vallen,
+ unsigned long long age)
{
unsigned int len;
char *ins;
@@ -501,41 +499,39 @@
unsigned char *key_enc, *val_enc;
unsigned int keyenc_len, valenc_len;
- dbh = getDBHandle(kv->db);
+ dbh = getDBHandle (kv->db);
if (dbh == NULL)
return SYSERR;
- len = strlen(kv->table);
- ins = MALLOC(len + 68);
+ len = strlen (kv->table);
+ ins = MALLOC (len + 68);
- sprintf(ins,
- "INSERT INTO %s(gn_key, gn_val, gn_age) values (?, ?, ?)",
- kv->table);
+ sprintf (ins,
+ "INSERT INTO %s(gn_key, gn_val, gn_age) values (?, ?, ?)",
+ kv->table);
- key_enc = MALLOC(keylen * 2);
- keyenc_len = sqlite_encode_binary(key, keylen, key_enc);
+ key_enc = MALLOC (keylen * 2);
+ keyenc_len = sqlite_encode_binary (key, keylen, key_enc);
- val_enc = MALLOC(vallen * 2);
- valenc_len = sqlite_encode_binary(val, vallen, val_enc);
+ val_enc = MALLOC (vallen * 2);
+ valenc_len = sqlite_encode_binary (val, vallen, val_enc);
- sq_prepare(dbh, ins, &stmt);
- sqlite3_bind_blob(stmt, 1, key_enc, keyenc_len, SQLITE_STATIC);
- sqlite3_bind_blob(stmt, 2, val_enc, valenc_len, SQLITE_STATIC);
- sqlite3_bind_int64(stmt, 3, age);
- if (sqlite3_step(stmt) != SQLITE_DONE)
- {
- FREE(ins);
- FREE(key_enc);
- FREE(val_enc);
- LOG_SQLITE(dbh->dbh,
- LOG_ERROR,
- "put");
- sqlite3_finalize(stmt);
- return SYSERR;
- }
- sqlite3_finalize(stmt);
- FREE(ins);
- FREE(key_enc);
- FREE(val_enc);
+ sq_prepare (dbh, ins, &stmt);
+ sqlite3_bind_blob (stmt, 1, key_enc, keyenc_len, SQLITE_STATIC);
+ sqlite3_bind_blob (stmt, 2, val_enc, valenc_len, SQLITE_STATIC);
+ sqlite3_bind_int64 (stmt, 3, age);
+ if (sqlite3_step (stmt) != SQLITE_DONE)
+ {
+ FREE (ins);
+ FREE (key_enc);
+ FREE (val_enc);
+ LOG_SQLITE (dbh->dbh, LOG_ERROR, "put");
+ sqlite3_finalize (stmt);
+ return SYSERR;
+ }
+ sqlite3_finalize (stmt);
+ FREE (ins);
+ FREE (key_enc);
+ FREE (val_enc);
return OK;
}
@@ -547,7 +543,8 @@
* @param age age of the items to delete (may be 0)
* @return OK on success, SYSERR otherwise
*/
-static int del(KVHandle *kv, void *key, int keylen, unsigned long long age)
+static int
+del (KVHandle * kv, void *key, int keylen, unsigned long long age)
{
unsigned int len;
char *del, *key_where, *age_where;
@@ -557,12 +554,12 @@
unsigned char *keyenc;
unsigned int keyenc_len;
- dbh = getDBHandle(kv->db);
+ dbh = getDBHandle (kv->db);
if (dbh == NULL)
return SYSERR;
- len = strlen(kv->table);
- del = MALLOC(len + 52);
+ len = strlen (kv->table);
+ del = MALLOC (len + 52);
bind = 1;
if (key)
@@ -575,35 +572,38 @@
else
age_where = "";
- sprintf(del, "DELETE from %s where %s %s %s", kv->table, key_where, age ?
"or" : "", age_where);
+ sprintf (del, "DELETE from %s where %s %s %s", kv->table, key_where,
+ age ? "or" : "", age_where);
- sq_prepare(dbh, del, &stmt);
- if (key) {
- keyenc = MALLOC(keylen * 2);
- keyenc_len = sqlite_encode_binary(key, keylen, keyenc);
- sqlite3_bind_blob(stmt, 1, keyenc, keyenc_len, SQLITE_STATIC);
- bind++;
- } else {
- keyenc = NULL;
- }
+ sq_prepare (dbh, del, &stmt);
+ if (key)
+ {
+ keyenc = MALLOC (keylen * 2);
+ keyenc_len = sqlite_encode_binary (key, keylen, keyenc);
+ sqlite3_bind_blob (stmt, 1, keyenc, keyenc_len, SQLITE_STATIC);
+ bind++;
+ }
+ else
+ {
+ keyenc = NULL;
+ }
if (age)
- sqlite3_bind_int64(stmt, bind, age);
+ sqlite3_bind_int64 (stmt, bind, age);
- if (sqlite3_step(stmt) != SQLITE_DONE)
- {
- FREE(del);
- FREENONNULL(keyenc);
- LOG_SQLITE(dbh->dbh,
- LOG_ERROR, "delete");
- sqlite3_finalize(stmt);
+ if (sqlite3_step (stmt) != SQLITE_DONE)
+ {
+ FREE (del);
+ FREENONNULL (keyenc);
+ LOG_SQLITE (dbh->dbh, LOG_ERROR, "delete");
+ sqlite3_finalize (stmt);
- return SYSERR;
- }
- sqlite3_finalize(stmt);
- FREE(del);
- FREENONNULL(keyenc);
+ return SYSERR;
+ }
+ sqlite3_finalize (stmt);
+ FREE (del);
+ FREENONNULL (keyenc);
return OK;
}
@@ -612,9 +612,11 @@
* @brief Close a handle to a Key/Value-Table
* @param kv the handle to close
*/
-static void closeTable(KVHandle *kv) {
- FREE(kv->table);
- FREE(kv->db);
+static void
+closeTable (KVHandle * kv)
+{
+ FREE (kv->table);
+ FREE (kv->db);
}
/**
@@ -622,43 +624,45 @@
* @param the handle to the table
* @return OK on success, SYSERR otherwise
*/
-static int dropTable(KVHandle *kv)
+static int
+dropTable (KVHandle * kv)
{
sqlite3_stmt *stmt;
sqliteHandle *dbh;
- char * drop;
+ char *drop;
- dbh = getDBHandle(kv->db);
+ dbh = getDBHandle (kv->db);
if (dbh == NULL)
return SYSERR;
- drop = MALLOC(12 + strlen(kv->table));
- sprintf(drop, "DROP TABLE %s", kv->table);
- sq_prepare(dbh, drop, &stmt);
- if (sqlite3_step(stmt) != SQLITE_DONE) {
- FREE(drop);
- LOG_SQLITE(dbh->dbh,
- LOG_ERROR, "drop");
- sqlite3_finalize(stmt);
- return SYSERR;
- }
- sqlite3_finalize(stmt);
- FREE(drop);
- closeTable(kv);
+ drop = MALLOC (12 + strlen (kv->table));
+ sprintf (drop, "DROP TABLE %s", kv->table);
+ sq_prepare (dbh, drop, &stmt);
+ if (sqlite3_step (stmt) != SQLITE_DONE)
+ {
+ FREE (drop);
+ LOG_SQLITE (dbh->dbh, LOG_ERROR, "drop");
+ sqlite3_finalize (stmt);
+ return SYSERR;
+ }
+ sqlite3_finalize (stmt);
+ FREE (drop);
+ closeTable (kv);
return OK;
}
KVstore_ServiceAPI *
-provide_module_kvstore_sqlite(CoreAPIForApplication * capi) {
+provide_module_kvstore_sqlite (CoreAPIForApplication * capi)
+{
static KVstore_ServiceAPI api;
ectx = capi->ectx;
#if DEBUG_SQLITE
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "KV-SQLite: initializing database\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "KV-SQLite: initializing database\n");
#endif
- lock = MUTEX_CREATE(NO);
+ lock = MUTEX_CREATE (NO);
coreAPI = capi;
api.closeTable = &closeTable;
api.del = &del;
@@ -673,20 +677,22 @@
/**
* Shutdown the module.
*/
-void release_module_kvstore_sqlite() {
+void
+release_module_kvstore_sqlite ()
+{
unsigned int idx;
for (idx = 0; idx < databases; idx++)
- close_database(dbs[idx]);
- GROW(dbs, databases, 0);
+ close_database (dbs[idx]);
+ GROW (dbs, databases, 0);
#if DEBUG_SQLITE
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite KVStore: database shutdown\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "SQLite KVStore: database shutdown\n");
#endif
- MUTEX_DESTROY(lock);
+ MUTEX_DESTROY (lock);
coreAPI = NULL;
}
Modified: GNUnet/src/applications/kvstore_sqlite/kv_sqlitetest.c
===================================================================
--- GNUnet/src/applications/kvstore_sqlite/kv_sqlitetest.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/kvstore_sqlite/kv_sqlitetest.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -37,66 +37,69 @@
/**
* Add testcode here!
*/
-static int test(KVstore_ServiceAPI * api) {
+static int
+test (KVstore_ServiceAPI * api)
+{
KVHandle *kv;
HashCode512 k, v;
HashCode512 *r;
cron_t timeStmp;
- kv = api->getTable("TEST", "KV");
- ASSERT(kv != NULL);
+ kv = api->getTable ("TEST", "KV");
+ ASSERT (kv != NULL);
- timeStmp = get_time();
- ASSERT(api->put(kv, (void *) &k, sizeof(k), (void *) &v, sizeof(v),
- timeStmp) == OK);
+ timeStmp = get_time ();
+ ASSERT (api->put (kv, (void *) &k, sizeof (k), (void *) &v, sizeof (v),
+ timeStmp) == OK);
- r = api->get(kv, (void *) &k, sizeof(k), 0, 0, NULL, NULL);
- ASSERT(r != NULL);
- ASSERT(memcmp(&v, r, sizeof(v)) == 0);
- FREE(r);
+ r = api->get (kv, (void *) &k, sizeof (k), 0, 0, NULL, NULL);
+ ASSERT (r != NULL);
+ ASSERT (memcmp (&v, r, sizeof (v)) == 0);
+ FREE (r);
- ASSERT(api->del(kv, (void *) &k, sizeof(k), 0) == OK);
+ ASSERT (api->del (kv, (void *) &k, sizeof (k), 0) == OK);
- ASSERT(api->get(kv, (void *) &k, sizeof(k), 0, 0, NULL, NULL) == NULL);
+ ASSERT (api->get (kv, (void *) &k, sizeof (k), 0, 0, NULL, NULL) == NULL);
- ASSERT(api->dropTable(kv) == OK);
+ ASSERT (api->dropTable (kv) == OK);
- api->dropDatabase("TEST");
+ api->dropDatabase ("TEST");
return OK;
- FAILURE:
- api->dropDatabase("TEST");
+FAILURE:
+ api->dropDatabase ("TEST");
return SYSERR;
}
#define TEST_DB "/tmp/GNUnet_sqstore_test/"
-int main(int argc, char *argv[]) {
- KVstore_ServiceAPI * api;
+int
+main (int argc, char *argv[])
+{
+ KVstore_ServiceAPI *api;
int ok;
- struct GC_Configuration * cfg;
- struct CronManager * cron;
+ struct GC_Configuration *cfg;
+ struct CronManager *cron;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- cron = cron_create(NULL);
- initCore(NULL,
- cfg,
- cron,
- NULL);
- api = requestService("kvstore_sqlite");
- if (api != NULL) {
- ok = test(api);
- releaseService(api);
- } else
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ cron = cron_create (NULL);
+ initCore (NULL, cfg, cron, NULL);
+ api = requestService ("kvstore_sqlite");
+ if (api != NULL)
+ {
+ ok = test (api);
+ releaseService (api);
+ }
+ else
ok = SYSERR;
- doneCore();
+ doneCore ();
if (ok == SYSERR)
return 1;
return 0;
Modified: GNUnet/src/applications/pingpong/pingpong.c
===================================================================
--- GNUnet/src/applications/pingpong/pingpong.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/pingpong/pingpong.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -49,7 +49,8 @@
* us a hello and then an arbitrary PONG reply (adversary
* must at least be able to sniff our outbound traffic).
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -73,28 +74,29 @@
#define MAX_PING_PONG 256
-typedef struct {
+typedef struct
+{
PeerIdentity receiverIdentity;
int challenge;
int plaintext;
CronJob method;
- void * data;
+ void *data;
TIME_T sendTime;
} PingPongEntry;
-static PingPongEntry * pingPongs;
+static PingPongEntry *pingPongs;
-static struct MUTEX * pingPongLock;
+static struct MUTEX *pingPongLock;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static Transport_ServiceAPI * transport;
+static Transport_ServiceAPI *transport;
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
static int stat_encryptedPongReceived;
@@ -117,65 +119,61 @@
/**
* We received a PING message, send the PONG reply.
*/
-static int pingReceived(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg) {
- const P2P_pingpong_MESSAGE * pmsg;
+static int
+pingReceived (const PeerIdentity * sender, const MESSAGE_HEADER * msg)
+{
+ const P2P_pingpong_MESSAGE *pmsg;
P2P_pingpong_MESSAGE pong;
- if (ntohs(msg->size) != sizeof(P2P_pingpong_MESSAGE) ) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER | GE_DEVELOPER,
- _("Received malformed `%s' message. Dropping.\n"),
- "ping");
- return SYSERR;
- }
+ if (ntohs (msg->size) != sizeof (P2P_pingpong_MESSAGE))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER | GE_DEVELOPER,
+ _("Received malformed `%s' message. Dropping.\n"), "ping");
+ return SYSERR;
+ }
if (stats != NULL)
- stats->change(stat_pingReceived, 1);
+ stats->change (stat_pingReceived, 1);
pmsg = (const P2P_pingpong_MESSAGE *) msg;
- if (0 != memcmp(coreAPI->myIdentity,
- &pmsg->receiver,
- sizeof(PeerIdentity))) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_ADMIN,
- _("Received ping for another peer. Dropping.\n"));
- return SYSERR; /* not for us */
- }
+ if (0 != memcmp (coreAPI->myIdentity,
+ &pmsg->receiver, sizeof (PeerIdentity)))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_ADMIN,
+ _("Received ping for another peer. Dropping.\n"));
+ return SYSERR; /* not for us */
+ }
#if DEBUG_PINGPONG
EncName enc;
- hash2enc(&sender->hashPubKey,
- &enc);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received ping from peer %s.\n",
- &enc);
+ hash2enc (&sender->hashPubKey, &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received ping from peer %s.\n", &enc);
#endif
pong = *pmsg;
- pong.header.type = htons(p2p_PROTO_PONG);
+ pong.header.type = htons (p2p_PROTO_PONG);
if (stats != NULL)
- stats->change(stat_pingReceived, 1);
- coreAPI->unicast(sender,
- &pong.header,
- EXTREME_PRIORITY,
- 0); /* send now! */
+ stats->change (stat_pingReceived, 1);
+ coreAPI->unicast (sender, &pong.header, EXTREME_PRIORITY, 0); /* send now! */
if (stats != NULL)
- stats->change(stat_pongSent, 1);
+ stats->change (stat_pongSent, 1);
return OK;
}
-static int sendPlaintext(const PeerIdentity * peer,
- const P2P_pingpong_MESSAGE * msg) {
- TSession * mytsession;
+static int
+sendPlaintext (const PeerIdentity * peer, const P2P_pingpong_MESSAGE * msg)
+{
+ TSession *mytsession;
int ret;
- mytsession = transport->connectFreely(peer, YES);
+ mytsession = transport->connectFreely (peer, YES);
if (mytsession == NULL)
return SYSERR;
- ret = coreAPI->sendPlaintext(mytsession,
- (char*)msg,
- sizeof(P2P_pingpong_MESSAGE));
- transport->disconnect(mytsession);
+ ret = coreAPI->sendPlaintext (mytsession,
+ (char *) msg, sizeof (P2P_pingpong_MESSAGE));
+ transport->disconnect (mytsession);
return ret;
}
@@ -183,198 +181,191 @@
* We received a PING message, send the PONG reply and notify the
* connection module that the session is still life.
*/
-static int plaintextPingReceived(const PeerIdentity * sender,
- const MESSAGE_HEADER * hmsg,
- TSession * tsession) {
+static int
+plaintextPingReceived (const PeerIdentity * sender,
+ const MESSAGE_HEADER * hmsg, TSession * tsession)
+{
#if DEBUG_PINGPONG
EncName enc;
#endif
- const P2P_pingpong_MESSAGE * pmsg;
+ const P2P_pingpong_MESSAGE *pmsg;
P2P_pingpong_MESSAGE pong;
int ret;
- if (ntohs(hmsg->size) != sizeof(P2P_pingpong_MESSAGE) ) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER | GE_DEVELOPER,
- _("Received malformed `%s' message. Dropping.\n"),
- "ping");
- GE_BREAK_OP(NULL, 0);
- return SYSERR;
- }
+ if (ntohs (hmsg->size) != sizeof (P2P_pingpong_MESSAGE))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER | GE_DEVELOPER,
+ _("Received malformed `%s' message. Dropping.\n"), "ping");
+ GE_BREAK_OP (NULL, 0);
+ return SYSERR;
+ }
pmsg = (const P2P_pingpong_MESSAGE *) hmsg;
- if (0 != memcmp(coreAPI->myIdentity,
- &pmsg->receiver,
- sizeof(PeerIdentity))) {
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_ADMIN,
- _("Received PING not destined for us!\n"));
- GE_BREAK_OP(NULL, 0);
- return SYSERR; /* not for us */
- }
+ if (0 != memcmp (coreAPI->myIdentity,
+ &pmsg->receiver, sizeof (PeerIdentity)))
+ {
+ GE_LOG (ectx,
+ GE_INFO | GE_REQUEST | GE_ADMIN,
+ _("Received PING not destined for us!\n"));
+ GE_BREAK_OP (NULL, 0);
+ return SYSERR; /* not for us */
+ }
#if DEBUG_PINGPONG
- hash2enc(&sender->hashPubKey,
- &enc);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received plaintext ping from peer %s.\n",
- &enc);
+ hash2enc (&sender->hashPubKey, &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received plaintext ping from peer %s.\n", &enc);
#endif
pong = *pmsg;
- pong.header.type = htons(p2p_PROTO_PONG);
+ pong.header.type = htons (p2p_PROTO_PONG);
/* allow using a different transport for sending the reply, the
transport may have been uni-directional! */
ret = SYSERR;
if (tsession != NULL)
- ret = coreAPI->sendPlaintext(tsession,
- (char*) &pong,
- sizeof(P2P_pingpong_MESSAGE));
+ ret = coreAPI->sendPlaintext (tsession,
+ (char *) &pong,
+ sizeof (P2P_pingpong_MESSAGE));
if (ret != OK)
- ret = sendPlaintext(sender, &pong);
- if (ret == OK) {
- if (stats != NULL)
- stats->change(stat_plaintextPongSent, 1);
- } else {
- if (stats != NULL)
- stats->change(stat_plaintextPongFailed, 1);
- }
+ ret = sendPlaintext (sender, &pong);
+ if (ret == OK)
+ {
+ if (stats != NULL)
+ stats->change (stat_plaintextPongSent, 1);
+ }
+ else
+ {
+ if (stats != NULL)
+ stats->change (stat_plaintextPongFailed, 1);
+ }
return ret;
}
/**
* Handler for a pong.
*/
-static int pongReceived(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg) {
+static int
+pongReceived (const PeerIdentity * sender, const MESSAGE_HEADER * msg)
+{
int i;
- const P2P_pingpong_MESSAGE * pmsg;
- PingPongEntry * entry;
+ const P2P_pingpong_MESSAGE *pmsg;
+ PingPongEntry *entry;
int matched;
#if DEBUG_PINGPONG
EncName enc;
#endif
pmsg = (const P2P_pingpong_MESSAGE *) msg;
- if ( (ntohs(msg->size) != sizeof(P2P_pingpong_MESSAGE)) ||
- (0 != memcmp(sender,
- &pmsg->receiver,
- sizeof(PeerIdentity))) ) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER | GE_DEVELOPER,
- _("Received malformed `%s' message. Dropping.\n"),
- "pong");
- return SYSERR; /* bad pong */
- }
+ if ((ntohs (msg->size) != sizeof (P2P_pingpong_MESSAGE)) ||
+ (0 != memcmp (sender, &pmsg->receiver, sizeof (PeerIdentity))))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER | GE_DEVELOPER,
+ _("Received malformed `%s' message. Dropping.\n"), "pong");
+ return SYSERR; /* bad pong */
+ }
#if DEBUG_PINGPONG
- hash2enc(&sender->hashPubKey,
- &enc);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received PONG from `%s'.\n",
- &enc);
+ hash2enc (&sender->hashPubKey, &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received PONG from `%s'.\n", &enc);
#endif
matched = 0;
if (stats != NULL)
- stats->change(stat_encryptedPongReceived, 1);
- MUTEX_LOCK(pingPongLock);
- for (i=0;i<MAX_PING_PONG;i++) {
- entry = &pingPongs[i];
- if ( ((int)ntohl(pmsg->challenge) == entry->challenge) &&
- (0 == memcmp(sender,
- &entry->receiverIdentity,
- sizeof(PeerIdentity))) &&
- (entry->plaintext == NO) ) {
- entry->method(entry->data);
- /* entry was valid for one time only */
- memset(entry,
- 0,
- sizeof(PingPongEntry));
- matched++;
+ stats->change (stat_encryptedPongReceived, 1);
+ MUTEX_LOCK (pingPongLock);
+ for (i = 0; i < MAX_PING_PONG; i++)
+ {
+ entry = &pingPongs[i];
+ if (((int) ntohl (pmsg->challenge) == entry->challenge) &&
+ (0 == memcmp (sender,
+ &entry->receiverIdentity,
+ sizeof (PeerIdentity))) && (entry->plaintext == NO))
+ {
+ entry->method (entry->data);
+ /* entry was valid for one time only */
+ memset (entry, 0, sizeof (PingPongEntry));
+ matched++;
+ }
}
- }
- MUTEX_UNLOCK(pingPongLock);
+ MUTEX_UNLOCK (pingPongLock);
#if DEBUG_PINGPONG
- hash2enc(&sender->hashPubKey,
- &enc);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received PONG from `%s' matched %u peers.\n",
- &enc,
- matched);
+ hash2enc (&sender->hashPubKey, &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received PONG from `%s' matched %u peers.\n", &enc, matched);
#endif
- if (matched == 0) {
+ if (matched == 0)
+ {
#if DEBUG_PINGPONG
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_ADMIN,
- _("Could not match PONG against any PING. "
- "Try increasing MAX_PING_PONG constant.\n"));
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_ADMIN,
+ _("Could not match PONG against any PING. "
+ "Try increasing MAX_PING_PONG constant.\n"));
#endif
- }
+ }
return OK;
}
/**
* Handler for a pong.
*/
-static int plaintextPongReceived(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg,
- TSession * session) {
+static int
+plaintextPongReceived (const PeerIdentity * sender,
+ const MESSAGE_HEADER * msg, TSession * session)
+{
int i;
- const P2P_pingpong_MESSAGE * pmsg;
- PingPongEntry * entry;
+ const P2P_pingpong_MESSAGE *pmsg;
+ PingPongEntry *entry;
int matched;
#if DEBUG_PINGPONG
EncName enc;
#endif
pmsg = (const P2P_pingpong_MESSAGE *) msg;
- if ( (ntohs(msg->size) != sizeof(P2P_pingpong_MESSAGE)) ||
- (0 != memcmp(sender,
- &pmsg->receiver,
- sizeof(PeerIdentity)))) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER | GE_DEVELOPER,
- _("Received malformed `%s' message. Dropping.\n"),
- "pong");
- return SYSERR; /* bad pong */
- }
+ if ((ntohs (msg->size) != sizeof (P2P_pingpong_MESSAGE)) ||
+ (0 != memcmp (sender, &pmsg->receiver, sizeof (PeerIdentity))))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER | GE_DEVELOPER,
+ _("Received malformed `%s' message. Dropping.\n"), "pong");
+ return SYSERR; /* bad pong */
+ }
if (stats != NULL)
- stats->change(stat_plaintextPongReceived, 1);
+ stats->change (stat_plaintextPongReceived, 1);
matched = 0;
- MUTEX_LOCK(pingPongLock);
- for (i=0;i<MAX_PING_PONG;i++) {
- entry = &pingPongs[i];
- if ( ((int)ntohl(pmsg->challenge) == entry->challenge) &&
- (0 == memcmp(sender,
- &entry->receiverIdentity,
- sizeof(PeerIdentity))) &&
- (entry->plaintext == YES) ) {
- entry->method(entry->data);
- /* entry was valid for one time only */
- memset(entry,
- 0,
- sizeof(PingPongEntry));
- matched++;
+ MUTEX_LOCK (pingPongLock);
+ for (i = 0; i < MAX_PING_PONG; i++)
+ {
+ entry = &pingPongs[i];
+ if (((int) ntohl (pmsg->challenge) == entry->challenge) &&
+ (0 == memcmp (sender,
+ &entry->receiverIdentity,
+ sizeof (PeerIdentity))) && (entry->plaintext == YES))
+ {
+ entry->method (entry->data);
+ /* entry was valid for one time only */
+ memset (entry, 0, sizeof (PingPongEntry));
+ matched++;
+ }
}
- }
- MUTEX_UNLOCK(pingPongLock);
+ MUTEX_UNLOCK (pingPongLock);
#if DEBUG_PINGPONG
- hash2enc(&sender->hashPubKey,
- &enc);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received plaintext PONG from `%s' matched %u peers.\n",
- &enc,
- matched);
+ hash2enc (&sender->hashPubKey, &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received plaintext PONG from `%s' matched %u peers.\n",
+ &enc, matched);
#endif
- if (matched == 0) {
+ if (matched == 0)
+ {
#if DEBUG_PINGPONG
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_ADMIN,
- _("Could not match PONG against any PING. "
- "Try increasing MAX_PING_PONG constant.\n"));
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_ADMIN,
+ _("Could not match PONG against any PING. "
+ "Try increasing MAX_PING_PONG constant.\n"));
#endif
- }
+ }
return OK;
}
@@ -391,51 +382,51 @@
* @returns NULL on error, otherwise the PING message
*/
static MESSAGE_HEADER *
-createPing(const PeerIdentity * receiver,
- CronJob method,
- void * data,
- int plaintext,
- int challenge) {
+createPing (const PeerIdentity * receiver,
+ CronJob method, void *data, int plaintext, int challenge)
+{
int i;
int j;
TIME_T min;
- PingPongEntry * entry;
+ PingPongEntry *entry;
TIME_T now;
- P2P_pingpong_MESSAGE * pmsg;
+ P2P_pingpong_MESSAGE *pmsg;
- MUTEX_LOCK(pingPongLock);
- now = TIME(&min); /* set both, tricky... */
+ MUTEX_LOCK (pingPongLock);
+ now = TIME (&min); /* set both, tricky... */
j = -1;
- for (i=0;i<MAX_PING_PONG;i++)
- if (min > pingPongs[i].sendTime) {
- min = pingPongs[i].sendTime;
- j = i;
+ for (i = 0; i < MAX_PING_PONG; i++)
+ if (min > pingPongs[i].sendTime)
+ {
+ min = pingPongs[i].sendTime;
+ j = i;
+ }
+ if (j == -1)
+ { /* all send this second!? */
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_ADMIN,
+ _("Cannot create PING, table full. "
+ "Try increasing MAX_PING_PONG.\n"));
+ MUTEX_UNLOCK (pingPongLock);
+ return NULL;
}
- if (j == -1) { /* all send this second!? */
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_ADMIN,
- _("Cannot create PING, table full. "
- "Try increasing MAX_PING_PONG.\n"));
- MUTEX_UNLOCK(pingPongLock);
- return NULL;
- }
entry = &pingPongs[j];
entry->sendTime = now;
entry->method = method;
entry->plaintext = plaintext;
- FREENONNULL(entry->data);
+ FREENONNULL (entry->data);
entry->data = data;
entry->receiverIdentity = *receiver;
- pmsg = MALLOC(sizeof(P2P_pingpong_MESSAGE));
- pmsg->header.size = htons(sizeof(P2P_pingpong_MESSAGE));
- pmsg->header.type = htons(p2p_PROTO_PING);
+ pmsg = MALLOC (sizeof (P2P_pingpong_MESSAGE));
+ pmsg->header.size = htons (sizeof (P2P_pingpong_MESSAGE));
+ pmsg->header.type = htons (p2p_PROTO_PING);
pmsg->receiver = *receiver;
entry->challenge = challenge;
- pmsg->challenge = htonl(challenge);
- MUTEX_UNLOCK(pingPongLock);
+ pmsg->challenge = htonl (challenge);
+ MUTEX_UNLOCK (pingPongLock);
if (stats != NULL)
- stats->change(stat_pingCreated, 1);
+ stats->change (stat_pingCreated, 1);
return &pmsg->header;
}
@@ -448,37 +439,32 @@
* @param data an argument to pass to the method.
* @returns OK on success, SYSERR on error
*/
-static int initiatePing(const PeerIdentity * receiver,
- CronJob method,
- void * data,
- int usePlaintext,
- int challenge) {
- MESSAGE_HEADER * pmsg;
+static int
+initiatePing (const PeerIdentity * receiver,
+ CronJob method, void *data, int usePlaintext, int challenge)
+{
+ MESSAGE_HEADER *pmsg;
- pmsg = createPing(receiver,
- method,
- data,
- usePlaintext,
- challenge);
+ pmsg = createPing (receiver, method, data, usePlaintext, challenge);
if (pmsg == NULL)
return SYSERR;
- if (usePlaintext == YES) {
- if (OK != sendPlaintext(receiver,
- (const P2P_pingpong_MESSAGE*) pmsg)) {
- FREE(pmsg);
- return SYSERR;
+ if (usePlaintext == YES)
+ {
+ if (OK != sendPlaintext (receiver, (const P2P_pingpong_MESSAGE *) pmsg))
+ {
+ FREE (pmsg);
+ return SYSERR;
+ }
+ if (stats != NULL)
+ stats->change (stat_plaintextPingSent, 1);
}
- if (stats != NULL)
- stats->change(stat_plaintextPingSent, 1);
- } else {
- coreAPI->unicast(receiver,
- pmsg,
- EXTREME_PRIORITY,
- 0);
- if (stats != NULL)
- stats->change(stat_ciphertextPingSent, 1);
- }
- FREE(pmsg);
+ else
+ {
+ coreAPI->unicast (receiver, pmsg, EXTREME_PRIORITY, 0);
+ if (stats != NULL)
+ stats->change (stat_ciphertextPingSent, 1);
+ }
+ FREE (pmsg);
return OK;
}
@@ -486,94 +472,92 @@
* Initialize the pingpong module.
*/
Pingpong_ServiceAPI *
-provide_module_pingpong(CoreAPIForApplication * capi) {
+provide_module_pingpong (CoreAPIForApplication * capi)
+{
static Pingpong_ServiceAPI ret;
ectx = capi->ectx;
- GE_ASSERT(ectx,
- sizeof(P2P_pingpong_MESSAGE) == 72);
+ GE_ASSERT (ectx, sizeof (P2P_pingpong_MESSAGE) == 72);
coreAPI = capi;
- identity = capi->requestService("identity");
- if (identity == NULL) {
- GE_BREAK(capi->ectx, 0);
- return NULL;
- }
- transport = capi->requestService("transport");
- if (transport == NULL) {
- GE_BREAK(capi->ectx, 0);
- capi->releaseService(identity);
- return NULL;
- }
- stats = capi->requestService("stats");
- if (stats != NULL) {
- stat_encryptedPongReceived
- = stats->create(gettext_noop("# encrypted PONG messages received"));
- stat_plaintextPongReceived
- = stats->create(gettext_noop("# plaintext PONG messages received"));
- stat_pingReceived
- = stats->create(gettext_noop("# encrypted PING messages received"));
- stat_pingCreated
- = stats->create(gettext_noop("# PING messages created"));
- stat_pongSent
- = stats->create(gettext_noop("# encrypted PONG messages sent"));
- stat_plaintextPingSent
- = stats->create(gettext_noop("# plaintext PING messages sent"));
- stat_ciphertextPingSent
- = stats->create(gettext_noop("# encrypted PING messages sent"));
- stat_plaintextPongSent
- = stats->create(gettext_noop("# plaintext PONG messages sent"));
- stat_plaintextPongFailed
- = stats->create(gettext_noop("# plaintext PONG transmissions failed"));
+ identity = capi->requestService ("identity");
+ if (identity == NULL)
+ {
+ GE_BREAK (capi->ectx, 0);
+ return NULL;
+ }
+ transport = capi->requestService ("transport");
+ if (transport == NULL)
+ {
+ GE_BREAK (capi->ectx, 0);
+ capi->releaseService (identity);
+ return NULL;
+ }
+ stats = capi->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_encryptedPongReceived
+ = stats->create (gettext_noop ("# encrypted PONG messages received"));
+ stat_plaintextPongReceived
+ = stats->create (gettext_noop ("# plaintext PONG messages received"));
+ stat_pingReceived
+ = stats->create (gettext_noop ("# encrypted PING messages received"));
+ stat_pingCreated
+ = stats->create (gettext_noop ("# PING messages created"));
+ stat_pongSent
+ = stats->create (gettext_noop ("# encrypted PONG messages sent"));
+ stat_plaintextPingSent
+ = stats->create (gettext_noop ("# plaintext PING messages sent"));
+ stat_ciphertextPingSent
+ = stats->create (gettext_noop ("# encrypted PING messages sent"));
+ stat_plaintextPongSent
+ = stats->create (gettext_noop ("# plaintext PONG messages sent"));
+ stat_plaintextPongFailed
+ =
+ stats->
+ create (gettext_noop ("# plaintext PONG transmissions failed"));
- }
- pingPongLock = capi->getConnectionModuleLock();
- pingPongs = (PingPongEntry*) MALLOC(sizeof(PingPongEntry)*MAX_PING_PONG);
- memset(pingPongs,
- 0,
- sizeof(PingPongEntry)*MAX_PING_PONG);
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- _("`%s' registering handlers %d %d (plaintext and ciphertext)\n"),
- "pingpong",
- p2p_PROTO_PING,
- p2p_PROTO_PONG);
- capi->registerHandler(p2p_PROTO_PING,
- &pingReceived);
- capi->registerHandler(p2p_PROTO_PONG,
- &pongReceived);
- capi->registerPlaintextHandler(p2p_PROTO_PING,
- &plaintextPingReceived);
- capi->registerPlaintextHandler(p2p_PROTO_PONG,
- &plaintextPongReceived);
+ }
+ pingPongLock = capi->getConnectionModuleLock ();
+ pingPongs =
+ (PingPongEntry *) MALLOC (sizeof (PingPongEntry) * MAX_PING_PONG);
+ memset (pingPongs, 0, sizeof (PingPongEntry) * MAX_PING_PONG);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ _("`%s' registering handlers %d %d (plaintext and ciphertext)\n"),
+ "pingpong", p2p_PROTO_PING, p2p_PROTO_PONG);
+ capi->registerHandler (p2p_PROTO_PING, &pingReceived);
+ capi->registerHandler (p2p_PROTO_PONG, &pongReceived);
+ capi->registerPlaintextHandler (p2p_PROTO_PING, &plaintextPingReceived);
+ capi->registerPlaintextHandler (p2p_PROTO_PONG, &plaintextPongReceived);
ret.ping = &initiatePing;
ret.pingUser = &createPing;
- ret.ping_size = sizeof(P2P_pingpong_MESSAGE);
+ ret.ping_size = sizeof (P2P_pingpong_MESSAGE);
return &ret;
}
/**
* Shutdown the pingpong module.
*/
-int release_module_pingpong() {
+int
+release_module_pingpong ()
+{
int i;
- coreAPI->releaseService(stats);
+ coreAPI->releaseService (stats);
stats = NULL;
- coreAPI->releaseService(transport);
+ coreAPI->releaseService (transport);
transport = NULL;
- coreAPI->releaseService(identity);
+ coreAPI->releaseService (identity);
identity = NULL;
- for (i=0;i<MAX_PING_PONG;i++)
- FREENONNULL(pingPongs[i].data);
- FREE(pingPongs);
- coreAPI->unregisterHandler(p2p_PROTO_PING,
- &pingReceived);
- coreAPI->unregisterHandler(p2p_PROTO_PONG,
- &pongReceived);
- coreAPI->unregisterPlaintextHandler(p2p_PROTO_PING,
- &plaintextPingReceived);
- coreAPI->unregisterPlaintextHandler(p2p_PROTO_PONG,
- &plaintextPongReceived);
+ for (i = 0; i < MAX_PING_PONG; i++)
+ FREENONNULL (pingPongs[i].data);
+ FREE (pingPongs);
+ coreAPI->unregisterHandler (p2p_PROTO_PING, &pingReceived);
+ coreAPI->unregisterHandler (p2p_PROTO_PONG, &pongReceived);
+ coreAPI->unregisterPlaintextHandler (p2p_PROTO_PING,
+ &plaintextPingReceived);
+ coreAPI->unregisterPlaintextHandler (p2p_PROTO_PONG,
+ &plaintextPongReceived);
coreAPI = NULL;
return OK;
}
Modified: GNUnet/src/applications/rpc/parameters.c
===================================================================
--- GNUnet/src/applications/rpc/parameters.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/rpc/parameters.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -34,10 +34,11 @@
* A parameter to/from an RPC call. These (and nothing else) are stored in
* the Vector of the RPC_Param structure.
*/
-typedef struct {
+typedef struct
+{
unsigned int dataLength;
- char * name;
- void * data;
+ char *name;
+ void *data;
} Parameter;
/**
@@ -45,8 +46,10 @@
*
* @return An empty RPC_Param structure
*/
-RPC_Param * RPC_paramNew() {
- return vectorNew(4);
+RPC_Param *
+RPC_paramNew ()
+{
+ return vectorNew (4);
}
/**
@@ -56,28 +59,32 @@
*
* @param param The RPC parameter structure to be freed
*/
-void RPC_paramFree(RPC_Param *param) {
+void
+RPC_paramFree (RPC_Param * param)
+{
if (param == NULL)
return;
- while (vectorSize(param) > 0) {
- Parameter * p = vectorRemoveLast (param);
- FREE(p->name);
- FREE(p->data);
- FREE(p);
- }
- vectorFree(param);
+ while (vectorSize (param) > 0)
+ {
+ Parameter *p = vectorRemoveLast (param);
+ FREE (p->name);
+ FREE (p->data);
+ FREE (p);
+ }
+ vectorFree (param);
}
/**
* Serialize the param array. target must point to at least
* RPC_paramSize(param) bytes of memory.
*/
-void RPC_paramSerialize(RPC_Param * param,
- char * target) {
+void
+RPC_paramSerialize (RPC_Param * param, char *target)
+{
int i;
- const char * paramName;
+ const char *paramName;
unsigned int dataLength;
- void * paramValue;
+ void *paramValue;
size_t pos;
if (param == NULL)
@@ -86,96 +93,89 @@
return;
pos = 0;
dataLength = 0;
- for (i = 0; i < RPC_paramCount(param); i++) {
- paramName = RPC_paramName(param, i);
- paramValue = NULL;
- RPC_paramValueByPosition(param,
- i,
- &dataLength,
- ¶mValue);
- memcpy(&target[pos],
- paramName,
- strlen(paramName)+1);
- pos += strlen(paramName)+1;
- *(unsigned int*) &target[pos] = htonl(dataLength);
- pos += sizeof(unsigned int);
- memcpy(&target[pos],
- paramValue,
- dataLength);
- pos += dataLength;
- }
+ for (i = 0; i < RPC_paramCount (param); i++)
+ {
+ paramName = RPC_paramName (param, i);
+ paramValue = NULL;
+ RPC_paramValueByPosition (param, i, &dataLength, ¶mValue);
+ memcpy (&target[pos], paramName, strlen (paramName) + 1);
+ pos += strlen (paramName) + 1;
+ *(unsigned int *) &target[pos] = htonl (dataLength);
+ pos += sizeof (unsigned int);
+ memcpy (&target[pos], paramValue, dataLength);
+ pos += dataLength;
+ }
}
/**
* Deserialize parameters from buffer.
*/
-RPC_Param * RPC_paramDeserialize(char * buffer,
- size_t size) {
- RPC_Param * ret;
+RPC_Param *
+RPC_paramDeserialize (char *buffer, size_t size)
+{
+ RPC_Param *ret;
size_t pos;
size_t xpos;
unsigned int dataLength;
if (buffer == NULL)
return NULL;
- ret = RPC_paramNew();
+ ret = RPC_paramNew ();
pos = 0;
- while (pos < size) {
- xpos = pos;
- while ( (pos < size) &&
- (buffer[pos] != '\0') )
+ while (pos < size)
+ {
+ xpos = pos;
+ while ((pos < size) && (buffer[pos] != '\0'))
+ pos++;
pos++;
- pos++;
- if (pos + sizeof(unsigned int) > size) {
- RPC_paramFree(ret);
- return NULL;
+ if (pos + sizeof (unsigned int) > size)
+ {
+ RPC_paramFree (ret);
+ return NULL;
+ }
+ dataLength = ntohl (*(unsigned int *) &buffer[pos]);
+ pos += sizeof (unsigned int);
+ if ((pos + dataLength < pos) || (pos + dataLength > size))
+ {
+ RPC_paramFree (ret);
+ return NULL;
+ }
+
+ RPC_paramAdd (ret, &buffer[xpos], dataLength, &buffer[pos]);
+ pos += dataLength;
}
- dataLength = ntohl(*(unsigned int*)&buffer[pos]);
- pos += sizeof(unsigned int);
- if ( (pos + dataLength < pos) ||
- (pos + dataLength > size) ) {
- RPC_paramFree(ret);
- return NULL;
- }
-
- RPC_paramAdd(ret,
- &buffer[xpos],
- dataLength,
- &buffer[pos]);
- pos += dataLength;
- }
return ret;
}
/**
* How many bytes are required to serialize the param array?
*/
-size_t RPC_paramSize(RPC_Param * param) {
+size_t
+RPC_paramSize (RPC_Param * param)
+{
int i;
- const char * paramName;
+ const char *paramName;
unsigned int dataLength;
- void * paramValue;
+ void *paramValue;
size_t pos;
if (param == NULL)
return 0;
pos = 0;
dataLength = 0;
- for (i = 0; i < RPC_paramCount(param); i++) {
- paramName = RPC_paramName(param, i);
- paramValue = NULL;
- RPC_paramValueByPosition(param,
- i,
- &dataLength,
- ¶mValue);
- if (pos + strlen(paramName)+1+sizeof(unsigned int) < pos)
- return 0;
- pos += strlen(paramName)+1;
- pos += sizeof(unsigned int);
- if (pos + dataLength < pos)
- return 0;
- pos += dataLength;
- }
+ for (i = 0; i < RPC_paramCount (param); i++)
+ {
+ paramName = RPC_paramName (param, i);
+ paramValue = NULL;
+ RPC_paramValueByPosition (param, i, &dataLength, ¶mValue);
+ if (pos + strlen (paramName) + 1 + sizeof (unsigned int) < pos)
+ return 0;
+ pos += strlen (paramName) + 1;
+ pos += sizeof (unsigned int);
+ if (pos + dataLength < pos)
+ return 0;
+ pos += dataLength;
+ }
return pos;
}
@@ -186,10 +186,12 @@
* @param param Target RPC parameter structure
* @return The number of parameters
*/
-unsigned int RPC_paramCount(RPC_Param *param) {
+unsigned int
+RPC_paramCount (RPC_Param * param)
+{
if (param == NULL)
return 0;
- return vectorSize(param);
+ return vectorSize (param);
}
@@ -205,24 +207,27 @@
* @param data Value of the parameter
*/
-void RPC_paramAdd(RPC_Param *param,
- const char *name,
- unsigned int dataLength,
- const void *data) {
- Parameter * new;
+void
+RPC_paramAdd (RPC_Param * param,
+ const char *name, unsigned int dataLength, const void *data)
+{
+ Parameter *new;
if (param == NULL)
return;
- new = MALLOC(sizeof (Parameter));
- new->name = STRDUP(name);
+ new = MALLOC (sizeof (Parameter));
+ new->name = STRDUP (name);
new->dataLength = dataLength;
- if (dataLength == 0) {
- new->data = NULL;
- } else {
- new->data = MALLOC(dataLength);
- memcpy(new->data, data, dataLength);
- }
- vectorInsertLast(param, new);
+ if (dataLength == 0)
+ {
+ new->data = NULL;
+ }
+ else
+ {
+ new->data = MALLOC (dataLength);
+ memcpy (new->data, data, dataLength);
+ }
+ vectorInsertLast (param, new);
}
@@ -237,25 +242,27 @@
* @param dataLength Length of the value of the parameter
* @param data Value of the parameter
*/
-void RPC_paramAddDataContainer(RPC_Param *param,
- const char *name,
- const DataContainer * data) {
- Parameter * new;
+void
+RPC_paramAddDataContainer (RPC_Param * param,
+ const char *name, const DataContainer * data)
+{
+ Parameter *new;
if (param == NULL)
return;
- new = MALLOC(sizeof(Parameter));
- new->name = STRDUP(name);
- new->dataLength = ntohl(data->size) - sizeof(DataContainer);
- if (new->dataLength == 0) {
- new->data = NULL;
- } else {
- new->data = MALLOC(new->dataLength);
- memcpy(new->data,
- &data[1],
- new->dataLength);
- }
- vectorInsertLast(param, new);
+ new = MALLOC (sizeof (Parameter));
+ new->name = STRDUP (name);
+ new->dataLength = ntohl (data->size) - sizeof (DataContainer);
+ if (new->dataLength == 0)
+ {
+ new->data = NULL;
+ }
+ else
+ {
+ new->data = MALLOC (new->dataLength);
+ memcpy (new->data, &data[1], new->dataLength);
+ }
+ vectorInsertLast (param, new);
}
/**
@@ -265,13 +272,14 @@
* @param param Target RPC parameter structure
* @return Name of the parameter
*/
-const char * RPC_paramName(RPC_Param *param,
- unsigned int i) {
- Parameter * p;
+const char *
+RPC_paramName (RPC_Param * param, unsigned int i)
+{
+ Parameter *p;
if (param == NULL)
return NULL;
- p = vectorGetAt(param, i);
+ p = vectorGetAt (param, i);
if (p)
return p->name;
else
@@ -286,24 +294,27 @@
* @param value set to the value of the named parameter
* @return SYSERR on error
*/
-int RPC_paramValueByName(RPC_Param *param,
- const char *name,
- unsigned int * dataLength,
- void ** value) {
+int
+RPC_paramValueByName (RPC_Param * param,
+ const char *name,
+ unsigned int *dataLength, void **value)
+{
Parameter *p;
if (param == NULL)
return SYSERR;
p = vectorGetFirst (param);
- while (p != NULL) {
- if (!strcmp (p->name, name)) {
- *value = p->data;
- *dataLength = p->dataLength;
- return OK;
+ while (p != NULL)
+ {
+ if (!strcmp (p->name, name))
+ {
+ *value = p->data;
+ *dataLength = p->dataLength;
+ return OK;
+ }
+ p = vectorGetNext (param);
}
- p = vectorGetNext(param);
- }
-
+
return SYSERR;
}
@@ -314,28 +325,27 @@
* @param value set to the value of the named parameter
* @return SYSERR on error
*/
-DataContainer * RPC_paramDataContainerByName(RPC_Param *param,
- const char *name) {
- Parameter * p;
- DataContainer * ret;
+DataContainer *
+RPC_paramDataContainerByName (RPC_Param * param, const char *name)
+{
+ Parameter *p;
+ DataContainer *ret;
if (param == NULL)
return NULL;
p = vectorGetFirst (param);
- while (p != NULL) {
- if (!strcmp (p->name, name)) {
- ret = MALLOC(sizeof(DataContainer)
- + p->dataLength);
- ret->size = htonl(sizeof(DataContainer)
- + p->dataLength);
- memcpy(&ret[1],
- p->data,
- p->dataLength);
- return ret;
+ while (p != NULL)
+ {
+ if (!strcmp (p->name, name))
+ {
+ ret = MALLOC (sizeof (DataContainer) + p->dataLength);
+ ret->size = htonl (sizeof (DataContainer) + p->dataLength);
+ memcpy (&ret[1], p->data, p->dataLength);
+ return ret;
+ }
+ p = vectorGetNext (param);
}
- p = vectorGetNext(param);
- }
-
+
return NULL;
}
@@ -345,20 +355,22 @@
* @param param Target RPC parameter structure
* @param value set to the value of the parameter
*/
-int RPC_paramValueByPosition(RPC_Param *param,
- unsigned int i,
- unsigned int * dataLength,
- void ** value) {
- Parameter * p;
+int
+RPC_paramValueByPosition (RPC_Param * param,
+ unsigned int i,
+ unsigned int *dataLength, void **value)
+{
+ Parameter *p;
if (param == NULL)
return SYSERR;
- p = vectorGetAt(param, i);
- if (p != NULL) {
- *dataLength = p->dataLength;
- *value = p->data;
- return OK;
- }
+ p = vectorGetAt (param, i);
+ if (p != NULL)
+ {
+ *dataLength = p->dataLength;
+ *value = p->data;
+ return OK;
+ }
return SYSERR;
}
@@ -369,26 +381,22 @@
* @param value set to the value of the parameter
*/
DataContainer *
-RPC_paramDataContainerByPosition(RPC_Param *param,
- unsigned int i) {
- Parameter * p;
- DataContainer * ret;
+RPC_paramDataContainerByPosition (RPC_Param * param, unsigned int i)
+{
+ Parameter *p;
+ DataContainer *ret;
if (param == NULL)
return NULL;
- p = vectorGetAt(param, i);
- if (p != NULL) {
- ret = MALLOC(sizeof(DataContainer)
- + p->dataLength);
- ret->size = htonl(sizeof(DataContainer)
- + p->dataLength);
- memcpy(&ret[1],
- p->data,
- p->dataLength);
- return ret;
- }
+ p = vectorGetAt (param, i);
+ if (p != NULL)
+ {
+ ret = MALLOC (sizeof (DataContainer) + p->dataLength);
+ ret->size = htonl (sizeof (DataContainer) + p->dataLength);
+ memcpy (&ret[1], p->data, p->dataLength);
+ return ret;
+ }
return NULL;
}
/* end of parameters.c */
-
Modified: GNUnet/src/applications/rpc/parameterstest.c
===================================================================
--- GNUnet/src/applications/rpc/parameterstest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/rpc/parameterstest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -26,86 +26,61 @@
#include "gnunet_util.h"
#include "parameters.c"
-int main(int argc, char * argv[]){
- RPC_Param * p;
- void * buf;
+int
+main (int argc, char *argv[])
+{
+ RPC_Param *p;
+ void *buf;
size_t size;
unsigned int len;
- p = RPC_paramNew();
+ p = RPC_paramNew ();
- if (SYSERR != RPC_paramValueByPosition(p,
- 0,
- &len,
- &buf))
+ if (SYSERR != RPC_paramValueByPosition (p, 0, &len, &buf))
return 1;
- if (SYSERR != RPC_paramValueByName(p,
- "not there",
- &len,
- &buf))
+ if (SYSERR != RPC_paramValueByName (p, "not there", &len, &buf))
return 1;
- if (RPC_paramCount(p) != 0)
+ if (RPC_paramCount (p) != 0)
return 1;
- RPC_paramAdd(p,
- "foo",
- 4,
- "bar");
- RPC_paramAdd(p,
- "bar",
- 4,
- "foo");
- if (RPC_paramCount(p) != 2)
+ RPC_paramAdd (p, "foo", 4, "bar");
+ RPC_paramAdd (p, "bar", 4, "foo");
+ if (RPC_paramCount (p) != 2)
return 1;
- if (0 != strcmp(RPC_paramName(p, 0),
- "foo"))
+ if (0 != strcmp (RPC_paramName (p, 0), "foo"))
return 1;
- if (0 != strcmp(RPC_paramName(p, 1),
- "bar"))
+ if (0 != strcmp (RPC_paramName (p, 1), "bar"))
return 1;
- size = RPC_paramSize(p);
- buf = MALLOC(size);
- RPC_paramSerialize(p, buf);
- RPC_paramFree(p);
- p = RPC_paramDeserialize(buf,
- size);
- FREE(buf);
+ size = RPC_paramSize (p);
+ buf = MALLOC (size);
+ RPC_paramSerialize (p, buf);
+ RPC_paramFree (p);
+ p = RPC_paramDeserialize (buf, size);
+ FREE (buf);
if (p == NULL)
return 1;
buf = NULL;
- if (OK != RPC_paramValueByName(p,
- "foo",
- &len,
- &buf))
+ if (OK != RPC_paramValueByName (p, "foo", &len, &buf))
return 1;
- if (strcmp("bar", buf) != 0)
+ if (strcmp ("bar", buf) != 0)
return 1;
buf = NULL;
if (4 != len)
return 1;
- if (OK != RPC_paramValueByPosition(p,
- 1,
- &len,
- &buf))
+ if (OK != RPC_paramValueByPosition (p, 1, &len, &buf))
return 1;
- if (strcmp("foo", buf) != 0)
+ if (strcmp ("foo", buf) != 0)
return 1;
if (4 != len)
return 1;
- if (SYSERR != RPC_paramValueByPosition(p,
- 2,
- &len,
- &buf))
+ if (SYSERR != RPC_paramValueByPosition (p, 2, &len, &buf))
return 1;
- if (SYSERR != RPC_paramValueByName(p,
- "not there",
- &len,
- &buf))
+ if (SYSERR != RPC_paramValueByName (p, "not there", &len, &buf))
return 1;
- RPC_paramFree(p);
+ RPC_paramFree (p);
return 0;
}
Modified: GNUnet/src/applications/rpc/rpc.c
===================================================================
--- GNUnet/src/applications/rpc/rpc.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/rpc/rpc.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -72,24 +72,25 @@
/**
* Access to GNUnet core API.
*/
-static CoreAPIForApplication * coreAPI = NULL;
+static CoreAPIForApplication *coreAPI = NULL;
/**
* A mutex for synchronous access to all module-wide data structures. This
* lock must be held by the thread that accesses any module-wide accessable
* data structures.
*/
-static struct MUTEX * rpcLock;
+static struct MUTEX *rpcLock;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
/* *************** RPC registration ****************** */
/**
* An RPC registered by the local node.
*/
-typedef struct {
- char * name;
+typedef struct
+{
+ char *name;
/**
* Callback for a synchronous RPC. NULL for async RPCs.
*/
@@ -105,7 +106,7 @@
* A set of RegisteredRPC structures, one for each RPC registered by the
* local node.
*/
-static struct Vector * list_of_callbacks;
+static struct Vector *list_of_callbacks;
/**
@@ -115,35 +116,36 @@
* @return OK on success, SYSERR on error
* (typically if a callback of that name is already in use).
*/
-static int RPC_register(const char *name,
- RPC_Function callback) {
- RegisteredRPC * rrpc;
+static int
+RPC_register (const char *name, RPC_Function callback)
+{
+ RegisteredRPC *rrpc;
- GE_ASSERT(ectx, name != NULL);
- GE_ASSERT(ectx, callback != NULL);
+ GE_ASSERT (ectx, name != NULL);
+ GE_ASSERT (ectx, callback != NULL);
MUTEX_LOCK (rpcLock);
- rrpc = vectorGetFirst(list_of_callbacks);
- while (rrpc != NULL) {
- if (0 == strcmp(rrpc->name, name)) {
- MUTEX_UNLOCK (rpcLock);
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("%s::%s - RPC %s:%p could not be registered:"
- " another callback is already using this name (%p)\n"),
- __FILE__, __FUNCTION__,
- name, callback, rrpc->callback);
- return SYSERR;
+ rrpc = vectorGetFirst (list_of_callbacks);
+ while (rrpc != NULL)
+ {
+ if (0 == strcmp (rrpc->name, name))
+ {
+ MUTEX_UNLOCK (rpcLock);
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("%s::%s - RPC %s:%p could not be registered:"
+ " another callback is already using this name (%p)\n"),
+ __FILE__, __FUNCTION__, name, callback, rrpc->callback);
+ return SYSERR;
+ }
+ rrpc = vectorGetNext (list_of_callbacks);
}
- rrpc = vectorGetNext(list_of_callbacks);
- }
- rrpc = MALLOC(sizeof (RegisteredRPC));
- rrpc->name = STRDUP(name);
+ rrpc = MALLOC (sizeof (RegisteredRPC));
+ rrpc->name = STRDUP (name);
rrpc->callback = callback;
rrpc->async_callback = NULL;
- vectorInsertLast(list_of_callbacks, rrpc);
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "%s::%s - Registered RPC %d: %s\n",
- __FILE__, __FUNCTION__,
- vectorSize(list_of_callbacks), name);
+ vectorInsertLast (list_of_callbacks, rrpc);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "%s::%s - Registered RPC %d: %s\n",
+ __FILE__, __FUNCTION__, vectorSize (list_of_callbacks), name);
MUTEX_UNLOCK (rpcLock);
return OK;
}
@@ -155,35 +157,36 @@
* @return OK on success, SYSERR on error
* (typically if a callback of that name is already in use).
*/
-static int RPC_register_async(const char *name,
- ASYNC_RPC_Function callback) {
- RegisteredRPC * rrpc;
+static int
+RPC_register_async (const char *name, ASYNC_RPC_Function callback)
+{
+ RegisteredRPC *rrpc;
- GE_ASSERT(ectx, name != NULL);
- GE_ASSERT(ectx, callback != NULL);
+ GE_ASSERT (ectx, name != NULL);
+ GE_ASSERT (ectx, callback != NULL);
MUTEX_LOCK (rpcLock);
- rrpc = vectorGetFirst(list_of_callbacks);
- while (rrpc != NULL) {
- if (0 == strcmp(rrpc->name, name)) {
- MUTEX_UNLOCK (rpcLock);
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("%s::%s - RPC %s:%p could not be registered:"
- " another callback is already using this name (%p)\n"),
- __FILE__, __FUNCTION__,
- name, callback, rrpc->callback);
- return SYSERR;
+ rrpc = vectorGetFirst (list_of_callbacks);
+ while (rrpc != NULL)
+ {
+ if (0 == strcmp (rrpc->name, name))
+ {
+ MUTEX_UNLOCK (rpcLock);
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("%s::%s - RPC %s:%p could not be registered:"
+ " another callback is already using this name (%p)\n"),
+ __FILE__, __FUNCTION__, name, callback, rrpc->callback);
+ return SYSERR;
+ }
+ rrpc = vectorGetNext (list_of_callbacks);
}
- rrpc = vectorGetNext(list_of_callbacks);
- }
- rrpc = MALLOC(sizeof (RegisteredRPC));
- rrpc->name = STRDUP(name);
+ rrpc = MALLOC (sizeof (RegisteredRPC));
+ rrpc->name = STRDUP (name);
rrpc->callback = NULL;
rrpc->async_callback = callback;
- vectorInsertLast(list_of_callbacks, rrpc);
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "%s::%s - Registered asynchronous RPC %d: %s\n",
- __FILE__, __FUNCTION__,
- vectorSize(list_of_callbacks), name);
+ vectorInsertLast (list_of_callbacks, rrpc);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "%s::%s - Registered asynchronous RPC %d: %s\n",
+ __FILE__, __FUNCTION__, vectorSize (list_of_callbacks), name);
MUTEX_UNLOCK (rpcLock);
return OK;
}
@@ -197,43 +200,43 @@
* (typically if a callback of that name does not exist or is
* bound to a different function).
*/
-static int RPC_unregister(const char *name,
- RPC_Function callback) {
- RegisteredRPC * rrpc;
+static int
+RPC_unregister (const char *name, RPC_Function callback)
+{
+ RegisteredRPC *rrpc;
- GE_ASSERT(ectx, name != NULL);
- MUTEX_LOCK(rpcLock);
- rrpc = vectorGetFirst(list_of_callbacks);
- while (rrpc != NULL) {
- if (0 == strcmp(rrpc->name, name)) {
- if ( (rrpc->callback != callback) &&
- (callback != NULL) ) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("%s::%s - RPC %s:%p could not be unregistered:"
- " another callback registered under that name: %p\n"),
- __FILE__, __FUNCTION__,
- name, callback, rrpc->callback);
+ GE_ASSERT (ectx, name != NULL);
+ MUTEX_LOCK (rpcLock);
+ rrpc = vectorGetFirst (list_of_callbacks);
+ while (rrpc != NULL)
+ {
+ if (0 == strcmp (rrpc->name, name))
+ {
+ if ((rrpc->callback != callback) && (callback != NULL))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("%s::%s - RPC %s:%p could not be unregistered:"
+ " another callback registered under that name: %p\n"),
+ __FILE__, __FUNCTION__, name, callback, rrpc->callback);
+ MUTEX_UNLOCK (rpcLock);
+ return SYSERR;
+ }
+ vectorRemoveObject (list_of_callbacks, rrpc);
+ FREE (rrpc->name);
+ FREE (rrpc);
+ MUTEX_UNLOCK (rpcLock);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "%s::%s - Unregistered RPC %s\n",
+ __FILE__, __FUNCTION__, name);
+ return OK;
+ }
+ rrpc = vectorGetNext (list_of_callbacks);
+ }
MUTEX_UNLOCK (rpcLock);
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("%s::%s - RPC %s:%p could not be unregistered: not found\n"),
+ __FILE__, __FUNCTION__, name, callback);
return SYSERR;
- }
- vectorRemoveObject(list_of_callbacks, rrpc);
- FREE(rrpc->name);
- FREE(rrpc);
- MUTEX_UNLOCK(rpcLock);
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "%s::%s - Unregistered RPC %s\n",
- __FILE__, __FUNCTION__,
- name);
- return OK;
- }
- rrpc = vectorGetNext(list_of_callbacks);
- }
- MUTEX_UNLOCK(rpcLock);
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("%s::%s - RPC %s:%p could not be unregistered: not found\n"),
- __FILE__, __FUNCTION__,
- name, callback);
- return SYSERR;
}
/**
@@ -244,43 +247,44 @@
* (typically if a callback of that name does not exist or is
* bound to a different function).
*/
-static int RPC_unregister_async(const char *name,
- ASYNC_RPC_Function callback) {
- RegisteredRPC * rrpc;
+static int
+RPC_unregister_async (const char *name, ASYNC_RPC_Function callback)
+{
+ RegisteredRPC *rrpc;
- GE_ASSERT(ectx, name != NULL);
- MUTEX_LOCK(rpcLock);
- rrpc = vectorGetFirst(list_of_callbacks);
- while (rrpc != NULL) {
- if (0 == strcmp(rrpc->name, name)) {
- if ( (rrpc->async_callback != callback) &&
- (callback != NULL) ) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("%s::%s - RPC %s:%p could not be unregistered:"
- " another callback registered under that name: %p\n"),
- __FILE__, __FUNCTION__,
- name, callback, rrpc->callback);
+ GE_ASSERT (ectx, name != NULL);
+ MUTEX_LOCK (rpcLock);
+ rrpc = vectorGetFirst (list_of_callbacks);
+ while (rrpc != NULL)
+ {
+ if (0 == strcmp (rrpc->name, name))
+ {
+ if ((rrpc->async_callback != callback) && (callback != NULL))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("%s::%s - RPC %s:%p could not be unregistered:"
+ " another callback registered under that name: %p\n"),
+ __FILE__, __FUNCTION__, name, callback, rrpc->callback);
+ MUTEX_UNLOCK (rpcLock);
+ return SYSERR;
+ }
+ vectorRemoveObject (list_of_callbacks, rrpc);
+ FREE (rrpc->name);
+ FREE (rrpc);
+ MUTEX_UNLOCK (rpcLock);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "%s::%s - Unregistered asynchronous RPC %s\n",
+ __FILE__, __FUNCTION__, name);
+ return OK;
+ }
+ rrpc = vectorGetNext (list_of_callbacks);
+ }
MUTEX_UNLOCK (rpcLock);
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("%s::%s - async RPC %s:%p could not be unregistered: not found\n"),
+ __FILE__, __FUNCTION__, name, callback);
return SYSERR;
- }
- vectorRemoveObject(list_of_callbacks, rrpc);
- FREE(rrpc->name);
- FREE(rrpc);
- MUTEX_UNLOCK(rpcLock);
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "%s::%s - Unregistered asynchronous RPC %s\n",
- __FILE__, __FUNCTION__,
- name);
- return OK;
- }
- rrpc = vectorGetNext(list_of_callbacks);
- }
- MUTEX_UNLOCK(rpcLock);
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("%s::%s - async RPC %s:%p could not be unregistered: not found\n"),
- __FILE__, __FUNCTION__,
- name, callback);
- return SYSERR;
}
@@ -299,7 +303,8 @@
/**
* A per-peer structure to store TCP-like data.
*/
-typedef struct {
+typedef struct
+{
PeerIdentity identity;
/**
@@ -344,19 +349,20 @@
* PeerIdentity) known to the RPC module. Peers are added as either RPC's
* are made to them from the local node, or an RPC call is received from them.
*/
-static struct Vector * peerInformation;
+static struct Vector *peerInformation;
-static PeerInfo * getPeerInfo(const PeerIdentity * id) {
- PeerInfo * pi;
+static PeerInfo *
+getPeerInfo (const PeerIdentity * id)
+{
+ PeerInfo *pi;
- pi = (PeerInfo*) vectorGetFirst(peerInformation);
- while (pi != NULL) {
- if (0 == memcmp(id,
- &pi->identity,
- sizeof(PeerIdentity)))
- return pi;
- pi = (PeerInfo*) vectorGetNext(peerInformation);
- }
+ pi = (PeerInfo *) vectorGetFirst (peerInformation);
+ while (pi != NULL)
+ {
+ if (0 == memcmp (id, &pi->identity, sizeof (PeerIdentity)))
+ return pi;
+ pi = (PeerInfo *) vectorGetNext (peerInformation);
+ }
return NULL;
}
@@ -364,40 +370,45 @@
* What is the expected response time for this peer?
* @return 0 for unknown
*/
-static cron_t getExpectedResponseTime(const PeerIdentity * peer) {
+static cron_t
+getExpectedResponseTime (const PeerIdentity * peer)
+{
cron_t result;
- PeerInfo * pi;
+ PeerInfo *pi;
- MUTEX_LOCK(rpcLock);
- pi = getPeerInfo(peer);
+ MUTEX_LOCK (rpcLock);
+ pi = getPeerInfo (peer);
if (pi == NULL)
result = 0;
else
result = pi->averageResponseTime;
- MUTEX_UNLOCK(rpcLock);
+ MUTEX_UNLOCK (rpcLock);
return result;
}
/**
* Cron-job used to age the peer statistics.
*/
-static void agePeerStats(void * unused) {
- PeerInfo * pi;
+static void
+agePeerStats (void *unused)
+{
+ PeerInfo *pi;
- MUTEX_LOCK(rpcLock);
- pi = vectorGetFirst(peerInformation);
- while (pi != NULL) {
- pi->agedActivitySend = pi->agedActivitySend / 2;
- pi->agedActivityRecv = pi->agedActivityRecv / 2;
- if ( (pi->agedActivitySend == 0) &&
- (pi->agedActivityRecv == 0) ) {
- vectorRemoveObject(peerInformation, pi);
- FREE(pi);
+ MUTEX_LOCK (rpcLock);
+ pi = vectorGetFirst (peerInformation);
+ while (pi != NULL)
+ {
+ pi->agedActivitySend = pi->agedActivitySend / 2;
+ pi->agedActivityRecv = pi->agedActivityRecv / 2;
+ if ((pi->agedActivitySend == 0) && (pi->agedActivityRecv == 0))
+ {
+ vectorRemoveObject (peerInformation, pi);
+ FREE (pi);
+ }
+
+ pi = vectorGetNext (peerInformation);
}
-
- pi = vectorGetNext(peerInformation);
- }
- MUTEX_UNLOCK(rpcLock);
+ MUTEX_UNLOCK (rpcLock);
}
/**
@@ -410,37 +421,41 @@
* Notification: we sent a message to the peer.
* @param messageID pseudo-unique ID of the request
*/
-static void notifyPeerRequest(PeerIdentity * peer,
- unsigned int messageID) {
+static void
+notifyPeerRequest (PeerIdentity * peer, unsigned int messageID)
+{
int i;
- PeerInfo * pi;
+ PeerInfo *pi;
- MUTEX_LOCK(rpcLock);
- pi = getPeerInfo(peer);
- if (pi != NULL) {
- for (i=0;i<MTRACK_COUNT;i++) {
- if (pi->lastRequestId[i] == messageID) {
- pi->lastRequestTimes[i] = 0; /* re-send! */
- MUTEX_UNLOCK(rpcLock);
- return;
- }
+ MUTEX_LOCK (rpcLock);
+ pi = getPeerInfo (peer);
+ if (pi != NULL)
+ {
+ for (i = 0; i < MTRACK_COUNT; i++)
+ {
+ if (pi->lastRequestId[i] == messageID)
+ {
+ pi->lastRequestTimes[i] = 0; /* re-send! */
+ MUTEX_UNLOCK (rpcLock);
+ return;
+ }
+ }
+ pi->agedActivitySend |= 0x80000000;
+ pi->lastRequestTimes[pi->oldestRTIndex] = get_time ();
+ pi->lastRequestId[pi->oldestRTIndex] = messageID;
+ pi->oldestRTIndex = (pi->oldestRTIndex + 1) % MTRACK_COUNT;
+ MUTEX_UNLOCK (rpcLock);
+ return;
}
- pi->agedActivitySend |= 0x80000000;
- pi->lastRequestTimes[pi->oldestRTIndex] = get_time();
- pi->lastRequestId[pi->oldestRTIndex] = messageID;
- pi->oldestRTIndex = (pi->oldestRTIndex+1) % MTRACK_COUNT;
- MUTEX_UNLOCK(rpcLock);
- return;
- }
- pi = MALLOC(sizeof(PeerInfo));
- memset(pi, 0, sizeof(PeerInfo));
+ pi = MALLOC (sizeof (PeerInfo));
+ memset (pi, 0, sizeof (PeerInfo));
pi->identity = *peer;
pi->agedActivitySend = 0x80000000;
- pi->lastRequestTimes[0] = get_time();
+ pi->lastRequestTimes[0] = get_time ();
pi->lastRequestId[0] = messageID;
pi->oldestRTIndex = 1;
- vectorInsertLast(peerInformation, pi);
- MUTEX_UNLOCK(rpcLock);
+ vectorInsertLast (peerInformation, pi);
+ MUTEX_UNLOCK (rpcLock);
}
/**
@@ -448,35 +463,40 @@
* @param messageID the ID of the message that a reply was received
* for
*/
-static void notifyPeerReply(const PeerIdentity * peer,
- unsigned int messageID) {
+static void
+notifyPeerReply (const PeerIdentity * peer, unsigned int messageID)
+{
int i;
- PeerInfo * pi;
+ PeerInfo *pi;
- MUTEX_LOCK(rpcLock);
- pi = vectorGetFirst(peerInformation);
- while (pi != NULL) {
- if (0 == memcmp(peer,
- &pi->identity,
- sizeof(PeerIdentity))) {
- for (i=0;i<MTRACK_COUNT;i++) {
- if (pi->lastRequestId[i] == messageID) {
- if (pi->lastRequestTimes[i] != 0) { /* resend */
- pi->averageResponseTime
- = (pi->averageResponseTime * (MTRACK_COUNT-1) +
- get_time() - pi->lastRequestTimes[i]) / MTRACK_COUNT;
- pi->agedActivityRecv |= 0x80000000;
- pi->lastRequestTimes[i] = 0;
+ MUTEX_LOCK (rpcLock);
+ pi = vectorGetFirst (peerInformation);
+ while (pi != NULL)
+ {
+ if (0 == memcmp (peer, &pi->identity, sizeof (PeerIdentity)))
+ {
+ for (i = 0; i < MTRACK_COUNT; i++)
+ {
+ if (pi->lastRequestId[i] == messageID)
+ {
+ if (pi->lastRequestTimes[i] != 0)
+ { /* resend */
+ pi->averageResponseTime
+ = (pi->averageResponseTime * (MTRACK_COUNT - 1) +
+ get_time () -
+ pi->lastRequestTimes[i]) / MTRACK_COUNT;
+ pi->agedActivityRecv |= 0x80000000;
+ pi->lastRequestTimes[i] = 0;
+ }
+ MUTEX_UNLOCK (rpcLock);
+ return;
+ }
+ }
+ break;
+ }
+ pi = vectorGetNext (peerInformation);
}
- MUTEX_UNLOCK(rpcLock);
- return;
- }
- }
- break;
- }
- pi = vectorGetNext(peerInformation);
- }
- MUTEX_UNLOCK(rpcLock);
+ MUTEX_UNLOCK (rpcLock);
}
/* ***************** RPC datastructures ****************** */
@@ -491,7 +511,8 @@
* error code). argumentCount must be 0 for errors and otherwise
* indicate the number of return values.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
TIME_T timestamp;
unsigned int sequenceNumber;
@@ -501,7 +522,8 @@
} P2P_rpc_MESSAGE;
-typedef struct {
+typedef struct
+{
P2P_rpc_MESSAGE rpc_message;
/**
* functionNameLength characters describing the function name
@@ -517,7 +539,8 @@
* RPC request is supposed to repeatedly send the RPC reply (until it
* times out).
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
* The number of the original request for which this is the
@@ -534,15 +557,16 @@
* @param errorCode 0 on success
* @param result the return values, NULL on error
*/
-typedef void (*RPCFinishedCallback)(void * context,
- unsigned int sequenceNumber,
- unsigned short errorCode,
- RPC_Param * result);
+typedef void (*RPCFinishedCallback) (void *context,
+ unsigned int sequenceNumber,
+ unsigned short errorCode,
+ RPC_Param * result);
/**
* A per-RPC structure.
*/
-typedef struct CallInstance {
+typedef struct CallInstance
+{
/**
* The sequence number of this RPC.
*/
@@ -557,7 +581,7 @@
* The message we are transmitting (either the request or the
* reply).
*/
- P2P_rpc_MESSAGE * msg;
+ P2P_rpc_MESSAGE *msg;
/**
* Time where this record times out (timeout value for original
@@ -594,7 +618,7 @@
/**
* Arguments to the callback.
*/
- void * rpcCallbackArgs;
+ void *rpcCallbackArgs;
/**
* How important is this RPC?
@@ -606,13 +630,13 @@
* A set of CallInstance structures for active incoming rpc calls.
* (requests without a reply).
*/
-static struct Vector * incomingCalls;
+static struct Vector *incomingCalls;
/**
* A set of CallInstance structures for active outgoing rpc calls.
* (reply messages without an ACK).
*/
-static struct Vector * outgoingCalls;
+static struct Vector *outgoingCalls;
/**
* A counter whose value is used for identifying the RPC's originating
@@ -627,137 +651,144 @@
* each CallInstance. Not renewed if the call times out,
* deleted if the appropriate response is received.
*/
-static void retryRPCJob(void * ctx) {
- CallInstance * call = ctx;
+static void
+retryRPCJob (void *ctx)
+{
+ CallInstance *call = ctx;
cron_t now;
- now = get_time();
- GE_ASSERT(ectx, (get_time() + 1 * cronMINUTES > call->expirationTime) ||
- (call->expirationTime - get_time() < 1 * cronHOURS) );
- MUTEX_LOCK(rpcLock);
- if (now > call->expirationTime) {
+ now = get_time ();
+ GE_ASSERT (ectx, (get_time () + 1 * cronMINUTES > call->expirationTime) ||
+ (call->expirationTime - get_time () < 1 * cronHOURS));
+ MUTEX_LOCK (rpcLock);
+ if (now > call->expirationTime)
+ {
#if DEBUG_RPC
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Completed RPC %p (timeout).\n",
- call);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Completed RPC %p (timeout).\n", call);
#endif
- if (call->finishedCallback != NULL) {
- call->finishedCallback(call->rpcCallbackArgs,
- call->sequenceNumber,
- RPC_ERROR_TIMEOUT,
- NULL);
- vectorRemoveObject(outgoingCalls, call);
- } else {
- vectorRemoveObject(incomingCalls, call);
+ if (call->finishedCallback != NULL)
+ {
+ call->finishedCallback (call->rpcCallbackArgs,
+ call->sequenceNumber,
+ RPC_ERROR_TIMEOUT, NULL);
+ vectorRemoveObject (outgoingCalls, call);
+ }
+ else
+ {
+ vectorRemoveObject (incomingCalls, call);
+ }
+ FREE (call->msg);
+ FREE (call);
}
- FREE(call->msg);
- FREE(call);
- } else {
- if ( (coreAPI != NULL) &&
- (call->expirationTime - now > 50 * cronMILLIS) ) {
- unsigned int maxdelay;
+ else
+ {
+ if ((coreAPI != NULL) && (call->expirationTime - now > 50 * cronMILLIS))
+ {
+ unsigned int maxdelay;
- if (call->repetitionFrequency == 0) {
- call->repetitionFrequency
- = getExpectedResponseTime(&call->receiver) * 2;
- if (call->repetitionFrequency == 0)
- call->repetitionFrequency = INITIAL_RPC_FREQUENCY;
- if (call->repetitionFrequency < MIN_RPC_FREQUENCY)
- call->repetitionFrequency = MIN_RPC_FREQUENCY;
- } else
- call->repetitionFrequency = 2 * call->repetitionFrequency;
- maxdelay = (now - call->expirationTime)/2;
- if (maxdelay > call->repetitionFrequency / 2)
- maxdelay = call->repetitionFrequency / 2;
- notifyPeerRequest(&call->receiver,
- MINGLE(call->sequenceNumber,
- ntohs(call->msg->header.type)));
+ if (call->repetitionFrequency == 0)
+ {
+ call->repetitionFrequency
+ = getExpectedResponseTime (&call->receiver) * 2;
+ if (call->repetitionFrequency == 0)
+ call->repetitionFrequency = INITIAL_RPC_FREQUENCY;
+ if (call->repetitionFrequency < MIN_RPC_FREQUENCY)
+ call->repetitionFrequency = MIN_RPC_FREQUENCY;
+ }
+ else
+ call->repetitionFrequency = 2 * call->repetitionFrequency;
+ maxdelay = (now - call->expirationTime) / 2;
+ if (maxdelay > call->repetitionFrequency / 2)
+ maxdelay = call->repetitionFrequency / 2;
+ notifyPeerRequest (&call->receiver,
+ MINGLE (call->sequenceNumber,
+ ntohs (call->msg->header.type)));
#if DEBUG_RPC
- if (ntohs(call->msg->header.type) == P2P_PROTO_rpc_REQ) {
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Sending RPC request %p: '%.*s' (expires in %llums, last attempt %llums
ago; attempt %u).\n",
- call,
- ntohs(call->msg->functionNameLength),
- &((P2P_rpc_MESSAGE_GENERIC*)call->msg)->data[0],
- call->expirationTime - now,
- now - call->lastAttempt,
- call->attempts);
- } else {
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Sending RPC reply %p (expires in %llums, last attempt %llums ago,
attempt %u).\n",
- call,
- call->expirationTime - now,
- now - call->lastAttempt,
- call->attempts);
- }
+ if (ntohs (call->msg->header.type) == P2P_PROTO_rpc_REQ)
+ {
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Sending RPC request %p: '%.*s' (expires in %llums, last
attempt %llums ago; attempt %u).\n",
+ call,
+ ntohs (call->msg->functionNameLength),
+ &((P2P_rpc_MESSAGE_GENERIC *) call->msg)->data[0],
+ call->expirationTime - now,
+ now - call->lastAttempt, call->attempts);
+ }
+ else
+ {
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Sending RPC reply %p (expires in %llums, last attempt
%llums ago, attempt %u).\n",
+ call,
+ call->expirationTime - now,
+ now - call->lastAttempt, call->attempts);
+ }
#endif
- call->lastAttempt = now;
- call->attempts++;
- coreAPI->unicast(&call->receiver,
- &call->msg->header,
- ntohl(call->msg->importance),
- maxdelay);
+ call->lastAttempt = now;
+ call->attempts++;
+ coreAPI->unicast (&call->receiver,
+ &call->msg->header,
+ ntohl (call->msg->importance), maxdelay);
+ }
+ GE_ASSERT (ectx, (get_time () + 1 * cronMINUTES > call->expirationTime)
+ || (call->expirationTime - get_time () < 1 * cronHOURS));
+ cron_add_job (coreAPI->cron, &retryRPCJob, call->repetitionFrequency, 0,
+ call);
}
- GE_ASSERT(ectx, (get_time() + 1 * cronMINUTES > call->expirationTime) ||
- (call->expirationTime - get_time() < 1 * cronHOURS) );
- cron_add_job(coreAPI->cron,
- &retryRPCJob,
- call->repetitionFrequency,
- 0,
- call);
- }
- MUTEX_UNLOCK(rpcLock);
+ MUTEX_UNLOCK (rpcLock);
}
/**
* Send an ACK message.
*/
-static void sendAck(const PeerIdentity * receiver,
- unsigned int sequenceNumber,
- unsigned int importance,
- unsigned int maxDelay) {
+static void
+sendAck (const PeerIdentity * receiver,
+ unsigned int sequenceNumber,
+ unsigned int importance, unsigned int maxDelay)
+{
RPC_ACK_Message msg;
- msg.header.size = htons(sizeof(RPC_ACK_Message));
- msg.header.type = htons(P2P_PROTO_rpc_ACK);
- msg.sequenceNumber = htonl(sequenceNumber);
- coreAPI->unicast(receiver,
- &msg.header,
- importance,
- maxDelay);
+ msg.header.size = htons (sizeof (RPC_ACK_Message));
+ msg.header.type = htons (P2P_PROTO_rpc_ACK);
+ msg.sequenceNumber = htonl (sequenceNumber);
+ coreAPI->unicast (receiver, &msg.header, importance, maxDelay);
}
-static char * getFunctionName(P2P_rpc_MESSAGE * req) {
- char * ret;
+static char *
+getFunctionName (P2P_rpc_MESSAGE * req)
+{
+ char *ret;
unsigned short slen;
- slen = ntohs(req->functionNameLength);
- if (ntohs(req->header.size) < sizeof(P2P_rpc_MESSAGE) + slen)
- return NULL; /* invalid! */
- ret = MALLOC(slen+1);
- memcpy(ret,
- &((P2P_rpc_MESSAGE_GENERIC*)req)->data[0],
- slen);
+ slen = ntohs (req->functionNameLength);
+ if (ntohs (req->header.size) < sizeof (P2P_rpc_MESSAGE) + slen)
+ return NULL; /* invalid! */
+ ret = MALLOC (slen + 1);
+ memcpy (ret, &((P2P_rpc_MESSAGE_GENERIC *) req)->data[0], slen);
ret[slen] = '\0';
return ret;
}
-static RPC_Param * deserializeArguments(P2P_rpc_MESSAGE * req) {
+static RPC_Param *
+deserializeArguments (P2P_rpc_MESSAGE * req)
+{
unsigned short slen;
- RPC_Param * ret;
+ RPC_Param *ret;
- if (ntohs(req->header.type) == P2P_PROTO_rpc_REQ)
- slen = ntohs(req->functionNameLength);
+ if (ntohs (req->header.type) == P2P_PROTO_rpc_REQ)
+ slen = ntohs (req->functionNameLength);
else
slen = 0;
- if (ntohs(req->header.size) < sizeof(P2P_rpc_MESSAGE) + slen)
- return NULL; /* invalid! */
- ret = RPC_paramDeserialize(&((P2P_rpc_MESSAGE_GENERIC*)req)->data[slen],
- ntohs(req->header.size) - sizeof(P2P_rpc_MESSAGE) - slen);
- if (RPC_paramCount(ret) != ntohs(req->argumentCount)) {
- RPC_paramFree(ret);
- return NULL; /* invalid! */
- }
+ if (ntohs (req->header.size) < sizeof (P2P_rpc_MESSAGE) + slen)
+ return NULL; /* invalid! */
+ ret = RPC_paramDeserialize (&((P2P_rpc_MESSAGE_GENERIC *) req)->data[slen],
+ ntohs (req->header.size) -
+ sizeof (P2P_rpc_MESSAGE) - slen);
+ if (RPC_paramCount (ret) != ntohs (req->argumentCount))
+ {
+ RPC_paramFree (ret);
+ return NULL; /* invalid! */
+ }
return ret;
}
@@ -771,46 +802,47 @@
* @param values the arguments or return values, maybe NULL
* @return the RPC message to transmit, caller must free
*/
-static P2P_rpc_MESSAGE * buildMessage(unsigned short errorCode,
- const char * name,
- unsigned int sequenceNumber,
- unsigned int importance,
- RPC_Param * values) {
- P2P_rpc_MESSAGE * ret;
- size_t size = sizeof(P2P_rpc_MESSAGE);
+static P2P_rpc_MESSAGE *
+buildMessage (unsigned short errorCode,
+ const char *name,
+ unsigned int sequenceNumber,
+ unsigned int importance, RPC_Param * values)
+{
+ P2P_rpc_MESSAGE *ret;
+ size_t size = sizeof (P2P_rpc_MESSAGE);
int slen;
- if (name != NULL) {
- slen = strlen(name);
- size += slen;
- } else
+ if (name != NULL)
+ {
+ slen = strlen (name);
+ size += slen;
+ }
+ else
slen = 0;
if (values != NULL)
- size += RPC_paramSize(values);
+ size += RPC_paramSize (values);
if (size >= MAX_BUFFER_SIZE)
- return NULL; /* message to big! */
- ret = MALLOC(size);
- ret->header.size = htons(size);
- ret->timestamp = htonl(TIME(NULL));
- ret->sequenceNumber = htonl(sequenceNumber);
- ret->importance = htonl(importance);
+ return NULL; /* message to big! */
+ ret = MALLOC (size);
+ ret->header.size = htons (size);
+ ret->timestamp = htonl (TIME (NULL));
+ ret->sequenceNumber = htonl (sequenceNumber);
+ ret->importance = htonl (importance);
if (name == NULL)
- ret->functionNameLength = htons(errorCode);
+ ret->functionNameLength = htons (errorCode);
else
- ret->functionNameLength = htons(slen);
- ret->argumentCount = htons(RPC_paramCount(values));
- if (name != NULL) {
- memcpy(&((P2P_rpc_MESSAGE_GENERIC*)ret)->data[0],
- name,
- slen);
- }
- RPC_paramSerialize(values,
- &((P2P_rpc_MESSAGE_GENERIC*)ret)->data[slen]);
+ ret->functionNameLength = htons (slen);
+ ret->argumentCount = htons (RPC_paramCount (values));
+ if (name != NULL)
+ {
+ memcpy (&((P2P_rpc_MESSAGE_GENERIC *) ret)->data[0], name, slen);
+ }
+ RPC_paramSerialize (values, &((P2P_rpc_MESSAGE_GENERIC *) ret)->data[slen]);
if (name == NULL)
- ret->header.type = htons(P2P_PROTO_rpc_RES);
+ ret->header.type = htons (P2P_PROTO_rpc_RES);
else
- ret->header.type = htons(P2P_PROTO_rpc_REQ);
+ ret->header.type = htons (P2P_PROTO_rpc_REQ);
return ret;
}
@@ -825,32 +857,27 @@
* sending back the reply. Also called in the synchronous RPC
* case o complete the reply (since it's the same code).
*/
-static void async_rpc_complete_callback(RPC_Param * results,
- int errorCode,
- CallInstance * calls) {
+static void
+async_rpc_complete_callback (RPC_Param * results,
+ int errorCode, CallInstance * calls)
+{
MUTEX_LOCK (rpcLock);
/* build reply message */
- calls->msg = buildMessage(errorCode,
- NULL,
- calls->sequenceNumber,
- calls->importance,
- results);
+ calls->msg = buildMessage (errorCode,
+ NULL,
+ calls->sequenceNumber,
+ calls->importance, results);
if (calls->msg == NULL)
- calls->msg = buildMessage(RPC_ERROR_RETURN_VALUE_TOO_LARGE,
- NULL,
- calls->sequenceNumber,
- calls->importance,
- results);
- vectorInsertLast(incomingCalls, calls);
+ calls->msg = buildMessage (RPC_ERROR_RETURN_VALUE_TOO_LARGE,
+ NULL,
+ calls->sequenceNumber,
+ calls->importance, results);
+ vectorInsertLast (incomingCalls, calls);
- GE_ASSERT(ectx, (get_time() + 1 * cronMINUTES > calls->expirationTime) ||
- (calls->expirationTime - get_time() < 1 * cronHOURS) );
+ GE_ASSERT (ectx, (get_time () + 1 * cronMINUTES > calls->expirationTime) ||
+ (calls->expirationTime - get_time () < 1 * cronHOURS));
/* for right now: schedule cron job to send reply! */
- cron_add_job(coreAPI->cron,
- &retryRPCJob,
- 0,
- 0,
- calls);
+ cron_add_job (coreAPI->cron, &retryRPCJob, 0, 0, calls);
MUTEX_UNLOCK (rpcLock);
}
@@ -860,33 +887,35 @@
* has been seen before, if not performs the call and sends
* reply.
*/
-static int handleRPCMessageReq(const PeerIdentity *sender,
- const MESSAGE_HEADER * message) {
- P2P_rpc_MESSAGE * req;
- CallInstance * calls;
+static int
+handleRPCMessageReq (const PeerIdentity * sender,
+ const MESSAGE_HEADER * message)
+{
+ P2P_rpc_MESSAGE *req;
+ CallInstance *calls;
unsigned int sq;
unsigned short errorCode;
- char * functionName;
- RPC_Param * argumentValues;
- RPC_Param * returnValues;
- RegisteredRPC * rpc;
+ char *functionName;
+ RPC_Param *argumentValues;
+ RPC_Param *returnValues;
+ RegisteredRPC *rpc;
unsigned int minSQ;
- if ( (ntohs(message->type) != P2P_PROTO_rpc_REQ) ||
- (ntohs(message->size) < sizeof(P2P_rpc_MESSAGE)) ) {
- GE_LOG(ectx,
- GE_WARNING | GE_REQUEST | GE_ADMIN,
- _("Invalid message of type %u received. Dropping.\n"),
- ntohs(message->type));
- return SYSERR;
- }
+ if ((ntohs (message->type) != P2P_PROTO_rpc_REQ) ||
+ (ntohs (message->size) < sizeof (P2P_rpc_MESSAGE)))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_REQUEST | GE_ADMIN,
+ _("Invalid message of type %u received. Dropping.\n"),
+ ntohs (message->type));
+ return SYSERR;
+ }
req = (P2P_rpc_MESSAGE *) message;
- sq = ntohl(req->sequenceNumber);
+ sq = ntohl (req->sequenceNumber);
#if DEBUG_RPC
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received RPC request with id %u.\n",
- sq);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received RPC request with id %u.\n", sq);
#endif
MUTEX_LOCK (rpcLock);
@@ -894,105 +923,104 @@
if so, update expiration, otherwise deserialize,
perform call, add reply and create cron job */
- calls = vectorGetFirst(incomingCalls);
+ calls = vectorGetFirst (incomingCalls);
if (calls == NULL)
minSQ = 0;
else
minSQ = 0xFFFFFFFF;
- while (calls != NULL) {
- if (calls->sequenceNumber < minSQ)
- minSQ = calls->sequenceNumber;
- if ( (calls->sequenceNumber == sq) &&
- (0 == memcmp(&calls->receiver,
- sender,
- sizeof(PeerIdentity))) )
- break;
- calls = vectorGetNext(incomingCalls);
- }
- if (calls != NULL) {
- PeerInfo * pi = getPeerInfo(sender);
+ while (calls != NULL)
+ {
+ if (calls->sequenceNumber < minSQ)
+ minSQ = calls->sequenceNumber;
+ if ((calls->sequenceNumber == sq) &&
+ (0 == memcmp (&calls->receiver, sender, sizeof (PeerIdentity))))
+ break;
+ calls = vectorGetNext (incomingCalls);
+ }
+ if (calls != NULL)
+ {
+ PeerInfo *pi = getPeerInfo (sender);
- if (pi != NULL) {
- if (pi->averageResponseTime < MAX_RPC_TIMEOUT / 2)
- pi->averageResponseTime *= 2;
+ if (pi != NULL)
+ {
+ if (pi->averageResponseTime < MAX_RPC_TIMEOUT / 2)
+ pi->averageResponseTime *= 2;
+ }
+ RPC_STATUS ("", "received duplicate request", calls);
+ calls->expirationTime = get_time () + MAX_RPC_TIMEOUT;
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Dropping RPC request %u, duplicate.\n", sq);
+ MUTEX_UNLOCK (rpcLock);
+ return OK; /* seen before */
}
- RPC_STATUS("", "received duplicate request", calls);
- calls->expirationTime = get_time() + MAX_RPC_TIMEOUT;
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Dropping RPC request %u, duplicate.\n",
- sq);
- MUTEX_UNLOCK(rpcLock);
- return OK; /* seen before */
- }
- if (minSQ > sq) {
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Dropping RPC request %u, sequence number too old (current minimum is
%u).\n",
- sq,
- minSQ);
- MUTEX_UNLOCK(rpcLock);
- return OK; /* seen before */
- }
+ if (minSQ > sq)
+ {
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Dropping RPC request %u, sequence number too old (current
minimum is %u).\n",
+ sq, minSQ);
+ MUTEX_UNLOCK (rpcLock);
+ return OK; /* seen before */
+ }
/* deserialize */
- functionName = getFunctionName(req);
- argumentValues = deserializeArguments(req);
- if ( (functionName == NULL) ||
- (argumentValues == NULL) ) {
- FREENONNULL(functionName);
- if (argumentValues != NULL)
- RPC_paramFree(argumentValues);
- MUTEX_UNLOCK(rpcLock);
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Dropping RPC request %u: message malformed.\n"));
- return SYSERR; /* message malformed */
- }
+ functionName = getFunctionName (req);
+ argumentValues = deserializeArguments (req);
+ if ((functionName == NULL) || (argumentValues == NULL))
+ {
+ FREENONNULL (functionName);
+ if (argumentValues != NULL)
+ RPC_paramFree (argumentValues);
+ MUTEX_UNLOCK (rpcLock);
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Dropping RPC request %u: message malformed.\n"));
+ return SYSERR; /* message malformed */
+ }
/* find matching RPC function */
- rpc = (RegisteredRPC*) vectorGetFirst(list_of_callbacks);
- while (rpc != NULL) {
- if (0 == strcmp(functionName,
- rpc->name))
- break;
- rpc = (RegisteredRPC*) vectorGetNext(list_of_callbacks);
- }
- calls = MALLOC(sizeof(CallInstance));
- RPC_STATUS(functionName, "received request", calls);
- FREE(functionName);
+ rpc = (RegisteredRPC *) vectorGetFirst (list_of_callbacks);
+ while (rpc != NULL)
+ {
+ if (0 == strcmp (functionName, rpc->name))
+ break;
+ rpc = (RegisteredRPC *) vectorGetNext (list_of_callbacks);
+ }
+ calls = MALLOC (sizeof (CallInstance));
+ RPC_STATUS (functionName, "received request", calls);
+ FREE (functionName);
calls->sequenceNumber = sq;
calls->receiver = *sender;
- calls->expirationTime = get_time() + MAX_RPC_TIMEOUT;
+ calls->expirationTime = get_time () + MAX_RPC_TIMEOUT;
calls->lastAttempt = 0;
calls->attempts = 0;
calls->finishedCallback = NULL;
calls->rpcCallbackArgs = NULL;
- calls->importance = ntohl(req->importance);
+ calls->importance = ntohl (req->importance);
/* if possible, perform RPC call */
- if (rpc == NULL) {
- RPC_paramFree(argumentValues);
- returnValues = NULL;
- errorCode = RPC_ERROR_UNKNOWN_FUNCTION;
- } else {
- if (rpc->callback == NULL) {
- /* asynchronous RPC */
- rpc->async_callback(sender,
- argumentValues,
- &async_rpc_complete_callback,
- calls);
- MUTEX_UNLOCK (rpcLock);
- return OK;
+ if (rpc == NULL)
+ {
+ RPC_paramFree (argumentValues);
+ returnValues = NULL;
+ errorCode = RPC_ERROR_UNKNOWN_FUNCTION;
}
- returnValues = RPC_paramNew();
- rpc->callback(sender,
- argumentValues,
- returnValues);
- RPC_paramFree(argumentValues);
- errorCode = RPC_ERROR_OK;
- }
- MUTEX_UNLOCK(rpcLock);
- async_rpc_complete_callback(returnValues,
- errorCode,
- calls);
+ else
+ {
+ if (rpc->callback == NULL)
+ {
+ /* asynchronous RPC */
+ rpc->async_callback (sender,
+ argumentValues,
+ &async_rpc_complete_callback, calls);
+ MUTEX_UNLOCK (rpcLock);
+ return OK;
+ }
+ returnValues = RPC_paramNew ();
+ rpc->callback (sender, argumentValues, returnValues);
+ RPC_paramFree (argumentValues);
+ errorCode = RPC_ERROR_OK;
+ }
+ MUTEX_UNLOCK (rpcLock);
+ async_rpc_complete_callback (returnValues, errorCode, calls);
return OK;
}
@@ -1001,87 +1029,84 @@
* if we are waiting for a reply, if so triggers the reply.
* Also always sends an ACK.
*/
-static int handleRPCMessageRes(const PeerIdentity * sender,
- const MESSAGE_HEADER * message) {
- P2P_rpc_MESSAGE * res;
- CallInstance * call;
+static int
+handleRPCMessageRes (const PeerIdentity * sender,
+ const MESSAGE_HEADER * message)
+{
+ P2P_rpc_MESSAGE *res;
+ CallInstance *call;
- if ( (ntohs(message->type) != P2P_PROTO_rpc_RES) ||
- (ntohs(message->size) < sizeof(P2P_rpc_MESSAGE)) ) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Invalid message of type %u received. Dropping.\n"),
- ntohs(message->type));
- return SYSERR;
- }
+ if ((ntohs (message->type) != P2P_PROTO_rpc_RES) ||
+ (ntohs (message->size) < sizeof (P2P_rpc_MESSAGE)))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Invalid message of type %u received. Dropping.\n"),
+ ntohs (message->type));
+ return SYSERR;
+ }
res = (P2P_rpc_MESSAGE *) message;
#if DEBUG_RPC
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Received RPC reply with id %u.\n",
- ntohl(res->sequenceNumber));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received RPC reply with id %u.\n", ntohl (res->sequenceNumber));
#endif
- cron_suspend(coreAPI->cron,
- NO);
+ cron_suspend (coreAPI->cron, NO);
MUTEX_LOCK (rpcLock);
/* Locate the CallInstance structure. */
- call = vectorGetFirst(outgoingCalls);
- while (call != NULL) {
- if ( (0 == memcmp(&call->receiver,
- sender,
- sizeof(PeerIdentity))) &&
- (call->sequenceNumber == ntohl(res->sequenceNumber)) )
- break;
- call = vectorGetNext(outgoingCalls);
- }
- if (NULL != call) {
- RPC_Param * reply;
- P2P_rpc_MESSAGE_GENERIC * gen;
- unsigned short error;
+ call = vectorGetFirst (outgoingCalls);
+ while (call != NULL)
+ {
+ if ((0 == memcmp (&call->receiver,
+ sender,
+ sizeof (PeerIdentity))) &&
+ (call->sequenceNumber == ntohl (res->sequenceNumber)))
+ break;
+ call = vectorGetNext (outgoingCalls);
+ }
+ if (NULL != call)
+ {
+ RPC_Param *reply;
+ P2P_rpc_MESSAGE_GENERIC *gen;
+ unsigned short error;
- RPC_STATUS("", "received reply", call);
- gen = (P2P_rpc_MESSAGE_GENERIC*)res;
- reply = NULL;
- error = ntohs(res->functionNameLength);
+ RPC_STATUS ("", "received reply", call);
+ gen = (P2P_rpc_MESSAGE_GENERIC *) res;
+ reply = NULL;
+ error = ntohs (res->functionNameLength);
- if (error == RPC_ERROR_OK) {
- reply = RPC_paramDeserialize(&gen->data[0],
- ntohs(message->size) - sizeof(P2P_rpc_MESSAGE));
- if (ntohs(res->argumentCount) != RPC_paramCount(reply)) {
- RPC_paramFree(reply);
- reply = NULL;
- error = RPC_ERROR_REPLY_MALFORMED;
- }
+ if (error == RPC_ERROR_OK)
+ {
+ reply = RPC_paramDeserialize (&gen->data[0],
+ ntohs (message->size) -
+ sizeof (P2P_rpc_MESSAGE));
+ if (ntohs (res->argumentCount) != RPC_paramCount (reply))
+ {
+ RPC_paramFree (reply);
+ reply = NULL;
+ error = RPC_ERROR_REPLY_MALFORMED;
+ }
+ }
+ if (call->finishedCallback != NULL)
+ {
+ call->finishedCallback (call->rpcCallbackArgs,
+ call->sequenceNumber, error, reply);
+ call->finishedCallback = NULL;
+ }
+ vectorRemoveObject (outgoingCalls, call);
+ notifyPeerReply (sender,
+ MINGLE (call->sequenceNumber, P2P_PROTO_rpc_REQ));
+ cron_del_job (coreAPI->cron, &retryRPCJob, 0, call);
+ FREE (call->msg);
+ FREE (call);
+ if (reply != NULL)
+ RPC_paramFree (reply);
}
- if (call->finishedCallback != NULL) {
- call->finishedCallback(call->rpcCallbackArgs,
- call->sequenceNumber,
- error,
- reply);
- call->finishedCallback = NULL;
- }
- vectorRemoveObject(outgoingCalls,
- call);
- notifyPeerReply(sender,
- MINGLE(call->sequenceNumber,
- P2P_PROTO_rpc_REQ));
- cron_del_job(coreAPI->cron,
- &retryRPCJob,
- 0,
- call);
- FREE(call->msg);
- FREE(call);
- if (reply != NULL)
- RPC_paramFree(reply);
- }
- sendAck(sender,
- ntohl(res->sequenceNumber),
- 0,/* not important, ACK should be tiny enough to go through anyway */
- 0 /* right away */);
+ sendAck (sender, ntohl (res->sequenceNumber), 0, /* not important, ACK
should be tiny enough to go through anyway */
+ 0 /* right away */ );
MUTEX_UNLOCK (rpcLock);
- cron_resume_jobs(coreAPI->cron,
- NO);
+ cron_resume_jobs (coreAPI->cron, NO);
return OK;
}
@@ -1089,78 +1114,80 @@
/**
* Handle a peer-to-peer message of type P2P_PROTO_rpc_ACK.
*/
-static int handleRPCMessageAck(const PeerIdentity *sender,
- const MESSAGE_HEADER * message) {
- RPC_ACK_Message * ack;
+static int
+handleRPCMessageAck (const PeerIdentity * sender,
+ const MESSAGE_HEADER * message)
+{
+ RPC_ACK_Message *ack;
CallInstance *call;
- if ( (ntohs(message->type) != P2P_PROTO_rpc_ACK) ||
- (ntohs(message->size) != sizeof(RPC_ACK_Message)) ) {
- GE_LOG(ectx,
- GE_WARNING | GE_REQUEST | GE_ADMIN,
- _("Invalid message of type %u received. Dropping.\n"),
- ntohs (message->type));
- return SYSERR;
- }
+ if ((ntohs (message->type) != P2P_PROTO_rpc_ACK) ||
+ (ntohs (message->size) != sizeof (RPC_ACK_Message)))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_REQUEST | GE_ADMIN,
+ _("Invalid message of type %u received. Dropping.\n"),
+ ntohs (message->type));
+ return SYSERR;
+ }
- ack = (RPC_ACK_Message*) message;
+ ack = (RPC_ACK_Message *) message;
#if DEBUG_RPC
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Received RPC ACK with id %u.\n",
- ntohl(ack->sequenceNumber));
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received RPC ACK with id %u.\n", ntohl (ack->sequenceNumber));
#endif
- cron_suspend(coreAPI->cron,
- NO);
- MUTEX_LOCK(rpcLock);
+ cron_suspend (coreAPI->cron, NO);
+ MUTEX_LOCK (rpcLock);
/* Locate the CallInstance structure. */
- call = (CallInstance*) vectorGetFirst(incomingCalls);
- while (call != NULL) {
- if ( (0 == memcmp(&call->receiver,
- sender,
- sizeof(PeerIdentity))) &&
- (call->sequenceNumber == ntohl(ack->sequenceNumber)) )
- break;
- call = (CallInstance*) vectorGetNext(incomingCalls);
- }
+ call = (CallInstance *) vectorGetFirst (incomingCalls);
+ while (call != NULL)
+ {
+ if ((0 == memcmp (&call->receiver,
+ sender,
+ sizeof (PeerIdentity))) &&
+ (call->sequenceNumber == ntohl (ack->sequenceNumber)))
+ break;
+ call = (CallInstance *) vectorGetNext (incomingCalls);
+ }
/* check if we're waiting for an ACK, if so remove job */
- if (NULL != call) {
- RPC_STATUS("", "acknowledged reply", call);
- notifyPeerReply(sender,
- MINGLE(ntohl(ack->sequenceNumber),
- P2P_PROTO_rpc_RES));
- cron_del_job(coreAPI->cron,
- &retryRPCJob,
- 0,
- call);
- vectorRemoveObject(incomingCalls,
- call);
- FREE(call->msg);
- FREE(call);
- } else {
- PeerInfo * pi = getPeerInfo(sender);
- if (pi != NULL) {
- if (pi->averageResponseTime < MAX_RPC_TIMEOUT / 2)
- pi->averageResponseTime *= 2;
+ if (NULL != call)
+ {
+ RPC_STATUS ("", "acknowledged reply", call);
+ notifyPeerReply (sender,
+ MINGLE (ntohl (ack->sequenceNumber),
+ P2P_PROTO_rpc_RES));
+ cron_del_job (coreAPI->cron, &retryRPCJob, 0, call);
+ vectorRemoveObject (incomingCalls, call);
+ FREE (call->msg);
+ FREE (call);
}
+ else
+ {
+ PeerInfo *pi = getPeerInfo (sender);
+ if (pi != NULL)
+ {
+ if (pi->averageResponseTime < MAX_RPC_TIMEOUT / 2)
+ pi->averageResponseTime *= 2;
+ }
#if DEBUG_RPC
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "ACK is a duplicate (or invalid).\n");
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "ACK is a duplicate (or invalid).\n");
#endif
- }
+ }
MUTEX_UNLOCK (rpcLock);
- cron_resume_jobs(coreAPI->cron,
- NO);
+ cron_resume_jobs (coreAPI->cron, NO);
return OK;
}
/* ********************* RPC service functions ******************** */
-typedef struct {
- struct SEMAPHORE * sem;
- RPC_Param * result;
+typedef struct
+{
+ struct SEMAPHORE *sem;
+ RPC_Param *result;
unsigned short ec;
} RPC_EXEC_CLS;
@@ -1168,28 +1195,22 @@
* Callback function invoked whenever the RPC is complete
* (timeout, error or success).
*/
-static void RPC_execute_callback(RPC_EXEC_CLS * context,
- unsigned int sq,
- unsigned short ec,
- RPC_Param * res) {
+static void
+RPC_execute_callback (RPC_EXEC_CLS * context,
+ unsigned int sq, unsigned short ec, RPC_Param * res)
+{
int i;
unsigned int dl;
- void * data;
+ void *data;
- for (i=RPC_paramCount(res)-1;i>=0;i--) {
- data = NULL;
- RPC_paramValueByPosition(res,
- i,
- &dl,
- &data);
- RPC_paramAdd(context->result,
- RPC_paramName(res,
- i),
- dl,
- data);
- }
+ for (i = RPC_paramCount (res) - 1; i >= 0; i--)
+ {
+ data = NULL;
+ RPC_paramValueByPosition (res, i, &dl, &data);
+ RPC_paramAdd (context->result, RPC_paramName (res, i), dl, data);
+ }
context->ec = ec;
- SEMAPHORE_UP(context->sem);
+ SEMAPHORE_UP (context->sem);
}
/**
@@ -1202,68 +1223,62 @@
*
* @return the error code of the operation (0 for success).
*/
-static int RPC_execute(const PeerIdentity *receiver,
- const char *name,
- RPC_Param *requestParam,
- RPC_Param *returnParam,
- unsigned int importance,
- cron_t timeout) {
+static int
+RPC_execute (const PeerIdentity * receiver,
+ const char *name,
+ RPC_Param * requestParam,
+ RPC_Param * returnParam, unsigned int importance, cron_t timeout)
+{
RPC_EXEC_CLS cls;
- CallInstance * call;
+ CallInstance *call;
- MUTEX_LOCK(rpcLock);
- cls.sem = SEMAPHORE_CREATE(0);
+ MUTEX_LOCK (rpcLock);
+ cls.sem = SEMAPHORE_CREATE (0);
cls.result = returnParam;
- call = MALLOC(sizeof(CallInstance));
- RPC_STATUS(name, "started synchronously", call);
+ call = MALLOC (sizeof (CallInstance));
+ RPC_STATUS (name, "started synchronously", call);
call->lastAttempt = 0;
call->attempts = 0;
- call->repetitionFrequency = getExpectedResponseTime(receiver);
- call->expirationTime = get_time() + timeout;
+ call->repetitionFrequency = getExpectedResponseTime (receiver);
+ call->expirationTime = get_time () + timeout;
call->receiver = *receiver;
call->sequenceNumber = rpcIdentifier++;
- call->msg = buildMessage(RPC_ERROR_OK,
- name,
- call->sequenceNumber,
- importance,
- requestParam);
- call->finishedCallback = (RPCFinishedCallback) &RPC_execute_callback;
+ call->msg = buildMessage (RPC_ERROR_OK,
+ name,
+ call->sequenceNumber, importance, requestParam);
+ call->finishedCallback = (RPCFinishedCallback) & RPC_execute_callback;
call->rpcCallbackArgs = &cls;
- vectorInsertLast(outgoingCalls, call);
- GE_ASSERT(ectx,
- (get_time() + 1 * cronMINUTES > call->expirationTime) ||
- (call->expirationTime - get_time() < 1 * cronHOURS) );
- cron_add_job(coreAPI->cron,
- &retryRPCJob,
- 0,
- 0,
- call);
+ vectorInsertLast (outgoingCalls, call);
+ GE_ASSERT (ectx,
+ (get_time () + 1 * cronMINUTES > call->expirationTime) ||
+ (call->expirationTime - get_time () < 1 * cronHOURS));
+ cron_add_job (coreAPI->cron, &retryRPCJob, 0, 0, call);
MUTEX_UNLOCK (rpcLock);
- SEMAPHORE_DOWN(cls.sem, YES);
- SEMAPHORE_DESTROY(cls.sem);
- RPC_STATUS(name, "completed synchronously", call);
+ SEMAPHORE_DOWN (cls.sem, YES);
+ SEMAPHORE_DESTROY (cls.sem);
+ RPC_STATUS (name, "completed synchronously", call);
return cls.ec;
}
-typedef struct RPC_Record {
+typedef struct RPC_Record
+{
PeerIdentity peer;
- CallInstance * call;
+ CallInstance *call;
RPC_Complete callback;
- void * closure;
+ void *closure;
unsigned short errorCode;
} RPC_Record;
-static void RPC_async_callback(RPC_Record * rec,
- unsigned int sequenceNumber,
- unsigned short errorCode,
- RPC_Param * result) {
- if ( (errorCode == RPC_ERROR_OK) &&
- (rec->callback != NULL) ) {
- rec->callback(&rec->peer,
- result,
- rec->closure);
- rec->callback = NULL; /* never call callback twice */
- }
+static void
+RPC_async_callback (RPC_Record * rec,
+ unsigned int sequenceNumber,
+ unsigned short errorCode, RPC_Param * result)
+{
+ if ((errorCode == RPC_ERROR_OK) && (rec->callback != NULL))
+ {
+ rec->callback (&rec->peer, result, rec->closure);
+ rec->callback = NULL; /* never call callback twice */
+ }
rec->errorCode = errorCode;
}
@@ -1277,51 +1292,46 @@
* @return value required to stop the RPC (and the RPC must
* be explicitly stopped to free resources!)
*/
-static RPC_Record * RPC_start(const PeerIdentity * receiver,
- const char * name,
- RPC_Param * request_param,
- unsigned int importance,
- cron_t timeout,
- RPC_Complete callback,
- void * closure) {
- RPC_Record * ret;
+static RPC_Record *
+RPC_start (const PeerIdentity * receiver,
+ const char *name,
+ RPC_Param * request_param,
+ unsigned int importance,
+ cron_t timeout, RPC_Complete callback, void *closure)
+{
+ RPC_Record *ret;
- if (timeout > 1 * cronHOURS) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("`%s' called with timeout above 1 hour (bug?)\n"),
- __FUNCTION__);
- timeout = 1 * cronHOURS;
- }
- ret = MALLOC(sizeof(RPC_Record));
- RPC_STATUS(name, "started asynchronously", ret);
+ if (timeout > 1 * cronHOURS)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("`%s' called with timeout above 1 hour (bug?)\n"),
+ __FUNCTION__);
+ timeout = 1 * cronHOURS;
+ }
+ ret = MALLOC (sizeof (RPC_Record));
+ RPC_STATUS (name, "started asynchronously", ret);
ret->peer = *receiver;
ret->callback = callback;
ret->closure = closure;
ret->errorCode = RPC_ERROR_TIMEOUT;
- MUTEX_LOCK(rpcLock);
- ret->call = MALLOC(sizeof(CallInstance));
+ MUTEX_LOCK (rpcLock);
+ ret->call = MALLOC (sizeof (CallInstance));
ret->call->lastAttempt = 0;
ret->call->attempts = 0;
- ret->call->repetitionFrequency = getExpectedResponseTime(receiver);
- ret->call->expirationTime = get_time() + timeout;
+ ret->call->repetitionFrequency = getExpectedResponseTime (receiver);
+ ret->call->expirationTime = get_time () + timeout;
ret->call->receiver = *receiver;
ret->call->sequenceNumber = rpcIdentifier++;
- ret->call->msg = buildMessage(RPC_ERROR_OK,
- name,
- ret->call->sequenceNumber,
- importance,
- request_param);
- ret->call->finishedCallback =
- (RPCFinishedCallback) &RPC_async_callback;
+ ret->call->msg = buildMessage (RPC_ERROR_OK,
+ name,
+ ret->call->sequenceNumber,
+ importance, request_param);
+ ret->call->finishedCallback = (RPCFinishedCallback) & RPC_async_callback;
ret->call->rpcCallbackArgs = ret;
- vectorInsertLast(outgoingCalls, ret->call);
- GE_ASSERT(ectx, (get_time() + 1 * cronMINUTES > ret->call->expirationTime)
||
- (ret->call->expirationTime - get_time() < 1 * cronHOURS) );
- cron_add_job(coreAPI->cron,
- &retryRPCJob,
- 0,
- 0,
- ret->call);
+ vectorInsertLast (outgoingCalls, ret->call);
+ GE_ASSERT (ectx, (get_time () + 1 * cronMINUTES > ret->call->expirationTime)
+ || (ret->call->expirationTime - get_time () < 1 * cronHOURS));
+ cron_add_job (coreAPI->cron, &retryRPCJob, 0, 0, ret->call);
MUTEX_UNLOCK (rpcLock);
return ret;
}
@@ -1333,26 +1343,24 @@
* @return RPC_ERROR_OK if the RPC was successful,
* another RPC_ERROR code if it was aborted
*/
-static int RPC_stop(RPC_Record * record) {
+static int
+RPC_stop (RPC_Record * record)
+{
int ret;
- RPC_STATUS("", "stopped", record);
- cron_suspend(coreAPI->cron,
- YES);
- cron_del_job(coreAPI->cron,
- &retryRPCJob,
- 0,
- record->call);
- cron_resume_jobs(coreAPI->cron,
- YES);
- MUTEX_LOCK(rpcLock);
- if (NULL != vectorRemoveObject(outgoingCalls, record->call)) {
- FREE(record->call->msg);
- FREE(record->call);
- }
- MUTEX_UNLOCK(rpcLock);
+ RPC_STATUS ("", "stopped", record);
+ cron_suspend (coreAPI->cron, YES);
+ cron_del_job (coreAPI->cron, &retryRPCJob, 0, record->call);
+ cron_resume_jobs (coreAPI->cron, YES);
+ MUTEX_LOCK (rpcLock);
+ if (NULL != vectorRemoveObject (outgoingCalls, record->call))
+ {
+ FREE (record->call->msg);
+ FREE (record->call);
+ }
+ MUTEX_UNLOCK (rpcLock);
ret = record->errorCode;
- FREE(record);
+ FREE (record);
return ret;
}
@@ -1362,64 +1370,62 @@
/**
* Shutdown RPC service.
*/
-void release_module_rpc() {
- CallInstance * call;
+void
+release_module_rpc ()
+{
+ CallInstance *call;
- cron_del_job(coreAPI->cron,
- &agePeerStats,
- PEER_TRACKING_TIME_INTERVAL,
- NULL);
- coreAPI->unregisterHandler(P2P_PROTO_rpc_REQ,
- &handleRPCMessageReq);
- coreAPI->unregisterHandler(P2P_PROTO_rpc_RES,
- &handleRPCMessageRes);
- coreAPI->unregisterHandler(P2P_PROTO_rpc_ACK,
- &handleRPCMessageAck);
- if (NULL != peerInformation) {
- while(vectorSize(peerInformation) > 0)
- FREE(vectorRemoveLast(peerInformation));
- vectorFree(peerInformation);
- peerInformation = NULL;
- }
- if (NULL != incomingCalls) {
- while(vectorSize (incomingCalls) > 0) {
- call = (CallInstance*) vectorRemoveLast(incomingCalls);
- cron_del_job(coreAPI->cron,
- &retryRPCJob,
- 0,
- call);
- FREE(call->msg);
- FREE(call);
+ cron_del_job (coreAPI->cron,
+ &agePeerStats, PEER_TRACKING_TIME_INTERVAL, NULL);
+ coreAPI->unregisterHandler (P2P_PROTO_rpc_REQ, &handleRPCMessageReq);
+ coreAPI->unregisterHandler (P2P_PROTO_rpc_RES, &handleRPCMessageRes);
+ coreAPI->unregisterHandler (P2P_PROTO_rpc_ACK, &handleRPCMessageAck);
+ if (NULL != peerInformation)
+ {
+ while (vectorSize (peerInformation) > 0)
+ FREE (vectorRemoveLast (peerInformation));
+ vectorFree (peerInformation);
+ peerInformation = NULL;
}
- vectorFree(incomingCalls);
- incomingCalls = NULL;
- }
- if (NULL != outgoingCalls) {
- while(vectorSize (outgoingCalls) > 0) {
- call = (CallInstance*) vectorRemoveLast(outgoingCalls);
- cron_del_job(coreAPI->cron,
- &retryRPCJob,
- 0,
- call);
- FREE(call->msg);
- FREE(call);
+ if (NULL != incomingCalls)
+ {
+ while (vectorSize (incomingCalls) > 0)
+ {
+ call = (CallInstance *) vectorRemoveLast (incomingCalls);
+ cron_del_job (coreAPI->cron, &retryRPCJob, 0, call);
+ FREE (call->msg);
+ FREE (call);
+ }
+ vectorFree (incomingCalls);
+ incomingCalls = NULL;
}
- vectorFree(outgoingCalls);
- outgoingCalls = NULL;
- }
- if (NULL != list_of_callbacks) {
- while(vectorSize(list_of_callbacks) > 0) {
- RegisteredRPC * rpc;
- rpc = (RegisteredRPC*) vectorRemoveLast(list_of_callbacks);
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("RPC not unregistered: %s:%p\n"),
- rpc->name, rpc->callback);
- FREE(rpc->name);
- FREE(rpc);
+ if (NULL != outgoingCalls)
+ {
+ while (vectorSize (outgoingCalls) > 0)
+ {
+ call = (CallInstance *) vectorRemoveLast (outgoingCalls);
+ cron_del_job (coreAPI->cron, &retryRPCJob, 0, call);
+ FREE (call->msg);
+ FREE (call);
+ }
+ vectorFree (outgoingCalls);
+ outgoingCalls = NULL;
}
- vectorFree(list_of_callbacks);
- list_of_callbacks = NULL;
- }
+ if (NULL != list_of_callbacks)
+ {
+ while (vectorSize (list_of_callbacks) > 0)
+ {
+ RegisteredRPC *rpc;
+ rpc = (RegisteredRPC *) vectorRemoveLast (list_of_callbacks);
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("RPC not unregistered: %s:%p\n"),
+ rpc->name, rpc->callback);
+ FREE (rpc->name);
+ FREE (rpc);
+ }
+ vectorFree (list_of_callbacks);
+ list_of_callbacks = NULL;
+ }
coreAPI = NULL;
rpcLock = NULL;
}
@@ -1427,182 +1433,177 @@
/**
* Initialize the RPC service.
*/
-RPC_ServiceAPI * provide_module_rpc(CoreAPIForApplication * capi) {
+RPC_ServiceAPI *
+provide_module_rpc (CoreAPIForApplication * capi)
+{
static RPC_ServiceAPI rpcAPI;
int rvalue;
ectx = capi->ectx;
- rpcLock = capi->getConnectionModuleLock();
+ rpcLock = capi->getConnectionModuleLock ();
coreAPI = capi;
- peerInformation = vectorNew(16);
- incomingCalls = vectorNew(16);
- outgoingCalls = vectorNew(16);
- list_of_callbacks = vectorNew(16);
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- _("`%s' registering handlers %d %d %d\n"),
- "rpc",
- P2P_PROTO_rpc_REQ,
- P2P_PROTO_rpc_RES,
- P2P_PROTO_rpc_ACK);
+ peerInformation = vectorNew (16);
+ incomingCalls = vectorNew (16);
+ outgoingCalls = vectorNew (16);
+ list_of_callbacks = vectorNew (16);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ _("`%s' registering handlers %d %d %d\n"),
+ "rpc", P2P_PROTO_rpc_REQ, P2P_PROTO_rpc_RES, P2P_PROTO_rpc_ACK);
rvalue = OK;
- if (capi->registerHandler(P2P_PROTO_rpc_REQ,
- &handleRPCMessageReq) ==
- SYSERR)
+ if (capi->registerHandler (P2P_PROTO_rpc_REQ,
+ &handleRPCMessageReq) == SYSERR)
rvalue = SYSERR;
- if (capi->registerHandler(P2P_PROTO_rpc_RES,
- &handleRPCMessageRes) ==
- SYSERR)
+ if (capi->registerHandler (P2P_PROTO_rpc_RES,
+ &handleRPCMessageRes) == SYSERR)
rvalue = SYSERR;
if (capi->registerHandler (P2P_PROTO_rpc_ACK,
- &handleRPCMessageAck) ==
- SYSERR)
+ &handleRPCMessageAck) == SYSERR)
rvalue = SYSERR;
- if (rvalue == SYSERR) {
- release_module_rpc();
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Failed to initialize `%s' service.\n"),
- "rpc");
- return NULL;
- } else {
- rpcAPI.RPC_execute = &RPC_execute;
- rpcAPI.RPC_register = &RPC_register;
- rpcAPI.RPC_unregister = &RPC_unregister;
- rpcAPI.RPC_register_async = &RPC_register_async;
- rpcAPI.RPC_unregister_async = &RPC_unregister_async;
- rpcAPI.RPC_start = &RPC_start;
- rpcAPI.RPC_stop = &RPC_stop;
- cron_add_job(coreAPI->cron,
- &agePeerStats,
- PEER_TRACKING_TIME_INTERVAL,
- PEER_TRACKING_TIME_INTERVAL,
- NULL);
- return &rpcAPI;
- }
+ if (rvalue == SYSERR)
+ {
+ release_module_rpc ();
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Failed to initialize `%s' service.\n"), "rpc");
+ return NULL;
+ }
+ else
+ {
+ rpcAPI.RPC_execute = &RPC_execute;
+ rpcAPI.RPC_register = &RPC_register;
+ rpcAPI.RPC_unregister = &RPC_unregister;
+ rpcAPI.RPC_register_async = &RPC_register_async;
+ rpcAPI.RPC_unregister_async = &RPC_unregister_async;
+ rpcAPI.RPC_start = &RPC_start;
+ rpcAPI.RPC_stop = &RPC_stop;
+ cron_add_job (coreAPI->cron,
+ &agePeerStats,
+ PEER_TRACKING_TIME_INTERVAL,
+ PEER_TRACKING_TIME_INTERVAL, NULL);
+ return &rpcAPI;
+ }
}
#if PROVIDE_RPC_TEST
-static void testCallback(const PeerIdentity * sender,
- RPC_Param * arguments,
- RPC_Param * results) {
+static void
+testCallback (const PeerIdentity * sender,
+ RPC_Param * arguments, RPC_Param * results)
+{
unsigned int dl;
- char * data;
+ char *data;
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "RPC callback invoked!\n");
- if ( (OK == RPC_paramValueByName(arguments,
- "command",
- &dl,
- (void**)&data)) &&
- (strncmp("Hello", data, dl) == 0) ) {
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "RPC callback received Hello command!\n");
- RPC_paramAdd(results,
- "response",
- strlen("Hello RPC World")+1,
- "Hello RPC World");
- }
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, "RPC callback invoked!\n");
+ if ((OK == RPC_paramValueByName (arguments,
+ "command",
+ &dl,
+ (void **) &data)) &&
+ (strncmp ("Hello", data, dl) == 0))
+ {
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "RPC callback received Hello command!\n");
+ RPC_paramAdd (results,
+ "response",
+ strlen ("Hello RPC World") + 1, "Hello RPC World");
+ }
}
-static void async_RPC_Complete_callback(RPC_Param * results,
- struct SEMAPHORE * sign) {
+static void
+async_RPC_Complete_callback (RPC_Param * results, struct SEMAPHORE *sign)
+{
unsigned int dl;
- char * reply;
+ char *reply;
- SEMAPHORE_DOWN(sign, YES);
- if ( (OK != RPC_paramValueByName(results,
- "response",
- &dl,
- (void**)&reply)) ||
- (strncmp("Hello RPC World",
- reply, dl) != 0) ) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("RPC async reply invalid.\n"));
- } else
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "RPC async reply received.\n");
+ SEMAPHORE_DOWN (sign, YES);
+ if ((OK != RPC_paramValueByName (results,
+ "response",
+ &dl,
+ (void **) &reply)) ||
+ (strncmp ("Hello RPC World", reply, dl) != 0))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("RPC async reply invalid.\n"));
+ }
+ else
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "RPC async reply received.\n");
}
-int initialize_module_rpc(CoreAPIForApplication * capi) {
- RPC_ServiceAPI * rpcAPI;
+int
+initialize_module_rpc (CoreAPIForApplication * capi)
+{
+ RPC_ServiceAPI *rpcAPI;
int ret;
- RPC_Param * args;
- RPC_Param * rets;
+ RPC_Param *args;
+ RPC_Param *rets;
unsigned int dl;
- char * reply;
+ char *reply;
int code;
- RPC_Record * record;
- struct SEMAPHORE * sign;
+ RPC_Record *record;
+ struct SEMAPHORE *sign;
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "RPC testcase starting\n");
- rpcAPI = capi->requestService("rpc");
- if (rpcAPI == NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, "RPC testcase starting\n");
+ rpcAPI = capi->requestService ("rpc");
+ if (rpcAPI == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
ret = OK;
- if (OK != rpcAPI->RPC_register("testFunction",
- &testCallback)) {
- GE_BREAK(ectx, 0);
- ret = SYSERR;
- }
+ if (OK != rpcAPI->RPC_register ("testFunction", &testCallback))
+ {
+ GE_BREAK (ectx, 0);
+ ret = SYSERR;
+ }
- args = RPC_paramNew();
- RPC_paramAdd(args,
- "command",
- strlen("Hello")+1,
- "Hello");
- sign = SEMAPHORE_CREATE(0);
- record = rpcAPI->RPC_start(coreAPI->myIdentity,
- "testFunction",
- args,
- 0,
- 5 * cronSECONDS,
- (RPC_Complete) &async_RPC_Complete_callback,
- sign);
- SEMAPHORE_UP(sign); /* allow callback now - forces async! */
- rets = RPC_paramNew();
- code = rpcAPI->RPC_execute(coreAPI->myIdentity,
- "testFunction",
- args,
- rets,
- 0,
- 5 * cronSECONDS);
- if (code != RPC_ERROR_OK) {
- GE_BREAK(ectx, 0);
- ret = SYSERR;
- }
- RPC_paramFree(args);
- if ( (OK != RPC_paramValueByName(rets,
- "response",
- &dl,
- (void**)&reply)) ||
- (strncmp("Hello RPC World",
- reply, dl) != 0) ) {
- GE_BREAK(ectx, 0);
- ret = SYSERR;
- }
- RPC_paramFree(rets);
- PTHREAD_SLEEP(1 * cronSECONDS);
- if (RPC_ERROR_OK != rpcAPI->RPC_stop(record))
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("async RPC reply not received.\n"));
+ args = RPC_paramNew ();
+ RPC_paramAdd (args, "command", strlen ("Hello") + 1, "Hello");
+ sign = SEMAPHORE_CREATE (0);
+ record = rpcAPI->RPC_start (coreAPI->myIdentity,
+ "testFunction",
+ args,
+ 0,
+ 5 * cronSECONDS,
+ (RPC_Complete) & async_RPC_Complete_callback,
+ sign);
+ SEMAPHORE_UP (sign); /* allow callback now - forces async! */
+ rets = RPC_paramNew ();
+ code = rpcAPI->RPC_execute (coreAPI->myIdentity,
+ "testFunction", args, rets, 0, 5 * cronSECONDS);
+ if (code != RPC_ERROR_OK)
+ {
+ GE_BREAK (ectx, 0);
+ ret = SYSERR;
+ }
+ RPC_paramFree (args);
+ if ((OK != RPC_paramValueByName (rets,
+ "response",
+ &dl,
+ (void **) &reply)) ||
+ (strncmp ("Hello RPC World", reply, dl) != 0))
+ {
+ GE_BREAK (ectx, 0);
+ ret = SYSERR;
+ }
+ RPC_paramFree (rets);
+ PTHREAD_SLEEP (1 * cronSECONDS);
+ if (RPC_ERROR_OK != rpcAPI->RPC_stop (record))
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("async RPC reply not received.\n"));
- if (OK != rpcAPI->RPC_unregister("testFunction",
- &testCallback)) {
- GE_BREAK(ectx, 0);
- ret = SYSERR;
- }
- if (OK != capi->releaseService(rpcAPI)) {
- GE_BREAK(ectx, 0);
- ret = SYSERR;
- }
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "RPC testcase completed with status %s\n",
- ret == OK ? "SUCCESS" : "FAILURE");
+ if (OK != rpcAPI->RPC_unregister ("testFunction", &testCallback))
+ {
+ GE_BREAK (ectx, 0);
+ ret = SYSERR;
+ }
+ if (OK != capi->releaseService (rpcAPI))
+ {
+ GE_BREAK (ectx, 0);
+ ret = SYSERR;
+ }
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "RPC testcase completed with status %s\n",
+ ret == OK ? "SUCCESS" : "FAILURE");
return ret;
}
@@ -1610,7 +1611,9 @@
* Does nothing (but must be present for clean unload of the
* testcase!).
*/
-int done_module_rpc() {
+int
+done_module_rpc ()
+{
return OK;
}
Modified: GNUnet/src/applications/session/connect.c
===================================================================
--- GNUnet/src/applications/session/connect.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/session/connect.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -41,19 +41,19 @@
#define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
-static Transport_ServiceAPI * transport;
+static Transport_ServiceAPI *transport;
-static Pingpong_ServiceAPI * pingpong;
+static Pingpong_ServiceAPI *pingpong;
-static Topology_ServiceAPI * topology;
+static Topology_ServiceAPI *topology;
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
static int stat_skeySent;
@@ -70,7 +70,8 @@
/**
* @brief message for session key exchange.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
* time when this key was created (network byte order)
@@ -95,7 +96,8 @@
/**
* @brief message for session key exchange.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
* time when this key was created (network byte order)
@@ -127,19 +129,19 @@
/**
* Not thread-safe, only use for debugging!
*/
-static const char * printSKEY(const SESSIONKEY * sk) {
+static const char *
+printSKEY (const SESSIONKEY * sk)
+{
static char r[512];
static char t[12];
int i;
- strcpy(r, "");
- for (i=0;i<SESSIONKEY_LEN;i++) {
- SNPRINTF(t,
- 12,
- "%02x",
- sk->key[i]);
- strcat(r,t);
- }
+ strcpy (r, "");
+ for (i = 0; i < SESSIONKEY_LEN; i++)
+ {
+ SNPRINTF (t, 12, "%02x", sk->key[i]);
+ strcat (r, t);
+ }
return r;
}
#endif
@@ -149,30 +151,28 @@
*
* @param hostId the peer that gave a sign of live
*/
-static void notifyPONG(void * arg) {
- PeerIdentity * hostId = arg;
+static void
+notifyPONG (void *arg)
+{
+ PeerIdentity *hostId = arg;
#if DEBUG_SESSION
EncName enc;
#endif
- GE_ASSERT(ectx, hostId != NULL);
+ GE_ASSERT (ectx, hostId != NULL);
#if DEBUG_SESSION
- IF_GELOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- hash2enc(&hostId->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Received `%s' from `%s', marking session as up.\n",
- "PONG",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ hash2enc (&hostId->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Received `%s' from `%s', marking session as up.\n", "PONG", &enc);
#endif
- GE_ASSERT(ectx, hostId != NULL);
+ GE_ASSERT (ectx, hostId != NULL);
if (stats != NULL)
- stats->change(stat_sessionEstablished,
- 1);
- coreAPI->confirmSessionUp(hostId);
- FREE(hostId);
+ stats->change (stat_sessionEstablished, 1);
+ coreAPI->confirmSessionUp (hostId);
+ FREE (hostId);
}
@@ -186,101 +186,94 @@
* @return SYSERR if invalid, OK if valid, NO if
* connections are disallowed
*/
-static int verifySKS(const PeerIdentity * hostId,
- const P2P_setkey_MESSAGE * sks,
- const Signature * signature) {
- char * limited;
+static int
+verifySKS (const PeerIdentity * hostId,
+ const P2P_setkey_MESSAGE * sks, const Signature * signature)
+{
+ char *limited;
EncName enc;
unsigned int rsize;
- if ( (sks == NULL) ||
- (hostId == NULL) ) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ if ((sks == NULL) || (hostId == NULL))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
/* check if we are allowed to accept connections
from that peer */
limited = NULL;
- GC_get_configuration_value_string(coreAPI->cfg,
- "GNUNETD",
- "LIMIT-ALLOW",
- "",
- &limited);
- if (strlen(limited) > 0) {
- hash2enc(&hostId->hashPubKey,
- &enc);
- if (NULL == strstr(limited,
- (char*) &enc)) {
+ GC_get_configuration_value_string (coreAPI->cfg,
+ "GNUNETD", "LIMIT-ALLOW", "", &limited);
+ if (strlen (limited) > 0)
+ {
+ hash2enc (&hostId->hashPubKey, &enc);
+ if (NULL == strstr (limited, (char *) &enc))
+ {
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Connection from peer `%s' was rejected (not allowed).\n",
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Connection from peer `%s' was rejected (not allowed).\n",
+ &enc);
#endif
- FREE(limited);
- return NO;
+ FREE (limited);
+ return NO;
+ }
}
- }
- FREE(limited);
+ FREE (limited);
limited = NULL;
- GC_get_configuration_value_string(coreAPI->cfg,
- "GNUNETD",
- "LIMIT-DENY",
- "",
- &limited);
- if (strlen(limited) > 0) {
- hash2enc(&hostId->hashPubKey,
- &enc);
- if (NULL != strstr(limited,
- (char*) &enc)) {
+ GC_get_configuration_value_string (coreAPI->cfg,
+ "GNUNETD", "LIMIT-DENY", "", &limited);
+ if (strlen (limited) > 0)
+ {
+ hash2enc (&hostId->hashPubKey, &enc);
+ if (NULL != strstr (limited, (char *) &enc))
+ {
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Connection from peer `%s' was rejected (explicitly denied).\n",
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Connection from peer `%s' was rejected (explicitly
denied).\n",
+ &enc);
#endif
- FREE(limited);
- return NO;
+ FREE (limited);
+ return NO;
+ }
}
- }
- FREE(limited);
+ FREE (limited);
- rsize = ntohs(sks->header.size);
- while (rsize > sizeof(P2P_new_setkey_MESSAGE))
+ rsize = ntohs (sks->header.size);
+ while (rsize > sizeof (P2P_new_setkey_MESSAGE))
rsize -= pingpong->ping_size;
- if (rsize < sizeof(P2P_setkey_MESSAGE)) {
- EncName enc;
+ if (rsize < sizeof (P2P_setkey_MESSAGE))
+ {
+ EncName enc;
- GE_BREAK_OP(ectx, 0);
- IF_GELOG(ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- hash2enc(&hostId->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- _("Session key from peer `%s' could not be verified.\n"),
- &enc);
- return SYSERR;
- }
- if (OK != identity->verifyPeerSignature(hostId,
- sks,
- rsize - sizeof(Signature),
- signature)) {
+ GE_BREAK_OP (ectx, 0);
+ IF_GELOG (ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ hash2enc (&hostId->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ _("Session key from peer `%s' could not be verified.\n"), &enc);
+ return SYSERR;
+ }
+ if (OK != identity->verifyPeerSignature (hostId,
+ sks,
+ rsize - sizeof (Signature),
+ signature))
+ {
#if DEBUG_SESSION
- EncName enc;
+ EncName enc;
- IF_GELOG(ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- hash2enc(&hostId->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- _("Session key from peer `%s' could not be verified.\n"),
- &enc);
+ IF_GELOG (ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ hash2enc (&hostId->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ _("Session key from peer `%s' could not be verified.\n"), &enc);
#endif
- return SYSERR; /*reject!*/
- }
- return OK; /* ok */
+ return SYSERR; /*reject! */
+ }
+ return OK; /* ok */
}
/**
@@ -296,126 +289,116 @@
* @return message on success, NULL on failure
*/
static P2P_new_setkey_MESSAGE *
-makeSessionKeySigned(const PeerIdentity * hostId,
- const SESSIONKEY * sk,
- TIME_T created,
- const MESSAGE_HEADER * ping,
- const MESSAGE_HEADER * pong) {
- P2P_hello_MESSAGE * foreignHello;
+makeSessionKeySigned (const PeerIdentity * hostId,
+ const SESSIONKEY * sk,
+ TIME_T created,
+ const MESSAGE_HEADER * ping,
+ const MESSAGE_HEADER * pong)
+{
+ P2P_hello_MESSAGE *foreignHello;
int size;
- P2P_new_setkey_MESSAGE * msg;
- char * pt;
+ P2P_new_setkey_MESSAGE *msg;
+ char *pt;
EncName enc;
PeerIdentity hc;
- GE_ASSERT(ectx, sk != NULL);
- foreignHello = identity->identity2Hello(hostId,
- ANY_PROTOCOL_NUMBER,
- YES);
+ GE_ASSERT (ectx, sk != NULL);
+ foreignHello = identity->identity2Hello (hostId, ANY_PROTOCOL_NUMBER, YES);
/* create and encrypt sessionkey */
- if (NULL == foreignHello) {
- hash2enc(&hostId->hashPubKey,
- &enc);
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- _("Cannot encrypt sessionkey, peer `%s' not known!\n"),
- &enc);
- return NULL; /* other host not known */
- }
- identity->getPeerIdentity(&foreignHello->publicKey,
- &hc);
- if ( (0 != memcmp(&hc,
- hostId,
- sizeof(PeerIdentity))) ||
- (0 != memcmp(&hc,
- &foreignHello->senderIdentity,
- sizeof(PeerIdentity))) ) {
- GE_BREAK_OP(NULL,
- 0 == memcmp(&hc,
- &foreignHello->senderIdentity,
- sizeof(PeerIdentity)));
- GE_BREAK_OP(NULL,
- 0 == memcmp(&hc,
- hostId,
- sizeof(PeerIdentity)));
- GE_BREAK_OP(NULL, 0);
- FREE(foreignHello);
- return NULL;
- }
+ if (NULL == foreignHello)
+ {
+ hash2enc (&hostId->hashPubKey, &enc);
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ _("Cannot encrypt sessionkey, peer `%s' not known!\n"), &enc);
+ return NULL; /* other host not known */
+ }
+ identity->getPeerIdentity (&foreignHello->publicKey, &hc);
+ if ((0 != memcmp (&hc,
+ hostId,
+ sizeof (PeerIdentity))) ||
+ (0 != memcmp (&hc,
+ &foreignHello->senderIdentity, sizeof (PeerIdentity))))
+ {
+ GE_BREAK_OP (NULL,
+ 0 == memcmp (&hc,
+ &foreignHello->senderIdentity,
+ sizeof (PeerIdentity)));
+ GE_BREAK_OP (NULL, 0 == memcmp (&hc, hostId, sizeof (PeerIdentity)));
+ GE_BREAK_OP (NULL, 0);
+ FREE (foreignHello);
+ return NULL;
+ }
- size = sizeof(P2P_new_setkey_MESSAGE);
+ size = sizeof (P2P_new_setkey_MESSAGE);
if (ping != NULL)
- size += ntohs(ping->size);
+ size += ntohs (ping->size);
if (pong != NULL)
- size += ntohs(pong->size);
- msg = MALLOC(size);
+ size += ntohs (pong->size);
+ msg = MALLOC (size);
msg->target = *hostId;
- if (SYSERR == encryptPrivateKey(sk,
- sizeof(SESSIONKEY),
- &foreignHello->publicKey,
- &msg->key)) {
- GE_BREAK_OP(ectx, 0);
- FREE(foreignHello);
- FREE(msg);
- return NULL; /* encrypt failed */
- }
- FREE(foreignHello);
+ if (SYSERR == encryptPrivateKey (sk,
+ sizeof (SESSIONKEY),
+ &foreignHello->publicKey, &msg->key))
+ {
+ GE_BREAK_OP (ectx, 0);
+ FREE (foreignHello);
+ FREE (msg);
+ return NULL; /* encrypt failed */
+ }
+ FREE (foreignHello);
/* complete header */
- msg->header.size = htons(size);
- msg->header.type = htons(P2P_PROTO_setkey);
- msg->creationTime = htonl(created);
- GE_ASSERT(ectx,
- SYSERR !=
- identity->signData(msg,
- sizeof(P2P_new_setkey_MESSAGE)
- - sizeof(Signature),
- &msg->signature));
+ msg->header.size = htons (size);
+ msg->header.type = htons (P2P_PROTO_setkey);
+ msg->creationTime = htonl (created);
+ GE_ASSERT (ectx,
+ SYSERR !=
+ identity->signData (msg,
+ sizeof (P2P_new_setkey_MESSAGE)
+ - sizeof (Signature), &msg->signature));
#if EXTRA_CHECKS
/* verify signature/SKS */
- GE_ASSERT(ectx,
- SYSERR != verifySKS(coreAPI->myIdentity,
- (const P2P_setkey_MESSAGE*) msg,
- &msg->signature));
+ GE_ASSERT (ectx,
+ SYSERR != verifySKS (coreAPI->myIdentity,
+ (const P2P_setkey_MESSAGE *) msg,
+ &msg->signature));
#endif
size = 0;
if (ping != NULL)
- size += ntohs(ping->size);
+ size += ntohs (ping->size);
if (pong != NULL)
- size += ntohs(pong->size);
- if (size > 0) {
- pt = MALLOC(size);
- size = 0;
- if (ping != NULL) {
- memcpy(&pt[size],
- ping,
- ntohs(ping->size));
- size += ntohs(ping->size);
- }
- if (pong != NULL) {
- memcpy(&pt[size],
- pong,
- ntohs(pong->size));
- size += ntohs(pong->size);
- }
+ size += ntohs (pong->size);
+ if (size > 0)
+ {
+ pt = MALLOC (size);
+ size = 0;
+ if (ping != NULL)
+ {
+ memcpy (&pt[size], ping, ntohs (ping->size));
+ size += ntohs (ping->size);
+ }
+ if (pong != NULL)
+ {
+ memcpy (&pt[size], pong, ntohs (pong->size));
+ size += ntohs (pong->size);
+ }
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Encrypting %d bytes of PINGPONG with key %s and IV %u\n",
- size,
- printSKEY(sk),
- *(int*)&msg->signature);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Encrypting %d bytes of PINGPONG with key %s and IV %u\n",
+ size, printSKEY (sk), *(int *) &msg->signature);
#endif
- GE_ASSERT(ectx,
- -1 != encryptBlock(pt,
- size,
- sk,
- (const INITVECTOR*) &msg->signature,
- (char*)&msg[1]));
- FREE(pt);
- }
+ GE_ASSERT (ectx,
+ -1 != encryptBlock (pt,
+ size,
+ sk,
+ (const INITVECTOR *) &msg->signature,
+ (char *) &msg[1]));
+ FREE (pt);
+ }
return msg;
}
@@ -428,134 +411,118 @@
* @param tsession session to use for the exchange (maybe NULL)
* @param pong pong to include (maybe NULL)
*/
-static int exchangeKey(const PeerIdentity * receiver,
- TSession * tsession,
- MESSAGE_HEADER * pong) {
- P2P_hello_MESSAGE * hello;
- P2P_new_setkey_MESSAGE * skey;
+static int
+exchangeKey (const PeerIdentity * receiver,
+ TSession * tsession, MESSAGE_HEADER * pong)
+{
+ P2P_hello_MESSAGE *hello;
+ P2P_new_setkey_MESSAGE *skey;
SESSIONKEY sk;
TIME_T age;
- MESSAGE_HEADER * ping;
- PeerIdentity * sndr;
+ MESSAGE_HEADER *ping;
+ PeerIdentity *sndr;
EncName enc;
- GE_ASSERT(ectx,
- receiver != NULL);
- if ( (tsession != NULL) &&
- (0 != memcmp(&tsession->peer,
- receiver,
- sizeof(PeerIdentity))) ) {
- GE_BREAK(ectx, 0);
- tsession = NULL;
- }
- if ( (topology != NULL) &&
- (topology->allowConnectionFrom(receiver) == SYSERR) )
+ GE_ASSERT (ectx, receiver != NULL);
+ if ((tsession != NULL) &&
+ (0 != memcmp (&tsession->peer, receiver, sizeof (PeerIdentity))))
+ {
+ GE_BREAK (ectx, 0);
+ tsession = NULL;
+ }
+ if ((topology != NULL) &&
+ (topology->allowConnectionFrom (receiver) == SYSERR))
return SYSERR;
- hash2enc(&receiver->hashPubKey,
- &enc);
+ hash2enc (&receiver->hashPubKey, &enc);
/* then try to connect on the transport level */
- if ( (tsession == NULL) ||
- (transport->associate(tsession) == SYSERR) )
- tsession = transport->connectFreely(receiver,
- YES);
- if (tsession == NULL) {
+ if ((tsession == NULL) || (transport->associate (tsession) == SYSERR))
+ tsession = transport->connectFreely (receiver, YES);
+ if (tsession == NULL)
+ {
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Key exchange with `%s' failed: could not connect.\n",
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Key exchange with `%s' failed: could not connect.\n", &enc);
#endif
- return SYSERR; /* failed to connect */
- }
+ return SYSERR; /* failed to connect */
+ }
/* create our ping */
- sndr = MALLOC(sizeof(PeerIdentity));
+ sndr = MALLOC (sizeof (PeerIdentity));
*sndr = *receiver;
- ping = pingpong->pingUser(receiver,
- ¬ifyPONG,
- sndr,
- NO,
- rand());
- if (ping == NULL) {
- FREE(sndr);
- transport->disconnect(tsession);
- return SYSERR;
- }
+ ping = pingpong->pingUser (receiver, ¬ifyPONG, sndr, NO, rand ());
+ if (ping == NULL)
+ {
+ FREE (sndr);
+ transport->disconnect (tsession);
+ return SYSERR;
+ }
/* get or create our session key */
- if (OK != coreAPI->getCurrentSessionKey(receiver,
- &sk,
- &age,
- YES)) {
- age = TIME(NULL);
- makeSessionkey(&sk);
+ if (OK != coreAPI->getCurrentSessionKey (receiver, &sk, &age, YES))
+ {
+ age = TIME (NULL);
+ makeSessionkey (&sk);
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Created fresh sessionkey `%s' for peer `%s'.\n",
- printSKEY(&sk),
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Created fresh sessionkey `%s' for peer `%s'.\n",
+ printSKEY (&sk), &enc);
#endif
- }
+ }
/* build SKEY message */
- skey = makeSessionKeySigned(receiver,
- &sk,
- age,
- ping,
- pong);
- FREE(ping);
- if (skey == NULL) {
- transport->disconnect(tsession);
- return SYSERR;
- }
+ skey = makeSessionKeySigned (receiver, &sk, age, ping, pong);
+ FREE (ping);
+ if (skey == NULL)
+ {
+ transport->disconnect (tsession);
+ return SYSERR;
+ }
/* create hello */
- hello = transport->createhello(tsession->ttype);
+ hello = transport->createhello (tsession->ttype);
if (NULL == hello)
- hello = transport->createhello(ANY_PROTOCOL_NUMBER);
- if (NULL == hello) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("Could not create any HELLO for myself!\n"));
- }
+ hello = transport->createhello (ANY_PROTOCOL_NUMBER);
+ if (NULL == hello)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _("Could not create any HELLO for myself!\n"));
+ }
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Sending session key `%s' to peer `%s'.\n",
- printSKEY(&sk),
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Sending session key `%s' to peer `%s'.\n", printSKEY (&sk), &enc);
#endif
- if (stats != NULL) {
- stats->change(stat_pingSent, 1);
- stats->change(stat_skeySent, 1);
- /* pong, if present, is accounted for
- by caller */
- }
- if (hello != NULL) {
- coreAPI->sendPlaintext(tsession,
- (const char*) hello,
- P2P_hello_MESSAGE_size(hello));
- FREE(hello);
- hello = NULL;
- coreAPI->sendPlaintext(tsession,
- (const char*) skey,
- ntohs(skey->header.size));
- }
- FREE(skey);
- if (0 != memcmp(receiver,
- &tsession->peer,
- sizeof(PeerIdentity))) {
- GE_BREAK(NULL, 0);
- transport->disconnect(tsession);
- } else {
- coreAPI->offerTSessionFor(receiver,
- tsession);
- }
- coreAPI->assignSessionKey(&sk,
- receiver,
- age,
- YES);
+ if (stats != NULL)
+ {
+ stats->change (stat_pingSent, 1);
+ stats->change (stat_skeySent, 1);
+ /* pong, if present, is accounted for
+ by caller */
+ }
+ if (hello != NULL)
+ {
+ coreAPI->sendPlaintext (tsession,
+ (const char *) hello,
+ P2P_hello_MESSAGE_size (hello));
+ FREE (hello);
+ hello = NULL;
+ coreAPI->sendPlaintext (tsession,
+ (const char *) skey, ntohs (skey->header.size));
+ }
+ FREE (skey);
+ if (0 != memcmp (receiver, &tsession->peer, sizeof (PeerIdentity)))
+ {
+ GE_BREAK (NULL, 0);
+ transport->disconnect (tsession);
+ }
+ else
+ {
+ coreAPI->offerTSessionFor (receiver, tsession);
+ }
+ coreAPI->assignSessionKey (&sk, receiver, age, YES);
return OK;
}
@@ -571,255 +538,249 @@
* @param msg message with the session key
* @return SYSERR or OK
*/
-static int acceptSessionKey(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg,
- TSession * tsession) {
+static int
+acceptSessionKey (const PeerIdentity * sender,
+ const MESSAGE_HEADER * msg, TSession * tsession)
+{
SESSIONKEY key;
- MESSAGE_HEADER * ping;
- MESSAGE_HEADER * pong;
- const P2P_setkey_MESSAGE * sessionkeySigned;
+ MESSAGE_HEADER *ping;
+ MESSAGE_HEADER *pong;
+ const P2P_setkey_MESSAGE *sessionkeySigned;
int size;
int pos;
- char * plaintext;
+ char *plaintext;
EncName enc;
int ret;
- const Signature * sig;
- const P2P_new_setkey_MESSAGE * newMsg;
- const void * end;
+ const Signature *sig;
+ const P2P_new_setkey_MESSAGE *newMsg;
+ const void *end;
- if (sender == NULL) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- hash2enc(&sender->hashPubKey,
- &enc);
- if ( (topology != NULL) &&
- (topology->allowConnectionFrom(sender) == SYSERR) ) {
+ if (sender == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ hash2enc (&sender->hashPubKey, &enc);
+ if ((topology != NULL) &&
+ (topology->allowConnectionFrom (sender) == SYSERR))
+ {
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Topology rejected session key from peer `%s'.\n",
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Topology rejected session key from peer `%s'.\n", &enc);
#endif
- return SYSERR;
- }
- if (equalsHashCode512(&sender->hashPubKey,
- &coreAPI->myIdentity->hashPubKey)) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ return SYSERR;
+ }
+ if (equalsHashCode512 (&sender->hashPubKey,
+ &coreAPI->myIdentity->hashPubKey))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Received session key from peer `%s'.\n",
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Received session key from peer `%s'.\n", &enc);
#endif
- if (ntohs(msg->size) < sizeof(P2P_setkey_MESSAGE)) {
- GE_LOG(ectx,
- GE_WARNING | GE_DEVELOPER | GE_USER | GE_BULK,
- _("Session key received from peer `%s' has invalid format
(discarded).\n"),
- &enc);
- return SYSERR;
- }
+ if (ntohs (msg->size) < sizeof (P2P_setkey_MESSAGE))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_DEVELOPER | GE_USER | GE_BULK,
+ _
+ ("Session key received from peer `%s' has invalid format
(discarded).\n"),
+ &enc);
+ return SYSERR;
+ }
sessionkeySigned = (const P2P_setkey_MESSAGE *) msg;
- if ( (ntohs(msg->size) == sizeof(P2P_new_setkey_MESSAGE)) ||
- (ntohs(msg->size) == sizeof(P2P_new_setkey_MESSAGE) +
pingpong->ping_size) ||
- (ntohs(msg->size) == sizeof(P2P_new_setkey_MESSAGE) +
pingpong->ping_size * 2) ) {
- newMsg = (const P2P_new_setkey_MESSAGE *) msg;
+ if ((ntohs (msg->size) == sizeof (P2P_new_setkey_MESSAGE)) ||
+ (ntohs (msg->size) ==
+ sizeof (P2P_new_setkey_MESSAGE) + pingpong->ping_size)
+ || (ntohs (msg->size) ==
+ sizeof (P2P_new_setkey_MESSAGE) + pingpong->ping_size * 2))
+ {
+ newMsg = (const P2P_new_setkey_MESSAGE *) msg;
- if (!equalsHashCode512(&coreAPI->myIdentity->hashPubKey,
- &newMsg->target.hashPubKey)) {
- EncName ta;
- hash2enc(&newMsg->target.hashPubKey,
- &ta);
- GE_LOG(ectx,
- GE_WARNING | GE_DEVELOPER | GE_USER | GE_BULK,
- _("Session key received from peer `%s' is for `%s' and not for me!\n"),
- &enc,
- &ta);
- return SYSERR; /* not for us! */
+ if (!equalsHashCode512 (&coreAPI->myIdentity->hashPubKey,
+ &newMsg->target.hashPubKey))
+ {
+ EncName ta;
+ hash2enc (&newMsg->target.hashPubKey, &ta);
+ GE_LOG (ectx,
+ GE_WARNING | GE_DEVELOPER | GE_USER | GE_BULK,
+ _
+ ("Session key received from peer `%s' is for `%s' and not
for me!\n"),
+ &enc, &ta);
+ return SYSERR; /* not for us! */
+ }
+ sig = &newMsg->signature;
}
- sig = &newMsg->signature;
- } else {
- sig = &sessionkeySigned->signature;
- newMsg = NULL;
- }
- ret = verifySKS(sender,
- sessionkeySigned,
- sig);
- if (OK != ret) {
+ else
+ {
+ sig = &sessionkeySigned->signature;
+ newMsg = NULL;
+ }
+ ret = verifySKS (sender, sessionkeySigned, sig);
+ if (OK != ret)
+ {
#if DEBUG_SESSION
- if (ret == SYSERR)
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_REQUEST | GE_DEVELOPER,
- "Signature of session key from `%s' failed"
- " verification (discarded).\n",
- &enc);
+ if (ret == SYSERR)
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_REQUEST | GE_DEVELOPER,
+ "Signature of session key from `%s' failed"
+ " verification (discarded).\n", &enc);
#endif
- if (stats != NULL)
- stats->change(stat_skeyRejected,
- 1);
- return SYSERR; /* rejected */
- }
- memset(&key, 0, sizeof(SESSIONKEY));
- size = identity->decryptData(&sessionkeySigned->key,
- &key,
- sizeof(SESSIONKEY));
- if (size != sizeof(SESSIONKEY)) {
- GE_LOG(ectx,
- GE_WARNING | GE_DEVELOPER | GE_USER | GE_BULK,
- _("Invalid `%s' message received from peer `%s'.\n"),
- "setkey",
- &enc);
- return SYSERR;
- }
- if (key.crc32 !=
- htonl(crc32N(&key, SESSIONKEY_LEN))) {
+ if (stats != NULL)
+ stats->change (stat_skeyRejected, 1);
+ return SYSERR; /* rejected */
+ }
+ memset (&key, 0, sizeof (SESSIONKEY));
+ size = identity->decryptData (&sessionkeySigned->key,
+ &key, sizeof (SESSIONKEY));
+ if (size != sizeof (SESSIONKEY))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_DEVELOPER | GE_USER | GE_BULK,
+ _("Invalid `%s' message received from peer `%s'.\n"),
+ "setkey", &enc);
+ return SYSERR;
+ }
+ if (key.crc32 != htonl (crc32N (&key, SESSIONKEY_LEN)))
+ {
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_WARNING | GE_DEVELOPER | GE_USER | GE_BULK,
- _("setkey `%s' from `%s' fails CRC check (have: %u, want %u).\n"),
- printSKEY(&key),
- &enc,
- ntohl(key.crc32),
- crc32N(&key, SESSIONKEY_LEN));
+ GE_LOG (ectx,
+ GE_WARNING | GE_DEVELOPER | GE_USER | GE_BULK,
+ _
+ ("setkey `%s' from `%s' fails CRC check (have: %u, want %u).\n"),
+ printSKEY (&key), &enc, ntohl (key.crc32), crc32N (&key,
+
SESSIONKEY_LEN));
#endif
- GE_BREAK_OP(ectx, 0);
- stats->change(stat_skeyRejected,
- 1);
- return SYSERR;
- }
+ GE_BREAK_OP (ectx, 0);
+ stats->change (stat_skeyRejected, 1);
+ return SYSERR;
+ }
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Received setkey message from `%s' with %u bytes of data and key `%s'.\n",
- &enc,
- ntohs(sessionkeySigned->header.size),
- printSKEY(&key));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Received setkey message from `%s' with %u bytes of data and key
`%s'.\n",
+ &enc, ntohs (sessionkeySigned->header.size), printSKEY (&key));
#endif
if (stats != NULL)
- stats->change(stat_skeyAccepted,
- 1);
+ stats->change (stat_skeyAccepted, 1);
/* notify core about session key */
- coreAPI->assignSessionKey(&key,
- sender,
- ntohl(sessionkeySigned->creationTime),
- NO);
- pos = sizeof(P2P_setkey_MESSAGE);
+ coreAPI->assignSessionKey (&key,
+ sender,
+ ntohl (sessionkeySigned->creationTime), NO);
+ pos = sizeof (P2P_setkey_MESSAGE);
ping = NULL;
pong = NULL;
plaintext = NULL;
- size = ntohs(sessionkeySigned->header.size);
- if ( ( (newMsg == NULL) &&
- (sizeof(P2P_setkey_MESSAGE) < size) ) ||
- ( (newMsg != NULL) &&
- (sizeof(P2P_new_setkey_MESSAGE) < size) ) ) {
- if (newMsg == NULL) {
- size -= sizeof(P2P_setkey_MESSAGE);
- end = &sessionkeySigned[1];
- } else {
- size -= sizeof(P2P_new_setkey_MESSAGE);
- end = &newMsg[1];
- }
- plaintext = MALLOC(size);
+ size = ntohs (sessionkeySigned->header.size);
+ if (((newMsg == NULL) &&
+ (sizeof (P2P_setkey_MESSAGE) < size)) ||
+ ((newMsg != NULL) && (sizeof (P2P_new_setkey_MESSAGE) < size)))
+ {
+ if (newMsg == NULL)
+ {
+ size -= sizeof (P2P_setkey_MESSAGE);
+ end = &sessionkeySigned[1];
+ }
+ else
+ {
+ size -= sizeof (P2P_new_setkey_MESSAGE);
+ end = &newMsg[1];
+ }
+ plaintext = MALLOC (size);
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Decrypting %d bytes of PINGPONG from `%s' with key `%s' and IV %u\n",
- size,
- &enc,
- printSKEY(&key),
- *(int*)sig);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Decrypting %d bytes of PINGPONG from `%s' with key `%s' and IV
%u\n",
+ size, &enc, printSKEY (&key), *(int *) sig);
#endif
- GE_ASSERT(ectx,
- -1 != decryptBlock(&key,
- end,
- size,
- (const INITVECTOR*) sig,
- plaintext));
- pos = 0;
- /* find pings & pongs! */
- while (pos + sizeof(MESSAGE_HEADER) < size) {
- MESSAGE_HEADER * hdr;
+ GE_ASSERT (ectx,
+ -1 != decryptBlock (&key,
+ end,
+ size,
+ (const INITVECTOR *) sig, plaintext));
+ pos = 0;
+ /* find pings & pongs! */
+ while (pos + sizeof (MESSAGE_HEADER) < size)
+ {
+ MESSAGE_HEADER *hdr;
- hdr = (MESSAGE_HEADER*) &plaintext[pos];
- if (htons(hdr->size) + pos > size) {
- GE_LOG(ectx,
- GE_WARNING | GE_DEVELOPER | GE_USER | GE_BULK,
- _("Error parsing encrypted session key from `%s', "
- "given message part size is invalid.\n"),
- &enc);
- break;
- }
- if (htons(hdr->type) == p2p_PROTO_PING)
- ping = hdr;
- else if (htons(hdr->type) == p2p_PROTO_PONG)
- pong = hdr;
- else
- GE_LOG(ectx,
- GE_WARNING | GE_DEVELOPER | GE_USER | GE_BULK,
- _("Unknown type in embedded message from `%s': %u (size: %u)\n"),
- &enc,
- htons(hdr->type),
- htons(hdr->size));
- pos += ntohs(hdr->size);
+ hdr = (MESSAGE_HEADER *) & plaintext[pos];
+ if (htons (hdr->size) + pos > size)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_DEVELOPER | GE_USER | GE_BULK,
+ _("Error parsing encrypted session key from `%s', "
+ "given message part size is invalid.\n"), &enc);
+ break;
+ }
+ if (htons (hdr->type) == p2p_PROTO_PING)
+ ping = hdr;
+ else if (htons (hdr->type) == p2p_PROTO_PONG)
+ pong = hdr;
+ else
+ GE_LOG (ectx,
+ GE_WARNING | GE_DEVELOPER | GE_USER | GE_BULK,
+ _
+ ("Unknown type in embedded message from `%s': %u (size:
%u)\n"),
+ &enc, htons (hdr->type), htons (hdr->size));
+ pos += ntohs (hdr->size);
+ }
}
- }
- if (pong != NULL) {
- /* we initiated, this is the response */
- /* notify ourselves about encapsulated pong */
+ if (pong != NULL)
+ {
+ /* we initiated, this is the response */
+ /* notify ourselves about encapsulated pong */
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Received PONG in session key from `%s', injecting!\n",
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Received PONG in session key from `%s', injecting!\n", &enc);
#endif
- coreAPI->injectMessage(sender,
- (char*) pong,
- ntohs(pong->size),
- YES,
- tsession);
- if (ping != NULL) { /* should always be true for well-behaved peers */
- /* pong can go out over ordinary channels */
+ coreAPI->injectMessage (sender,
+ (char *) pong,
+ ntohs (pong->size), YES, tsession);
+ if (ping != NULL)
+ { /* should always be true for well-behaved
peers */
+ /* pong can go out over ordinary channels */
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Received PING in session key from `%s', "
- "sending PONG over normal encrypted session!\n",
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Received PING in session key from `%s', "
+ "sending PONG over normal encrypted session!\n", &enc);
#endif
- ping->type = htons(p2p_PROTO_PONG);
- if (stats != NULL)
- stats->change(stat_pongSent, 1);
- coreAPI->unicast(sender,
- ping,
- EXTREME_PRIORITY,
- 0);
+ ping->type = htons (p2p_PROTO_PONG);
+ if (stats != NULL)
+ stats->change (stat_pongSent, 1);
+ coreAPI->unicast (sender, ping, EXTREME_PRIORITY, 0);
+ }
}
- } else {
- if (ping != NULL) {
+ else
+ {
+ if (ping != NULL)
+ {
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Received ping in session key from `%s', "
- "sending pong together with my session key!\n",
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Received ping in session key from `%s', "
+ "sending pong together with my session key!\n", &enc);
#endif
- ping->type = htons(p2p_PROTO_PONG);
- if (stats != NULL)
- stats->change(stat_pongSent, 1);
- exchangeKey(sender,
- tsession,
- ping); /* ping is now pong */
- } else {
- GE_BREAK_OP(ectx, 0);
- /* PING not included in SKEY - bug (in other peer!?) */
+ ping->type = htons (p2p_PROTO_PONG);
+ if (stats != NULL)
+ stats->change (stat_pongSent, 1);
+ exchangeKey (sender, tsession, ping); /* ping is now pong */
+ }
+ else
+ {
+ GE_BREAK_OP (ectx, 0);
+ /* PING not included in SKEY - bug (in other peer!?) */
+ }
}
- }
- FREENONNULL(plaintext);
+ FREENONNULL (plaintext);
return OK;
}
@@ -830,41 +791,40 @@
* YES if a connection is established upon return,
* NO if we're going to try to establish one asynchronously
*/
-static int tryConnect(const PeerIdentity * peer) {
+static int
+tryConnect (const PeerIdentity * peer)
+{
#if DEBUG_SESSION
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- hash2enc(&peer->hashPubKey,
- &enc));
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ hash2enc (&peer->hashPubKey, &enc));
#endif
- if ( (topology != NULL) &&
- (topology->allowConnectionFrom(peer) == SYSERR) ) {
+ if ((topology != NULL) && (topology->allowConnectionFrom (peer) == SYSERR))
+ {
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Topology rejected connecting to `%s'.\n",
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Topology rejected connecting to `%s'.\n", &enc);
#endif
- return SYSERR;
- }
- if (coreAPI->queryPeerStatus(peer, NULL, NULL) == OK) {
+ return SYSERR;
+ }
+ if (coreAPI->queryPeerStatus (peer, NULL, NULL) == OK)
+ {
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Connection to `%s' already up\n",
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Connection to `%s' already up\n", &enc);
#endif
- return YES; /* trivial case */
- }
+ return YES; /* trivial case */
+ }
#if DEBUG_SESSION
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Trying to exchange key with `%s'.\n",
- &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Trying to exchange key with `%s'.\n", &enc);
#endif
- if (OK == exchangeKey(peer, NULL, NULL))
+ if (OK == exchangeKey (peer, NULL, NULL))
return NO;
return SYSERR;
}
@@ -874,11 +834,11 @@
* The reaction is to update our key to the new
* value. (Rekeying).
*/
-static int acceptSessionKeyUpdate(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg) {
- acceptSessionKey(sender,
- msg,
- NULL);
+static int
+acceptSessionKeyUpdate (const PeerIdentity * sender,
+ const MESSAGE_HEADER * msg)
+{
+ acceptSessionKey (sender, msg, NULL);
return OK;
}
@@ -887,59 +847,60 @@
* Initialize the module.
*/
Session_ServiceAPI *
-provide_module_session(CoreAPIForApplication * capi) {
+provide_module_session (CoreAPIForApplication * capi)
+{
static Session_ServiceAPI ret;
ectx = capi->ectx;
- GE_ASSERT(ectx, sizeof(P2P_setkey_MESSAGE) == 520);
+ GE_ASSERT (ectx, sizeof (P2P_setkey_MESSAGE) == 520);
coreAPI = capi;
- identity = capi->requestService("identity");
- if (identity == NULL) {
- GE_BREAK(ectx, 0);
- return NULL;
- }
- transport = capi->requestService("transport");
- if (transport == NULL) {
- GE_BREAK(ectx, 0);
- coreAPI->releaseService(identity);
- identity = NULL;
- return NULL;
- }
- pingpong = capi->requestService("pingpong");
- if (pingpong == NULL) {
- GE_BREAK(ectx, 0);
- coreAPI->releaseService(transport);
- transport = NULL;
- coreAPI->releaseService(identity);
- identity = NULL;
- return NULL;
- }
- topology = capi->requestService("topology");
- stats = capi->requestService("stats");
- if (stats != NULL) {
- stat_skeySent
- = stats->create(gettext_noop("# session keys sent"));
- stat_skeyRejected
- = stats->create(gettext_noop("# session keys rejected"));
- stat_skeyAccepted
- = stats->create(gettext_noop("# session keys accepted"));
- stat_sessionEstablished
- = stats->create(gettext_noop("# sessions established"));
- stat_pingSent
- = stats->create(gettext_noop("# encrypted PING messages sent"));
- stat_pongSent
- = stats->create(gettext_noop("# encrypted PONG messages sent"));
- }
+ identity = capi->requestService ("identity");
+ if (identity == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
+ transport = capi->requestService ("transport");
+ if (transport == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ coreAPI->releaseService (identity);
+ identity = NULL;
+ return NULL;
+ }
+ pingpong = capi->requestService ("pingpong");
+ if (pingpong == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ coreAPI->releaseService (transport);
+ transport = NULL;
+ coreAPI->releaseService (identity);
+ identity = NULL;
+ return NULL;
+ }
+ topology = capi->requestService ("topology");
+ stats = capi->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_skeySent = stats->create (gettext_noop ("# session keys sent"));
+ stat_skeyRejected
+ = stats->create (gettext_noop ("# session keys rejected"));
+ stat_skeyAccepted
+ = stats->create (gettext_noop ("# session keys accepted"));
+ stat_sessionEstablished
+ = stats->create (gettext_noop ("# sessions established"));
+ stat_pingSent
+ = stats->create (gettext_noop ("# encrypted PING messages sent"));
+ stat_pongSent
+ = stats->create (gettext_noop ("# encrypted PONG messages sent"));
+ }
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- _("`%s' registering handler %d (plaintext and ciphertext)\n"),
- "session",
- P2P_PROTO_setkey);
- coreAPI->registerPlaintextHandler(P2P_PROTO_setkey,
- &acceptSessionKey);
- coreAPI->registerHandler(P2P_PROTO_setkey,
- &acceptSessionKeyUpdate);
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ _("`%s' registering handler %d (plaintext and ciphertext)\n"),
+ "session", P2P_PROTO_setkey);
+ coreAPI->registerPlaintextHandler (P2P_PROTO_setkey, &acceptSessionKey);
+ coreAPI->registerHandler (P2P_PROTO_setkey, &acceptSessionKeyUpdate);
ret.tryConnect = &tryConnect;
return &ret;
}
@@ -947,22 +908,23 @@
/**
* Shutdown the module.
*/
-int release_module_session() {
- coreAPI->unregisterPlaintextHandler(P2P_PROTO_setkey,
- &acceptSessionKey);
- coreAPI->unregisterHandler(P2P_PROTO_setkey,
- &acceptSessionKeyUpdate);
- if (topology != NULL) {
- coreAPI->releaseService(topology);
- topology = NULL;
- }
- coreAPI->releaseService(stats);
+int
+release_module_session ()
+{
+ coreAPI->unregisterPlaintextHandler (P2P_PROTO_setkey, &acceptSessionKey);
+ coreAPI->unregisterHandler (P2P_PROTO_setkey, &acceptSessionKeyUpdate);
+ if (topology != NULL)
+ {
+ coreAPI->releaseService (topology);
+ topology = NULL;
+ }
+ coreAPI->releaseService (stats);
stats = NULL;
- coreAPI->releaseService(identity);
+ coreAPI->releaseService (identity);
identity = NULL;
- coreAPI->releaseService(transport);
+ coreAPI->releaseService (transport);
transport = NULL;
- coreAPI->releaseService(pingpong);
+ coreAPI->releaseService (pingpong);
pingpong = NULL;
coreAPI = NULL;
return OK;
Modified: GNUnet/src/applications/session/sessiontest.c
===================================================================
--- GNUnet/src/applications/session/sessiontest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/session/sessiontest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -36,15 +36,14 @@
static int ok;
-static int waitForConnect(const char * name,
- unsigned long long value,
- void * cls) {
- if ( (value > 0) &&
- (0 == strcmp(_("# of connected peers"),
- name)) ) {
- ok = 1;
- return SYSERR;
- }
+static int
+waitForConnect (const char *name, unsigned long long value, void *cls)
+{
+ if ((value > 0) && (0 == strcmp (_("# of connected peers"), name)))
+ {
+ ok = 1;
+ return SYSERR;
+ }
return OK;
}
@@ -55,104 +54,103 @@
* @param argv command line arguments
* @return 0: ok, -1: error
*/
-int main(int argc, char ** argv) {
+int
+main (int argc, char **argv)
+{
#if START_PEERS
- struct DaemonContext * peers;
+ struct DaemonContext *peers;
#endif
int ret;
- struct ClientServerConnection * sock1;
- struct ClientServerConnection * sock2;
+ struct ClientServerConnection *sock1;
+ struct ClientServerConnection *sock2;
int left;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_PEERS
- peers = gnunet_testing_start_daemons(NULL == strstr(argv[0], "_udp") ? "tcp"
: "udp",
- "advertising stats",
- "/tmp/gnunet-session-test",
- 2087,
- 10000,
- 2);
- if (peers == NULL) {
- GC_free(cfg);
- return -1;
- }
-#endif
- gnunet_testing_connect_daemons(2087,
- 12087);
- if (OK == connection_wait_for_running(NULL,
- cfg,
- 30 * cronSECONDS)) {
- sock1 = client_connection_create(NULL,
- cfg);
- GC_set_configuration_value_string(cfg,
- NULL,
- "NETWORK",
- "HOST",
- "localhost:12087");
- sock2 = client_connection_create(NULL,
- cfg);
- left = 30; /* how many iterations should we wait? */
- while (OK == STATS_getStatistics(NULL,
- sock1,
- &waitForConnect,
- NULL)) {
- printf("Waiting for peers to connect (%u iterations left)...\n",
- left);
- sleep(5);
- left--;
- if (left == 0) {
- ret = 1;
- break;
- }
+ peers =
+ gnunet_testing_start_daemons (NULL ==
+ strstr (argv[0], "_udp") ? "tcp" : "udp",
+ "advertising stats",
+ "/tmp/gnunet-session-test", 2087, 10000, 2);
+ if (peers == NULL)
+ {
+ GC_free (cfg);
+ return -1;
}
+#endif
+ gnunet_testing_connect_daemons (2087, 12087);
+ if (OK == connection_wait_for_running (NULL, cfg, 30 * cronSECONDS))
+ {
+ sock1 = client_connection_create (NULL, cfg);
+ GC_set_configuration_value_string (cfg,
+ NULL,
+ "NETWORK",
+ "HOST", "localhost:12087");
+ sock2 = client_connection_create (NULL, cfg);
+ left = 30; /* how many iterations should we wait? */
+ while (OK == STATS_getStatistics (NULL, sock1, &waitForConnect, NULL))
+ {
+ printf ("Waiting for peers to connect (%u iterations left)...\n",
+ left);
+ sleep (5);
+ left--;
+ if (left == 0)
+ {
+ ret = 1;
+ break;
+ }
+ }
#if 0
- if (ok == 1) {
- for (left=0;left<10;left++) {
- ok = 0;
- while (GNUNET_SHUTDOWN_TEST() == NO) {
- printf("Checking that peers are staying connected 1...\n");
- STATS_getStatistics(NULL,
- sock1,
- &waitForConnect,
- NULL);
- sleep(1);
- if (ok == 0) {
- printf("Peers disconnected!\n");
- break;
- }
- printf("Checking that peers are staying connected 2...\n");
- STATS_getStatistics(NULL,
- sock2,
- &waitForConnect,
- NULL);
- sleep(1);
- if (ok == 0) {
- printf("Peers disconnected!\n");
- break;
- }
- }
- }
- } else {
- printf("Peers failed to connect!\n");
- }
+ if (ok == 1)
+ {
+ for (left = 0; left < 10; left++)
+ {
+ ok = 0;
+ while (GNUNET_SHUTDOWN_TEST () == NO)
+ {
+ printf ("Checking that peers are staying connected 1...\n");
+ STATS_getStatistics (NULL, sock1, &waitForConnect, NULL);
+ sleep (1);
+ if (ok == 0)
+ {
+ printf ("Peers disconnected!\n");
+ break;
+ }
+ printf ("Checking that peers are staying connected 2...\n");
+ STATS_getStatistics (NULL, sock2, &waitForConnect, NULL);
+ sleep (1);
+ if (ok == 0)
+ {
+ printf ("Peers disconnected!\n");
+ break;
+ }
+ }
+ }
+ }
+ else
+ {
+ printf ("Peers failed to connect!\n");
+ }
#endif
- connection_destroy(sock1);
- connection_destroy(sock2);
- } else {
- printf("Could not establish connection with peer.\n");
- ret = 1;
- }
+ connection_destroy (sock1);
+ connection_destroy (sock2);
+ }
+ else
+ {
+ printf ("Could not establish connection with peer.\n");
+ ret = 1;
+ }
#if START_PEERS
- gnunet_testing_stop_daemons(peers);
+ gnunet_testing_stop_daemons (peers);
#endif
- GC_free(cfg);
+ GC_free (cfg);
return (ok == 0) ? 1 : 0;
}
Modified: GNUnet/src/applications/session/sessiontest2.c
===================================================================
--- GNUnet/src/applications/session/sessiontest2.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/session/sessiontest2.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -36,15 +36,14 @@
static int ok;
-static int waitForConnect(const char * name,
- unsigned long long value,
- void * cls) {
- if ( (value > 0) &&
- (0 == strcmp(_("# of connected peers"),
- name)) ) {
- ok = 1;
- return SYSERR;
- }
+static int
+waitForConnect (const char *name, unsigned long long value, void *cls)
+{
+ if ((value > 0) && (0 == strcmp (_("# of connected peers"), name)))
+ {
+ ok = 1;
+ return SYSERR;
+ }
return OK;
}
@@ -56,64 +55,50 @@
* @param port2 client port of the second daemon
* @return OK on success, SYSERR on failure
*/
-static int connect_daemons(unsigned short port1,
- unsigned short port2) {
+static int
+connect_daemons (unsigned short port1, unsigned short port2)
+{
char host[128];
- GC_Configuration * cfg1 = GC_create_C_impl();
- GC_Configuration * cfg2 = GC_create_C_impl();
- struct ClientServerConnection * sock1;
- struct ClientServerConnection * sock2;
+ GC_Configuration *cfg1 = GC_create_C_impl ();
+ GC_Configuration *cfg2 = GC_create_C_impl ();
+ struct ClientServerConnection *sock1;
+ struct ClientServerConnection *sock2;
int ret;
- P2P_hello_MESSAGE * h1;
+ P2P_hello_MESSAGE *h1;
ret = SYSERR;
- SNPRINTF(host,
- 128,
- "localhost:%u",
- port1);
- GC_set_configuration_value_string(cfg1,
- NULL,
- "NETWORK",
- "HOST",
- host);
- SNPRINTF(host,
- 128,
- "localhost:%u",
- port2);
- GC_set_configuration_value_string(cfg2,
- NULL,
- "NETWORK",
- "HOST",
- host);
- if ( (OK == connection_wait_for_running(NULL,
- cfg1,
- 300 * cronSECONDS) ) &&
- (OK == connection_wait_for_running(NULL,
- cfg2,
- 300 * cronSECONDS) ) ) {
- sock1 = client_connection_create(NULL,
- cfg1);
- sock2 = client_connection_create(NULL,
- cfg2);
- h1 = NULL;
- fprintf(stderr, "Notifying NATed peer about other peer");
- if ( (OK == gnunet_identity_get_self(sock1,
- &h1)) &&
- (OK == gnunet_identity_peer_add(sock2,
- h1)) ) {
- fprintf(stderr, "!\n");
- ret = OK;
- } else
- fprintf(stderr, "?\n");
- FREENONNULL(h1);
- connection_destroy(sock1);
- connection_destroy(sock2);
- } else {
- fprintf(stderr,
- "Failed to establish connection with peers.\n");
- }
- GC_free(cfg1);
- GC_free(cfg2);
+ SNPRINTF (host, 128, "localhost:%u", port1);
+ GC_set_configuration_value_string (cfg1, NULL, "NETWORK", "HOST", host);
+ SNPRINTF (host, 128, "localhost:%u", port2);
+ GC_set_configuration_value_string (cfg2, NULL, "NETWORK", "HOST", host);
+ if ((OK == connection_wait_for_running (NULL,
+ cfg1,
+ 300 * cronSECONDS)) &&
+ (OK == connection_wait_for_running (NULL, cfg2, 300 * cronSECONDS)))
+ {
+ sock1 = client_connection_create (NULL, cfg1);
+ sock2 = client_connection_create (NULL, cfg2);
+ h1 = NULL;
+ fprintf (stderr, "Notifying NATed peer about other peer");
+ if ((OK == gnunet_identity_get_self (sock1,
+ &h1)) &&
+ (OK == gnunet_identity_peer_add (sock2, h1)))
+ {
+ fprintf (stderr, "!\n");
+ ret = OK;
+ }
+ else
+ fprintf (stderr, "?\n");
+ FREENONNULL (h1);
+ connection_destroy (sock1);
+ connection_destroy (sock2);
+ }
+ else
+ {
+ fprintf (stderr, "Failed to establish connection with peers.\n");
+ }
+ GC_free (cfg1);
+ GC_free (cfg2);
return ret;
}
@@ -125,72 +110,68 @@
* @param argv command line arguments
* @return 0: ok, -1: error
*/
-int main(int argc, char ** argv) {
+int
+main (int argc, char **argv)
+{
#if START_PEERS
pid_t peer1;
pid_t peer2;
#endif
int ret;
- struct ClientServerConnection * sock;
+ struct ClientServerConnection *sock;
int left;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_PEERS
- peer1 = os_daemon_start(NULL,
- cfg,
- "tcp-peer.conf",
- NO);
- if (peer1 == -1) {
- GC_free(cfg);
- return -1;
- }
- peer2 = os_daemon_start(NULL,
- cfg,
- "nat-peer.conf",
- NO);
- if (peer2 == -1) {
- os_daemon_stop(NULL, peer1);
- GC_free(cfg);
- return -1;
- }
+ peer1 = os_daemon_start (NULL, cfg, "tcp-peer.conf", NO);
+ if (peer1 == -1)
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ peer2 = os_daemon_start (NULL, cfg, "nat-peer.conf", NO);
+ if (peer2 == -1)
+ {
+ os_daemon_stop (NULL, peer1);
+ GC_free (cfg);
+ return -1;
+ }
#endif
- connect_daemons(2087,
- 12087);
- if (OK == connection_wait_for_running(NULL,
- cfg,
- 30 * cronSECONDS)) {
- sock = client_connection_create(NULL,
- cfg);
- left = 30; /* how many iterations should we wait? */
- while (OK == STATS_getStatistics(NULL,
- sock,
- &waitForConnect,
- NULL)) {
- printf("Waiting for peers to connect (%u iterations left)...\n",
- left);
- sleep(5);
- left--;
- if (left == 0) {
- ret = 1;
- break;
- }
+ connect_daemons (2087, 12087);
+ if (OK == connection_wait_for_running (NULL, cfg, 30 * cronSECONDS))
+ {
+ sock = client_connection_create (NULL, cfg);
+ left = 30; /* how many iterations should we wait? */
+ while (OK == STATS_getStatistics (NULL, sock, &waitForConnect, NULL))
+ {
+ printf ("Waiting for peers to connect (%u iterations left)...\n",
+ left);
+ sleep (5);
+ left--;
+ if (left == 0)
+ {
+ ret = 1;
+ break;
+ }
+ }
+ connection_destroy (sock);
}
- connection_destroy(sock);
- } else {
- printf("Could not establish connection with peer.\n");
- ret = 1;
- }
+ else
+ {
+ printf ("Could not establish connection with peer.\n");
+ ret = 1;
+ }
#if START_PEERS
- os_daemon_stop(NULL, peer1);
- os_daemon_stop(NULL, peer2);
+ os_daemon_stop (NULL, peer1);
+ os_daemon_stop (NULL, peer2);
#endif
- GC_free(cfg);
+ GC_free (cfg);
return (ok == 0) ? 1 : 0;
}
Modified: GNUnet/src/applications/session/sessiontest_http.c
===================================================================
--- GNUnet/src/applications/session/sessiontest_http.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/session/sessiontest_http.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -36,15 +36,14 @@
static int ok;
-static int waitForConnect(const char * name,
- unsigned long long value,
- void * cls) {
- if ( (value > 0) &&
- (0 == strcmp(_("# of connected peers"),
- name)) ) {
- ok = 1;
- return SYSERR;
- }
+static int
+waitForConnect (const char *name, unsigned long long value, void *cls)
+{
+ if ((value > 0) && (0 == strcmp (_("# of connected peers"), name)))
+ {
+ ok = 1;
+ return SYSERR;
+ }
return OK;
}
@@ -56,64 +55,50 @@
* @param port2 client port of the second daemon
* @return OK on success, SYSERR on failure
*/
-static int connect_daemons(unsigned short port1,
- unsigned short port2) {
+static int
+connect_daemons (unsigned short port1, unsigned short port2)
+{
char host[128];
- GC_Configuration * cfg1 = GC_create_C_impl();
- GC_Configuration * cfg2 = GC_create_C_impl();
- struct ClientServerConnection * sock1;
- struct ClientServerConnection * sock2;
+ GC_Configuration *cfg1 = GC_create_C_impl ();
+ GC_Configuration *cfg2 = GC_create_C_impl ();
+ struct ClientServerConnection *sock1;
+ struct ClientServerConnection *sock2;
int ret;
- P2P_hello_MESSAGE * h1;
+ P2P_hello_MESSAGE *h1;
ret = SYSERR;
- SNPRINTF(host,
- 128,
- "localhost:%u",
- port1);
- GC_set_configuration_value_string(cfg1,
- NULL,
- "NETWORK",
- "HOST",
- host);
- SNPRINTF(host,
- 128,
- "localhost:%u",
- port2);
- GC_set_configuration_value_string(cfg2,
- NULL,
- "NETWORK",
- "HOST",
- host);
- if ( (OK == connection_wait_for_running(NULL,
- cfg1,
- 300 * cronSECONDS) ) &&
- (OK == connection_wait_for_running(NULL,
- cfg2,
- 300 * cronSECONDS) ) ) {
- sock1 = client_connection_create(NULL,
- cfg1);
- sock2 = client_connection_create(NULL,
- cfg2);
- h1 = NULL;
- fprintf(stderr, "Notifying NATed peer about other peer");
- if ( (OK == gnunet_identity_get_self(sock1,
- &h1)) &&
- (OK == gnunet_identity_peer_add(sock2,
- h1)) ) {
- fprintf(stderr, "!\n");
- ret = OK;
- } else
- fprintf(stderr, "?\n");
- FREENONNULL(h1);
- connection_destroy(sock1);
- connection_destroy(sock2);
- } else {
- fprintf(stderr,
- "Failed to establish connection with peers.\n");
- }
- GC_free(cfg1);
- GC_free(cfg2);
+ SNPRINTF (host, 128, "localhost:%u", port1);
+ GC_set_configuration_value_string (cfg1, NULL, "NETWORK", "HOST", host);
+ SNPRINTF (host, 128, "localhost:%u", port2);
+ GC_set_configuration_value_string (cfg2, NULL, "NETWORK", "HOST", host);
+ if ((OK == connection_wait_for_running (NULL,
+ cfg1,
+ 300 * cronSECONDS)) &&
+ (OK == connection_wait_for_running (NULL, cfg2, 300 * cronSECONDS)))
+ {
+ sock1 = client_connection_create (NULL, cfg1);
+ sock2 = client_connection_create (NULL, cfg2);
+ h1 = NULL;
+ fprintf (stderr, "Notifying NATed peer about other peer");
+ if ((OK == gnunet_identity_get_self (sock1,
+ &h1)) &&
+ (OK == gnunet_identity_peer_add (sock2, h1)))
+ {
+ fprintf (stderr, "!\n");
+ ret = OK;
+ }
+ else
+ fprintf (stderr, "?\n");
+ FREENONNULL (h1);
+ connection_destroy (sock1);
+ connection_destroy (sock2);
+ }
+ else
+ {
+ fprintf (stderr, "Failed to establish connection with peers.\n");
+ }
+ GC_free (cfg1);
+ GC_free (cfg2);
return ret;
}
@@ -125,72 +110,68 @@
* @param argv command line arguments
* @return 0: ok, -1: error
*/
-int main(int argc, char ** argv) {
+int
+main (int argc, char **argv)
+{
#if START_PEERS
pid_t peer1;
pid_t peer2;
#endif
int ret;
- struct ClientServerConnection * sock;
+ struct ClientServerConnection *sock;
int left;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_PEERS
- peer1 = os_daemon_start(NULL,
- cfg,
- "http-peer.conf",
- NO);
- if (peer1 == -1) {
- GC_free(cfg);
- return -1;
- }
- peer2 = os_daemon_start(NULL,
- cfg,
- "nat-http-peer.conf",
- NO);
- if (peer2 == -1) {
- os_daemon_stop(NULL, peer1);
- GC_free(cfg);
- return -1;
- }
+ peer1 = os_daemon_start (NULL, cfg, "http-peer.conf", NO);
+ if (peer1 == -1)
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ peer2 = os_daemon_start (NULL, cfg, "nat-http-peer.conf", NO);
+ if (peer2 == -1)
+ {
+ os_daemon_stop (NULL, peer1);
+ GC_free (cfg);
+ return -1;
+ }
#endif
- connect_daemons(2087,
- 12087);
- if (OK == connection_wait_for_running(NULL,
- cfg,
- 30 * cronSECONDS)) {
- sock = client_connection_create(NULL,
- cfg);
- left = 30; /* how many iterations should we wait? */
- while (OK == STATS_getStatistics(NULL,
- sock,
- &waitForConnect,
- NULL)) {
- printf("Waiting for peers to connect (%u iterations left)...\n",
- left);
- sleep(5);
- left--;
- if (left == 0) {
- ret = 1;
- break;
- }
+ connect_daemons (2087, 12087);
+ if (OK == connection_wait_for_running (NULL, cfg, 30 * cronSECONDS))
+ {
+ sock = client_connection_create (NULL, cfg);
+ left = 30; /* how many iterations should we wait? */
+ while (OK == STATS_getStatistics (NULL, sock, &waitForConnect, NULL))
+ {
+ printf ("Waiting for peers to connect (%u iterations left)...\n",
+ left);
+ sleep (5);
+ left--;
+ if (left == 0)
+ {
+ ret = 1;
+ break;
+ }
+ }
+ connection_destroy (sock);
}
- connection_destroy(sock);
- } else {
- printf("Could not establish connection with peer.\n");
- ret = 1;
- }
+ else
+ {
+ printf ("Could not establish connection with peer.\n");
+ ret = 1;
+ }
#if START_PEERS
- os_daemon_stop(NULL, peer1);
- os_daemon_stop(NULL, peer2);
+ os_daemon_stop (NULL, peer1);
+ os_daemon_stop (NULL, peer2);
#endif
- GC_free(cfg);
+ GC_free (cfg);
return (ok == 0) ? 1 : 0;
}
Modified: GNUnet/src/applications/sqstore_mysql/mysql.c
===================================================================
--- GNUnet/src/applications/sqstore_mysql/mysql.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/sqstore_mysql/mysql.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -145,9 +145,9 @@
*/
#define LOG_MYSQL(level, cmd, dbh) do { GE_LOG(ectx, level, _("`%s' failed at
%s:%d with error: %s\n"), cmd, __FILE__, __LINE__, mysql_error((dbh)->dbf)); }
while(0);
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
static unsigned int stat_size;
@@ -159,43 +159,44 @@
/**
* Lock for updating content_size
*/
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
/**
* @brief mysql wrapper
*/
-typedef struct {
- MYSQL * dbf;
+typedef struct
+{
+ MYSQL *dbf;
- char * cnffile;
+ char *cnffile;
int prepare;
int valid;
- MYSQL_STMT * insert;
+ MYSQL_STMT *insert;
MYSQL_BIND bind[7];
- MYSQL_STMT * select;
+ MYSQL_STMT *select;
- MYSQL_STMT * selectc;
+ MYSQL_STMT *selectc;
- MYSQL_STMT * selects;
+ MYSQL_STMT *selects;
- MYSQL_STMT * selectsc;
+ MYSQL_STMT *selectsc;
MYSQL_BIND sbind[2];
- MYSQL_STMT * deleteh;
+ MYSQL_STMT *deleteh;
- MYSQL_STMT * deleteg;
+ MYSQL_STMT *deleteg;
MYSQL_BIND dbind[7];
- MYSQL_STMT * update;
+ MYSQL_STMT *update;
MYSQL_BIND ubind[5];
@@ -222,7 +223,7 @@
#define UPDATE_SAMPLE "UPDATE gn070 SET
prio=prio+?,expire=IF(expire>=?,expire,?) WHERE hash=? AND value=?"
-static mysqlHandle * dbh;
+static mysqlHandle *dbh;
/**
@@ -230,61 +231,59 @@
* order, assemble it into a Datastore_Datum representation.
*
*/
-static Datastore_Datum * assembleDatum(MYSQL_RES * res,
- MYSQL_ROW sql_row,
- mysqlHandle * dbhI) {
- Datastore_Datum * datum;
+static Datastore_Datum *
+assembleDatum (MYSQL_RES * res, MYSQL_ROW sql_row, mysqlHandle * dbhI)
+{
+ Datastore_Datum *datum;
int contentSize;
- unsigned long * lens;
+ unsigned long *lens;
unsigned int type;
unsigned int prio;
unsigned int level;
unsigned long long exp;
- contentSize = atol(sql_row[0]) - sizeof(Datastore_Value);
+ contentSize = atol (sql_row[0]) - sizeof (Datastore_Value);
if (contentSize < 0)
- return NULL; /* error */
+ return NULL; /* error */
- lens = mysql_fetch_lengths(res);
- if ( (lens[5] != sizeof(HashCode512)) ||
- (lens[6] != contentSize) ||
- (sscanf(sql_row[1], "%u", &type) != 1) ||
- (sscanf(sql_row[2], "%u", &prio) != 1) ||
- (sscanf(sql_row[3], "%u", &level) != 1) ||
- (SSCANF(sql_row[4], "%llu", &exp) != 1) ) {
- mysql_free_result(res);
- if ( (lens[5] != sizeof(HashCode512)) ||
- (lens[6] != contentSize) ) {
- char scratch[512];
+ lens = mysql_fetch_lengths (res);
+ if ((lens[5] != sizeof (HashCode512)) ||
+ (lens[6] != contentSize) ||
+ (sscanf (sql_row[1], "%u", &type) != 1) ||
+ (sscanf (sql_row[2], "%u", &prio) != 1) ||
+ (sscanf (sql_row[3], "%u", &level) != 1) ||
+ (SSCANF (sql_row[4], "%llu", &exp) != 1))
+ {
+ mysql_free_result (res);
+ if ((lens[5] != sizeof (HashCode512)) || (lens[6] != contentSize))
+ {
+ char scratch[512];
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Invalid data in %s. Trying to fix (by deletion).\n"),
- _("mysql datastore"));
- SNPRINTF(scratch,
- 512,
- "DELETE FROM gn070 WHERE NOT ((LENGTH(hash)=%u) AND (size=%u +
LENGTH(value)))",
- sizeof(HashCode512),
- sizeof(Datastore_Value));
- if (0 != mysql_query(dbhI->dbf, scratch))
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbhI);
- } else {
- GE_BREAK(ectx, 0); /* should really never happen */
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Invalid data in %s. Trying to fix (by deletion).\n"),
+ _("mysql datastore"));
+ SNPRINTF (scratch,
+ 512,
+ "DELETE FROM gn070 WHERE NOT ((LENGTH(hash)=%u) AND
(size=%u + LENGTH(value)))",
+ sizeof (HashCode512), sizeof (Datastore_Value));
+ if (0 != mysql_query (dbhI->dbf, scratch))
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbhI);
+ }
+ else
+ {
+ GE_BREAK (ectx, 0); /* should really never happen */
+ }
+ return NULL;
}
- return NULL;
- }
- datum = MALLOC(sizeof(Datastore_Datum) + contentSize);
- datum->value.size = htonl(contentSize + sizeof(Datastore_Value));
- datum->value.type = htonl(type);
- datum->value.prio = htonl(prio);
- datum->value.anonymityLevel = htonl(level);
- datum->value.expirationTime = htonll(exp);
- memcpy(&datum->key,
- sql_row[5],
- sizeof(HashCode512));
- memcpy(&datum[1],
- sql_row[6],
- contentSize);
+ datum = MALLOC (sizeof (Datastore_Datum) + contentSize);
+ datum->value.size = htonl (contentSize + sizeof (Datastore_Value));
+ datum->value.type = htonl (type);
+ datum->value.prio = htonl (prio);
+ datum->value.anonymityLevel = htonl (level);
+ datum->value.expirationTime = htonll (exp);
+ memcpy (&datum->key, sql_row[5], sizeof (HashCode512));
+ memcpy (&datum[1], sql_row[6], contentSize);
return datum;
}
@@ -300,236 +299,204 @@
* and do not setup prepared statements)
* @return OK on success
*/
-static int iopen(mysqlHandle * dbhI,
- int prepare) {
- char * dbname;
+static int
+iopen (mysqlHandle * dbhI, int prepare)
+{
+ char *dbname;
my_bool reconnect = 0;
- unsigned int timeout = 60; /* in seconds */
+ unsigned int timeout = 60; /* in seconds */
cron_t start;
if (dbhI->cnffile == NULL)
return SYSERR;
- dbhI->dbf = mysql_init(NULL);
+ dbhI->dbf = mysql_init (NULL);
if (dbhI->dbf == NULL)
return SYSERR;
- mysql_options(dbhI->dbf,
- MYSQL_READ_DEFAULT_FILE,
- dbh->cnffile);
- mysql_options(dbhI->dbf,
- MYSQL_READ_DEFAULT_GROUP,
- "client");
- mysql_options(dbhI->dbf,
- MYSQL_OPT_RECONNECT,
- &reconnect);
- mysql_options(dbhI->dbf,
- MYSQL_OPT_CONNECT_TIMEOUT,
- (const void*) &timeout);
- if (! prepare)
+ mysql_options (dbhI->dbf, MYSQL_READ_DEFAULT_FILE, dbh->cnffile);
+ mysql_options (dbhI->dbf, MYSQL_READ_DEFAULT_GROUP, "client");
+ mysql_options (dbhI->dbf, MYSQL_OPT_RECONNECT, &reconnect);
+ mysql_options (dbhI->dbf,
+ MYSQL_OPT_CONNECT_TIMEOUT, (const void *) &timeout);
+ if (!prepare)
timeout = 28800;
- mysql_options(dbhI->dbf,
- MYSQL_OPT_READ_TIMEOUT,
- (const void*) &timeout);
- mysql_options(dbhI->dbf,
- MYSQL_OPT_WRITE_TIMEOUT,
- (const void*) &timeout);
+ mysql_options (dbhI->dbf, MYSQL_OPT_READ_TIMEOUT, (const void *) &timeout);
+ mysql_options (dbhI->dbf, MYSQL_OPT_WRITE_TIMEOUT, (const void *) &timeout);
dbname = NULL;
- GC_get_configuration_value_string(coreAPI->cfg,
- "MYSQL",
- "DATABASE",
- "gnunet",
- &dbname);
- GE_ASSERT(ectx, dbname != NULL);
- mysql_real_connect(dbhI->dbf,
- NULL,
- NULL,
- NULL,
- dbname,
- 0,
- NULL,
- 0);
- FREE(dbname);
- if (mysql_error(dbhI->dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_real_connect",
- dbhI);
- dbhI->dbf = NULL;
- return SYSERR;
- }
- if (prepare) {
- dbhI->prepare = YES;
- mysql_query(dbhI->dbf,
- "SET SESSION net_read_timeout=60, SESSION
net_write_timeout=60");
- if (mysql_error(dbhI->dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- dbhI);
- mysql_close(dbhI->dbf);
+ GC_get_configuration_value_string (coreAPI->cfg,
+ "MYSQL", "DATABASE", "gnunet", &dbname);
+ GE_ASSERT (ectx, dbname != NULL);
+ mysql_real_connect (dbhI->dbf, NULL, NULL, NULL, dbname, 0, NULL, 0);
+ FREE (dbname);
+ if (mysql_error (dbhI->dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_real_connect", dbhI);
dbhI->dbf = NULL;
return SYSERR;
}
- mysql_query(dbhI->dbf,
- "CREATE TABLE IF NOT EXISTS gn070 ("
- " size INT(11) NOT NULL DEFAULT 0,"
- " type INT(11) NOT NULL DEFAULT 0,"
- " prio INT(11) NOT NULL DEFAULT 0,"
- " anonLevel INT(11) NOT NULL DEFAULT 0,"
- " expire BIGINT NOT NULL DEFAULT 0,"
- " hash TINYBLOB NOT NULL DEFAULT '',"
- " value BLOB NOT NULL DEFAULT '',"
- " INDEX (hash(64)),"
- " INDEX (prio),"
- " INDEX (expire),"
- " INDEX (expire,anonLevel,type)"
- ") TYPE=InnoDB");
- if (mysql_error(dbhI->dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- dbhI);
- mysql_close(dbhI->dbf);
- dbhI->dbf = NULL;
- return SYSERR;
+ if (prepare)
+ {
+ dbhI->prepare = YES;
+ mysql_query (dbhI->dbf,
+ "SET SESSION net_read_timeout=60, SESSION
net_write_timeout=60");
+ if (mysql_error (dbhI->dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbhI);
+ mysql_close (dbhI->dbf);
+ dbhI->dbf = NULL;
+ return SYSERR;
+ }
+ mysql_query (dbhI->dbf,
+ "CREATE TABLE IF NOT EXISTS gn070 ("
+ " size INT(11) NOT NULL DEFAULT 0,"
+ " type INT(11) NOT NULL DEFAULT 0,"
+ " prio INT(11) NOT NULL DEFAULT 0,"
+ " anonLevel INT(11) NOT NULL DEFAULT 0,"
+ " expire BIGINT NOT NULL DEFAULT 0,"
+ " hash TINYBLOB NOT NULL DEFAULT '',"
+ " value BLOB NOT NULL DEFAULT '',"
+ " INDEX (hash(64)),"
+ " INDEX (prio),"
+ " INDEX (expire),"
+ " INDEX (expire,anonLevel,type)" ") TYPE=InnoDB");
+ if (mysql_error (dbhI->dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbhI);
+ mysql_close (dbhI->dbf);
+ dbhI->dbf = NULL;
+ return SYSERR;
+ }
+ mysql_query (dbhI->dbf, "SET AUTOCOMMIT = 1");
+ if (mysql_error (dbhI->dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbhI);
+ mysql_close (dbhI->dbf);
+ dbhI->dbf = NULL;
+ return SYSERR;
+ }
+ dbhI->insert = mysql_stmt_init (dbhI->dbf);
+ dbhI->select = mysql_stmt_init (dbhI->dbf);
+ dbhI->selectc = mysql_stmt_init (dbhI->dbf);
+ dbhI->selects = mysql_stmt_init (dbhI->dbf);
+ dbhI->selectsc = mysql_stmt_init (dbhI->dbf);
+ dbhI->update = mysql_stmt_init (dbhI->dbf);
+ dbhI->deleteh = mysql_stmt_init (dbhI->dbf);
+ dbhI->deleteg = mysql_stmt_init (dbhI->dbf);
+ if ((dbhI->insert == NULL) ||
+ (dbhI->update == NULL) ||
+ (dbhI->select == NULL) ||
+ (dbhI->selectc == NULL) ||
+ (dbhI->selects == NULL) ||
+ (dbhI->selectsc == NULL) ||
+ (dbhI->deleteh == NULL) || (dbhI->deleteg == NULL))
+ {
+ GE_BREAK (ectx, 0);
+ if (dbhI->insert != NULL)
+ mysql_stmt_close (dbhI->insert);
+ if (dbhI->update != NULL)
+ mysql_stmt_close (dbhI->update);
+ if (dbhI->select != NULL)
+ mysql_stmt_close (dbhI->select);
+ if (dbhI->selectc != NULL)
+ mysql_stmt_close (dbhI->selectc);
+ if (dbhI->selects != NULL)
+ mysql_stmt_close (dbhI->selects);
+ if (dbhI->selectsc != NULL)
+ mysql_stmt_close (dbhI->selectsc);
+ mysql_close (dbhI->dbf);
+ dbhI->dbf = NULL;
+ return SYSERR;
+ }
+ start = get_time ();
+ if (mysql_stmt_prepare (dbhI->insert,
+ INSERT_SAMPLE,
+ strlen (INSERT_SAMPLE)) ||
+ mysql_stmt_prepare (dbhI->select,
+ SELECT_SAMPLE,
+ strlen (SELECT_SAMPLE)) ||
+ mysql_stmt_prepare (dbhI->selectc,
+ SELECT_SAMPLE_COUNT,
+ strlen (SELECT_SAMPLE_COUNT)) ||
+ mysql_stmt_prepare (dbhI->selects,
+ SELECT_TYPE_SAMPLE,
+ strlen (SELECT_TYPE_SAMPLE)) ||
+ mysql_stmt_prepare (dbhI->selectsc,
+ SELECT_TYPE_SAMPLE_COUNT,
+ strlen (SELECT_TYPE_SAMPLE_COUNT)) ||
+ mysql_stmt_prepare (dbhI->update,
+ UPDATE_SAMPLE,
+ strlen (UPDATE_SAMPLE)) ||
+ mysql_stmt_prepare (dbhI->deleteh,
+ SELECT_HASH_SAMPLE,
+ strlen (SELECT_HASH_SAMPLE)) ||
+ mysql_stmt_prepare (dbhI->deleteg,
+ DELETE_GENERIC_SAMPLE,
+ strlen (DELETE_GENERIC_SAMPLE)))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("`%s' failed at %s:%d with error: I/%s S/%s SC/%s SS/%s
SSC/%s U/%s D/%s DG/%s after %llums\n"),
+ "mysql_stmt_prepare", __FILE__, __LINE__,
+ mysql_stmt_error (dbhI->insert),
+ mysql_stmt_error (dbhI->select),
+ mysql_stmt_error (dbhI->selectc),
+ mysql_stmt_error (dbhI->selects),
+ mysql_stmt_error (dbhI->selectsc),
+ mysql_stmt_error (dbhI->update),
+ mysql_stmt_error (dbhI->deleteh),
+ mysql_stmt_error (dbhI->deleteg), get_time () - start);
+ mysql_stmt_close (dbhI->insert);
+ mysql_stmt_close (dbhI->select);
+ mysql_stmt_close (dbhI->selectc);
+ mysql_stmt_close (dbhI->selects);
+ mysql_stmt_close (dbhI->selectsc);
+ mysql_stmt_close (dbhI->update);
+ mysql_stmt_close (dbhI->deleteh);
+ mysql_stmt_close (dbhI->deleteg);
+ mysql_close (dbhI->dbf);
+ dbhI->dbf = NULL;
+ return SYSERR;
+ }
+ memset (dbhI->bind, 0, sizeof (dbhI->bind));
+ dbhI->bind[0].buffer_type = MYSQL_TYPE_LONG; /* size */
+ dbhI->bind[1].buffer_type = MYSQL_TYPE_LONG; /* type */
+ dbhI->bind[2].buffer_type = MYSQL_TYPE_LONG; /* prio */
+ dbhI->bind[3].buffer_type = MYSQL_TYPE_LONG; /* anon level */
+ dbhI->bind[4].buffer_type = MYSQL_TYPE_LONGLONG; /* expiration */
+ dbhI->bind[5].buffer_type = MYSQL_TYPE_TINY_BLOB; /* hash */
+ dbhI->bind[6].buffer_type = MYSQL_TYPE_BLOB; /* value */
+ memset (dbhI->sbind, 0, sizeof (dbhI->sbind));
+ dbhI->sbind[0].buffer_type = MYSQL_TYPE_TINY_BLOB; /* hash */
+ dbhI->sbind[1].buffer_type = MYSQL_TYPE_LONG; /* type */
+ memset (dbhI->dbind, 0, sizeof (dbhI->dbind));
+ dbhI->dbind[0].buffer_type = MYSQL_TYPE_TINY_BLOB; /* hash */
+ dbhI->dbind[1].buffer_type = MYSQL_TYPE_LONG; /* size */
+ dbhI->dbind[2].buffer_type = MYSQL_TYPE_LONG; /* type */
+ dbhI->dbind[3].buffer_type = MYSQL_TYPE_LONG; /* prio */
+ dbhI->dbind[4].buffer_type = MYSQL_TYPE_LONG; /* anon level */
+ dbhI->dbind[5].buffer_type = MYSQL_TYPE_LONGLONG; /* expiration */
+ dbhI->dbind[6].buffer_type = MYSQL_TYPE_BLOB; /* value */
+ memset (dbhI->ubind, 0, sizeof (dbhI->ubind));
+ dbhI->ubind[0].buffer_type = MYSQL_TYPE_LONG;
+ dbhI->ubind[1].buffer_type = MYSQL_TYPE_LONG;
+ dbhI->ubind[2].buffer_type = MYSQL_TYPE_LONG;
+ dbhI->ubind[3].buffer_type = MYSQL_TYPE_BLOB;
+ dbhI->ubind[4].buffer_type = MYSQL_TYPE_BLOB;
}
- mysql_query(dbhI->dbf,
- "SET AUTOCOMMIT = 1");
- if (mysql_error(dbhI->dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- dbhI);
- mysql_close(dbhI->dbf);
- dbhI->dbf = NULL;
- return SYSERR;
+ else
+ {
+ dbhI->prepare = NO;
+ mysql_query (dbhI->dbf,
+ "SET SESSION net_read_timeout=28800, SESSION
net_write_timeout=28800");
+ if (mysql_error (dbhI->dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbhI);
+ mysql_close (dbhI->dbf);
+ dbhI->dbf = NULL;
+ return SYSERR;
+ }
}
- dbhI->insert = mysql_stmt_init(dbhI->dbf);
- dbhI->select = mysql_stmt_init(dbhI->dbf);
- dbhI->selectc = mysql_stmt_init(dbhI->dbf);
- dbhI->selects = mysql_stmt_init(dbhI->dbf);
- dbhI->selectsc = mysql_stmt_init(dbhI->dbf);
- dbhI->update = mysql_stmt_init(dbhI->dbf);
- dbhI->deleteh = mysql_stmt_init(dbhI->dbf);
- dbhI->deleteg = mysql_stmt_init(dbhI->dbf);
- if ( (dbhI->insert == NULL) ||
- (dbhI->update == NULL) ||
- (dbhI->select == NULL) ||
- (dbhI->selectc == NULL) ||
- (dbhI->selects == NULL) ||
- (dbhI->selectsc == NULL) ||
- (dbhI->deleteh == NULL) ||
- (dbhI->deleteg == NULL) ) {
- GE_BREAK(ectx, 0);
- if (dbhI->insert != NULL)
- mysql_stmt_close(dbhI->insert);
- if (dbhI->update != NULL)
- mysql_stmt_close(dbhI->update);
- if (dbhI->select != NULL)
- mysql_stmt_close(dbhI->select);
- if (dbhI->selectc != NULL)
- mysql_stmt_close(dbhI->selectc);
- if (dbhI->selects != NULL)
- mysql_stmt_close(dbhI->selects);
- if (dbhI->selectsc != NULL)
- mysql_stmt_close(dbhI->selectsc);
- mysql_close(dbhI->dbf);
- dbhI->dbf = NULL;
- return SYSERR;
- }
- start = get_time();
- if (mysql_stmt_prepare(dbhI->insert,
- INSERT_SAMPLE,
- strlen(INSERT_SAMPLE)) ||
- mysql_stmt_prepare(dbhI->select,
- SELECT_SAMPLE,
- strlen(SELECT_SAMPLE)) ||
- mysql_stmt_prepare(dbhI->selectc,
- SELECT_SAMPLE_COUNT,
- strlen(SELECT_SAMPLE_COUNT)) ||
- mysql_stmt_prepare(dbhI->selects,
- SELECT_TYPE_SAMPLE,
- strlen(SELECT_TYPE_SAMPLE)) ||
- mysql_stmt_prepare(dbhI->selectsc,
- SELECT_TYPE_SAMPLE_COUNT,
- strlen(SELECT_TYPE_SAMPLE_COUNT)) ||
- mysql_stmt_prepare(dbhI->update,
- UPDATE_SAMPLE,
- strlen(UPDATE_SAMPLE)) ||
- mysql_stmt_prepare(dbhI->deleteh,
- SELECT_HASH_SAMPLE,
- strlen(SELECT_HASH_SAMPLE)) ||
- mysql_stmt_prepare(dbhI->deleteg,
- DELETE_GENERIC_SAMPLE,
- strlen(DELETE_GENERIC_SAMPLE)) ) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: I/%s S/%s SC/%s SS/%s SSC/%s
U/%s D/%s DG/%s after %llums\n"),
- "mysql_stmt_prepare",
- __FILE__, __LINE__,
- mysql_stmt_error(dbhI->insert),
- mysql_stmt_error(dbhI->select),
- mysql_stmt_error(dbhI->selectc),
- mysql_stmt_error(dbhI->selects),
- mysql_stmt_error(dbhI->selectsc),
- mysql_stmt_error(dbhI->update),
- mysql_stmt_error(dbhI->deleteh),
- mysql_stmt_error(dbhI->deleteg),
- get_time() - start);
- mysql_stmt_close(dbhI->insert);
- mysql_stmt_close(dbhI->select);
- mysql_stmt_close(dbhI->selectc);
- mysql_stmt_close(dbhI->selects);
- mysql_stmt_close(dbhI->selectsc);
- mysql_stmt_close(dbhI->update);
- mysql_stmt_close(dbhI->deleteh);
- mysql_stmt_close(dbhI->deleteg);
- mysql_close(dbhI->dbf);
- dbhI->dbf = NULL;
- return SYSERR;
- }
- memset(dbhI->bind,
- 0,
- sizeof(dbhI->bind));
- dbhI->bind[0].buffer_type = MYSQL_TYPE_LONG; /* size */
- dbhI->bind[1].buffer_type = MYSQL_TYPE_LONG; /* type */
- dbhI->bind[2].buffer_type = MYSQL_TYPE_LONG; /* prio */
- dbhI->bind[3].buffer_type = MYSQL_TYPE_LONG; /* anon level */
- dbhI->bind[4].buffer_type = MYSQL_TYPE_LONGLONG; /* expiration */
- dbhI->bind[5].buffer_type = MYSQL_TYPE_TINY_BLOB; /* hash */
- dbhI->bind[6].buffer_type = MYSQL_TYPE_BLOB; /* value */
- memset(dbhI->sbind,
- 0,
- sizeof(dbhI->sbind));
- dbhI->sbind[0].buffer_type = MYSQL_TYPE_TINY_BLOB; /* hash */
- dbhI->sbind[1].buffer_type = MYSQL_TYPE_LONG; /* type */
- memset(dbhI->dbind,
- 0,
- sizeof(dbhI->dbind));
- dbhI->dbind[0].buffer_type = MYSQL_TYPE_TINY_BLOB; /* hash */
- dbhI->dbind[1].buffer_type = MYSQL_TYPE_LONG; /* size */
- dbhI->dbind[2].buffer_type = MYSQL_TYPE_LONG; /* type */
- dbhI->dbind[3].buffer_type = MYSQL_TYPE_LONG; /* prio */
- dbhI->dbind[4].buffer_type = MYSQL_TYPE_LONG; /* anon level */
- dbhI->dbind[5].buffer_type = MYSQL_TYPE_LONGLONG; /* expiration */
- dbhI->dbind[6].buffer_type = MYSQL_TYPE_BLOB; /* value */
- memset(dbhI->ubind,
- 0,
- sizeof(dbhI->ubind));
- dbhI->ubind[0].buffer_type = MYSQL_TYPE_LONG;
- dbhI->ubind[1].buffer_type = MYSQL_TYPE_LONG;
- dbhI->ubind[2].buffer_type = MYSQL_TYPE_LONG;
- dbhI->ubind[3].buffer_type = MYSQL_TYPE_BLOB;
- dbhI->ubind[4].buffer_type = MYSQL_TYPE_BLOB;
- } else {
- dbhI->prepare = NO;
- mysql_query(dbhI->dbf,
- "SET SESSION net_read_timeout=28800, SESSION
net_write_timeout=28800");
- if (mysql_error(dbhI->dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- dbhI);
- mysql_close(dbhI->dbf);
- dbhI->dbf = NULL;
- return SYSERR;
- }
- }
dbhI->valid = YES;
return OK;
}
@@ -537,28 +504,31 @@
/**
* Close the database connection.
*/
-static int iclose(mysqlHandle * dbhI) {
+static int
+iclose (mysqlHandle * dbhI)
+{
if (dbhI->dbf == NULL)
return SYSERR;
- if (dbhI->prepare == YES) {
- mysql_stmt_free_result(dbhI->update);
- mysql_stmt_free_result(dbhI->insert);
- mysql_stmt_free_result(dbhI->select);
- mysql_stmt_free_result(dbhI->selectc);
- mysql_stmt_free_result(dbhI->selects);
- mysql_stmt_free_result(dbhI->selectsc);
- mysql_stmt_free_result(dbhI->deleteh);
- mysql_stmt_free_result(dbhI->deleteg);
- mysql_stmt_close(dbhI->update);
- mysql_stmt_close(dbhI->insert);
- mysql_stmt_close(dbhI->select);
- mysql_stmt_close(dbhI->selectc);
- mysql_stmt_close(dbhI->selects);
- mysql_stmt_close(dbhI->selectsc);
- mysql_stmt_close(dbhI->deleteh);
- mysql_stmt_close(dbhI->deleteg);
- }
- mysql_close(dbhI->dbf);
+ if (dbhI->prepare == YES)
+ {
+ mysql_stmt_free_result (dbhI->update);
+ mysql_stmt_free_result (dbhI->insert);
+ mysql_stmt_free_result (dbhI->select);
+ mysql_stmt_free_result (dbhI->selectc);
+ mysql_stmt_free_result (dbhI->selects);
+ mysql_stmt_free_result (dbhI->selectsc);
+ mysql_stmt_free_result (dbhI->deleteh);
+ mysql_stmt_free_result (dbhI->deleteg);
+ mysql_stmt_close (dbhI->update);
+ mysql_stmt_close (dbhI->insert);
+ mysql_stmt_close (dbhI->select);
+ mysql_stmt_close (dbhI->selectc);
+ mysql_stmt_close (dbhI->selects);
+ mysql_stmt_close (dbhI->selectsc);
+ mysql_stmt_close (dbhI->deleteh);
+ mysql_stmt_close (dbhI->deleteg);
+ }
+ mysql_close (dbhI->dbf);
dbhI->dbf = NULL;
dbhI->valid = NO;
return OK;
@@ -582,90 +552,82 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateHelper(unsigned int type,
- const char * query,
- Datum_Iterator iter,
- void * closure) {
+static int
+iterateHelper (unsigned int type,
+ const char *query, Datum_Iterator iter, void *closure)
+{
MYSQL_RES *sql_res;
MYSQL_ROW sql_row;
- Datastore_Datum * datum;
- char * scratch;
+ Datastore_Datum *datum;
+ char *scratch;
char typestr[32];
int count = 0;
mysqlHandle dbhI;
cron_t now;
- dbhI.cnffile = dbh->cnffile; /* shared */
- if (OK != iopen(&dbhI, NO))
+ dbhI.cnffile = dbh->cnffile; /* shared */
+ if (OK != iopen (&dbhI, NO))
return SYSERR;
- mysql_thread_init();
- mysql_query(dbhI.dbf,
- "SET AUTOCOMMIT = 0");
- mysql_query(dbhI.dbf,
- "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
- if (type==0) {
- typestr[0] = '\0';
- } else {
- SNPRINTF(typestr,
- 32,
- "WHERE type=%u ",
- type);
- }
- now = get_time();
- scratch = MALLOC(256);
- SNPRINTF(scratch,
- 256,
- query,
- typestr,
- now);
- mysql_query(dbhI.dbf,
- scratch);
- FREE(scratch);
- if (mysql_error(dbhI.dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- &dbhI);
- mysql_thread_end();
- iclose(&dbhI);
- return SYSERR;
- }
- if (!(sql_res=mysql_use_result(dbhI.dbf))) {
- iclose(&dbhI);
- return SYSERR;
- }
- while ((sql_row=mysql_fetch_row(sql_res))) {
- datum = assembleDatum(sql_res,
- sql_row,
- &dbhI);
- if (datum == NULL) {
- mysql_thread_end();
- iclose(&dbhI);
- return count;
+ mysql_thread_init ();
+ mysql_query (dbhI.dbf, "SET AUTOCOMMIT = 0");
+ mysql_query (dbhI.dbf,
+ "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
+ if (type == 0)
+ {
+ typestr[0] = '\0';
}
- if ( (iter != NULL) &&
- (SYSERR == iter(&datum->key,
- &datum->value,
- closure) ) ) {
- count = SYSERR;
- FREE(datum);
- break;
+ else
+ {
+ SNPRINTF (typestr, 32, "WHERE type=%u ", type);
}
- FREE(datum);
- count++;
- }
- if (mysql_error(dbhI.dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- &dbhI);
- mysql_free_result(sql_res);
- mysql_thread_end();
- iclose(&dbhI);
- return SYSERR;
- }
- mysql_free_result(sql_res);
- mysql_thread_end();
- iclose(&dbhI);
+ now = get_time ();
+ scratch = MALLOC (256);
+ SNPRINTF (scratch, 256, query, typestr, now);
+ mysql_query (dbhI.dbf, scratch);
+ FREE (scratch);
+ if (mysql_error (dbhI.dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", &dbhI);
+ mysql_thread_end ();
+ iclose (&dbhI);
+ return SYSERR;
+ }
+ if (!(sql_res = mysql_use_result (dbhI.dbf)))
+ {
+ iclose (&dbhI);
+ return SYSERR;
+ }
+ while ((sql_row = mysql_fetch_row (sql_res)))
+ {
+ datum = assembleDatum (sql_res, sql_row, &dbhI);
+ if (datum == NULL)
+ {
+ mysql_thread_end ();
+ iclose (&dbhI);
+ return count;
+ }
+ if ((iter != NULL) &&
+ (SYSERR == iter (&datum->key, &datum->value, closure)))
+ {
+ count = SYSERR;
+ FREE (datum);
+ break;
+ }
+ FREE (datum);
+ count++;
+ }
+ if (mysql_error (dbhI.dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", &dbhI);
+ mysql_free_result (sql_res);
+ mysql_thread_end ();
+ iclose (&dbhI);
+ return SYSERR;
+ }
+ mysql_free_result (sql_res);
+ mysql_thread_end ();
+ iclose (&dbhI);
return count;
}
@@ -679,15 +641,12 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateLowPriority(unsigned int type,
- Datum_Iterator iter,
- void * closure) {
- return iterateHelper(type,
- "SELECT SQL_NO_CACHE * FROM gn070"
- " %s"
- "ORDER BY prio ASC",
- iter,
- closure);
+static int
+iterateLowPriority (unsigned int type, Datum_Iterator iter, void *closure)
+{
+ return iterateHelper (type,
+ "SELECT SQL_NO_CACHE * FROM gn070"
+ " %s" "ORDER BY prio ASC", iter, closure);
}
/**
@@ -700,26 +659,23 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateNonAnonymous(unsigned int type,
- int on_demand,
- Datum_Iterator iter,
- void * closure) {
+static int
+iterateNonAnonymous (unsigned int type,
+ int on_demand, Datum_Iterator iter, void *closure)
+{
char limit[512];
if (on_demand == YES)
- SNPRINTF(limit,
- 512,
- "SELECT SQL_NO_CACHE * FROM gn070"
- " %%s WHERE expire > %%llu AND anonLevel = 0 AND type != %d",
- ONDEMAND_BLOCK);
+ SNPRINTF (limit,
+ 512,
+ "SELECT SQL_NO_CACHE * FROM gn070"
+ " %%s WHERE expire > %%llu AND anonLevel = 0 AND type != %d",
+ ONDEMAND_BLOCK);
else
- strcpy(limit,
- "SELECT SQL_NO_CACHE * FROM gn070"
- " %s WHERE expire > %llu AND anonLevel = 0");
- return iterateHelper(type,
- limit,
- iter,
- closure);
+ strcpy (limit,
+ "SELECT SQL_NO_CACHE * FROM gn070"
+ " %s WHERE expire > %llu AND anonLevel = 0");
+ return iterateHelper (type, limit, iter, closure);
}
/**
@@ -732,15 +688,12 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateExpirationTime(unsigned int type,
- Datum_Iterator iter,
- void * closure) {
- return iterateHelper(type,
- "SELECT SQL_NO_CACHE * FROM gn070"
- " %s"
- " ORDER BY expire ASC",
- iter,
- closure);
+static int
+iterateExpirationTime (unsigned int type, Datum_Iterator iter, void *closure)
+{
+ return iterateHelper (type,
+ "SELECT SQL_NO_CACHE * FROM gn070"
+ " %s" " ORDER BY expire ASC", iter, closure);
}
/**
@@ -751,14 +704,13 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateMigrationOrder(Datum_Iterator iter,
- void * closure) {
- return iterateHelper(0,
- "SELECT SQL_NO_CACHE * FROM gn070"
- " %s WHERE expire > %llu"
- " ORDER BY expire DESC",
- iter,
- closure);
+static int
+iterateMigrationOrder (Datum_Iterator iter, void *closure)
+{
+ return iterateHelper (0,
+ "SELECT SQL_NO_CACHE * FROM gn070"
+ " %s WHERE expire > %llu"
+ " ORDER BY expire DESC", iter, closure);
}
/**
@@ -769,12 +721,10 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateAllNow(Datum_Iterator iter,
- void * closure) {
- return iterateHelper(0,
- "SELECT SQL_NO_CACHE * FROM gn070",
- iter,
- closure);
+static int
+iterateAllNow (Datum_Iterator iter, void *closure)
+{
+ return iterateHelper (0, "SELECT SQL_NO_CACHE * FROM gn070", iter, closure);
}
#define MAX_DATUM_SIZE 65536
@@ -790,13 +740,13 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int get(const HashCode512 * query,
- unsigned int type,
- Datum_Iterator iter,
- void * closure) {
- MYSQL_RES * sql_res;
+static int
+get (const HashCode512 * query,
+ unsigned int type, Datum_Iterator iter, void *closure)
+{
+ MYSQL_RES *sql_res;
int count;
- MYSQL_STMT * stmt;
+ MYSQL_STMT *stmt;
unsigned int size;
unsigned int rtype;
unsigned int prio;
@@ -804,7 +754,7 @@
unsigned long long expiration;
unsigned long datasize;
unsigned long twenty;
- Datastore_Value * datum;
+ Datastore_Value *datum;
HashCode512 key;
unsigned long hashSize;
#if DEBUG_MYSQL
@@ -812,221 +762,214 @@
#endif
if (query == NULL)
- return iterateLowPriority(type, iter, closure);
+ return iterateLowPriority (type, iter, closure);
#if DEBUG_MYSQL
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(query,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "MySQL looks for `%s' of type %u\n",
- &enc,
- type);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (query, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "MySQL looks for `%s' of type %u\n", &enc, type);
#endif
- MUTEX_LOCK(lock);
- mysql_thread_init();
- if (OK != CHECK_DBH) {
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- if (type != 0) {
- if (iter == NULL)
- stmt = dbh->selectsc;
- else
- stmt = dbh->selects;
- } else {
- if (iter == NULL)
- stmt = dbh->selectc;
- else
- stmt = dbh->select;
- }
- hashSize = sizeof(HashCode512);
- dbh->sbind[0].buffer = (char*) query;
- dbh->sbind[1].buffer = (char*) &type;
+ MUTEX_LOCK (lock);
+ mysql_thread_init ();
+ if (OK != CHECK_DBH)
+ {
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ if (type != 0)
+ {
+ if (iter == NULL)
+ stmt = dbh->selectsc;
+ else
+ stmt = dbh->selects;
+ }
+ else
+ {
+ if (iter == NULL)
+ stmt = dbh->selectc;
+ else
+ stmt = dbh->select;
+ }
+ hashSize = sizeof (HashCode512);
+ dbh->sbind[0].buffer = (char *) query;
+ dbh->sbind[1].buffer = (char *) &type;
dbh->sbind[0].length = &hashSize;
- GE_ASSERT(ectx, mysql_stmt_param_count(stmt) <= 2);
- sql_res = mysql_stmt_result_metadata(stmt);
- if (! sql_res) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_result_metadata",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- if ( (iter != NULL) &&
- (7 != mysql_num_fields(sql_res)) ) {
- GE_BREAK(ectx, 0);
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- if (mysql_stmt_bind_param(stmt,
- dbh->sbind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_param",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- if (mysql_stmt_execute(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_execute",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- if (iter == NULL) {
- count = mysql_stmt_affected_rows(stmt);
- mysql_stmt_reset(stmt);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return count;
- }
- datum = MALLOC(sizeof(Datastore_Value) + MAX_DATUM_SIZE);
- twenty = sizeof(HashCode512);
- dbh->bind[0].buffer = (char*) &size;
- dbh->bind[1].buffer = (char*) &rtype;
- dbh->bind[2].buffer = (char*) &prio;
- dbh->bind[3].buffer = (char*) &level;
- dbh->bind[4].buffer = (char*) &expiration;
- dbh->bind[5].buffer = (char*) &key;
- dbh->bind[6].buffer = (char*) &datum[1];
+ GE_ASSERT (ectx, mysql_stmt_param_count (stmt) <= 2);
+ sql_res = mysql_stmt_result_metadata (stmt);
+ if (!sql_res)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_result_metadata",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ if ((iter != NULL) && (7 != mysql_num_fields (sql_res)))
+ {
+ GE_BREAK (ectx, 0);
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ if (mysql_stmt_bind_param (stmt, dbh->sbind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_param",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ if (mysql_stmt_execute (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_execute",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ if (iter == NULL)
+ {
+ count = mysql_stmt_affected_rows (stmt);
+ mysql_stmt_reset (stmt);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return count;
+ }
+ datum = MALLOC (sizeof (Datastore_Value) + MAX_DATUM_SIZE);
+ twenty = sizeof (HashCode512);
+ dbh->bind[0].buffer = (char *) &size;
+ dbh->bind[1].buffer = (char *) &rtype;
+ dbh->bind[2].buffer = (char *) &prio;
+ dbh->bind[3].buffer = (char *) &level;
+ dbh->bind[4].buffer = (char *) &expiration;
+ dbh->bind[5].buffer = (char *) &key;
+ dbh->bind[6].buffer = (char *) &datum[1];
dbh->bind[5].length = &twenty;
dbh->bind[6].length = &datasize;
- dbh->bind[5].buffer_length = sizeof(HashCode512);
+ dbh->bind[5].buffer_length = sizeof (HashCode512);
dbh->bind[6].buffer_length = MAX_DATUM_SIZE;
- if (mysql_stmt_bind_result(stmt,
- dbh->bind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_result",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- FREE(datum);
- return SYSERR;
- }
- if (mysql_stmt_store_result(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_store_result",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- FREE(datum);
- return SYSERR;
- }
+ if (mysql_stmt_bind_result (stmt, dbh->bind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_result",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ FREE (datum);
+ return SYSERR;
+ }
+ if (mysql_stmt_store_result (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_store_result",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ FREE (datum);
+ return SYSERR;
+ }
datasize = MAX_DATUM_SIZE;
count = 0;
- while (0 == mysql_stmt_fetch(stmt)) {
- if ( (twenty != sizeof(HashCode512)) ||
- (datasize != size - sizeof(Datastore_Value)) ) {
- char scratch[512];
+ while (0 == mysql_stmt_fetch (stmt))
+ {
+ if ((twenty != sizeof (HashCode512)) ||
+ (datasize != size - sizeof (Datastore_Value)))
+ {
+ char scratch[512];
- mysql_free_result(sql_res);
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Invalid data in %s. Trying to fix (by deletion).\n"),
- _("mysql datastore"));
- SNPRINTF(scratch,
- 512,
- "DELETE FROM gn070 WHERE NOT ((LENGTH(hash)=%u) AND (size=%u +
LENGTH(value)))",
- sizeof(HashCode512),
- sizeof(Datastore_Value));
- if (0 != mysql_query(dbh->dbf, scratch))
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- dbh);
+ mysql_free_result (sql_res);
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Invalid data in %s. Trying to fix (by deletion).\n"),
+ _("mysql datastore"));
+ SNPRINTF (scratch,
+ 512,
+ "DELETE FROM gn070 WHERE NOT ((LENGTH(hash)=%u) AND
(size=%u + LENGTH(value)))",
+ sizeof (HashCode512), sizeof (Datastore_Value));
+ if (0 != mysql_query (dbh->dbf, scratch))
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbh);
- FREE(datum);
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return count;
- }
- count++;
- datum->size = htonl(size);
- datum->type = htonl(rtype);
- datum->prio = htonl(prio);
- datum->anonymityLevel = htonl(level);
- datum->expirationTime = htonll(expiration);
+ FREE (datum);
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return count;
+ }
+ count++;
+ datum->size = htonl (size);
+ datum->type = htonl (rtype);
+ datum->prio = htonl (prio);
+ datum->anonymityLevel = htonl (level);
+ datum->expirationTime = htonll (expiration);
#if DEBUG_MYSQL
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Found in database block with type %u.\n",
- ntohl(*(int*)&datum[1]));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Found in database block with type %u.\n",
+ ntohl (*(int *) &datum[1]));
#endif
- if (SYSERR == iter(&key,
- datum,
- closure) ) {
- count = SYSERR;
- break;
+ if (SYSERR == iter (&key, datum, closure))
+ {
+ count = SYSERR;
+ break;
+ }
+ datasize = MAX_DATUM_SIZE;
}
- datasize = MAX_DATUM_SIZE;
- }
- if (mysql_stmt_errno(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_fetch",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_free_result(sql_res);
- FREE(datum);
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- mysql_free_result(sql_res);
- FREE(datum);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
+ if (mysql_stmt_errno (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_fetch",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_free_result (sql_res);
+ FREE (datum);
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ mysql_free_result (sql_res);
+ FREE (datum);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
#if DEBUG_MYSQL
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(query,
- &enc));
- if (count > 0) {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "MySQL found %d results for `%s' of type %u.\n",
- count,
- &enc,
- type);
- } else {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "MySQL iteration aborted looking for `%s' of type %u.\n",
- &enc,
- type);
- }
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (query, &enc));
+ if (count > 0)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "MySQL found %d results for `%s' of type %u.\n",
+ count, &enc, type);
+ }
+ else
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "MySQL iteration aborted looking for `%s' of type %u.\n",
+ &enc, type);
+ }
#endif
return count;
}
@@ -1036,8 +979,9 @@
*
* @return OK on success, SYSERR on error
*/
-static int put(const HashCode512 * key,
- const Datastore_Value * value) {
+static int
+put (const HashCode512 * key, const Datastore_Value * value)
+{
unsigned long contentSize;
unsigned long hashSize;
unsigned int size;
@@ -1049,74 +993,70 @@
EncName enc;
#endif
- if ( (ntohl(value->size) < sizeof(Datastore_Value)) ) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- MUTEX_LOCK(lock);
- mysql_thread_init();
- if (OK != CHECK_DBH) {
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- contentSize = ntohl(value->size)-sizeof(Datastore_Value);
- hashSize = sizeof(HashCode512);
- size = ntohl(value->size);
- type = ntohl(value->type);
- prio = ntohl(value->prio);
- level = ntohl(value->anonymityLevel);
- expiration = ntohll(value->expirationTime);
+ if ((ntohl (value->size) < sizeof (Datastore_Value)))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ MUTEX_LOCK (lock);
+ mysql_thread_init ();
+ if (OK != CHECK_DBH)
+ {
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ contentSize = ntohl (value->size) - sizeof (Datastore_Value);
+ hashSize = sizeof (HashCode512);
+ size = ntohl (value->size);
+ type = ntohl (value->type);
+ prio = ntohl (value->prio);
+ level = ntohl (value->anonymityLevel);
+ expiration = ntohll (value->expirationTime);
#if DEBUG_MYSQL
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(key,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Storing in database block with type %u and key %s.\n",
- type,
- &enc);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (key, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Storing in database block with type %u and key %s.\n", type, &enc);
#endif
- dbh->bind[0].buffer = (char*) &size;
- dbh->bind[1].buffer = (char*) &type;
- dbh->bind[2].buffer = (char*) &prio;
- dbh->bind[3].buffer = (char*) &level;
- dbh->bind[4].buffer = (char*) &expiration;
- dbh->bind[5].buffer = (char*) key;
- dbh->bind[6].buffer = (char*) &value[1];
+ dbh->bind[0].buffer = (char *) &size;
+ dbh->bind[1].buffer = (char *) &type;
+ dbh->bind[2].buffer = (char *) &prio;
+ dbh->bind[3].buffer = (char *) &level;
+ dbh->bind[4].buffer = (char *) &expiration;
+ dbh->bind[5].buffer = (char *) key;
+ dbh->bind[6].buffer = (char *) &value[1];
dbh->bind[5].length = &hashSize;
dbh->bind[6].length = &contentSize;
- if (mysql_stmt_bind_param(dbh->insert,
- dbh->bind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_param",
- __FILE__, __LINE__,
- mysql_stmt_error(dbh->insert));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
+ if (mysql_stmt_bind_param (dbh->insert, dbh->bind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_param",
+ __FILE__, __LINE__, mysql_stmt_error (dbh->insert));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
- if (mysql_stmt_execute(dbh->insert)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_execute",
- __FILE__, __LINE__,
- mysql_stmt_error(dbh->insert));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- mysql_thread_end();
- content_size += ntohl(value->size);
- MUTEX_UNLOCK(lock);
+ if (mysql_stmt_execute (dbh->insert))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_execute",
+ __FILE__, __LINE__, mysql_stmt_error (dbh->insert));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ mysql_thread_end ();
+ content_size += ntohl (value->size);
+ MUTEX_UNLOCK (lock);
return OK;
}
@@ -1128,243 +1068,238 @@
* @return the number of items deleted, 0 if
* none were found, SYSERR on errors
*/
-static int del(const HashCode512 * key,
- const Datastore_Value * value) {
+static int
+del (const HashCode512 * key, const Datastore_Value * value)
+{
int count;
unsigned long twenty;
- MYSQL_STMT * stmt;
+ MYSQL_STMT *stmt;
unsigned int size;
unsigned int type;
unsigned int prio;
unsigned int anon;
unsigned long long expiration;
unsigned long datasize;
- Datastore_Value * svalue;
- MYSQL_RES * sql_res;
+ Datastore_Value *svalue;
+ MYSQL_RES *sql_res;
unsigned int rtype;
unsigned int level;
HashCode512 skey;
#if DEBUG_MYSQL
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(key,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "MySQL is executing deletion request for content of query `%s' and type
%u\n",
- &enc,
- value == NULL ? 0 : ntohl(value->type));
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (key, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "MySQL is executing deletion request for content of query `%s' and
type %u\n",
+ &enc, value == NULL ? 0 : ntohl (value->type));
#endif
- twenty = sizeof(HashCode512);
+ twenty = sizeof (HashCode512);
svalue = NULL;
- MUTEX_LOCK(lock);
- mysql_thread_init();
- if (OK != CHECK_DBH) {
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- if (value == NULL) {
- stmt = dbh->deleteh;
- dbh->dbind[0].buffer = (char*) key;
- dbh->dbind[0].length = &twenty;
- GE_ASSERT(ectx, mysql_stmt_param_count(stmt) <= 1);
-
- sql_res = mysql_stmt_result_metadata(stmt);
- if (! sql_res) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_result_metadata",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
+ MUTEX_LOCK (lock);
+ mysql_thread_init ();
+ if (OK != CHECK_DBH)
+ {
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
return SYSERR;
}
- if (7 != mysql_num_fields(sql_res)) {
- GE_BREAK(ectx, 0);
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- if (mysql_stmt_bind_param(stmt,
- dbh->dbind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_param",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- if (mysql_stmt_execute(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_execute",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- svalue = MALLOC(sizeof(Datastore_Value) + MAX_DATUM_SIZE);
- twenty = sizeof(HashCode512);
- dbh->bind[0].buffer = (char*) &size;
- dbh->bind[1].buffer = (char*) &rtype;
- dbh->bind[2].buffer = (char*) &prio;
- dbh->bind[3].buffer = (char*) &level;
- dbh->bind[4].buffer = (char*) &expiration;
- dbh->bind[5].buffer = (char*) &skey;
- dbh->bind[6].buffer = (char*) &svalue[1];
- dbh->bind[5].length = &twenty;
- dbh->bind[6].length = &datasize;
- dbh->bind[5].buffer_length = sizeof(HashCode512);
- dbh->bind[6].buffer_length = MAX_DATUM_SIZE;
- if (mysql_stmt_bind_result(stmt,
- dbh->bind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_result",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- FREE(svalue);
- return SYSERR;
- }
- if (mysql_stmt_store_result(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_store_result",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- FREE(svalue);
- return SYSERR;
- }
- datasize = MAX_DATUM_SIZE;
- if (0 != mysql_stmt_fetch(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_fetch",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- FREE(svalue);
- return SYSERR;
- }
- if ( (twenty != sizeof(HashCode512)) ||
- (datasize != size - sizeof(Datastore_Value)) ) {
- char scratch[512];
+ if (value == NULL)
+ {
+ stmt = dbh->deleteh;
+ dbh->dbind[0].buffer = (char *) key;
+ dbh->dbind[0].length = &twenty;
+ GE_ASSERT (ectx, mysql_stmt_param_count (stmt) <= 1);
- mysql_free_result(sql_res);
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Invalid data in %s. Trying to fix (by deletion).\n"),
- _("mysql datastore"));
- SNPRINTF(scratch,
- 512,
- "DELETE FROM gn070 WHERE NOT ((LENGTH(hash)=%u) AND (size=%u +
LENGTH(value)))",
- sizeof(HashCode512),
- sizeof(Datastore_Value));
- if (0 != mysql_query(dbh->dbf, scratch))
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query", dbh);
- FREE(svalue);
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return 1;
+ sql_res = mysql_stmt_result_metadata (stmt);
+ if (!sql_res)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_result_metadata",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ if (7 != mysql_num_fields (sql_res))
+ {
+ GE_BREAK (ectx, 0);
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ if (mysql_stmt_bind_param (stmt, dbh->dbind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_param",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ if (mysql_stmt_execute (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_execute",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ svalue = MALLOC (sizeof (Datastore_Value) + MAX_DATUM_SIZE);
+ twenty = sizeof (HashCode512);
+ dbh->bind[0].buffer = (char *) &size;
+ dbh->bind[1].buffer = (char *) &rtype;
+ dbh->bind[2].buffer = (char *) &prio;
+ dbh->bind[3].buffer = (char *) &level;
+ dbh->bind[4].buffer = (char *) &expiration;
+ dbh->bind[5].buffer = (char *) &skey;
+ dbh->bind[6].buffer = (char *) &svalue[1];
+ dbh->bind[5].length = &twenty;
+ dbh->bind[6].length = &datasize;
+ dbh->bind[5].buffer_length = sizeof (HashCode512);
+ dbh->bind[6].buffer_length = MAX_DATUM_SIZE;
+ if (mysql_stmt_bind_result (stmt, dbh->bind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_result",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ FREE (svalue);
+ return SYSERR;
+ }
+ if (mysql_stmt_store_result (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_store_result",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ FREE (svalue);
+ return SYSERR;
+ }
+ datasize = MAX_DATUM_SIZE;
+ if (0 != mysql_stmt_fetch (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_fetch",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ FREE (svalue);
+ return SYSERR;
+ }
+ if ((twenty != sizeof (HashCode512)) ||
+ (datasize != size - sizeof (Datastore_Value)))
+ {
+ char scratch[512];
+
+ mysql_free_result (sql_res);
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Invalid data in %s. Trying to fix (by deletion).\n"),
+ _("mysql datastore"));
+ SNPRINTF (scratch,
+ 512,
+ "DELETE FROM gn070 WHERE NOT ((LENGTH(hash)=%u) AND
(size=%u + LENGTH(value)))",
+ sizeof (HashCode512), sizeof (Datastore_Value));
+ if (0 != mysql_query (dbh->dbf, scratch))
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbh);
+ FREE (svalue);
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return 1;
+ }
+ mysql_free_result (sql_res);
+ svalue->size = htonl (size);
+ svalue->type = htonl (rtype);
+ svalue->prio = htonl (prio);
+ svalue->anonymityLevel = htonl (level);
+ svalue->expirationTime = htonll (expiration);
+ value = svalue;
}
- mysql_free_result(sql_res);
- svalue->size = htonl(size);
- svalue->type = htonl(rtype);
- svalue->prio = htonl(prio);
- svalue->anonymityLevel = htonl(level);
- svalue->expirationTime = htonll(expiration);
- value = svalue;
- }
stmt = dbh->deleteg;
- type = ntohl(value->type);
- size = ntohl(value->size);
- prio = ntohl(value->prio);
- anon = ntohl(value->anonymityLevel);
- expiration = ntohll(value->expirationTime);
- datasize = ntohl(value->size) - sizeof(Datastore_Value);
- dbh->dbind[0].buffer = (char*) key;
+ type = ntohl (value->type);
+ size = ntohl (value->size);
+ prio = ntohl (value->prio);
+ anon = ntohl (value->anonymityLevel);
+ expiration = ntohll (value->expirationTime);
+ datasize = ntohl (value->size) - sizeof (Datastore_Value);
+ dbh->dbind[0].buffer = (char *) key;
dbh->dbind[0].length = &twenty;
- dbh->dbind[1].buffer = (char*) &size;
- dbh->dbind[2].buffer = (char*) &type;
- dbh->dbind[3].buffer = (char*) &prio;
- dbh->dbind[4].buffer = (char*) &anon;
- dbh->dbind[5].buffer = (char*) &expiration;
- dbh->dbind[6].buffer = (char*) &value[1];
+ dbh->dbind[1].buffer = (char *) &size;
+ dbh->dbind[2].buffer = (char *) &type;
+ dbh->dbind[3].buffer = (char *) &prio;
+ dbh->dbind[4].buffer = (char *) &anon;
+ dbh->dbind[5].buffer = (char *) &expiration;
+ dbh->dbind[6].buffer = (char *) &value[1];
dbh->dbind[6].length = &datasize;
#if 0
- dbh->dbind[0].buffer_length = sizeof(HashCode512);
- dbh->dbind[6].buffer_length = size - sizeof(Datastore_Value);
+ dbh->dbind[0].buffer_length = sizeof (HashCode512);
+ dbh->dbind[6].buffer_length = size - sizeof (Datastore_Value);
#endif
- GE_ASSERT(ectx, mysql_stmt_param_count(stmt) <= 7);
- if (mysql_stmt_bind_param(stmt,
- dbh->dbind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_param",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- if (svalue != NULL)
- FREE(svalue);
- return SYSERR;
- }
- if (mysql_stmt_execute(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_execute",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- if (svalue != NULL)
- FREE(svalue);
- return SYSERR;
- }
- count = mysql_stmt_affected_rows(stmt);
- mysql_thread_end();
+ GE_ASSERT (ectx, mysql_stmt_param_count (stmt) <= 7);
+ if (mysql_stmt_bind_param (stmt, dbh->dbind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_param",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ if (svalue != NULL)
+ FREE (svalue);
+ return SYSERR;
+ }
+ if (mysql_stmt_execute (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_execute",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ if (svalue != NULL)
+ FREE (svalue);
+ return SYSERR;
+ }
+ count = mysql_stmt_affected_rows (stmt);
+ mysql_thread_end ();
#if DEBUG_MYSQL
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "MySQL DELETE operation affected %d rows.\n",
- count);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "MySQL DELETE operation affected %d rows.\n", count);
#endif
- content_size -= ntohl(value->size);
- MUTEX_UNLOCK(lock);
+ content_size -= ntohl (value->size);
+ MUTEX_UNLOCK (lock);
if (svalue != NULL)
- FREE(svalue);
+ FREE (svalue);
return count;
}
@@ -1372,66 +1307,65 @@
* Update the priority for a particular key
* in the datastore.
*/
-static int update(const HashCode512 * key,
- const Datastore_Value * value,
- int delta,
- cron_t expire) {
+static int
+update (const HashCode512 * key,
+ const Datastore_Value * value, int delta, cron_t expire)
+{
unsigned long contentSize;
unsigned long twenty;
cron_t start;
- twenty = sizeof(HashCode512);
- MUTEX_LOCK(lock);
- mysql_thread_init();
- if (OK != CHECK_DBH) {
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- contentSize = ntohl(value->size)-sizeof(Datastore_Value);
- dbh->ubind[0].buffer = (char*) δ
- dbh->ubind[1].buffer = (char*) &expire;
- dbh->ubind[2].buffer = (char*) &expire;
- dbh->ubind[3].buffer = (char*) key;
+ twenty = sizeof (HashCode512);
+ MUTEX_LOCK (lock);
+ mysql_thread_init ();
+ if (OK != CHECK_DBH)
+ {
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ contentSize = ntohl (value->size) - sizeof (Datastore_Value);
+ dbh->ubind[0].buffer = (char *) δ
+ dbh->ubind[1].buffer = (char *) &expire;
+ dbh->ubind[2].buffer = (char *) &expire;
+ dbh->ubind[3].buffer = (char *) key;
dbh->ubind[3].length = &twenty;
- dbh->ubind[4].buffer = (char*) &value[1];
+ dbh->ubind[4].buffer = (char *) &value[1];
dbh->ubind[4].length = &contentSize;
- GE_ASSERT(ectx,
- mysql_stmt_param_count(dbh->update) <= 5);
- if (mysql_stmt_bind_param(dbh->update,
- dbh->ubind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_param",
- __FILE__, __LINE__,
- mysql_stmt_error(dbh->update));
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
+ GE_ASSERT (ectx, mysql_stmt_param_count (dbh->update) <= 5);
+ if (mysql_stmt_bind_param (dbh->update, dbh->ubind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_param",
+ __FILE__, __LINE__, mysql_stmt_error (dbh->update));
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
/* NOTE: as the table entry for 'prio' is defined as unsigned,
* mysql will zero the value if its about to go negative. (This
* will generate a warning though, but its probably not seen
* at all in this context.)
*/
- start = get_time();
- if (mysql_stmt_execute(dbh->update)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error `%s' after %llums\n"),
- "mysql_stmt_execute",
- __FILE__, __LINE__,
- mysql_stmt_error(dbh->update),
- get_time() - start);
- iclose(dbh);
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
+ start = get_time ();
+ if (mysql_stmt_execute (dbh->update))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error `%s' after %llums\n"),
+ "mysql_stmt_execute",
+ __FILE__, __LINE__,
+ mysql_stmt_error (dbh->update), get_time () - start);
+ iclose (dbh);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
return OK;
}
@@ -1441,165 +1375,164 @@
* available.
* @return number of bytes used on disk
*/
-static unsigned long long getSize() {
+static unsigned long long
+getSize ()
+{
unsigned long long ret;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
ret = content_size;
if (stats)
- stats->set(stat_size, ret);
- MUTEX_UNLOCK(lock);
- return ret * 2; /* common overhead seems to be 100%! */
+ stats->set (stat_size, ret);
+ MUTEX_UNLOCK (lock);
+ return ret * 2; /* common overhead seems to be 100%! */
}
/**
* Delete the database. The next operation is
* guaranteed to be unloading of the module.
*/
-static void drop() {
- MUTEX_LOCK(lock);
- mysql_thread_init();
- if (OK != CHECK_DBH) {
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
- return;
- }
- mysql_query(dbh->dbf,
- "DROP TABLE gn070");
- if (mysql_error(dbh->dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- dbh);
- iclose(dbh);
- } else {
- content_size = 0;
- }
- mysql_thread_end();
- MUTEX_UNLOCK(lock);
+static void
+drop ()
+{
+ MUTEX_LOCK (lock);
+ mysql_thread_init ();
+ if (OK != CHECK_DBH)
+ {
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
+ return;
+ }
+ mysql_query (dbh->dbf, "DROP TABLE gn070");
+ if (mysql_error (dbh->dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbh);
+ iclose (dbh);
+ }
+ else
+ {
+ content_size = 0;
+ }
+ mysql_thread_end ();
+ MUTEX_UNLOCK (lock);
}
SQstore_ServiceAPI *
-provide_module_sqstore_mysql(CoreAPIForApplication * capi) {
+provide_module_sqstore_mysql (CoreAPIForApplication * capi)
+{
static SQstore_ServiceAPI api;
- State_ServiceAPI * state;
- char * cnffile;
- FILE * fp;
- struct passwd * pw;
+ State_ServiceAPI *state;
+ char *cnffile;
+ FILE *fp;
+ struct passwd *pw;
size_t nX;
- char * home_dir;
- unsigned long long * sb;
+ char *home_dir;
+ unsigned long long *sb;
MYSQL_RES *sql_res;
MYSQL_ROW sql_row;
ectx = capi->ectx;
coreAPI = capi;
- stats = coreAPI->requestService("stats");
+ stats = coreAPI->requestService ("stats");
if (stats)
- stat_size
- = stats->create(gettext_noop("# bytes in datastore"));
+ stat_size = stats->create (gettext_noop ("# bytes in datastore"));
/* verify that .my.cnf can be found */
#ifndef WINDOWS
- pw = getpwuid(getuid());
- if(!pw)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "getpwuid");
- home_dir = STRDUP(pw->pw_dir);
+ pw = getpwuid (getuid ());
+ if (!pw)
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_ADMIN | GE_IMMEDIATE, "getpwuid");
+ home_dir = STRDUP (pw->pw_dir);
#else
- home_dir = (char *) MALLOC(_MAX_PATH + 1);
- plibc_conv_to_win_path("~/", home_dir);
+ home_dir = (char *) MALLOC (_MAX_PATH + 1);
+ plibc_conv_to_win_path ("~/", home_dir);
#endif
- nX = strlen(home_dir)+10;
- cnffile = MALLOC(nX);
- SNPRINTF(cnffile,
- nX,
- "%s/.my.cnf",
- home_dir);
- FREE(home_dir);
- GC_get_configuration_value_filename(capi->cfg,
- "MYSQL",
- "CONFIG",
- cnffile,
- &home_dir);
- FREE(cnffile);
+ nX = strlen (home_dir) + 10;
+ cnffile = MALLOC (nX);
+ SNPRINTF (cnffile, nX, "%s/.my.cnf", home_dir);
+ FREE (home_dir);
+ GC_get_configuration_value_filename (capi->cfg,
+ "MYSQL", "CONFIG", cnffile, &home_dir);
+ FREE (cnffile);
cnffile = home_dir;
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _("Trying to use file `%s' for MySQL configuration.\n"),
- cnffile);
- fp = FOPEN(cnffile, "r");
- if (!fp) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "fopen",
- cnffile);
- if (stats != NULL)
- coreAPI->releaseService(stats);
- FREE(cnffile);
- return NULL;
- } else {
- fclose(fp);
- }
- dbh = MALLOC(sizeof(mysqlHandle));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ _("Trying to use file `%s' for MySQL configuration.\n"), cnffile);
+ fp = FOPEN (cnffile, "r");
+ if (!fp)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK, "fopen", cnffile);
+ if (stats != NULL)
+ coreAPI->releaseService (stats);
+ FREE (cnffile);
+ return NULL;
+ }
+ else
+ {
+ fclose (fp);
+ }
+ dbh = MALLOC (sizeof (mysqlHandle));
dbh->cnffile = cnffile;
- if (OK != iopen(dbh, YES)) {
- FREE(cnffile);
- FREE(dbh);
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Failed to load MySQL database module. Check that MySQL is running and
configured properly!\n"));
- dbh = NULL;
- if (stats != NULL)
- coreAPI->releaseService(stats);
- return NULL;
- }
+ if (OK != iopen (dbh, YES))
+ {
+ FREE (cnffile);
+ FREE (dbh);
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("Failed to load MySQL database module. Check that MySQL is
running and configured properly!\n"));
+ dbh = NULL;
+ if (stats != NULL)
+ coreAPI->releaseService (stats);
+ return NULL;
+ }
- lock = MUTEX_CREATE(NO);
- state = coreAPI->requestService("state");
+ lock = MUTEX_CREATE (NO);
+ state = coreAPI->requestService ("state");
sb = NULL;
- if (sizeof(unsigned long long)
- != state->read(ectx,
- "mysql-size",
- (void*) &sb)) {
-
- /* need to recompute! */
- sql_res = NULL;
- mysql_query(dbh->dbf,
- SELECT_SIZE);
- if ( (mysql_error(dbh->dbf)[0]) ||
- (!(sql_res=mysql_use_result(dbh->dbf))) ||
- (!(sql_row=mysql_fetch_row(sql_res))) ) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- dbh);
- content_size = 0;
- iclose(dbh);
- } else {
- if ( (mysql_num_fields(sql_res) != 1) ||
- (sql_row[0] == NULL) ) {
- GE_BREAK(ectx, mysql_num_fields(sql_res) == 1);
- content_size = 0;
- } else {
- if (1 != SSCANF(sql_row[0],
- "%llu",
- &content_size)) {
- GE_BREAK(ectx, 0);
- content_size = 0;
- }
- }
+ if (sizeof (unsigned long long)
+ != state->read (ectx, "mysql-size", (void *) &sb))
+ {
+ /* need to recompute! */
+ sql_res = NULL;
+ mysql_query (dbh->dbf, SELECT_SIZE);
+ if ((mysql_error (dbh->dbf)[0]) ||
+ (!(sql_res = mysql_use_result (dbh->dbf))) ||
+ (!(sql_row = mysql_fetch_row (sql_res))))
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbh);
+ content_size = 0;
+ iclose (dbh);
+ }
+ else
+ {
+ if ((mysql_num_fields (sql_res) != 1) || (sql_row[0] == NULL))
+ {
+ GE_BREAK (ectx, mysql_num_fields (sql_res) == 1);
+ content_size = 0;
+ }
+ else
+ {
+ if (1 != SSCANF (sql_row[0], "%llu", &content_size))
+ {
+ GE_BREAK (ectx, 0);
+ content_size = 0;
+ }
+ }
+ }
+ if (sql_res != NULL)
+ mysql_free_result (sql_res);
}
- if (sql_res != NULL)
- mysql_free_result(sql_res);
- } else {
- content_size = *sb;
- FREE(sb);
- /* no longer valid! remember it by deleting
- the outdated state file! */
- state->unlink(ectx,
- "mysql-size");
- }
- coreAPI->releaseService(state);
+ else
+ {
+ content_size = *sb;
+ FREE (sb);
+ /* no longer valid! remember it by deleting
+ the outdated state file! */
+ state->unlink (ectx, "mysql-size");
+ }
+ coreAPI->releaseService (state);
api.getSize = &getSize;
api.put = &put;
api.get = &get;
@@ -1617,23 +1550,23 @@
/**
* Shutdown the module.
*/
-void release_module_sqstore_mysql() {
- State_ServiceAPI * state;
- iclose(dbh);
- FREE(dbh->cnffile);
- FREE(dbh);
+void
+release_module_sqstore_mysql ()
+{
+ State_ServiceAPI *state;
+ iclose (dbh);
+ FREE (dbh->cnffile);
+ FREE (dbh);
dbh = NULL;
if (stats != NULL)
- coreAPI->releaseService(stats);
- MUTEX_DESTROY(lock);
- state = coreAPI->requestService("state");
- state->write(ectx,
- "mysql-size",
- sizeof(unsigned long long),
- &content_size);
- coreAPI->releaseService(state);
- mysql_library_end();
+ coreAPI->releaseService (stats);
+ MUTEX_DESTROY (lock);
+ state = coreAPI->requestService ("state");
+ state->write (ectx,
+ "mysql-size", sizeof (unsigned long long), &content_size);
+ coreAPI->releaseService (state);
+ mysql_library_end ();
ectx = NULL;
coreAPI = NULL;
}
Modified: GNUnet/src/applications/sqstore_mysql/mysqltest.c
===================================================================
--- GNUnet/src/applications/sqstore_mysql/mysqltest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/sqstore_mysql/mysqltest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -35,101 +35,104 @@
static cron_t now;
-static Datastore_Value * initValue(int i) {
- Datastore_Value * value;
+static Datastore_Value *
+initValue (int i)
+{
+ Datastore_Value *value;
- value = MALLOC(sizeof(Datastore_Value) + 8 * i);
- value->size = htonl(sizeof(Datastore_Value) + 8 * i);
- value->type = htonl(i);
- value->prio = htonl(i+1);
- value->anonymityLevel = htonl(i);
- value->expirationTime = htonll(now - i * cronSECONDS);
- memset(&value[1], i, 8*i);
+ value = MALLOC (sizeof (Datastore_Value) + 8 * i);
+ value->size = htonl (sizeof (Datastore_Value) + 8 * i);
+ value->type = htonl (i);
+ value->prio = htonl (i + 1);
+ value->anonymityLevel = htonl (i);
+ value->expirationTime = htonll (now - i * cronSECONDS);
+ memset (&value[1], i, 8 * i);
return value;
}
-static int checkValue(const HashCode512 * key,
- const Datastore_Value * val,
- void * closure) {
+static int
+checkValue (const HashCode512 * key,
+ const Datastore_Value * val, void *closure)
+{
int i;
int ret;
- Datastore_Value * value;
+ Datastore_Value *value;
- i = *(int*) closure;
- value = initValue(i);
- if ( ( value->size == val->size) &&
- (0 == memcmp(val,
- value,
- ntohl(val->size)) ) )
+ i = *(int *) closure;
+ value = initValue (i);
+ if ((value->size == val->size) &&
+ (0 == memcmp (val, value, ntohl (val->size))))
ret = OK;
- else {
- /*
- printf("Wanted: %u, %llu; got %u, %llu - %d\n",
- ntohl(value->size), ntohll(value->expirationTime),
- ntohl(val->size), ntohll(val->expirationTime),
- memcmp(val, value, ntohl(val->size))); */
- ret = SYSERR;
- }
- FREE(value);
+ else
+ {
+ /*
+ printf("Wanted: %u, %llu; got %u, %llu - %d\n",
+ ntohl(value->size), ntohll(value->expirationTime),
+ ntohl(val->size), ntohll(val->expirationTime),
+ memcmp(val, value, ntohl(val->size))); */
+ ret = SYSERR;
+ }
+ FREE (value);
return ret;
}
-static int iterateUp(const HashCode512 * key,
- const Datastore_Value * val,
- int * closure) {
+static int
+iterateUp (const HashCode512 * key, const Datastore_Value * val, int *closure)
+{
int ret;
- ret = checkValue(key, val, closure);
+ ret = checkValue (key, val, closure);
(*closure) += 2;
return ret;
}
-static int iterateDown(const HashCode512 * key,
- const Datastore_Value * val,
- int * closure) {
+static int
+iterateDown (const HashCode512 * key,
+ const Datastore_Value * val, int *closure)
+{
int ret;
(*closure) -= 2;
- ret = checkValue(key, val, closure);
+ ret = checkValue (key, val, closure);
return ret;
}
-static int iterateDelete(const HashCode512 * key,
- const Datastore_Value * val,
- SQstore_ServiceAPI * api) {
- if (1 == api->del(key, val))
- return OK;
+static int
+iterateDelete (const HashCode512 * key,
+ const Datastore_Value * val, SQstore_ServiceAPI * api)
+{
+ if (1 == api->del (key, val))
+ return OK;
else
- return SYSERR;
+ return SYSERR;
}
-static int priorityCheck(const HashCode512 * key,
- const Datastore_Value * val,
- int * closure) {
+static int
+priorityCheck (const HashCode512 * key,
+ const Datastore_Value * val, int *closure)
+{
int id;
id = (*closure);
- if (id + 1 == ntohl(val->prio))
+ if (id + 1 == ntohl (val->prio))
return OK;
else
return SYSERR;
}
-static int multipleCheck(const HashCode512 * key,
- const Datastore_Value * val,
- Datastore_Value ** last) {
- if (*last != NULL) {
- if ( ((*last)->size == val->size) &&
- (0 == memcmp(*last,
- val,
- ntohl(val->size)) ) )
- return SYSERR; /* duplicate! */
- FREE(*last);
- }
- *last = MALLOC(ntohl(val->size));
- memcpy(*last,
- val,
- ntohl(val->size));
+static int
+multipleCheck (const HashCode512 * key,
+ const Datastore_Value * val, Datastore_Value ** last)
+{
+ if (*last != NULL)
+ {
+ if (((*last)->size == val->size) &&
+ (0 == memcmp (*last, val, ntohl (val->size))))
+ return SYSERR; /* duplicate! */
+ FREE (*last);
+ }
+ *last = MALLOC (ntohl (val->size));
+ memcpy (*last, val, ntohl (val->size));
return OK;
}
@@ -137,125 +140,119 @@
/**
* Add testcode here!
*/
-static int test(SQstore_ServiceAPI * api) {
- Datastore_Value * value;
+static int
+test (SQstore_ServiceAPI * api)
+{
+ Datastore_Value *value;
HashCode512 key;
unsigned long long oldSize;
int i;
now = 1000000;
- oldSize = api->getSize();
- for (i=0;i<256;i++) {
- value = initValue(i);
- memset(&key, 256-i, sizeof(HashCode512));
- ASSERT(OK == api->put(&key, value));
- FREE(value);
- }
- ASSERT(oldSize < api->getSize());
- ASSERT(256 == api->iterateLowPriority(ANY_BLOCK,
- NULL,
- NULL));
- ASSERT(256 == api->iterateExpirationTime(ANY_BLOCK,
- NULL,
- NULL));
- for (i=255;i>=0;i--) {
- memset(&key, 256-i, sizeof(HashCode512));
- ASSERT(1 == api->get(&key, i, &checkValue, (void*) &i));
- }
+ oldSize = api->getSize ();
+ for (i = 0; i < 256; i++)
+ {
+ value = initValue (i);
+ memset (&key, 256 - i, sizeof (HashCode512));
+ ASSERT (OK == api->put (&key, value));
+ FREE (value);
+ }
+ ASSERT (oldSize < api->getSize ());
+ ASSERT (256 == api->iterateLowPriority (ANY_BLOCK, NULL, NULL));
+ ASSERT (256 == api->iterateExpirationTime (ANY_BLOCK, NULL, NULL));
+ for (i = 255; i >= 0; i--)
+ {
+ memset (&key, 256 - i, sizeof (HashCode512));
+ ASSERT (1 == api->get (&key, i, &checkValue, (void *) &i));
+ }
- oldSize = api->getSize();
- for (i=255;i>=0;i-=2) {
- memset(&key, 256-i, sizeof(HashCode512));
- value = initValue(i);
- ASSERT(1 == api->del(&key, value));
- FREE(value);
- }
- ASSERT(oldSize > api->getSize());
+ oldSize = api->getSize ();
+ for (i = 255; i >= 0; i -= 2)
+ {
+ memset (&key, 256 - i, sizeof (HashCode512));
+ value = initValue (i);
+ ASSERT (1 == api->del (&key, value));
+ FREE (value);
+ }
+ ASSERT (oldSize > api->getSize ());
i = 0;
- ASSERT(128 == api->iterateLowPriority(ANY_BLOCK,
- (Datum_Iterator) &iterateUp,
- &i));
- ASSERT(256 == i);
- ASSERT(128 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &iterateDown,
- &i));
- ASSERT(0 == i);
- ASSERT(128 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &iterateDelete,
- api));
- ASSERT(0 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &iterateDown,
- &i));
+ ASSERT (128 == api->iterateLowPriority (ANY_BLOCK,
+ (Datum_Iterator) & iterateUp, &i));
+ ASSERT (256 == i);
+ ASSERT (128 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & iterateDown,
+ &i));
+ ASSERT (0 == i);
+ ASSERT (128 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & iterateDelete,
+ api));
+ ASSERT (0 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & iterateDown,
+ &i));
i = 42;
- value = initValue(i);
- memset(&key, 256-i, sizeof(HashCode512));
- api->put(&key, value);
- ASSERT(1 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &priorityCheck,
- &i));
- api->update(&key,
- value,
- 4,
- 0);
+ value = initValue (i);
+ memset (&key, 256 - i, sizeof (HashCode512));
+ api->put (&key, value);
+ ASSERT (1 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & priorityCheck,
+ &i));
+ api->update (&key, value, 4, 0);
i += 4;
- ASSERT(1 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &priorityCheck,
- &i));
- FREE(value);
+ ASSERT (1 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & priorityCheck,
+ &i));
+ FREE (value);
/* test multiple results */
- value = initValue(i+1);
- api->put(&key, value);
- FREE(value);
+ value = initValue (i + 1);
+ api->put (&key, value);
+ FREE (value);
value = NULL;
- ASSERT(2 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &multipleCheck,
- &value));
- FREE(value);
- api->del(&key,
- NULL);
- api->del(&key,
- NULL);
- ASSERT(0 == api->iterateExpirationTime(ANY_BLOCK,
- NULL,
- NULL));
- api->drop();
+ ASSERT (2 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & multipleCheck,
+ &value));
+ FREE (value);
+ api->del (&key, NULL);
+ api->del (&key, NULL);
+ ASSERT (0 == api->iterateExpirationTime (ANY_BLOCK, NULL, NULL));
+ api->drop ();
return OK;
- FAILURE:
- api->drop();
+FAILURE:
+ api->drop ();
return SYSERR;
}
-int main(int argc, char *argv[]) {
- SQstore_ServiceAPI * api;
+int
+main (int argc, char *argv[])
+{
+ SQstore_ServiceAPI *api;
int ok;
- struct GC_Configuration * cfg;
- struct CronManager * cron;
+ struct GC_Configuration *cfg;
+ struct CronManager *cron;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- cron = cron_create(NULL);
- initCore(NULL,
- cfg,
- cron,
- NULL);
- api = requestService("sqstore");
- if (api != NULL) {
- ok = test(api);
- releaseService(api);
- } else
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ cron = cron_create (NULL);
+ initCore (NULL, cfg, cron, NULL);
+ api = requestService ("sqstore");
+ if (api != NULL)
+ {
+ ok = test (api);
+ releaseService (api);
+ }
+ else
ok = SYSERR;
- doneCore();
- cron_destroy(cron);
- GC_free(cfg);
+ doneCore ();
+ cron_destroy (cron);
+ GC_free (cfg);
if (ok == SYSERR)
return 1;
return 0;
Modified: GNUnet/src/applications/sqstore_mysql/mysqltest2.c
===================================================================
--- GNUnet/src/applications/sqstore_mysql/mysqltest2.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/sqstore_mysql/mysqltest2.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -123,67 +123,65 @@
static cron_t start_time;
-static int putValue(SQstore_ServiceAPI * api,
- int i) {
- Datastore_Value * value;
+static int
+putValue (SQstore_ServiceAPI * api, int i)
+{
+ Datastore_Value *value;
size_t size;
static HashCode512 key;
static int ic;
/* most content is 32k */
- size = sizeof(Datastore_Value) + 32 * 1024;
- if (weak_randomi(16) == 0) /* but some of it is less! */
- size = sizeof(Datastore_Value) + weak_randomi(32 * 1024);
- size = size - (size & 7); /* always multiple of 8 */
+ size = sizeof (Datastore_Value) + 32 * 1024;
+ if (weak_randomi (16) == 0) /* but some of it is less! */
+ size = sizeof (Datastore_Value) + weak_randomi (32 * 1024);
+ size = size - (size & 7); /* always multiple of 8 */
/* generate random key */
- hash(&key,
- sizeof(HashCode512),
- &key);
- value = MALLOC(size);
- value->size = htonl(size);
- value->type = htonl(i);
- value->prio = htonl(weak_randomi(100));
- value->anonymityLevel = htonl(i);
- value->expirationTime = htonll(get_time() + weak_randomi(1000));
- memset(&value[1],
- i,
- size - sizeof(Datastore_Value));
- if (OK != api->put(&key, value)) {
- FREE(value);
- fprintf(stderr, "E");
- return SYSERR;
- }
+ hash (&key, sizeof (HashCode512), &key);
+ value = MALLOC (size);
+ value->size = htonl (size);
+ value->type = htonl (i);
+ value->prio = htonl (weak_randomi (100));
+ value->anonymityLevel = htonl (i);
+ value->expirationTime = htonll (get_time () + weak_randomi (1000));
+ memset (&value[1], i, size - sizeof (Datastore_Value));
+ if (OK != api->put (&key, value))
+ {
+ FREE (value);
+ fprintf (stderr, "E");
+ return SYSERR;
+ }
ic++;
#if REPORT_ID
if (ic % REP_FREQ == 0)
- fprintf(stderr, "I");
+ fprintf (stderr, "I");
#endif
- stored_bytes += ntohl(value->size);
+ stored_bytes += ntohl (value->size);
stored_ops++;
stored_entries++;
- FREE(value);
+ FREE (value);
return OK;
}
static int
-iterateDelete(const HashCode512 * key,
- const Datastore_Value * val,
- void * cls) {
- SQstore_ServiceAPI * api = cls;
+iterateDelete (const HashCode512 * key,
+ const Datastore_Value * val, void *cls)
+{
+ SQstore_ServiceAPI *api = cls;
static int dc;
- if (api->getSize() < MAX_SIZE)
+ if (api->getSize () < MAX_SIZE)
return SYSERR;
- if (GNUNET_SHUTDOWN_TEST() == YES)
+ if (GNUNET_SHUTDOWN_TEST () == YES)
return SYSERR;
dc++;
#if REPORT_ID
if (dc % REP_FREQ == 0)
- fprintf(stderr, "D");
+ fprintf (stderr, "D");
#endif
- GE_ASSERT(NULL, 1 == api->del(key, val));
- stored_bytes -= ntohl(val->size);
+ GE_ASSERT (NULL, 1 == api->del (key, val));
+ stored_bytes -= ntohl (val->size);
stored_entries--;
return OK;
}
@@ -191,87 +189,88 @@
/**
* Add testcode here!
*/
-static int test(SQstore_ServiceAPI * api) {
+static int
+test (SQstore_ServiceAPI * api)
+{
int i;
int j;
unsigned long long size;
int have_file;
struct stat sbuf;
- have_file = 0 == stat(DB_NAME, &sbuf);
+ have_file = 0 == stat (DB_NAME, &sbuf);
- for (i=0;i<ITERATIONS;i++) {
+ for (i = 0; i < ITERATIONS; i++)
+ {
#if REPORT_ID
- fprintf(stderr, ".");
+ fprintf (stderr, ".");
#endif
- /* insert data equivalent to 1/10th of MAX_SIZE */
- for (j=0;j<PUT_10;j++) {
- ASSERT(OK == putValue(api, j));
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
+ /* insert data equivalent to 1/10th of MAX_SIZE */
+ for (j = 0; j < PUT_10; j++)
+ {
+ ASSERT (OK == putValue (api, j));
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
- /* trim down below MAX_SIZE again */
- if ((i % 2) == 0)
- api->iterateLowPriority(0, &iterateDelete, api);
- else
- api->iterateExpirationTime(0, &iterateDelete, api);
+ /* trim down below MAX_SIZE again */
+ if ((i % 2) == 0)
+ api->iterateLowPriority (0, &iterateDelete, api);
+ else
+ api->iterateExpirationTime (0, &iterateDelete, api);
- size = 0;
- if (have_file)
- disk_file_size(NULL,
- DB_NAME,
- &size,
- NO);
- printf(
+ size = 0;
+ if (have_file)
+ disk_file_size (NULL, DB_NAME, &size, NO);
+ printf (
#if REPORT_ID
- "\n"
+ "\n"
#endif
- "Useful %llu, API %llu, disk %llu (%.2f%%) / %lluk ops / %llu ops/s\n",
- stored_bytes / 1024, /* used size in k */
- api->getSize() / 1024, /* API-reported size in k */
- size / 1024, /* disk size in kb */
- (100.0 * size / stored_bytes) - 100, /* overhead */
- (stored_ops * 2 - stored_entries) / 1024, /* total operations (in k) */
- 1000 * (stored_ops * 2 - stored_entries) / (1 + get_time() -
start_time)); /* operations per second */
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- api->drop();
+ "Useful %llu, API %llu, disk %llu (%.2f%%) / %lluk ops / %llu
ops/s\n", stored_bytes / 1024, /* used size in k */
+ api->getSize () / 1024, /* API-reported size in k */
+ size / 1024, /* disk size in kb */
+ (100.0 * size / stored_bytes) - 100, /* overhead */
+ (stored_ops * 2 - stored_entries) / 1024, /* total
operations (in k) */
+ 1000 * (stored_ops * 2 - stored_entries) / (1 + get_time () -
start_time)); /* operations per second */
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
+ api->drop ();
return OK;
- FAILURE:
- api->drop();
+FAILURE:
+ api->drop ();
return SYSERR;
}
-int main(int argc, char *argv[]) {
- SQstore_ServiceAPI * api;
+int
+main (int argc, char *argv[])
+{
+ SQstore_ServiceAPI *api;
int ok;
- struct GC_Configuration * cfg;
- struct CronManager * cron;
+ struct GC_Configuration *cfg;
+ struct CronManager *cron;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- cron = cron_create(NULL);
- initCore(NULL,
- cfg,
- cron,
- NULL);
- api = requestService("sqstore");
- if (api != NULL) {
- start_time = get_time();
- ok = test(api);
- releaseService(api);
- } else
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ cron = cron_create (NULL);
+ initCore (NULL, cfg, cron, NULL);
+ api = requestService ("sqstore");
+ if (api != NULL)
+ {
+ start_time = get_time ();
+ ok = test (api);
+ releaseService (api);
+ }
+ else
ok = SYSERR;
- doneCore();
- cron_destroy(cron);
- GC_free(cfg);
+ doneCore ();
+ cron_destroy (cron);
+ GC_free (cfg);
if (ok == SYSERR)
return 1;
return 0;
Modified: GNUnet/src/applications/sqstore_mysql/mysqltest3.c
===================================================================
--- GNUnet/src/applications/sqstore_mysql/mysqltest3.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/sqstore_mysql/mysqltest3.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -55,141 +55,144 @@
static cron_t start_time;
-static int putValue(SQstore_ServiceAPI * api,
- int i) {
- Datastore_Value * value;
+static int
+putValue (SQstore_ServiceAPI * api, int i)
+{
+ Datastore_Value *value;
size_t size;
static HashCode512 key;
static int ic;
/* most content is 32k */
- size = sizeof(Datastore_Value) + 32 * 1024;
- if (weak_randomi(16) == 0) /* but some of it is less! */
- size = sizeof(Datastore_Value) + weak_randomi(32 * 1024);
- size = size - (size & 7); /* always multiple of 8 */
+ size = sizeof (Datastore_Value) + 32 * 1024;
+ if (weak_randomi (16) == 0) /* but some of it is less! */
+ size = sizeof (Datastore_Value) + weak_randomi (32 * 1024);
+ size = size - (size & 7); /* always multiple of 8 */
/* generate random key */
- hash(&key,
- sizeof(HashCode512),
- &key);
- value = MALLOC(size);
- value->size = htonl(size);
- value->type = htonl(i);
- value->prio = htonl(weak_randomi(100));
- value->anonymityLevel = htonl(i);
- value->expirationTime = htonll(get_time() + 60 * cronHOURS +
weak_randomi(1000));
- memset(&value[1],
- i,
- size - sizeof(Datastore_Value));
- if (OK != api->put(&key, value)) {
- FREE(value);
- fprintf(stderr, "E");
- return SYSERR;
- }
+ hash (&key, sizeof (HashCode512), &key);
+ value = MALLOC (size);
+ value->size = htonl (size);
+ value->type = htonl (i);
+ value->prio = htonl (weak_randomi (100));
+ value->anonymityLevel = htonl (i);
+ value->expirationTime =
+ htonll (get_time () + 60 * cronHOURS + weak_randomi (1000));
+ memset (&value[1], i, size - sizeof (Datastore_Value));
+ if (OK != api->put (&key, value))
+ {
+ FREE (value);
+ fprintf (stderr, "E");
+ return SYSERR;
+ }
ic++;
- stored_bytes += ntohl(value->size);
+ stored_bytes += ntohl (value->size);
stored_ops++;
stored_entries++;
- FREE(value);
+ FREE (value);
return OK;
}
static int
-iterateDummy(const HashCode512 * key,
- const Datastore_Value * val,
- void * cls) {
- if (GNUNET_SHUTDOWN_TEST() == YES)
+iterateDummy (const HashCode512 * key, const Datastore_Value * val, void *cls)
+{
+ if (GNUNET_SHUTDOWN_TEST () == YES)
return SYSERR;
return OK;
}
-static int test(SQstore_ServiceAPI * api) {
+static int
+test (SQstore_ServiceAPI * api)
+{
int i;
int j;
cron_t start;
cron_t end;
- for (i=0;i<ITERATIONS;i++) {
- /* insert data equivalent to 1/10th of MAX_SIZE */
- start = get_time();
- for (j=0;j<PUT_10;j++) {
- if (OK != putValue(api, j))
- break;
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
+ for (i = 0; i < ITERATIONS; i++)
+ {
+ /* insert data equivalent to 1/10th of MAX_SIZE */
+ start = get_time ();
+ for (j = 0; j < PUT_10; j++)
+ {
+ if (OK != putValue (api, j))
+ break;
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
+ end = get_time ();
+ printf ("%3u insertion took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateLowPriority (0, &iterateDummy, api);
+ end = get_time ();
+ printf ("%3u low priority iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateExpirationTime (0, &iterateDummy, api);
+ end = get_time ();
+ printf ("%3u expiration t iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateNonAnonymous (0, NO, &iterateDummy, api);
+ end = get_time ();
+ printf ("%3u non anonymou iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateNonAnonymous (0, YES, &iterateDummy, api);
+ end = get_time ();
+ printf ("%3u non anon YES iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateMigrationOrder (&iterateDummy, api);
+ end = get_time ();
+ printf ("%3u migration or iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateAllNow (&iterateDummy, api);
+ end = get_time ();
+ printf ("%3u all now iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
}
- end = get_time();
- printf("%3u insertion took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateLowPriority(0, &iterateDummy, api);
- end = get_time();
- printf("%3u low priority iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateExpirationTime(0, &iterateDummy, api);
- end = get_time();
- printf("%3u expiration t iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateNonAnonymous(0, NO, &iterateDummy, api);
- end = get_time();
- printf("%3u non anonymou iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateNonAnonymous(0, YES, &iterateDummy, api);
- end = get_time();
- printf("%3u non anon YES iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateMigrationOrder(&iterateDummy, api);
- end = get_time();
- printf("%3u migration or iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateAllNow(&iterateDummy, api);
- end = get_time();
- printf("%3u all now iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- api->drop();
+ api->drop ();
return OK;
}
-int main(int argc, char *argv[]) {
- SQstore_ServiceAPI * api;
+int
+main (int argc, char *argv[])
+{
+ SQstore_ServiceAPI *api;
int ok;
- struct GC_Configuration * cfg;
- struct CronManager * cron;
+ struct GC_Configuration *cfg;
+ struct CronManager *cron;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- cron = cron_create(NULL);
- initCore(NULL,
- cfg,
- cron,
- NULL);
- api = requestService("sqstore");
- if (api != NULL) {
- start_time = get_time();
- ok = test(api);
- releaseService(api);
- } else
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ cron = cron_create (NULL);
+ initCore (NULL, cfg, cron, NULL);
+ api = requestService ("sqstore");
+ if (api != NULL)
+ {
+ start_time = get_time ();
+ ok = test (api);
+ releaseService (api);
+ }
+ else
ok = SYSERR;
- doneCore();
- cron_destroy(cron);
- GC_free(cfg);
+ doneCore ();
+ cron_destroy (cron);
+ GC_free (cfg);
if (ok == SYSERR)
return 1;
return 0;
Modified: GNUnet/src/applications/sqstore_mysql_embedded/mysql.c
===================================================================
--- GNUnet/src/applications/sqstore_mysql_embedded/mysql.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/sqstore_mysql_embedded/mysql.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -145,9 +145,9 @@
*/
#define LOG_MYSQL(level, cmd, dbh) do { GE_LOG(ectx, level, _("`%s' failed at
%s:%d with error: %s\n"), cmd, __FILE__, __LINE__, mysql_error((dbh)->dbf)); }
while(0);
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
static unsigned int stat_size;
@@ -159,45 +159,46 @@
/**
* Lock for updating content_size
*/
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
/**
* @brief mysql wrapper
*/
-typedef struct {
- MYSQL * dbf;
+typedef struct
+{
+ MYSQL *dbf;
- char * cnffile;
+ char *cnffile;
int prepare;
- MYSQL_STMT * insert;
+ MYSQL_STMT *insert;
MYSQL_BIND bind[7];
- MYSQL_STMT * select;
+ MYSQL_STMT *select;
- MYSQL_STMT * selectc;
+ MYSQL_STMT *selectc;
- MYSQL_STMT * selects;
+ MYSQL_STMT *selects;
- MYSQL_STMT * selectsc;
+ MYSQL_STMT *selectsc;
MYSQL_BIND sbind[2];
- MYSQL_STMT * deleteh;
+ MYSQL_STMT *deleteh;
- MYSQL_STMT * deleteg;
+ MYSQL_STMT *deleteg;
MYSQL_BIND dbind[7];
- MYSQL_STMT * update;
+ MYSQL_STMT *update;
MYSQL_BIND ubind[5];
- struct MUTEX * DATABASE_Lock_;
+ struct MUTEX *DATABASE_Lock_;
} mysqlHandle;
@@ -222,68 +223,66 @@
#define UPDATE_SAMPLE "UPDATE gn070 SET
prio=prio+?,expire=IF(expire>=?,expire,?) WHERE hash=? AND value=?"
-static mysqlHandle * dbh;
+static mysqlHandle *dbh;
/**
* Given a full (SELECT *) sql_row from gn070 table in database
* order, assemble it into a Datastore_Datum representation.
*
*/
-static Datastore_Datum * assembleDatum(MYSQL_RES * res,
- MYSQL_ROW sql_row,
- mysqlHandle * dbhI) {
- Datastore_Datum * datum;
+static Datastore_Datum *
+assembleDatum (MYSQL_RES * res, MYSQL_ROW sql_row, mysqlHandle * dbhI)
+{
+ Datastore_Datum *datum;
int contentSize;
- unsigned long * lens;
+ unsigned long *lens;
unsigned int type;
unsigned int prio;
unsigned int level;
unsigned long long exp;
- contentSize = atol(sql_row[0]) - sizeof(Datastore_Value);
+ contentSize = atol (sql_row[0]) - sizeof (Datastore_Value);
if (contentSize < 0)
- return NULL; /* error */
+ return NULL; /* error */
- lens = mysql_fetch_lengths(res);
- if ( (lens[5] != sizeof(HashCode512)) ||
- (lens[6] != contentSize) ||
- (sscanf(sql_row[1], "%u", &type) != 1) ||
- (sscanf(sql_row[2], "%u", &prio) != 1) ||
- (sscanf(sql_row[3], "%u", &level) != 1) ||
- (SSCANF(sql_row[4], "%llu", &exp) != 1) ) {
- mysql_free_result(res);
- if ( (lens[5] != sizeof(HashCode512)) ||
- (lens[6] != contentSize) ) {
- char scratch[512];
+ lens = mysql_fetch_lengths (res);
+ if ((lens[5] != sizeof (HashCode512)) ||
+ (lens[6] != contentSize) ||
+ (sscanf (sql_row[1], "%u", &type) != 1) ||
+ (sscanf (sql_row[2], "%u", &prio) != 1) ||
+ (sscanf (sql_row[3], "%u", &level) != 1) ||
+ (SSCANF (sql_row[4], "%llu", &exp) != 1))
+ {
+ mysql_free_result (res);
+ if ((lens[5] != sizeof (HashCode512)) || (lens[6] != contentSize))
+ {
+ char scratch[512];
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Invalid data in %s. Trying to fix (by deletion).\n"),
- _("mysql datastore"));
- SNPRINTF(scratch,
- 512,
- "DELETE FROM gn070 WHERE NOT ((LENGTH(hash)=%u) AND (size=%u +
LENGTH(value)))",
- sizeof(HashCode512),
- sizeof(Datastore_Value));
- if (0 != mysql_query(dbhI->dbf, scratch))
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbhI);
- } else {
- GE_BREAK(ectx, 0); /* should really never happen */
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Invalid data in %s. Trying to fix (by deletion).\n"),
+ _("mysql datastore"));
+ SNPRINTF (scratch,
+ 512,
+ "DELETE FROM gn070 WHERE NOT ((LENGTH(hash)=%u) AND
(size=%u + LENGTH(value)))",
+ sizeof (HashCode512), sizeof (Datastore_Value));
+ if (0 != mysql_query (dbhI->dbf, scratch))
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbhI);
+ }
+ else
+ {
+ GE_BREAK (ectx, 0); /* should really never happen */
+ }
+ return NULL;
}
- return NULL;
- }
- datum = MALLOC(sizeof(Datastore_Datum) + contentSize);
- datum->value.size = htonl(contentSize + sizeof(Datastore_Value));
- datum->value.type = htonl(type);
- datum->value.prio = htonl(prio);
- datum->value.anonymityLevel = htonl(level);
- datum->value.expirationTime = htonll(exp);
- memcpy(&datum->key,
- sql_row[5],
- sizeof(HashCode512));
- memcpy(&datum[1],
- sql_row[6],
- contentSize);
+ datum = MALLOC (sizeof (Datastore_Datum) + contentSize);
+ datum->value.size = htonl (contentSize + sizeof (Datastore_Value));
+ datum->value.type = htonl (type);
+ datum->value.prio = htonl (prio);
+ datum->value.anonymityLevel = htonl (level);
+ datum->value.expirationTime = htonll (exp);
+ memcpy (&datum->key, sql_row[5], sizeof (HashCode512));
+ memcpy (&datum[1], sql_row[6], contentSize);
return datum;
}
@@ -293,223 +292,202 @@
* so that must be set already.
* @return OK on success
*/
-static int iopen(mysqlHandle * dbhI,
- int prepare) {
- char * dbname;
+static int
+iopen (mysqlHandle * dbhI, int prepare)
+{
+ char *dbname;
if (dbhI->cnffile == NULL)
return SYSERR;
- dbhI->dbf = mysql_init(NULL);
+ dbhI->dbf = mysql_init (NULL);
if (dbhI->dbf == NULL)
return SYSERR;
- mysql_options(dbhI->dbf,
- MYSQL_READ_DEFAULT_FILE,
- dbh->cnffile);
- mysql_options(dbhI->dbf,
- MYSQL_READ_DEFAULT_GROUP,
- "client");
+ mysql_options (dbhI->dbf, MYSQL_READ_DEFAULT_FILE, dbh->cnffile);
+ mysql_options (dbhI->dbf, MYSQL_READ_DEFAULT_GROUP, "client");
dbname = NULL;
- GC_get_configuration_value_string(coreAPI->cfg,
- "MYSQL",
- "DATABASE",
- "gnunet",
- &dbname);
- GE_ASSERT(ectx, dbname != NULL);
- mysql_real_connect(dbhI->dbf,
- NULL,
- NULL,
- NULL,
- dbname,
- 0,
- NULL,
- 0);
- FREE(dbname);
- if (mysql_error(dbhI->dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_real_connect",
- dbhI);
- dbhI->dbf = NULL;
- return SYSERR;
- }
- if (prepare) {
- mysql_query(dbhI->dbf,
- "CREATE TABLE IF NOT EXISTS gn070 ("
- " size INT(11) NOT NULL DEFAULT 0,"
- " type INT(11) NOT NULL DEFAULT 0,"
- " prio INT(11) NOT NULL DEFAULT 0,"
- " anonLevel INT(11) NOT NULL DEFAULT 0,"
- " expire BIGINT NOT NULL DEFAULT 0,"
- " hash TINYBLOB NOT NULL DEFAULT '',"
- " value BLOB NOT NULL DEFAULT '',"
- " INDEX (hash(64)),"
- " INDEX (prio),"
- " INDEX (expire)"
- ") TYPE=InnoDB");
- if (mysql_error(dbhI->dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- dbhI);
- mysql_close(dbhI->dbf);
+ GC_get_configuration_value_string (coreAPI->cfg,
+ "MYSQL", "DATABASE", "gnunet", &dbname);
+ GE_ASSERT (ectx, dbname != NULL);
+ mysql_real_connect (dbhI->dbf, NULL, NULL, NULL, dbname, 0, NULL, 0);
+ FREE (dbname);
+ if (mysql_error (dbhI->dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_real_connect", dbhI);
dbhI->dbf = NULL;
return SYSERR;
}
- mysql_query(dbhI->dbf,
- "SET AUTOCOMMIT = 1");
- if (mysql_error(dbhI->dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- dbhI);
- mysql_close(dbhI->dbf);
- dbhI->dbf = NULL;
- return SYSERR;
+ if (prepare)
+ {
+ mysql_query (dbhI->dbf,
+ "CREATE TABLE IF NOT EXISTS gn070 ("
+ " size INT(11) NOT NULL DEFAULT 0,"
+ " type INT(11) NOT NULL DEFAULT 0,"
+ " prio INT(11) NOT NULL DEFAULT 0,"
+ " anonLevel INT(11) NOT NULL DEFAULT 0,"
+ " expire BIGINT NOT NULL DEFAULT 0,"
+ " hash TINYBLOB NOT NULL DEFAULT '',"
+ " value BLOB NOT NULL DEFAULT '',"
+ " INDEX (hash(64)),"
+ " INDEX (prio)," " INDEX (expire)" ") TYPE=InnoDB");
+ if (mysql_error (dbhI->dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbhI);
+ mysql_close (dbhI->dbf);
+ dbhI->dbf = NULL;
+ return SYSERR;
+ }
+ mysql_query (dbhI->dbf, "SET AUTOCOMMIT = 1");
+ if (mysql_error (dbhI->dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbhI);
+ mysql_close (dbhI->dbf);
+ dbhI->dbf = NULL;
+ return SYSERR;
+ }
+ dbhI->insert = mysql_stmt_init (dbhI->dbf);
+ dbhI->select = mysql_stmt_init (dbhI->dbf);
+ dbhI->selectc = mysql_stmt_init (dbhI->dbf);
+ dbhI->selects = mysql_stmt_init (dbhI->dbf);
+ dbhI->selectsc = mysql_stmt_init (dbhI->dbf);
+ dbhI->update = mysql_stmt_init (dbhI->dbf);
+ dbhI->deleteh = mysql_stmt_init (dbhI->dbf);
+ dbhI->deleteg = mysql_stmt_init (dbhI->dbf);
+ if ((dbhI->insert == NULL) ||
+ (dbhI->update == NULL) ||
+ (dbhI->select == NULL) ||
+ (dbhI->selectc == NULL) ||
+ (dbhI->selects == NULL) ||
+ (dbhI->selectsc == NULL) ||
+ (dbhI->deleteh == NULL) || (dbhI->deleteg == NULL))
+ {
+ GE_BREAK (ectx, 0);
+ if (dbhI->insert != NULL)
+ mysql_stmt_close (dbhI->insert);
+ if (dbhI->update != NULL)
+ mysql_stmt_close (dbhI->update);
+ if (dbhI->select != NULL)
+ mysql_stmt_close (dbhI->select);
+ if (dbhI->selectc != NULL)
+ mysql_stmt_close (dbhI->selectc);
+ if (dbhI->selects != NULL)
+ mysql_stmt_close (dbhI->selects);
+ if (dbhI->selectsc != NULL)
+ mysql_stmt_close (dbhI->selectsc);
+ mysql_close (dbhI->dbf);
+ dbhI->dbf = NULL;
+ return SYSERR;
+ }
+ if (mysql_stmt_prepare (dbhI->insert,
+ INSERT_SAMPLE,
+ strlen (INSERT_SAMPLE)) ||
+ mysql_stmt_prepare (dbhI->select,
+ SELECT_SAMPLE,
+ strlen (SELECT_SAMPLE)) ||
+ mysql_stmt_prepare (dbhI->selectc,
+ SELECT_SAMPLE_COUNT,
+ strlen (SELECT_SAMPLE_COUNT)) ||
+ mysql_stmt_prepare (dbhI->selects,
+ SELECT_TYPE_SAMPLE,
+ strlen (SELECT_TYPE_SAMPLE)) ||
+ mysql_stmt_prepare (dbhI->selectsc,
+ SELECT_TYPE_SAMPLE_COUNT,
+ strlen (SELECT_TYPE_SAMPLE_COUNT)) ||
+ mysql_stmt_prepare (dbhI->update,
+ UPDATE_SAMPLE,
+ strlen (UPDATE_SAMPLE)) ||
+ mysql_stmt_prepare (dbhI->deleteh,
+ SELECT_HASH_SAMPLE,
+ strlen (SELECT_HASH_SAMPLE)) ||
+ mysql_stmt_prepare (dbhI->deleteg,
+ DELETE_GENERIC_SAMPLE,
+ strlen (DELETE_GENERIC_SAMPLE)))
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("`%s' failed at %s:%d with error: I/%s S/%s SC/%s SS/%s
SSC/%s U/%s D/%s DG/%s\n"),
+ "mysql_stmt_prepare", __FILE__, __LINE__,
+ mysql_stmt_error (dbhI->insert),
+ mysql_stmt_error (dbhI->select),
+ mysql_stmt_error (dbhI->selectc),
+ mysql_stmt_error (dbhI->selects),
+ mysql_stmt_error (dbhI->selectsc),
+ mysql_stmt_error (dbhI->update),
+ mysql_stmt_error (dbhI->deleteh),
+ mysql_stmt_error (dbhI->deleteg));
+ mysql_stmt_close (dbhI->insert);
+ mysql_stmt_close (dbhI->select);
+ mysql_stmt_close (dbhI->selectc);
+ mysql_stmt_close (dbhI->selects);
+ mysql_stmt_close (dbhI->selectsc);
+ mysql_stmt_close (dbhI->update);
+ mysql_stmt_close (dbhI->deleteh);
+ mysql_stmt_close (dbhI->deleteg);
+ mysql_close (dbhI->dbf);
+ dbhI->dbf = NULL;
+ return SYSERR;
+ }
+ memset (dbhI->bind, 0, sizeof (dbhI->bind));
+ dbhI->bind[0].buffer_type = MYSQL_TYPE_LONG; /* size */
+ dbhI->bind[1].buffer_type = MYSQL_TYPE_LONG; /* type */
+ dbhI->bind[2].buffer_type = MYSQL_TYPE_LONG; /* prio */
+ dbhI->bind[3].buffer_type = MYSQL_TYPE_LONG; /* anon level */
+ dbhI->bind[4].buffer_type = MYSQL_TYPE_LONGLONG; /* expiration */
+ dbhI->bind[5].buffer_type = MYSQL_TYPE_TINY_BLOB; /* hash */
+ dbhI->bind[6].buffer_type = MYSQL_TYPE_BLOB; /* value */
+ memset (dbhI->sbind, 0, sizeof (dbhI->sbind));
+ dbhI->sbind[0].buffer_type = MYSQL_TYPE_TINY_BLOB; /* hash */
+ dbhI->sbind[1].buffer_type = MYSQL_TYPE_LONG; /* type */
+ memset (dbhI->dbind, 0, sizeof (dbhI->dbind));
+ dbhI->dbind[0].buffer_type = MYSQL_TYPE_TINY_BLOB; /* hash */
+ dbhI->dbind[1].buffer_type = MYSQL_TYPE_LONG; /* size */
+ dbhI->dbind[2].buffer_type = MYSQL_TYPE_LONG; /* type */
+ dbhI->dbind[3].buffer_type = MYSQL_TYPE_LONG; /* prio */
+ dbhI->dbind[4].buffer_type = MYSQL_TYPE_LONG; /* anon level */
+ dbhI->dbind[5].buffer_type = MYSQL_TYPE_LONGLONG; /* expiration */
+ dbhI->dbind[6].buffer_type = MYSQL_TYPE_BLOB; /* value */
+ memset (dbhI->ubind, 0, sizeof (dbhI->ubind));
+ dbhI->ubind[0].buffer_type = MYSQL_TYPE_LONG;
+ dbhI->ubind[1].buffer_type = MYSQL_TYPE_LONG;
+ dbhI->ubind[2].buffer_type = MYSQL_TYPE_LONG;
+ dbhI->ubind[3].buffer_type = MYSQL_TYPE_BLOB;
+ dbhI->ubind[4].buffer_type = MYSQL_TYPE_BLOB;
+ dbhI->prepare = YES;
}
- dbhI->insert = mysql_stmt_init(dbhI->dbf);
- dbhI->select = mysql_stmt_init(dbhI->dbf);
- dbhI->selectc = mysql_stmt_init(dbhI->dbf);
- dbhI->selects = mysql_stmt_init(dbhI->dbf);
- dbhI->selectsc = mysql_stmt_init(dbhI->dbf);
- dbhI->update = mysql_stmt_init(dbhI->dbf);
- dbhI->deleteh = mysql_stmt_init(dbhI->dbf);
- dbhI->deleteg = mysql_stmt_init(dbhI->dbf);
- if ( (dbhI->insert == NULL) ||
- (dbhI->update == NULL) ||
- (dbhI->select == NULL) ||
- (dbhI->selectc == NULL) ||
- (dbhI->selects == NULL) ||
- (dbhI->selectsc == NULL) ||
- (dbhI->deleteh == NULL) ||
- (dbhI->deleteg == NULL) ) {
- GE_BREAK(ectx, 0);
- if (dbhI->insert != NULL)
- mysql_stmt_close(dbhI->insert);
- if (dbhI->update != NULL)
- mysql_stmt_close(dbhI->update);
- if (dbhI->select != NULL)
- mysql_stmt_close(dbhI->select);
- if (dbhI->selectc != NULL)
- mysql_stmt_close(dbhI->selectc);
- if (dbhI->selects != NULL)
- mysql_stmt_close(dbhI->selects);
- if (dbhI->selectsc != NULL)
- mysql_stmt_close(dbhI->selectsc);
- mysql_close(dbhI->dbf);
- dbhI->dbf = NULL;
- return SYSERR;
- }
- if (mysql_stmt_prepare(dbhI->insert,
- INSERT_SAMPLE,
- strlen(INSERT_SAMPLE)) ||
- mysql_stmt_prepare(dbhI->select,
- SELECT_SAMPLE,
- strlen(SELECT_SAMPLE)) ||
- mysql_stmt_prepare(dbhI->selectc,
- SELECT_SAMPLE_COUNT,
- strlen(SELECT_SAMPLE_COUNT)) ||
- mysql_stmt_prepare(dbhI->selects,
- SELECT_TYPE_SAMPLE,
- strlen(SELECT_TYPE_SAMPLE)) ||
- mysql_stmt_prepare(dbhI->selectsc,
- SELECT_TYPE_SAMPLE_COUNT,
- strlen(SELECT_TYPE_SAMPLE_COUNT)) ||
- mysql_stmt_prepare(dbhI->update,
- UPDATE_SAMPLE,
- strlen(UPDATE_SAMPLE)) ||
- mysql_stmt_prepare(dbhI->deleteh,
- SELECT_HASH_SAMPLE,
- strlen(SELECT_HASH_SAMPLE)) ||
- mysql_stmt_prepare(dbhI->deleteg,
- DELETE_GENERIC_SAMPLE,
- strlen(DELETE_GENERIC_SAMPLE)) ) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: I/%s S/%s SC/%s SS/%s SSC/%s U/%s D/%s
DG/%s\n"),
- "mysql_stmt_prepare",
- __FILE__, __LINE__,
- mysql_stmt_error(dbhI->insert),
- mysql_stmt_error(dbhI->select),
- mysql_stmt_error(dbhI->selectc),
- mysql_stmt_error(dbhI->selects),
- mysql_stmt_error(dbhI->selectsc),
- mysql_stmt_error(dbhI->update),
- mysql_stmt_error(dbhI->deleteh),
- mysql_stmt_error(dbhI->deleteg));
- mysql_stmt_close(dbhI->insert);
- mysql_stmt_close(dbhI->select);
- mysql_stmt_close(dbhI->selectc);
- mysql_stmt_close(dbhI->selects);
- mysql_stmt_close(dbhI->selectsc);
- mysql_stmt_close(dbhI->update);
- mysql_stmt_close(dbhI->deleteh);
- mysql_stmt_close(dbhI->deleteg);
- mysql_close(dbhI->dbf);
- dbhI->dbf = NULL;
- return SYSERR;
- }
- memset(dbhI->bind,
- 0,
- sizeof(dbhI->bind));
- dbhI->bind[0].buffer_type = MYSQL_TYPE_LONG; /* size */
- dbhI->bind[1].buffer_type = MYSQL_TYPE_LONG; /* type */
- dbhI->bind[2].buffer_type = MYSQL_TYPE_LONG; /* prio */
- dbhI->bind[3].buffer_type = MYSQL_TYPE_LONG; /* anon level */
- dbhI->bind[4].buffer_type = MYSQL_TYPE_LONGLONG; /* expiration */
- dbhI->bind[5].buffer_type = MYSQL_TYPE_TINY_BLOB; /* hash */
- dbhI->bind[6].buffer_type = MYSQL_TYPE_BLOB; /* value */
- memset(dbhI->sbind,
- 0,
- sizeof(dbhI->sbind));
- dbhI->sbind[0].buffer_type = MYSQL_TYPE_TINY_BLOB; /* hash */
- dbhI->sbind[1].buffer_type = MYSQL_TYPE_LONG; /* type */
- memset(dbhI->dbind,
- 0,
- sizeof(dbhI->dbind));
- dbhI->dbind[0].buffer_type = MYSQL_TYPE_TINY_BLOB; /* hash */
- dbhI->dbind[1].buffer_type = MYSQL_TYPE_LONG; /* size */
- dbhI->dbind[2].buffer_type = MYSQL_TYPE_LONG; /* type */
- dbhI->dbind[3].buffer_type = MYSQL_TYPE_LONG; /* prio */
- dbhI->dbind[4].buffer_type = MYSQL_TYPE_LONG; /* anon level */
- dbhI->dbind[5].buffer_type = MYSQL_TYPE_LONGLONG; /* expiration */
- dbhI->dbind[6].buffer_type = MYSQL_TYPE_BLOB; /* value */
- memset(dbhI->ubind,
- 0,
- sizeof(dbhI->ubind));
- dbhI->ubind[0].buffer_type = MYSQL_TYPE_LONG;
- dbhI->ubind[1].buffer_type = MYSQL_TYPE_LONG;
- dbhI->ubind[2].buffer_type = MYSQL_TYPE_LONG;
- dbhI->ubind[3].buffer_type = MYSQL_TYPE_BLOB;
- dbhI->ubind[4].buffer_type = MYSQL_TYPE_BLOB;
- dbhI->prepare = YES;
- } else
+ else
dbhI->prepare = NO;
- dbhI->DATABASE_Lock_ = MUTEX_CREATE(NO);
+ dbhI->DATABASE_Lock_ = MUTEX_CREATE (NO);
return OK;
}
/**
* Close the database connection.
*/
-static int iclose(mysqlHandle * dbhI) {
+static int
+iclose (mysqlHandle * dbhI)
+{
if (dbhI->dbf == NULL)
return SYSERR;
- if (dbhI->prepare == YES) {
- mysql_stmt_free_result(dbhI->update);
- mysql_stmt_free_result(dbhI->insert);
- mysql_stmt_free_result(dbhI->select);
- mysql_stmt_free_result(dbhI->selectc);
- mysql_stmt_free_result(dbhI->selects);
- mysql_stmt_free_result(dbhI->selectsc);
- mysql_stmt_free_result(dbhI->deleteh);
- mysql_stmt_free_result(dbhI->deleteg);
- mysql_stmt_close(dbhI->update);
- mysql_stmt_close(dbhI->insert);
- mysql_stmt_close(dbhI->select);
- mysql_stmt_close(dbhI->selectc);
- mysql_stmt_close(dbhI->selects);
- mysql_stmt_close(dbhI->selectsc);
- mysql_stmt_close(dbhI->deleteh);
- mysql_stmt_close(dbhI->deleteg);
- }
- MUTEX_DESTROY(dbhI->DATABASE_Lock_);
- mysql_close(dbhI->dbf);
+ if (dbhI->prepare == YES)
+ {
+ mysql_stmt_free_result (dbhI->update);
+ mysql_stmt_free_result (dbhI->insert);
+ mysql_stmt_free_result (dbhI->select);
+ mysql_stmt_free_result (dbhI->selectc);
+ mysql_stmt_free_result (dbhI->selects);
+ mysql_stmt_free_result (dbhI->selectsc);
+ mysql_stmt_free_result (dbhI->deleteh);
+ mysql_stmt_free_result (dbhI->deleteg);
+ mysql_stmt_close (dbhI->update);
+ mysql_stmt_close (dbhI->insert);
+ mysql_stmt_close (dbhI->select);
+ mysql_stmt_close (dbhI->selectc);
+ mysql_stmt_close (dbhI->selects);
+ mysql_stmt_close (dbhI->selectsc);
+ mysql_stmt_close (dbhI->deleteh);
+ mysql_stmt_close (dbhI->deleteg);
+ }
+ MUTEX_DESTROY (dbhI->DATABASE_Lock_);
+ mysql_close (dbhI->dbf);
dbhI->dbf = NULL;
return OK;
}
@@ -526,96 +504,88 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateHelper(unsigned int type,
- const char * query,
- Datum_Iterator iter,
- void * closure) {
+static int
+iterateHelper (unsigned int type,
+ const char *query, Datum_Iterator iter, void *closure)
+{
MYSQL_RES *sql_res;
MYSQL_ROW sql_row;
- Datastore_Datum * datum;
- char * scratch;
+ Datastore_Datum *datum;
+ char *scratch;
char typestr[32];
int count = 0;
mysqlHandle dbhI;
cron_t now;
- dbhI.cnffile = dbh->cnffile; /* shared */
- if (OK != iopen(&dbhI, NO))
+ dbhI.cnffile = dbh->cnffile; /* shared */
+ if (OK != iopen (&dbhI, NO))
return SYSERR;
- MUTEX_LOCK(dbhI.DATABASE_Lock_);
- mysql_thread_init();
- mysql_query(dbhI.dbf,
- "SET AUTOCOMMIT = 0");
- mysql_query(dbhI.dbf,
- "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED");
- if (type==0) {
- typestr[0] = '\0';
- } else {
- SNPRINTF(typestr,
- 32,
- "WHERE type=%u ",
- type);
- }
- now = get_time();
- scratch = MALLOC(256);
- SNPRINTF(scratch,
- 256,
- query,
- typestr,
- now);
- mysql_query(dbhI.dbf,
- scratch);
- FREE(scratch);
- if (mysql_error(dbhI.dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- &dbhI);
- mysql_thread_end();
- MUTEX_UNLOCK(dbhI.DATABASE_Lock_);
- iclose(&dbhI);
- return SYSERR;
- }
- if (!(sql_res=mysql_use_result(dbhI.dbf))) {
- MUTEX_UNLOCK(dbhI.DATABASE_Lock_);
- iclose(&dbhI);
- return SYSERR;
- }
- while ((sql_row=mysql_fetch_row(sql_res))) {
- datum = assembleDatum(sql_res,
- sql_row,
- &dbhI);
- if (datum == NULL) {
- mysql_thread_end();
- MUTEX_UNLOCK(dbhI.DATABASE_Lock_);
- iclose(&dbhI);
- return count;
+ MUTEX_LOCK (dbhI.DATABASE_Lock_);
+ mysql_thread_init ();
+ mysql_query (dbhI.dbf, "SET AUTOCOMMIT = 0");
+ mysql_query (dbhI.dbf,
+ "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED");
+ if (type == 0)
+ {
+ typestr[0] = '\0';
}
- if ( (iter != NULL) &&
- (SYSERR == iter(&datum->key,
- &datum->value,
- closure) ) ) {
- count = SYSERR;
- FREE(datum);
- break;
+ else
+ {
+ SNPRINTF (typestr, 32, "WHERE type=%u ", type);
}
- FREE(datum);
- count++;
- }
- if (mysql_error(dbhI.dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- &dbhI);
- mysql_free_result(sql_res);
- mysql_thread_end();
- MUTEX_UNLOCK(dbhI.DATABASE_Lock_);
- iclose(&dbhI);
- return SYSERR;
- }
- mysql_free_result(sql_res);
- mysql_thread_end();
- MUTEX_UNLOCK(dbhI.DATABASE_Lock_);
- iclose(&dbhI);
+ now = get_time ();
+ scratch = MALLOC (256);
+ SNPRINTF (scratch, 256, query, typestr, now);
+ mysql_query (dbhI.dbf, scratch);
+ FREE (scratch);
+ if (mysql_error (dbhI.dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", &dbhI);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbhI.DATABASE_Lock_);
+ iclose (&dbhI);
+ return SYSERR;
+ }
+ if (!(sql_res = mysql_use_result (dbhI.dbf)))
+ {
+ MUTEX_UNLOCK (dbhI.DATABASE_Lock_);
+ iclose (&dbhI);
+ return SYSERR;
+ }
+ while ((sql_row = mysql_fetch_row (sql_res)))
+ {
+ datum = assembleDatum (sql_res, sql_row, &dbhI);
+ if (datum == NULL)
+ {
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbhI.DATABASE_Lock_);
+ iclose (&dbhI);
+ return count;
+ }
+ if ((iter != NULL) &&
+ (SYSERR == iter (&datum->key, &datum->value, closure)))
+ {
+ count = SYSERR;
+ FREE (datum);
+ break;
+ }
+ FREE (datum);
+ count++;
+ }
+ if (mysql_error (dbhI.dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", &dbhI);
+ mysql_free_result (sql_res);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbhI.DATABASE_Lock_);
+ iclose (&dbhI);
+ return SYSERR;
+ }
+ mysql_free_result (sql_res);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbhI.DATABASE_Lock_);
+ iclose (&dbhI);
return count;
}
@@ -629,15 +599,12 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateLowPriority(unsigned int type,
- Datum_Iterator iter,
- void * closure) {
- return iterateHelper(type,
- "SELECT SQL_NO_CACHE * FROM gn070"
- " %s"
- "ORDER BY prio ASC",
- iter,
- closure);
+static int
+iterateLowPriority (unsigned int type, Datum_Iterator iter, void *closure)
+{
+ return iterateHelper (type,
+ "SELECT SQL_NO_CACHE * FROM gn070"
+ " %s" "ORDER BY prio ASC", iter, closure);
}
/**
@@ -650,26 +617,23 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateNonAnonymous(unsigned int type,
- int on_demand,
- Datum_Iterator iter,
- void * closure) {
+static int
+iterateNonAnonymous (unsigned int type,
+ int on_demand, Datum_Iterator iter, void *closure)
+{
char limit[512];
if (on_demand == YES)
- SNPRINTF(limit,
- 512,
- "SELECT SQL_NO_CACHE * FROM gn070"
- " %%s WHERE expire > %%llu AND anonLevel = 0 AND type != %d",
- ONDEMAND_BLOCK);
+ SNPRINTF (limit,
+ 512,
+ "SELECT SQL_NO_CACHE * FROM gn070"
+ " %%s WHERE expire > %%llu AND anonLevel = 0 AND type != %d",
+ ONDEMAND_BLOCK);
else
- strcpy(limit,
- "SELECT SQL_NO_CACHE * FROM gn070"
- " %s WHERE expire > %llu AND anonLevel = 0");
- return iterateHelper(type,
- limit,
- iter,
- closure);
+ strcpy (limit,
+ "SELECT SQL_NO_CACHE * FROM gn070"
+ " %s WHERE expire > %llu AND anonLevel = 0");
+ return iterateHelper (type, limit, iter, closure);
}
/**
@@ -682,15 +646,12 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateExpirationTime(unsigned int type,
- Datum_Iterator iter,
- void * closure) {
- return iterateHelper(type,
- "SELECT SQL_NO_CACHE * FROM gn070"
- " %s"
- " ORDER BY expire ASC",
- iter,
- closure);
+static int
+iterateExpirationTime (unsigned int type, Datum_Iterator iter, void *closure)
+{
+ return iterateHelper (type,
+ "SELECT SQL_NO_CACHE * FROM gn070"
+ " %s" " ORDER BY expire ASC", iter, closure);
}
/**
@@ -701,14 +662,13 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateMigrationOrder(Datum_Iterator iter,
- void * closure) {
- return iterateHelper(0,
- "SELECT SQL_NO_CACHE * FROM gn070"
- " %s WHERE expire > %llu"
- " ORDER BY expire DESC",
- iter,
- closure);
+static int
+iterateMigrationOrder (Datum_Iterator iter, void *closure)
+{
+ return iterateHelper (0,
+ "SELECT SQL_NO_CACHE * FROM gn070"
+ " %s WHERE expire > %llu"
+ " ORDER BY expire DESC", iter, closure);
}
/**
@@ -719,12 +679,10 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateAllNow(Datum_Iterator iter,
- void * closure) {
- return iterateHelper(0,
- "SELECT SQL_NO_CACHE * FROM gn070",
- iter,
- closure);
+static int
+iterateAllNow (Datum_Iterator iter, void *closure)
+{
+ return iterateHelper (0, "SELECT SQL_NO_CACHE * FROM gn070", iter, closure);
}
#define MAX_DATUM_SIZE 65536
@@ -740,13 +698,13 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int get(const HashCode512 * query,
- unsigned int type,
- Datum_Iterator iter,
- void * closure) {
- MYSQL_RES * sql_res;
+static int
+get (const HashCode512 * query,
+ unsigned int type, Datum_Iterator iter, void *closure)
+{
+ MYSQL_RES *sql_res;
int count;
- MYSQL_STMT * stmt;
+ MYSQL_STMT *stmt;
unsigned int size;
unsigned int rtype;
unsigned int prio;
@@ -754,7 +712,7 @@
unsigned long long expiration;
unsigned long datasize;
unsigned long twenty;
- Datastore_Value * datum;
+ Datastore_Value *datum;
HashCode512 key;
unsigned long hashSize;
#if DEBUG_MYSQL
@@ -762,196 +720,191 @@
#endif
if (query == NULL)
- return iterateLowPriority(type, iter, closure);
+ return iterateLowPriority (type, iter, closure);
#if DEBUG_MYSQL
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(query,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "MySQL looks for `%s' of type %u\n",
- &enc,
- type);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (query, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "MySQL looks for `%s' of type %u\n", &enc, type);
#endif
- MUTEX_LOCK(dbh->DATABASE_Lock_);
- mysql_thread_init();
- if (type != 0) {
- if (iter == NULL)
- stmt = dbh->selectsc;
- else
- stmt = dbh->selects;
- } else {
- if (iter == NULL)
- stmt = dbh->selectc;
- else
- stmt = dbh->select;
- }
- hashSize = sizeof(HashCode512);
- dbh->sbind[0].buffer = (char*) query;
- dbh->sbind[1].buffer = (char*) &type;
+ MUTEX_LOCK (dbh->DATABASE_Lock_);
+ mysql_thread_init ();
+ if (type != 0)
+ {
+ if (iter == NULL)
+ stmt = dbh->selectsc;
+ else
+ stmt = dbh->selects;
+ }
+ else
+ {
+ if (iter == NULL)
+ stmt = dbh->selectc;
+ else
+ stmt = dbh->select;
+ }
+ hashSize = sizeof (HashCode512);
+ dbh->sbind[0].buffer = (char *) query;
+ dbh->sbind[1].buffer = (char *) &type;
dbh->sbind[0].length = &hashSize;
- GE_ASSERT(ectx, mysql_stmt_param_count(stmt) <= 2);
- sql_res = mysql_stmt_result_metadata(stmt);
- if (! sql_res) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_result_metadata",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return SYSERR;
- }
- if (7 != mysql_num_fields(sql_res)) {
- GE_BREAK(ectx, 0);
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return SYSERR;
- }
- if (mysql_stmt_bind_param(stmt,
- dbh->sbind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_param",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return SYSERR;
- }
- if (mysql_stmt_execute(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_execute",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return SYSERR;
- }
+ GE_ASSERT (ectx, mysql_stmt_param_count (stmt) <= 2);
+ sql_res = mysql_stmt_result_metadata (stmt);
+ if (!sql_res)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_result_metadata",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return SYSERR;
+ }
+ if (7 != mysql_num_fields (sql_res))
+ {
+ GE_BREAK (ectx, 0);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return SYSERR;
+ }
+ if (mysql_stmt_bind_param (stmt, dbh->sbind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_param",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return SYSERR;
+ }
+ if (mysql_stmt_execute (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_execute",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return SYSERR;
+ }
- datum = MALLOC(sizeof(Datastore_Value) + MAX_DATUM_SIZE);
- twenty = sizeof(HashCode512);
- dbh->bind[0].buffer = (char*) &size;
- dbh->bind[1].buffer = (char*) &rtype;
- dbh->bind[2].buffer = (char*) &prio;
- dbh->bind[3].buffer = (char*) &level;
- dbh->bind[4].buffer = (char*) &expiration;
- dbh->bind[5].buffer = (char*) &key;
- dbh->bind[6].buffer = (char*) &datum[1];
+ datum = MALLOC (sizeof (Datastore_Value) + MAX_DATUM_SIZE);
+ twenty = sizeof (HashCode512);
+ dbh->bind[0].buffer = (char *) &size;
+ dbh->bind[1].buffer = (char *) &rtype;
+ dbh->bind[2].buffer = (char *) &prio;
+ dbh->bind[3].buffer = (char *) &level;
+ dbh->bind[4].buffer = (char *) &expiration;
+ dbh->bind[5].buffer = (char *) &key;
+ dbh->bind[6].buffer = (char *) &datum[1];
dbh->bind[5].length = &twenty;
dbh->bind[6].length = &datasize;
- dbh->bind[5].buffer_length = sizeof(HashCode512);
+ dbh->bind[5].buffer_length = sizeof (HashCode512);
dbh->bind[6].buffer_length = MAX_DATUM_SIZE;
- if (mysql_stmt_bind_result(stmt,
- dbh->bind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_result",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- FREE(datum);
- return SYSERR;
- }
- if (mysql_stmt_store_result(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_store_result",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- FREE(datum);
- return SYSERR;
- }
+ if (mysql_stmt_bind_result (stmt, dbh->bind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_result",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ FREE (datum);
+ return SYSERR;
+ }
+ if (mysql_stmt_store_result (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_store_result",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ FREE (datum);
+ return SYSERR;
+ }
datasize = MAX_DATUM_SIZE;
count = 0;
- while (0 == mysql_stmt_fetch(stmt)) {
- if ( (twenty != sizeof(HashCode512)) ||
- (datasize != size - sizeof(Datastore_Value)) ) {
- char scratch[512];
+ while (0 == mysql_stmt_fetch (stmt))
+ {
+ if ((twenty != sizeof (HashCode512)) ||
+ (datasize != size - sizeof (Datastore_Value)))
+ {
+ char scratch[512];
- mysql_free_result(sql_res);
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Invalid data in %s. Trying to fix (by deletion).\n"),
- _("mysql datastore"));
- SNPRINTF(scratch,
- 512,
- "DELETE FROM gn070 WHERE NOT ((LENGTH(hash)=%u) AND (size=%u +
LENGTH(value)))",
- sizeof(HashCode512),
- sizeof(Datastore_Value));
- if (0 != mysql_query(dbh->dbf, scratch))
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbh);
+ mysql_free_result (sql_res);
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Invalid data in %s. Trying to fix (by deletion).\n"),
+ _("mysql datastore"));
+ SNPRINTF (scratch,
+ 512,
+ "DELETE FROM gn070 WHERE NOT ((LENGTH(hash)=%u) AND
(size=%u + LENGTH(value)))",
+ sizeof (HashCode512), sizeof (Datastore_Value));
+ if (0 != mysql_query (dbh->dbf, scratch))
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbh);
- FREE(datum);
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return count;
- }
- count++;
- if (iter != NULL) {
- datum->size = htonl(size);
- datum->type = htonl(rtype);
- datum->prio = htonl(prio);
- datum->anonymityLevel = htonl(level);
- datum->expirationTime = htonll(expiration);
+ FREE (datum);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return count;
+ }
+ count++;
+ if (iter != NULL)
+ {
+ datum->size = htonl (size);
+ datum->type = htonl (rtype);
+ datum->prio = htonl (prio);
+ datum->anonymityLevel = htonl (level);
+ datum->expirationTime = htonll (expiration);
#if DEBUG_MYSQL
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Found in database block with type %u.\n",
- ntohl(*(int*)&datum[1]));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Found in database block with type %u.\n",
+ ntohl (*(int *) &datum[1]));
#endif
- if( SYSERR == iter(&key,
- datum,
- closure) ) {
- count = SYSERR;
- break;
- }
+ if (SYSERR == iter (&key, datum, closure))
+ {
+ count = SYSERR;
+ break;
+ }
+ }
+ datasize = MAX_DATUM_SIZE;
}
- datasize = MAX_DATUM_SIZE;
- }
- if (mysql_stmt_errno(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_fetch",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- }
- mysql_free_result(sql_res);
- FREE(datum);
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
+ if (mysql_stmt_errno (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_fetch",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ }
+ mysql_free_result (sql_res);
+ FREE (datum);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
#if DEBUG_MYSQL
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(query,
- &enc));
- if (count > 0) {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "MySQL found %d results for `%s' of type %u.\n",
- count,
- &enc,
- type);
- } else {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "MySQL iteration aborted looking for `%s' of type %u.\n",
- &enc,
- type);
- }
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (query, &enc));
+ if (count > 0)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "MySQL found %d results for `%s' of type %u.\n",
+ count, &enc, type);
+ }
+ else
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "MySQL iteration aborted looking for `%s' of type %u.\n",
+ &enc, type);
+ }
#endif
return count;
}
@@ -961,8 +914,9 @@
*
* @return OK on success, SYSERR on error
*/
-static int put(const HashCode512 * key,
- const Datastore_Value * value) {
+static int
+put (const HashCode512 * key, const Datastore_Value * value)
+{
unsigned long contentSize;
unsigned long hashSize;
unsigned int size;
@@ -974,69 +928,64 @@
EncName enc;
#endif
- if ( (ntohl(value->size) < sizeof(Datastore_Value)) ) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- MUTEX_LOCK(dbh->DATABASE_Lock_);
- mysql_thread_init();
- contentSize = ntohl(value->size)-sizeof(Datastore_Value);
- hashSize = sizeof(HashCode512);
- size = ntohl(value->size);
- type = ntohl(value->type);
- prio = ntohl(value->prio);
- level = ntohl(value->anonymityLevel);
- expiration = ntohll(value->expirationTime);
+ if ((ntohl (value->size) < sizeof (Datastore_Value)))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ MUTEX_LOCK (dbh->DATABASE_Lock_);
+ mysql_thread_init ();
+ contentSize = ntohl (value->size) - sizeof (Datastore_Value);
+ hashSize = sizeof (HashCode512);
+ size = ntohl (value->size);
+ type = ntohl (value->type);
+ prio = ntohl (value->prio);
+ level = ntohl (value->anonymityLevel);
+ expiration = ntohll (value->expirationTime);
#if DEBUG_MYSQL
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(key,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Storing in database block with type %u and key %s.\n",
- type,
- &enc);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (key, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Storing in database block with type %u and key %s.\n", type, &enc);
#endif
- dbh->bind[0].buffer = (char*) &size;
- dbh->bind[1].buffer = (char*) &type;
- dbh->bind[2].buffer = (char*) &prio;
- dbh->bind[3].buffer = (char*) &level;
- dbh->bind[4].buffer = (char*) &expiration;
- dbh->bind[5].buffer = (char*) key;
- dbh->bind[6].buffer = (char*) &value[1];
+ dbh->bind[0].buffer = (char *) &size;
+ dbh->bind[1].buffer = (char *) &type;
+ dbh->bind[2].buffer = (char *) &prio;
+ dbh->bind[3].buffer = (char *) &level;
+ dbh->bind[4].buffer = (char *) &expiration;
+ dbh->bind[5].buffer = (char *) key;
+ dbh->bind[6].buffer = (char *) &value[1];
dbh->bind[5].length = &hashSize;
dbh->bind[6].length = &contentSize;
- if (mysql_stmt_bind_param(dbh->insert,
- dbh->bind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_param",
- __FILE__, __LINE__,
- mysql_stmt_error(dbh->insert));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return SYSERR;
- }
+ if (mysql_stmt_bind_param (dbh->insert, dbh->bind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_param",
+ __FILE__, __LINE__, mysql_stmt_error (dbh->insert));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return SYSERR;
+ }
- if (mysql_stmt_execute(dbh->insert)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_execute",
- __FILE__, __LINE__,
- mysql_stmt_error(dbh->insert));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return SYSERR;
- }
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- MUTEX_LOCK(lock);
- content_size += ntohl(value->size);
- MUTEX_UNLOCK(lock);
+ if (mysql_stmt_execute (dbh->insert))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_execute",
+ __FILE__, __LINE__, mysql_stmt_error (dbh->insert));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return SYSERR;
+ }
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ MUTEX_LOCK (lock);
+ content_size += ntohl (value->size);
+ MUTEX_UNLOCK (lock);
return OK;
}
@@ -1048,229 +997,223 @@
* @return the number of items deleted, 0 if
* none were found, SYSERR on errors
*/
-static int del(const HashCode512 * key,
- const Datastore_Value * value) {
+static int
+del (const HashCode512 * key, const Datastore_Value * value)
+{
int count;
unsigned long twenty;
- MYSQL_STMT * stmt;
+ MYSQL_STMT *stmt;
unsigned int size;
unsigned int type;
unsigned int prio;
unsigned int anon;
unsigned long long expiration;
unsigned long datasize;
- Datastore_Value * svalue;
- MYSQL_RES * sql_res;
+ Datastore_Value *svalue;
+ MYSQL_RES *sql_res;
unsigned int rtype;
unsigned int level;
HashCode512 skey;
#if DEBUG_MYSQL
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(key,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "MySQL is executing deletion request for content of query `%s' and type
%u\n",
- &enc,
- value == NULL ? 0 : ntohl(value->type));
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (key, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "MySQL is executing deletion request for content of query `%s' and
type %u\n",
+ &enc, value == NULL ? 0 : ntohl (value->type));
#endif
- MUTEX_LOCK(dbh->DATABASE_Lock_);
- mysql_thread_init();
- twenty = sizeof(HashCode512);
+ MUTEX_LOCK (dbh->DATABASE_Lock_);
+ mysql_thread_init ();
+ twenty = sizeof (HashCode512);
svalue = NULL;
- if (value == NULL) {
- stmt = dbh->deleteh;
- dbh->dbind[0].buffer = (char*) key;
- dbh->dbind[0].length = &twenty;
- GE_ASSERT(ectx, mysql_stmt_param_count(stmt) <= 1);
+ if (value == NULL)
+ {
+ stmt = dbh->deleteh;
+ dbh->dbind[0].buffer = (char *) key;
+ dbh->dbind[0].length = &twenty;
+ GE_ASSERT (ectx, mysql_stmt_param_count (stmt) <= 1);
- sql_res = mysql_stmt_result_metadata(stmt);
- if (! sql_res) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_result_metadata",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return SYSERR;
- }
- if (7 != mysql_num_fields(sql_res)) {
- GE_BREAK(ectx, 0);
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return SYSERR;
- }
- if (mysql_stmt_bind_param(stmt,
- dbh->dbind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_param",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return SYSERR;
- }
- if (mysql_stmt_execute(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_execute",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return SYSERR;
- }
- svalue = MALLOC(sizeof(Datastore_Value) + MAX_DATUM_SIZE);
- twenty = sizeof(HashCode512);
- dbh->bind[0].buffer = (char*) &size;
- dbh->bind[1].buffer = (char*) &rtype;
- dbh->bind[2].buffer = (char*) &prio;
- dbh->bind[3].buffer = (char*) &level;
- dbh->bind[4].buffer = (char*) &expiration;
- dbh->bind[5].buffer = (char*) &skey;
- dbh->bind[6].buffer = (char*) &svalue[1];
- dbh->bind[5].length = &twenty;
- dbh->bind[6].length = &datasize;
- dbh->bind[5].buffer_length = sizeof(HashCode512);
- dbh->bind[6].buffer_length = MAX_DATUM_SIZE;
- if (mysql_stmt_bind_result(stmt,
- dbh->bind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_result",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- FREE(svalue);
- return SYSERR;
- }
- if (mysql_stmt_store_result(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_store_result",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- FREE(svalue);
- return SYSERR;
- }
- datasize = MAX_DATUM_SIZE;
- if (0 != mysql_stmt_fetch(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_fetch",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- FREE(svalue);
- return SYSERR;
- }
- if ( (twenty != sizeof(HashCode512)) ||
- (datasize != size - sizeof(Datastore_Value)) ) {
- char scratch[512];
+ sql_res = mysql_stmt_result_metadata (stmt);
+ if (!sql_res)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_result_metadata",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return SYSERR;
+ }
+ if (7 != mysql_num_fields (sql_res))
+ {
+ GE_BREAK (ectx, 0);
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return SYSERR;
+ }
+ if (mysql_stmt_bind_param (stmt, dbh->dbind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_param",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return SYSERR;
+ }
+ if (mysql_stmt_execute (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_execute",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return SYSERR;
+ }
+ svalue = MALLOC (sizeof (Datastore_Value) + MAX_DATUM_SIZE);
+ twenty = sizeof (HashCode512);
+ dbh->bind[0].buffer = (char *) &size;
+ dbh->bind[1].buffer = (char *) &rtype;
+ dbh->bind[2].buffer = (char *) &prio;
+ dbh->bind[3].buffer = (char *) &level;
+ dbh->bind[4].buffer = (char *) &expiration;
+ dbh->bind[5].buffer = (char *) &skey;
+ dbh->bind[6].buffer = (char *) &svalue[1];
+ dbh->bind[5].length = &twenty;
+ dbh->bind[6].length = &datasize;
+ dbh->bind[5].buffer_length = sizeof (HashCode512);
+ dbh->bind[6].buffer_length = MAX_DATUM_SIZE;
+ if (mysql_stmt_bind_result (stmt, dbh->bind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_result",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ FREE (svalue);
+ return SYSERR;
+ }
+ if (mysql_stmt_store_result (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_store_result",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ FREE (svalue);
+ return SYSERR;
+ }
+ datasize = MAX_DATUM_SIZE;
+ if (0 != mysql_stmt_fetch (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_fetch",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ FREE (svalue);
+ return SYSERR;
+ }
+ if ((twenty != sizeof (HashCode512)) ||
+ (datasize != size - sizeof (Datastore_Value)))
+ {
+ char scratch[512];
- mysql_free_result(sql_res);
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Invalid data in %s. Trying to fix (by deletion).\n"),
- _("mysql datastore"));
- SNPRINTF(scratch,
- 512,
- "DELETE FROM gn070 WHERE NOT ((LENGTH(hash)=%u) AND (size=%u +
LENGTH(value)))",
- sizeof(HashCode512),
- sizeof(Datastore_Value));
- if (0 != mysql_query(dbh->dbf, scratch))
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query", dbh);
- FREE(svalue);
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return 1;
+ mysql_free_result (sql_res);
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Invalid data in %s. Trying to fix (by deletion).\n"),
+ _("mysql datastore"));
+ SNPRINTF (scratch,
+ 512,
+ "DELETE FROM gn070 WHERE NOT ((LENGTH(hash)=%u) AND
(size=%u + LENGTH(value)))",
+ sizeof (HashCode512), sizeof (Datastore_Value));
+ if (0 != mysql_query (dbh->dbf, scratch))
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbh);
+ FREE (svalue);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return 1;
+ }
+ mysql_free_result (sql_res);
+ svalue->size = htonl (size);
+ svalue->type = htonl (rtype);
+ svalue->prio = htonl (prio);
+ svalue->anonymityLevel = htonl (level);
+ svalue->expirationTime = htonll (expiration);
+ value = svalue;
}
- mysql_free_result(sql_res);
- svalue->size = htonl(size);
- svalue->type = htonl(rtype);
- svalue->prio = htonl(prio);
- svalue->anonymityLevel = htonl(level);
- svalue->expirationTime = htonll(expiration);
- value = svalue;
- }
stmt = dbh->deleteg;
- type = ntohl(value->type);
- size = ntohl(value->size);
- prio = ntohl(value->prio);
- anon = ntohl(value->anonymityLevel);
- expiration = ntohll(value->expirationTime);
- datasize = ntohl(value->size) - sizeof(Datastore_Value);
- dbh->dbind[0].buffer = (char*) key;
+ type = ntohl (value->type);
+ size = ntohl (value->size);
+ prio = ntohl (value->prio);
+ anon = ntohl (value->anonymityLevel);
+ expiration = ntohll (value->expirationTime);
+ datasize = ntohl (value->size) - sizeof (Datastore_Value);
+ dbh->dbind[0].buffer = (char *) key;
dbh->dbind[0].length = &twenty;
- dbh->dbind[1].buffer = (char*) &size;
- dbh->dbind[2].buffer = (char*) &type;
- dbh->dbind[3].buffer = (char*) &prio;
- dbh->dbind[4].buffer = (char*) &anon;
- dbh->dbind[5].buffer = (char*) &expiration;
- dbh->dbind[6].buffer = (char*) &value[1];
+ dbh->dbind[1].buffer = (char *) &size;
+ dbh->dbind[2].buffer = (char *) &type;
+ dbh->dbind[3].buffer = (char *) &prio;
+ dbh->dbind[4].buffer = (char *) &anon;
+ dbh->dbind[5].buffer = (char *) &expiration;
+ dbh->dbind[6].buffer = (char *) &value[1];
dbh->dbind[6].length = &datasize;
#if 0
- dbh->dbind[0].buffer_length = sizeof(HashCode512);
- dbh->dbind[6].buffer_length = size - sizeof(Datastore_Value);
+ dbh->dbind[0].buffer_length = sizeof (HashCode512);
+ dbh->dbind[6].buffer_length = size - sizeof (Datastore_Value);
#endif
- GE_ASSERT(ectx, mysql_stmt_param_count(stmt) <= 7);
- if (mysql_stmt_bind_param(stmt,
- dbh->dbind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_param",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- if (svalue != NULL)
- FREE(svalue);
- return SYSERR;
- }
- if (mysql_stmt_execute(stmt)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_execute",
- __FILE__, __LINE__,
- mysql_stmt_error(stmt));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- if (svalue != NULL)
- FREE(svalue);
- return SYSERR;
- }
- count = mysql_stmt_affected_rows(stmt);
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
+ GE_ASSERT (ectx, mysql_stmt_param_count (stmt) <= 7);
+ if (mysql_stmt_bind_param (stmt, dbh->dbind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_param",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ if (svalue != NULL)
+ FREE (svalue);
+ return SYSERR;
+ }
+ if (mysql_stmt_execute (stmt))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_execute",
+ __FILE__, __LINE__, mysql_stmt_error (stmt));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ if (svalue != NULL)
+ FREE (svalue);
+ return SYSERR;
+ }
+ count = mysql_stmt_affected_rows (stmt);
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
#if DEBUG_MYSQL
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "MySQL DELETE operation affected %d rows.\n",
- count);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "MySQL DELETE operation affected %d rows.\n", count);
#endif
- MUTEX_LOCK(lock);
- content_size -= ntohl(value->size);
- MUTEX_UNLOCK(lock);
+ MUTEX_LOCK (lock);
+ content_size -= ntohl (value->size);
+ MUTEX_UNLOCK (lock);
if (svalue != NULL)
- FREE(svalue);
+ FREE (svalue);
return count;
}
@@ -1278,56 +1221,54 @@
* Update the priority for a particular key
* in the datastore.
*/
-static int update(const HashCode512 * key,
- const Datastore_Value * value,
- int delta,
- cron_t expire) {
+static int
+update (const HashCode512 * key,
+ const Datastore_Value * value, int delta, cron_t expire)
+{
unsigned long contentSize;
unsigned long twenty;
- twenty = sizeof(HashCode512);
- MUTEX_LOCK(dbh->DATABASE_Lock_);
- mysql_thread_init();
- contentSize = ntohl(value->size)-sizeof(Datastore_Value);
- dbh->ubind[0].buffer = (char*) δ
- dbh->ubind[1].buffer = (char*) &expire;
- dbh->ubind[2].buffer = (char*) &expire;
- dbh->ubind[3].buffer = (char*) key;
+ twenty = sizeof (HashCode512);
+ MUTEX_LOCK (dbh->DATABASE_Lock_);
+ mysql_thread_init ();
+ contentSize = ntohl (value->size) - sizeof (Datastore_Value);
+ dbh->ubind[0].buffer = (char *) δ
+ dbh->ubind[1].buffer = (char *) &expire;
+ dbh->ubind[2].buffer = (char *) &expire;
+ dbh->ubind[3].buffer = (char *) key;
dbh->ubind[3].length = &twenty;
- dbh->ubind[4].buffer = (char*) &value[1];
+ dbh->ubind[4].buffer = (char *) &value[1];
dbh->ubind[4].length = &contentSize;
- GE_ASSERT(ectx,
- mysql_stmt_param_count(dbh->update) <= 5);
- if (mysql_stmt_bind_param(dbh->update,
- dbh->ubind)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_bind_param",
- __FILE__, __LINE__,
- mysql_stmt_error(dbh->update));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return SYSERR;
- }
+ GE_ASSERT (ectx, mysql_stmt_param_count (dbh->update) <= 5);
+ if (mysql_stmt_bind_param (dbh->update, dbh->ubind))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_bind_param",
+ __FILE__, __LINE__, mysql_stmt_error (dbh->update));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return SYSERR;
+ }
/* NOTE: as the table entry for 'prio' is defined as unsigned,
* mysql will zero the value if its about to go negative. (This
* will generate a warning though, but its probably not seen
* at all in this context.)
*/
- if (mysql_stmt_execute(dbh->update)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("`%s' failed at %s:%d with error: %s\n"),
- "mysql_stmt_execute",
- __FILE__, __LINE__,
- mysql_stmt_error(dbh->update));
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
- return SYSERR;
- }
- mysql_thread_end();
- MUTEX_UNLOCK(dbh->DATABASE_Lock_);
+ if (mysql_stmt_execute (dbh->update))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("`%s' failed at %s:%d with error: %s\n"),
+ "mysql_stmt_execute",
+ __FILE__, __LINE__, mysql_stmt_error (dbh->update));
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
+ return SYSERR;
+ }
+ mysql_thread_end ();
+ MUTEX_UNLOCK (dbh->DATABASE_Lock_);
return OK;
}
@@ -1337,153 +1278,151 @@
* available.
* @return number of bytes used on disk
*/
-static unsigned long long getSize() {
+static unsigned long long
+getSize ()
+{
unsigned long long ret;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
ret = content_size;
if (stats)
- stats->set(stat_size, ret);
- MUTEX_UNLOCK(lock);
- return ret * 2; /* common overhead seems to be 100%! */
+ stats->set (stat_size, ret);
+ MUTEX_UNLOCK (lock);
+ return ret * 2; /* common overhead seems to be 100%! */
}
/**
* Delete the database. The next operation is
* guaranteed to be unloading of the module.
*/
-static void drop() {
- mysql_query(dbh->dbf,
- "DROP TABLE gn070");
- if (mysql_error(dbh->dbf)[0]) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- dbh);
- } else
+static void
+drop ()
+{
+ mysql_query (dbh->dbf, "DROP TABLE gn070");
+ if (mysql_error (dbh->dbf)[0])
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbh);
+ }
+ else
content_size = 0;
}
SQstore_ServiceAPI *
-provide_module_sqstore_mysql_embedded(CoreAPIForApplication * capi) {
+provide_module_sqstore_mysql_embedded (CoreAPIForApplication * capi)
+{
static SQstore_ServiceAPI api;
- State_ServiceAPI * state;
- char * cnffile;
- FILE * fp;
- struct passwd * pw;
+ State_ServiceAPI *state;
+ char *cnffile;
+ FILE *fp;
+ struct passwd *pw;
size_t nX;
- char * home_dir;
- unsigned long long * sb;
+ char *home_dir;
+ unsigned long long *sb;
MYSQL_RES *sql_res;
MYSQL_ROW sql_row;
ectx = capi->ectx;
coreAPI = capi;
- stats = coreAPI->requestService("stats");
+ stats = coreAPI->requestService ("stats");
if (stats)
- stat_size
- = stats->create(gettext_noop("# bytes in datastore"));
+ stat_size = stats->create (gettext_noop ("# bytes in datastore"));
/* verify that .my.cnf can be found */
#ifndef WINDOWS
- pw = getpwuid(getuid());
- if(!pw)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "getpwuid");
- home_dir = STRDUP(pw->pw_dir);
+ pw = getpwuid (getuid ());
+ if (!pw)
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_ADMIN | GE_IMMEDIATE, "getpwuid");
+ home_dir = STRDUP (pw->pw_dir);
#else
- home_dir = (char *) MALLOC(_MAX_PATH + 1);
- plibc_conv_to_win_path("~/", home_dir);
+ home_dir = (char *) MALLOC (_MAX_PATH + 1);
+ plibc_conv_to_win_path ("~/", home_dir);
#endif
- nX = strlen(home_dir)+10;
- cnffile = MALLOC(nX);
- SNPRINTF(cnffile,
- nX,
- "%s/.my.cnf",
- home_dir);
- FREE(home_dir);
- GC_get_configuration_value_filename(capi->cfg,
- "MYSQL",
- "CONFIG",
- cnffile,
- &home_dir);
- FREE(cnffile);
+ nX = strlen (home_dir) + 10;
+ cnffile = MALLOC (nX);
+ SNPRINTF (cnffile, nX, "%s/.my.cnf", home_dir);
+ FREE (home_dir);
+ GC_get_configuration_value_filename (capi->cfg,
+ "MYSQL", "CONFIG", cnffile, &home_dir);
+ FREE (cnffile);
cnffile = home_dir;
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _("Trying to use file `%s' for MySQL configuration.\n"),
- cnffile);
- fp = FOPEN(cnffile, "r");
- if (!fp) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "fopen",
- cnffile);
- if (stats != NULL)
- coreAPI->releaseService(stats);
- FREE(cnffile);
- return NULL;
- } else {
- fclose(fp);
- }
- dbh = MALLOC(sizeof(mysqlHandle));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ _("Trying to use file `%s' for MySQL configuration.\n"), cnffile);
+ fp = FOPEN (cnffile, "r");
+ if (!fp)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK, "fopen", cnffile);
+ if (stats != NULL)
+ coreAPI->releaseService (stats);
+ FREE (cnffile);
+ return NULL;
+ }
+ else
+ {
+ fclose (fp);
+ }
+ dbh = MALLOC (sizeof (mysqlHandle));
dbh->cnffile = cnffile;
- if (OK != iopen(dbh, YES)) {
- FREE(cnffile);
- FREE(dbh);
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Failed to load MySQL database module. Check that MySQL is running and
configured properly!\n"));
- dbh = NULL;
- if (stats != NULL)
- coreAPI->releaseService(stats);
- return NULL;
- }
+ if (OK != iopen (dbh, YES))
+ {
+ FREE (cnffile);
+ FREE (dbh);
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("Failed to load MySQL database module. Check that MySQL is
running and configured properly!\n"));
+ dbh = NULL;
+ if (stats != NULL)
+ coreAPI->releaseService (stats);
+ return NULL;
+ }
- lock = MUTEX_CREATE(NO);
- state = coreAPI->requestService("state");
+ lock = MUTEX_CREATE (NO);
+ state = coreAPI->requestService ("state");
sb = NULL;
- if (sizeof(unsigned long long)
- != state->read(ectx,
- "mysql-size",
- (void*) &sb)) {
+ if (sizeof (unsigned long long)
+ != state->read (ectx, "mysql-size", (void *) &sb))
+ {
- /* need to recompute! */
- sql_res = NULL;
- mysql_query(dbh->dbf,
- SELECT_SIZE);
- if ( (mysql_error(dbh->dbf)[0]) ||
- (!(sql_res=mysql_use_result(dbh->dbf))) ||
- (!(sql_row=mysql_fetch_row(sql_res))) ) {
- LOG_MYSQL(GE_ERROR | GE_ADMIN | GE_BULK,
- "mysql_query",
- dbh);
- content_size = 0;
- } else {
- if ( (mysql_num_fields(sql_res) != 1) ||
- (sql_row[0] == NULL) ) {
- GE_BREAK(ectx, mysql_num_fields(sql_res) == 1);
- content_size = 0;
- } else {
- if (1 != SSCANF(sql_row[0],
- "%llu",
- &content_size)) {
- GE_BREAK(ectx, 0);
- content_size = 0;
- }
- }
+ /* need to recompute! */
+ sql_res = NULL;
+ mysql_query (dbh->dbf, SELECT_SIZE);
+ if ((mysql_error (dbh->dbf)[0]) ||
+ (!(sql_res = mysql_use_result (dbh->dbf))) ||
+ (!(sql_row = mysql_fetch_row (sql_res))))
+ {
+ LOG_MYSQL (GE_ERROR | GE_ADMIN | GE_BULK, "mysql_query", dbh);
+ content_size = 0;
+ }
+ else
+ {
+ if ((mysql_num_fields (sql_res) != 1) || (sql_row[0] == NULL))
+ {
+ GE_BREAK (ectx, mysql_num_fields (sql_res) == 1);
+ content_size = 0;
+ }
+ else
+ {
+ if (1 != SSCANF (sql_row[0], "%llu", &content_size))
+ {
+ GE_BREAK (ectx, 0);
+ content_size = 0;
+ }
+ }
+ }
+ if (sql_res != NULL)
+ mysql_free_result (sql_res);
}
- if (sql_res != NULL)
- mysql_free_result(sql_res);
- } else {
- content_size = *sb;
- FREE(sb);
- /* no longer valid! remember it by deleting
- the outdated state file! */
- state->unlink(ectx,
- "mysql-size");
- }
- coreAPI->releaseService(state);
+ else
+ {
+ content_size = *sb;
+ FREE (sb);
+ /* no longer valid! remember it by deleting
+ the outdated state file! */
+ state->unlink (ectx, "mysql-size");
+ }
+ coreAPI->releaseService (state);
api.getSize = &getSize;
api.put = &put;
api.get = &get;
@@ -1501,23 +1440,23 @@
/**
* Shutdown the module.
*/
-void release_module_sqstore_mysql_embedded() {
- State_ServiceAPI * state;
- iclose(dbh);
- FREE(dbh->cnffile);
- FREE(dbh);
+void
+release_module_sqstore_mysql_embedded ()
+{
+ State_ServiceAPI *state;
+ iclose (dbh);
+ FREE (dbh->cnffile);
+ FREE (dbh);
dbh = NULL;
if (stats != NULL)
- coreAPI->releaseService(stats);
- MUTEX_DESTROY(lock);
- state = coreAPI->requestService("state");
- state->write(ectx,
- "mysql-size",
- sizeof(unsigned long long),
- &content_size);
- coreAPI->releaseService(state);
- mysql_library_end();
+ coreAPI->releaseService (stats);
+ MUTEX_DESTROY (lock);
+ state = coreAPI->requestService ("state");
+ state->write (ectx,
+ "mysql-size", sizeof (unsigned long long), &content_size);
+ coreAPI->releaseService (state);
+ mysql_library_end ();
ectx = NULL;
coreAPI = NULL;
}
Modified: GNUnet/src/applications/sqstore_mysql_embedded/mysqltest.c
===================================================================
--- GNUnet/src/applications/sqstore_mysql_embedded/mysqltest.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/sqstore_mysql_embedded/mysqltest.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -35,101 +35,104 @@
static cron_t now;
-static Datastore_Value * initValue(int i) {
- Datastore_Value * value;
+static Datastore_Value *
+initValue (int i)
+{
+ Datastore_Value *value;
- value = MALLOC(sizeof(Datastore_Value) + 8 * i);
- value->size = htonl(sizeof(Datastore_Value) + 8 * i);
- value->type = htonl(i);
- value->prio = htonl(i+1);
- value->anonymityLevel = htonl(i);
- value->expirationTime = htonll(now - i * cronSECONDS);
- memset(&value[1], i, 8*i);
+ value = MALLOC (sizeof (Datastore_Value) + 8 * i);
+ value->size = htonl (sizeof (Datastore_Value) + 8 * i);
+ value->type = htonl (i);
+ value->prio = htonl (i + 1);
+ value->anonymityLevel = htonl (i);
+ value->expirationTime = htonll (now - i * cronSECONDS);
+ memset (&value[1], i, 8 * i);
return value;
}
-static int checkValue(const HashCode512 * key,
- const Datastore_Value * val,
- void * closure) {
+static int
+checkValue (const HashCode512 * key,
+ const Datastore_Value * val, void *closure)
+{
int i;
int ret;
- Datastore_Value * value;
+ Datastore_Value *value;
- i = *(int*) closure;
- value = initValue(i);
- if ( ( value->size == val->size) &&
- (0 == memcmp(val,
- value,
- ntohl(val->size)) ) )
+ i = *(int *) closure;
+ value = initValue (i);
+ if ((value->size == val->size) &&
+ (0 == memcmp (val, value, ntohl (val->size))))
ret = OK;
- else {
- /*
- printf("Wanted: %u, %llu; got %u, %llu - %d\n",
- ntohl(value->size), ntohll(value->expirationTime),
- ntohl(val->size), ntohll(val->expirationTime),
- memcmp(val, value, ntohl(val->size))); */
- ret = SYSERR;
- }
- FREE(value);
+ else
+ {
+ /*
+ printf("Wanted: %u, %llu; got %u, %llu - %d\n",
+ ntohl(value->size), ntohll(value->expirationTime),
+ ntohl(val->size), ntohll(val->expirationTime),
+ memcmp(val, value, ntohl(val->size))); */
+ ret = SYSERR;
+ }
+ FREE (value);
return ret;
}
-static int iterateUp(const HashCode512 * key,
- const Datastore_Value * val,
- int * closure) {
+static int
+iterateUp (const HashCode512 * key, const Datastore_Value * val, int *closure)
+{
int ret;
- ret = checkValue(key, val, closure);
+ ret = checkValue (key, val, closure);
(*closure) += 2;
return ret;
}
-static int iterateDown(const HashCode512 * key,
- const Datastore_Value * val,
- int * closure) {
+static int
+iterateDown (const HashCode512 * key,
+ const Datastore_Value * val, int *closure)
+{
int ret;
(*closure) -= 2;
- ret = checkValue(key, val, closure);
+ ret = checkValue (key, val, closure);
return ret;
}
-static int iterateDelete(const HashCode512 * key,
- const Datastore_Value * val,
- SQstore_ServiceAPI * api) {
- if (1 == api->del(key, val))
- return OK;
+static int
+iterateDelete (const HashCode512 * key,
+ const Datastore_Value * val, SQstore_ServiceAPI * api)
+{
+ if (1 == api->del (key, val))
+ return OK;
else
- return SYSERR;
+ return SYSERR;
}
-static int priorityCheck(const HashCode512 * key,
- const Datastore_Value * val,
- int * closure) {
+static int
+priorityCheck (const HashCode512 * key,
+ const Datastore_Value * val, int *closure)
+{
int id;
id = (*closure);
- if (id + 1 == ntohl(val->prio))
+ if (id + 1 == ntohl (val->prio))
return OK;
else
return SYSERR;
}
-static int multipleCheck(const HashCode512 * key,
- const Datastore_Value * val,
- Datastore_Value ** last) {
- if (*last != NULL) {
- if ( ((*last)->size == val->size) &&
- (0 == memcmp(*last,
- val,
- ntohl(val->size)) ) )
- return SYSERR; /* duplicate! */
- FREE(*last);
- }
- *last = MALLOC(ntohl(val->size));
- memcpy(*last,
- val,
- ntohl(val->size));
+static int
+multipleCheck (const HashCode512 * key,
+ const Datastore_Value * val, Datastore_Value ** last)
+{
+ if (*last != NULL)
+ {
+ if (((*last)->size == val->size) &&
+ (0 == memcmp (*last, val, ntohl (val->size))))
+ return SYSERR; /* duplicate! */
+ FREE (*last);
+ }
+ *last = MALLOC (ntohl (val->size));
+ memcpy (*last, val, ntohl (val->size));
return OK;
}
@@ -137,125 +140,119 @@
/**
* Add testcode here!
*/
-static int test(SQstore_ServiceAPI * api) {
- Datastore_Value * value;
+static int
+test (SQstore_ServiceAPI * api)
+{
+ Datastore_Value *value;
HashCode512 key;
unsigned long long oldSize;
int i;
now = 1000000;
- oldSize = api->getSize();
- for (i=0;i<256;i++) {
- value = initValue(i);
- memset(&key, 256-i, sizeof(HashCode512));
- ASSERT(OK == api->put(&key, value));
- FREE(value);
- }
- ASSERT(oldSize < api->getSize());
- ASSERT(256 == api->iterateLowPriority(ANY_BLOCK,
- NULL,
- NULL));
- ASSERT(256 == api->iterateExpirationTime(ANY_BLOCK,
- NULL,
- NULL));
- for (i=255;i>=0;i--) {
- memset(&key, 256-i, sizeof(HashCode512));
- ASSERT(1 == api->get(&key, i, &checkValue, (void*) &i));
- }
+ oldSize = api->getSize ();
+ for (i = 0; i < 256; i++)
+ {
+ value = initValue (i);
+ memset (&key, 256 - i, sizeof (HashCode512));
+ ASSERT (OK == api->put (&key, value));
+ FREE (value);
+ }
+ ASSERT (oldSize < api->getSize ());
+ ASSERT (256 == api->iterateLowPriority (ANY_BLOCK, NULL, NULL));
+ ASSERT (256 == api->iterateExpirationTime (ANY_BLOCK, NULL, NULL));
+ for (i = 255; i >= 0; i--)
+ {
+ memset (&key, 256 - i, sizeof (HashCode512));
+ ASSERT (1 == api->get (&key, i, &checkValue, (void *) &i));
+ }
- oldSize = api->getSize();
- for (i=255;i>=0;i-=2) {
- memset(&key, 256-i, sizeof(HashCode512));
- value = initValue(i);
- ASSERT(1 == api->del(&key, value));
- FREE(value);
- }
- ASSERT(oldSize > api->getSize());
+ oldSize = api->getSize ();
+ for (i = 255; i >= 0; i -= 2)
+ {
+ memset (&key, 256 - i, sizeof (HashCode512));
+ value = initValue (i);
+ ASSERT (1 == api->del (&key, value));
+ FREE (value);
+ }
+ ASSERT (oldSize > api->getSize ());
i = 0;
- ASSERT(128 == api->iterateLowPriority(ANY_BLOCK,
- (Datum_Iterator) &iterateUp,
- &i));
- ASSERT(256 == i);
- ASSERT(128 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &iterateDown,
- &i));
- ASSERT(0 == i);
- ASSERT(128 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &iterateDelete,
- api));
- ASSERT(0 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &iterateDown,
- &i));
+ ASSERT (128 == api->iterateLowPriority (ANY_BLOCK,
+ (Datum_Iterator) & iterateUp, &i));
+ ASSERT (256 == i);
+ ASSERT (128 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & iterateDown,
+ &i));
+ ASSERT (0 == i);
+ ASSERT (128 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & iterateDelete,
+ api));
+ ASSERT (0 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & iterateDown,
+ &i));
i = 42;
- value = initValue(i);
- memset(&key, 256-i, sizeof(HashCode512));
- api->put(&key, value);
- ASSERT(1 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &priorityCheck,
- &i));
- api->update(&key,
- value,
- 4,
- 0);
+ value = initValue (i);
+ memset (&key, 256 - i, sizeof (HashCode512));
+ api->put (&key, value);
+ ASSERT (1 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & priorityCheck,
+ &i));
+ api->update (&key, value, 4, 0);
i += 4;
- ASSERT(1 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &priorityCheck,
- &i));
- FREE(value);
+ ASSERT (1 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & priorityCheck,
+ &i));
+ FREE (value);
/* test multiple results */
- value = initValue(i+1);
- api->put(&key, value);
- FREE(value);
+ value = initValue (i + 1);
+ api->put (&key, value);
+ FREE (value);
value = NULL;
- ASSERT(2 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &multipleCheck,
- &value));
- FREE(value);
- api->del(&key,
- NULL);
- api->del(&key,
- NULL);
- ASSERT(0 == api->iterateExpirationTime(ANY_BLOCK,
- NULL,
- NULL));
- api->drop();
+ ASSERT (2 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & multipleCheck,
+ &value));
+ FREE (value);
+ api->del (&key, NULL);
+ api->del (&key, NULL);
+ ASSERT (0 == api->iterateExpirationTime (ANY_BLOCK, NULL, NULL));
+ api->drop ();
return OK;
- FAILURE:
- api->drop();
+FAILURE:
+ api->drop ();
return SYSERR;
}
-int main(int argc, char *argv[]) {
- SQstore_ServiceAPI * api;
+int
+main (int argc, char *argv[])
+{
+ SQstore_ServiceAPI *api;
int ok;
- struct GC_Configuration * cfg;
- struct CronManager * cron;
+ struct GC_Configuration *cfg;
+ struct CronManager *cron;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- cron = cron_create(NULL);
- initCore(NULL,
- cfg,
- cron,
- NULL);
- api = requestService("sqstore");
- if (api != NULL) {
- ok = test(api);
- releaseService(api);
- } else
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ cron = cron_create (NULL);
+ initCore (NULL, cfg, cron, NULL);
+ api = requestService ("sqstore");
+ if (api != NULL)
+ {
+ ok = test (api);
+ releaseService (api);
+ }
+ else
ok = SYSERR;
- doneCore();
- cron_destroy(cron);
- GC_free(cfg);
+ doneCore ();
+ cron_destroy (cron);
+ GC_free (cfg);
if (ok == SYSERR)
return 1;
return 0;
Modified: GNUnet/src/applications/sqstore_mysql_embedded/mysqltest2.c
===================================================================
--- GNUnet/src/applications/sqstore_mysql_embedded/mysqltest2.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/sqstore_mysql_embedded/mysqltest2.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -123,67 +123,65 @@
static cron_t start_time;
-static int putValue(SQstore_ServiceAPI * api,
- int i) {
- Datastore_Value * value;
+static int
+putValue (SQstore_ServiceAPI * api, int i)
+{
+ Datastore_Value *value;
size_t size;
static HashCode512 key;
static int ic;
/* most content is 32k */
- size = sizeof(Datastore_Value) + 32 * 1024;
- if (weak_randomi(16) == 0) /* but some of it is less! */
- size = sizeof(Datastore_Value) + weak_randomi(32 * 1024);
- size = size - (size & 7); /* always multiple of 8 */
+ size = sizeof (Datastore_Value) + 32 * 1024;
+ if (weak_randomi (16) == 0) /* but some of it is less! */
+ size = sizeof (Datastore_Value) + weak_randomi (32 * 1024);
+ size = size - (size & 7); /* always multiple of 8 */
/* generate random key */
- hash(&key,
- sizeof(HashCode512),
- &key);
- value = MALLOC(size);
- value->size = htonl(size);
- value->type = htonl(i);
- value->prio = htonl(weak_randomi(100));
- value->anonymityLevel = htonl(i);
- value->expirationTime = htonll(get_time() + weak_randomi(1000));
- memset(&value[1],
- i,
- size - sizeof(Datastore_Value));
- if (OK != api->put(&key, value)) {
- FREE(value);
- fprintf(stderr, "E");
- return SYSERR;
- }
+ hash (&key, sizeof (HashCode512), &key);
+ value = MALLOC (size);
+ value->size = htonl (size);
+ value->type = htonl (i);
+ value->prio = htonl (weak_randomi (100));
+ value->anonymityLevel = htonl (i);
+ value->expirationTime = htonll (get_time () + weak_randomi (1000));
+ memset (&value[1], i, size - sizeof (Datastore_Value));
+ if (OK != api->put (&key, value))
+ {
+ FREE (value);
+ fprintf (stderr, "E");
+ return SYSERR;
+ }
ic++;
#if REPORT_ID
if (ic % REP_FREQ == 0)
- fprintf(stderr, "I");
+ fprintf (stderr, "I");
#endif
- stored_bytes += ntohl(value->size);
+ stored_bytes += ntohl (value->size);
stored_ops++;
stored_entries++;
- FREE(value);
+ FREE (value);
return OK;
}
static int
-iterateDelete(const HashCode512 * key,
- const Datastore_Value * val,
- void * cls) {
- SQstore_ServiceAPI * api = cls;
+iterateDelete (const HashCode512 * key,
+ const Datastore_Value * val, void *cls)
+{
+ SQstore_ServiceAPI *api = cls;
static int dc;
- if (api->getSize() < MAX_SIZE)
+ if (api->getSize () < MAX_SIZE)
return SYSERR;
- if (GNUNET_SHUTDOWN_TEST() == YES)
+ if (GNUNET_SHUTDOWN_TEST () == YES)
return SYSERR;
dc++;
#if REPORT_ID
if (dc % REP_FREQ == 0)
- fprintf(stderr, "D");
+ fprintf (stderr, "D");
#endif
- GE_ASSERT(NULL, 1 == api->del(key, val));
- stored_bytes -= ntohl(val->size);
+ GE_ASSERT (NULL, 1 == api->del (key, val));
+ stored_bytes -= ntohl (val->size);
stored_entries--;
return OK;
}
@@ -191,87 +189,88 @@
/**
* Add testcode here!
*/
-static int test(SQstore_ServiceAPI * api) {
+static int
+test (SQstore_ServiceAPI * api)
+{
int i;
int j;
unsigned long long size;
int have_file;
struct stat sbuf;
- have_file = 0 == stat(DB_NAME, &sbuf);
+ have_file = 0 == stat (DB_NAME, &sbuf);
- for (i=0;i<ITERATIONS;i++) {
+ for (i = 0; i < ITERATIONS; i++)
+ {
#if REPORT_ID
- fprintf(stderr, ".");
+ fprintf (stderr, ".");
#endif
- /* insert data equivalent to 1/10th of MAX_SIZE */
- for (j=0;j<PUT_10;j++) {
- ASSERT(OK == putValue(api, j));
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
+ /* insert data equivalent to 1/10th of MAX_SIZE */
+ for (j = 0; j < PUT_10; j++)
+ {
+ ASSERT (OK == putValue (api, j));
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
- /* trim down below MAX_SIZE again */
- if ((i % 2) == 0)
- api->iterateLowPriority(0, &iterateDelete, api);
- else
- api->iterateExpirationTime(0, &iterateDelete, api);
+ /* trim down below MAX_SIZE again */
+ if ((i % 2) == 0)
+ api->iterateLowPriority (0, &iterateDelete, api);
+ else
+ api->iterateExpirationTime (0, &iterateDelete, api);
- size = 0;
- if (have_file)
- disk_file_size(NULL,
- DB_NAME,
- &size,
- NO);
- printf(
+ size = 0;
+ if (have_file)
+ disk_file_size (NULL, DB_NAME, &size, NO);
+ printf (
#if REPORT_ID
- "\n"
+ "\n"
#endif
- "Useful %llu, API %llu, disk %llu (%.2f%%) / %lluk ops / %llu ops/s\n",
- stored_bytes / 1024, /* used size in k */
- api->getSize() / 1024, /* API-reported size in k */
- size / 1024, /* disk size in kb */
- (100.0 * size / stored_bytes) - 100, /* overhead */
- (stored_ops * 2 - stored_entries) / 1024, /* total operations (in k) */
- 1000 * (stored_ops * 2 - stored_entries) / (1 + get_time() -
start_time)); /* operations per second */
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- api->drop();
+ "Useful %llu, API %llu, disk %llu (%.2f%%) / %lluk ops / %llu
ops/s\n", stored_bytes / 1024, /* used size in k */
+ api->getSize () / 1024, /* API-reported size in k */
+ size / 1024, /* disk size in kb */
+ (100.0 * size / stored_bytes) - 100, /* overhead */
+ (stored_ops * 2 - stored_entries) / 1024, /* total
operations (in k) */
+ 1000 * (stored_ops * 2 - stored_entries) / (1 + get_time () -
start_time)); /* operations per second */
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
+ api->drop ();
return OK;
- FAILURE:
- api->drop();
+FAILURE:
+ api->drop ();
return SYSERR;
}
-int main(int argc, char *argv[]) {
- SQstore_ServiceAPI * api;
+int
+main (int argc, char *argv[])
+{
+ SQstore_ServiceAPI *api;
int ok;
- struct GC_Configuration * cfg;
- struct CronManager * cron;
+ struct GC_Configuration *cfg;
+ struct CronManager *cron;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- cron = cron_create(NULL);
- initCore(NULL,
- cfg,
- cron,
- NULL);
- api = requestService("sqstore");
- if (api != NULL) {
- start_time = get_time();
- ok = test(api);
- releaseService(api);
- } else
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ cron = cron_create (NULL);
+ initCore (NULL, cfg, cron, NULL);
+ api = requestService ("sqstore");
+ if (api != NULL)
+ {
+ start_time = get_time ();
+ ok = test (api);
+ releaseService (api);
+ }
+ else
ok = SYSERR;
- doneCore();
- cron_destroy(cron);
- GC_free(cfg);
+ doneCore ();
+ cron_destroy (cron);
+ GC_free (cfg);
if (ok == SYSERR)
return 1;
return 0;
Modified: GNUnet/src/applications/sqstore_mysql_embedded/mysqltest3.c
===================================================================
--- GNUnet/src/applications/sqstore_mysql_embedded/mysqltest3.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/sqstore_mysql_embedded/mysqltest3.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -55,141 +55,144 @@
static cron_t start_time;
-static int putValue(SQstore_ServiceAPI * api,
- int i) {
- Datastore_Value * value;
+static int
+putValue (SQstore_ServiceAPI * api, int i)
+{
+ Datastore_Value *value;
size_t size;
static HashCode512 key;
static int ic;
/* most content is 32k */
- size = sizeof(Datastore_Value) + 32 * 1024;
- if (weak_randomi(16) == 0) /* but some of it is less! */
- size = sizeof(Datastore_Value) + weak_randomi(32 * 1024);
- size = size - (size & 7); /* always multiple of 8 */
+ size = sizeof (Datastore_Value) + 32 * 1024;
+ if (weak_randomi (16) == 0) /* but some of it is less! */
+ size = sizeof (Datastore_Value) + weak_randomi (32 * 1024);
+ size = size - (size & 7); /* always multiple of 8 */
/* generate random key */
- hash(&key,
- sizeof(HashCode512),
- &key);
- value = MALLOC(size);
- value->size = htonl(size);
- value->type = htonl(i);
- value->prio = htonl(weak_randomi(100));
- value->anonymityLevel = htonl(i);
- value->expirationTime = htonll(get_time() + 60 * cronHOURS +
weak_randomi(1000));
- memset(&value[1],
- i,
- size - sizeof(Datastore_Value));
- if (OK != api->put(&key, value)) {
- FREE(value);
- fprintf(stderr, "E");
- return SYSERR;
- }
+ hash (&key, sizeof (HashCode512), &key);
+ value = MALLOC (size);
+ value->size = htonl (size);
+ value->type = htonl (i);
+ value->prio = htonl (weak_randomi (100));
+ value->anonymityLevel = htonl (i);
+ value->expirationTime =
+ htonll (get_time () + 60 * cronHOURS + weak_randomi (1000));
+ memset (&value[1], i, size - sizeof (Datastore_Value));
+ if (OK != api->put (&key, value))
+ {
+ FREE (value);
+ fprintf (stderr, "E");
+ return SYSERR;
+ }
ic++;
- stored_bytes += ntohl(value->size);
+ stored_bytes += ntohl (value->size);
stored_ops++;
stored_entries++;
- FREE(value);
+ FREE (value);
return OK;
}
static int
-iterateDummy(const HashCode512 * key,
- const Datastore_Value * val,
- void * cls) {
- if (GNUNET_SHUTDOWN_TEST() == YES)
+iterateDummy (const HashCode512 * key, const Datastore_Value * val, void *cls)
+{
+ if (GNUNET_SHUTDOWN_TEST () == YES)
return SYSERR;
return OK;
}
-static int test(SQstore_ServiceAPI * api) {
+static int
+test (SQstore_ServiceAPI * api)
+{
int i;
int j;
cron_t start;
cron_t end;
- for (i=0;i<ITERATIONS;i++) {
- /* insert data equivalent to 1/10th of MAX_SIZE */
- start = get_time();
- for (j=0;j<PUT_10;j++) {
- if (OK != putValue(api, j))
- break;
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
+ for (i = 0; i < ITERATIONS; i++)
+ {
+ /* insert data equivalent to 1/10th of MAX_SIZE */
+ start = get_time ();
+ for (j = 0; j < PUT_10; j++)
+ {
+ if (OK != putValue (api, j))
+ break;
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
+ end = get_time ();
+ printf ("%3u insertion took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateLowPriority (0, &iterateDummy, api);
+ end = get_time ();
+ printf ("%3u low priority iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateExpirationTime (0, &iterateDummy, api);
+ end = get_time ();
+ printf ("%3u expiration t iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateNonAnonymous (0, NO, &iterateDummy, api);
+ end = get_time ();
+ printf ("%3u non anonymou iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateNonAnonymous (0, YES, &iterateDummy, api);
+ end = get_time ();
+ printf ("%3u non anon YES iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateMigrationOrder (&iterateDummy, api);
+ end = get_time ();
+ printf ("%3u migration or iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateAllNow (&iterateDummy, api);
+ end = get_time ();
+ printf ("%3u all now iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
}
- end = get_time();
- printf("%3u insertion took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateLowPriority(0, &iterateDummy, api);
- end = get_time();
- printf("%3u low priority iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateExpirationTime(0, &iterateDummy, api);
- end = get_time();
- printf("%3u expiration t iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateNonAnonymous(0, NO, &iterateDummy, api);
- end = get_time();
- printf("%3u non anonymou iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateNonAnonymous(0, YES, &iterateDummy, api);
- end = get_time();
- printf("%3u non anon YES iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateMigrationOrder(&iterateDummy, api);
- end = get_time();
- printf("%3u migration or iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateAllNow(&iterateDummy, api);
- end = get_time();
- printf("%3u all now iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- api->drop();
+ api->drop ();
return OK;
}
-int main(int argc, char *argv[]) {
- SQstore_ServiceAPI * api;
+int
+main (int argc, char *argv[])
+{
+ SQstore_ServiceAPI *api;
int ok;
- struct GC_Configuration * cfg;
- struct CronManager * cron;
+ struct GC_Configuration *cfg;
+ struct CronManager *cron;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- cron = cron_create(NULL);
- initCore(NULL,
- cfg,
- cron,
- NULL);
- api = requestService("sqstore");
- if (api != NULL) {
- start_time = get_time();
- ok = test(api);
- releaseService(api);
- } else
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ cron = cron_create (NULL);
+ initCore (NULL, cfg, cron, NULL);
+ api = requestService ("sqstore");
+ if (api != NULL)
+ {
+ start_time = get_time ();
+ ok = test (api);
+ releaseService (api);
+ }
+ else
ok = SYSERR;
- doneCore();
- cron_destroy(cron);
- GC_free(cfg);
+ doneCore ();
+ cron_destroy (cron);
+ GC_free (cfg);
if (ok == SYSERR)
return 1;
return 0;
Modified: GNUnet/src/applications/sqstore_sqlite/sqlite.c
===================================================================
--- GNUnet/src/applications/sqstore_sqlite/sqlite.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/sqstore_sqlite/sqlite.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -64,18 +64,19 @@
*/
#define BUSY_TIMEOUT_MS 250
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
static unsigned int stat_size;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
/**
* @brief Wrapper for SQLite
*/
-typedef struct {
+typedef struct
+{
/**
* Native SQLite database handle - may not be shared between threads!
@@ -85,30 +86,31 @@
/**
* Thread ID owning this handle
*/
- struct PTHREAD * tid;
+ struct PTHREAD *tid;
/**
* Precompiled SQL
*/
- sqlite3_stmt * exists;
+ sqlite3_stmt *exists;
- sqlite3_stmt * countContent;
+ sqlite3_stmt *countContent;
- sqlite3_stmt * updPrio;
+ sqlite3_stmt *updPrio;
- sqlite3_stmt * insertContent;
+ sqlite3_stmt *insertContent;
} sqliteHandle;
/**
* @brief Information about the database
*/
-typedef struct {
+typedef struct
+{
- struct MUTEX * DATABASE_Lock_;
+ struct MUTEX *DATABASE_Lock_;
/**
* filename of this bucket
*/
- char * fn;
+ char *fn;
/**
* bytes used
@@ -125,24 +127,23 @@
/**
* List of open handles
*/
- sqliteHandle ** handles;
+ sqliteHandle **handles;
} sqliteDatabase;
-static sqliteDatabase * db;
+static sqliteDatabase *db;
/**
* @brief Prepare a SQL statement
*/
-static int sq_prepare(sqlite3 * dbh,
- const char *zSql, /* SQL statement, UTF-8 encoded */
- sqlite3_stmt **ppStmt) { /* OUT: Statement handle */
- char * dummy;
- return sqlite3_prepare(dbh,
- zSql,
- strlen(zSql),
- ppStmt,
- (const char**) &dummy);
+static int
+sq_prepare (sqlite3 * dbh, const char *zSql, /* SQL statement, UTF-8
encoded */
+ sqlite3_stmt ** ppStmt)
+{ /* OUT: Statement handle */
+ char *dummy;
+ return sqlite3_prepare (dbh,
+ zSql,
+ strlen (zSql), ppStmt, (const char **) &dummy);
}
#if 1
@@ -154,28 +155,30 @@
#define CHECK(a) if (! a) { fprintf(stderr, "%s\n", e); sqlite3_free(e); }
#endif
-static void createIndices(sqlite3 * dbh) {
+static void
+createIndices (sqlite3 * dbh)
+{
/* create indices */
- CHECK(SQLITE_OK ==
- sqlite3_exec(dbh,
- "CREATE INDEX idx_hash ON gn070 (hash)",
- NULL, NULL, ENULL));
- CHECK(SQLITE_OK ==
- sqlite3_exec(dbh,
- "CREATE INDEX idx_prio ON gn070 (prio)",
- NULL, NULL, ENULL));
- CHECK(SQLITE_OK ==
- sqlite3_exec(dbh,
- "CREATE INDEX idx_expire ON gn070 (expire)",
- NULL, NULL, ENULL));
- CHECK(SQLITE_OK ==
- sqlite3_exec(dbh,
- "CREATE INDEX idx_comb1 ON gn070 (prio,expire,hash)",
- NULL, NULL, ENULL));
- CHECK(SQLITE_OK ==
- sqlite3_exec(dbh,
- "CREATE INDEX idx_comb2 ON gn070 (expire,prio,hash)",
- NULL, NULL, ENULL));
+ CHECK (SQLITE_OK ==
+ sqlite3_exec (dbh,
+ "CREATE INDEX idx_hash ON gn070 (hash)",
+ NULL, NULL, ENULL));
+ CHECK (SQLITE_OK ==
+ sqlite3_exec (dbh,
+ "CREATE INDEX idx_prio ON gn070 (prio)",
+ NULL, NULL, ENULL));
+ CHECK (SQLITE_OK ==
+ sqlite3_exec (dbh,
+ "CREATE INDEX idx_expire ON gn070 (expire)",
+ NULL, NULL, ENULL));
+ CHECK (SQLITE_OK ==
+ sqlite3_exec (dbh,
+ "CREATE INDEX idx_comb1 ON gn070 (prio,expire,hash)",
+ NULL, NULL, ENULL));
+ CHECK (SQLITE_OK ==
+ sqlite3_exec (dbh,
+ "CREATE INDEX idx_comb2 ON gn070 (expire,prio,hash)",
+ NULL, NULL, ENULL));
}
/**
@@ -185,133 +188,135 @@
* We therefore (re)open the database in each thread.
* @return the native SQLite database handle
*/
-static sqliteHandle * getDBHandle() {
+static sqliteHandle *
+getDBHandle ()
+{
unsigned int idx;
- sqliteHandle * ret;
- sqlite3_stmt * stmt;
+ sqliteHandle *ret;
+ sqlite3_stmt *stmt;
#if ENULL_DEFINED
- char * e;
+ char *e;
#endif
/* Is the DB already open? */
for (idx = 0; idx < db->handle_count; idx++)
- if (PTHREAD_TEST_SELF(db->handles[idx]->tid))
+ if (PTHREAD_TEST_SELF (db->handles[idx]->tid))
return db->handles[idx];
/* we haven't opened the DB for this thread yet */
- ret = MALLOC(sizeof(sqliteHandle));
+ ret = MALLOC (sizeof (sqliteHandle));
/* Open database and precompile statements */
- if (sqlite3_open(db->fn, &ret->dbh) != SQLITE_OK) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Unable to initialize SQLite: %s.\n"),
- sqlite3_errmsg(ret->dbh));
- sqlite3_close(ret->dbh);
- FREE(ret);
- return NULL;
- }
+ if (sqlite3_open (db->fn, &ret->dbh) != SQLITE_OK)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Unable to initialize SQLite: %s.\n"),
+ sqlite3_errmsg (ret->dbh));
+ sqlite3_close (ret->dbh);
+ FREE (ret);
+ return NULL;
+ }
- CHECK(SQLITE_OK ==
- sqlite3_exec(ret->dbh,
- "PRAGMA temp_store=MEMORY", NULL, NULL, ENULL));
- CHECK(SQLITE_OK ==
- sqlite3_exec(ret->dbh,
- "PRAGMA synchronous=OFF", NULL, NULL, ENULL));
- CHECK(SQLITE_OK ==
- sqlite3_exec(ret->dbh,
- "PRAGMA count_changes=OFF", NULL, NULL, ENULL));
- CHECK(SQLITE_OK ==
- sqlite3_exec(ret->dbh,
- "PRAGMA page_size=4092", NULL, NULL, ENULL));
+ CHECK (SQLITE_OK ==
+ sqlite3_exec (ret->dbh,
+ "PRAGMA temp_store=MEMORY", NULL, NULL, ENULL));
+ CHECK (SQLITE_OK ==
+ sqlite3_exec (ret->dbh,
+ "PRAGMA synchronous=OFF", NULL, NULL, ENULL));
+ CHECK (SQLITE_OK ==
+ sqlite3_exec (ret->dbh,
+ "PRAGMA count_changes=OFF", NULL, NULL, ENULL));
+ CHECK (SQLITE_OK ==
+ sqlite3_exec (ret->dbh, "PRAGMA page_size=4092", NULL, NULL, ENULL));
- CHECK(SQLITE_OK ==
- sqlite3_busy_timeout(ret->dbh,
- BUSY_TIMEOUT_MS));
+ CHECK (SQLITE_OK == sqlite3_busy_timeout (ret->dbh, BUSY_TIMEOUT_MS));
/* We have to do it here, because otherwise precompiling SQL might fail */
- CHECK(SQLITE_OK ==
- sq_prepare(ret->dbh,
- "Select 1 from sqlite_master where tbl_name = 'gn070'",
- &stmt));
- if (sqlite3_step(stmt) == SQLITE_DONE) {
- if (sqlite3_exec(ret->dbh,
- "CREATE TABLE gn070 ("
- " size INTEGER NOT NULL DEFAULT 0,"
- " type INTEGER NOT NULL DEFAULT 0,"
- " prio INTEGER NOT NULL DEFAULT 0,"
- " anonLevel INTEGER NOT NULL DEFAULT 0,"
- " expire INTEGER NOT NULL DEFAULT 0,"
- " hash TEXT NOT NULL DEFAULT '',"
- " value BLOB NOT NULL DEFAULT '')", NULL, NULL,
- NULL) != SQLITE_OK) {
- LOG_SQLITE(ret,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_create");
- sqlite3_finalize(stmt);
- FREE(ret);
+ CHECK (SQLITE_OK ==
+ sq_prepare (ret->dbh,
+ "Select 1 from sqlite_master where tbl_name = 'gn070'",
+ &stmt));
+ if (sqlite3_step (stmt) == SQLITE_DONE)
+ {
+ if (sqlite3_exec (ret->dbh,
+ "CREATE TABLE gn070 ("
+ " size INTEGER NOT NULL DEFAULT 0,"
+ " type INTEGER NOT NULL DEFAULT 0,"
+ " prio INTEGER NOT NULL DEFAULT 0,"
+ " anonLevel INTEGER NOT NULL DEFAULT 0,"
+ " expire INTEGER NOT NULL DEFAULT 0,"
+ " hash TEXT NOT NULL DEFAULT '',"
+ " value BLOB NOT NULL DEFAULT '')", NULL, NULL,
+ NULL) != SQLITE_OK)
+ {
+ LOG_SQLITE (ret,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "sqlite_create");
+ sqlite3_finalize (stmt);
+ FREE (ret);
+ return NULL;
+ }
+ createIndices (ret->dbh);
+ }
+ sqlite3_finalize (stmt);
+
+ if ((sq_prepare (ret->dbh,
+ "SELECT COUNT(*) FROM gn070 WHERE hash=?",
+ &ret->countContent) != SQLITE_OK) ||
+ (sq_prepare (ret->dbh,
+ "SELECT LENGTH(hash), LENGTH(value), size, type, prio,
anonLevel, expire "
+ "FROM gn070 WHERE hash=?",
+ &ret->exists) != SQLITE_OK) ||
+ (sq_prepare (ret->dbh,
+ "UPDATE gn070 SET prio = prio + ?, expire = MAX(expire,?)
WHERE "
+ "hash = ? AND value = ? AND prio + ? < ?",
+ &ret->updPrio) != SQLITE_OK) ||
+ (sq_prepare (ret->dbh,
+ "INSERT INTO gn070 (size, type, prio, "
+ "anonLevel, expire, hash, value) VALUES "
+ "(?, ?, ?, ?, ?, ?, ?)",
+ &ret->insertContent) != SQLITE_OK))
+ {
+ LOG_SQLITE (ret,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "precompiling");
+ if (ret->countContent != NULL)
+ sqlite3_finalize (ret->countContent);
+ if (ret->exists != NULL)
+ sqlite3_finalize (ret->exists);
+ if (ret->updPrio != NULL)
+ sqlite3_finalize (ret->updPrio);
+ if (ret->insertContent != NULL)
+ sqlite3_finalize (ret->insertContent);
+ FREE (ret);
return NULL;
}
- createIndices(ret->dbh);
- }
- sqlite3_finalize(stmt);
+ ret->tid = PTHREAD_GET_SELF ();
- if ( (sq_prepare(ret->dbh,
- "SELECT COUNT(*) FROM gn070 WHERE hash=?",
- &ret->countContent) != SQLITE_OK) ||
- (sq_prepare(ret->dbh,
- "SELECT LENGTH(hash), LENGTH(value), size, type, prio, anonLevel,
expire "
- "FROM gn070 WHERE hash=?",
- &ret->exists) != SQLITE_OK) ||
- (sq_prepare(ret->dbh,
- "UPDATE gn070 SET prio = prio + ?, expire = MAX(expire,?) WHERE "
- "hash = ? AND value = ? AND prio + ? < ?",
- &ret->updPrio) != SQLITE_OK) ||
- (sq_prepare(ret->dbh,
- "INSERT INTO gn070 (size, type, prio, "
- "anonLevel, expire, hash, value) VALUES "
- "(?, ?, ?, ?, ?, ?, ?)",
- &ret->insertContent) != SQLITE_OK) ) {
- LOG_SQLITE(ret,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "precompiling");
- if (ret->countContent != NULL)
- sqlite3_finalize(ret->countContent);
- if (ret->exists != NULL)
- sqlite3_finalize(ret->exists);
- if (ret->updPrio != NULL)
- sqlite3_finalize(ret->updPrio);
- if (ret->insertContent != NULL)
- sqlite3_finalize(ret->insertContent);
- FREE(ret);
- return NULL;
- }
- ret->tid = PTHREAD_GET_SELF();
-
- MUTEX_LOCK(db->DATABASE_Lock_);
- APPEND(db->handles,
- db->handle_count,
- ret);
- MUTEX_UNLOCK(db->DATABASE_Lock_);
+ MUTEX_LOCK (db->DATABASE_Lock_);
+ APPEND (db->handles, db->handle_count, ret);
+ MUTEX_UNLOCK (db->DATABASE_Lock_);
return ret;
}
/**
* @brief Returns the storage needed for the specfied int
*/
-static unsigned int getIntSize(unsigned long long l) {
+static unsigned int
+getIntSize (unsigned long long l)
+{
if ((l & 0x7FFFFFFFFFFFLL) == l)
if ((l & 0x7FFFFFFF) == l)
if ((l & 0x7FFFFF) == l)
- if ((l & 0x7FFF) == l)
- if ((l & 0x7F) == l)
- return 1;
- else
- return 2;
- else
- return 3;
+ if ((l & 0x7FFF) == l)
+ if ((l & 0x7F) == l)
+ return 1;
+ else
+ return 2;
+ else
+ return 3;
else
- return 4;
+ return 4;
else
return 6;
else
@@ -325,10 +330,14 @@
* row length = hash length + block length + numbers + column count +
estimated index size + 1
* </pre>
*/
-static unsigned int getContentDatastoreSize(const Datastore_Value * value) {
- return sizeof(HashCode512) + ntohl(value->size) - sizeof(Datastore_Value)
- + getIntSize(ntohl(value->size)) + getIntSize(ntohl(value->type)) +
getIntSize(ntohl(value->prio))
- + getIntSize(ntohl(value->anonymityLevel)) +
getIntSize(ntohll(value->expirationTime)) + 7 + 245 + 1;
+static unsigned int
+getContentDatastoreSize (const Datastore_Value * value)
+{
+ return sizeof (HashCode512) + ntohl (value->size) - sizeof (Datastore_Value)
+ + getIntSize (ntohl (value->size)) + getIntSize (ntohl (value->type)) +
+ getIntSize (ntohl (value->prio)) +
+ getIntSize (ntohl (value->anonymityLevel)) +
+ getIntSize (ntohll (value->expirationTime)) + 7 + 245 + 1;
}
@@ -339,14 +348,16 @@
*
* @return number of bytes used on disk
*/
-static unsigned long long getSize() {
+static unsigned long long
+getSize ()
+{
double ret;
- MUTEX_LOCK(db->DATABASE_Lock_);
+ MUTEX_LOCK (db->DATABASE_Lock_);
ret = db->payload;
if (stats)
- stats->set(stat_size, ret);
- MUTEX_UNLOCK(db->DATABASE_Lock_);
+ stats->set (stat_size, ret);
+ MUTEX_UNLOCK (db->DATABASE_Lock_);
return (unsigned long long) (ret * 1.06);
/* benchmarking shows 2-12% overhead */
}
@@ -356,81 +367,76 @@
* assemble it into a Datastore_Datum representation.
*/
static Datastore_Datum *
-assembleDatum(sqliteHandle * handle,
- sqlite3_stmt *stmt) {
- Datastore_Datum * datum;
- Datastore_Value * value;
+assembleDatum (sqliteHandle * handle, sqlite3_stmt * stmt)
+{
+ Datastore_Datum *datum;
+ Datastore_Value *value;
int contentSize;
- sqlite3 * dbh;
+ sqlite3 *dbh;
unsigned int type;
- type = sqlite3_column_int(stmt, 1);
+ type = sqlite3_column_int (stmt, 1);
if (type == RESERVED_BLOCK)
return NULL;
- contentSize = sqlite3_column_int(stmt, 0) - sizeof(Datastore_Value);
+ contentSize = sqlite3_column_int (stmt, 0) - sizeof (Datastore_Value);
dbh = handle->dbh;
- if (contentSize < 0) {
- sqlite3_stmt * stmt;
+ if (contentSize < 0)
+ {
+ sqlite3_stmt *stmt;
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Invalid data in %s (NCS). Trying to fix (by deletion).\n"),
- _("sqlite datastore"));
- if (sq_prepare(dbh,
- "DELETE FROM gn070 WHERE size < ?", &stmt) == SQLITE_OK) {
- sqlite3_bind_int(stmt,
- 1,
- sizeof(Datastore_Value));
- sqlite3_step(stmt);
- sqlite3_finalize(stmt);
- } else
- LOG_SQLITE(handle,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sq_prepare");
- return NULL; /* error */
- }
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Invalid data in %s (NCS). Trying to fix (by deletion).\n"),
+ _("sqlite datastore"));
+ if (sq_prepare (dbh,
+ "DELETE FROM gn070 WHERE size < ?", &stmt) == SQLITE_OK)
+ {
+ sqlite3_bind_int (stmt, 1, sizeof (Datastore_Value));
+ sqlite3_step (stmt);
+ sqlite3_finalize (stmt);
+ }
+ else
+ LOG_SQLITE (handle,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sq_prepare");
+ return NULL; /* error */
+ }
- if (sqlite3_column_bytes(stmt, 5) != sizeof(HashCode512) ||
- sqlite3_column_bytes(stmt, 6) != contentSize) {
- sqlite3_stmt * stmt;
+ if (sqlite3_column_bytes (stmt, 5) != sizeof (HashCode512) ||
+ sqlite3_column_bytes (stmt, 6) != contentSize)
+ {
+ sqlite3_stmt *stmt;
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Invalid data in %s. Trying to fix (by deletion).\n"),
- _("sqlite datastore"));
- if (sq_prepare(dbh,
- "DELETE FROM gn070 WHERE NOT ((LENGTH(hash) = ?) AND (size =
LENGTH(value) + ?))",
- &stmt) == SQLITE_OK) {
- sqlite3_bind_int(stmt,
- 1,
- sizeof(HashCode512));
- sqlite3_bind_int(stmt,
- 2,
- sizeof(Datastore_Value));
- sqlite3_step(stmt);
- sqlite3_finalize(stmt);
- } else
- LOG_SQLITE(handle,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sq_prepare");
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Invalid data in %s. Trying to fix (by deletion).\n"),
+ _("sqlite datastore"));
+ if (sq_prepare (dbh,
+ "DELETE FROM gn070 WHERE NOT ((LENGTH(hash) = ?) AND
(size = LENGTH(value) + ?))",
+ &stmt) == SQLITE_OK)
+ {
+ sqlite3_bind_int (stmt, 1, sizeof (HashCode512));
+ sqlite3_bind_int (stmt, 2, sizeof (Datastore_Value));
+ sqlite3_step (stmt);
+ sqlite3_finalize (stmt);
+ }
+ else
+ LOG_SQLITE (handle,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sq_prepare");
- return NULL;
- }
+ return NULL;
+ }
- datum = MALLOC(sizeof(Datastore_Datum) + contentSize);
+ datum = MALLOC (sizeof (Datastore_Datum) + contentSize);
value = &datum->value;
- value->size = htonl(contentSize + sizeof(Datastore_Value));
- value->type = htonl(type);
- value->prio = htonl(sqlite3_column_int(stmt, 2));
- value->anonymityLevel = htonl(sqlite3_column_int(stmt, 3));
- value->expirationTime = htonll(sqlite3_column_int64(stmt, 4));
- memcpy(&datum->key,
- sqlite3_column_blob(stmt, 5),
- sizeof(HashCode512));
- memcpy(&value[1],
- sqlite3_column_blob(stmt, 6),
- contentSize);
+ value->size = htonl (contentSize + sizeof (Datastore_Value));
+ value->type = htonl (type);
+ value->prio = htonl (sqlite3_column_int (stmt, 2));
+ value->anonymityLevel = htonl (sqlite3_column_int (stmt, 3));
+ value->expirationTime = htonll (sqlite3_column_int64 (stmt, 4));
+ memcpy (&datum->key, sqlite3_column_blob (stmt, 5), sizeof (HashCode512));
+ memcpy (&value[1], sqlite3_column_blob (stmt, 6), contentSize);
return datum;
}
@@ -440,40 +446,40 @@
* @param key kind of stat to retrieve
* @return SYSERR on error, the value otherwise
*/
-static unsigned long long getStat(sqliteHandle * handle,
- const char * key) {
+static unsigned long long
+getStat (sqliteHandle * handle, const char *key)
+{
int i;
sqlite3_stmt *stmt;
unsigned long long ret = SYSERR;
- i = sq_prepare(handle->dbh,
- "SELECT expire FROM gn070 WHERE hash = ?",
- &stmt);
- if (i == SQLITE_OK) {
- sqlite3_bind_text(stmt,
- 1,
- key,
- strlen(key),
- SQLITE_STATIC);
- i = sqlite3_step(stmt);
+ i = sq_prepare (handle->dbh,
+ "SELECT expire FROM gn070 WHERE hash = ?", &stmt);
+ if (i == SQLITE_OK)
+ {
+ sqlite3_bind_text (stmt, 1, key, strlen (key), SQLITE_STATIC);
+ i = sqlite3_step (stmt);
- if (i == SQLITE_DONE) {
- ret = 0;
- i = SQLITE_OK;
- } else if (i == SQLITE_ROW) {
- ret = sqlite3_column_int64(stmt, 0);
- i = SQLITE_OK;
+ if (i == SQLITE_DONE)
+ {
+ ret = 0;
+ i = SQLITE_OK;
+ }
+ else if (i == SQLITE_ROW)
+ {
+ ret = sqlite3_column_int64 (stmt, 0);
+ i = SQLITE_OK;
+ }
}
- }
- sqlite3_finalize(stmt);
+ sqlite3_finalize (stmt);
if (i == SQLITE_BUSY)
return SYSERR;
- if (i != SQLITE_OK) {
- LOG_SQLITE(handle,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_getStat");
- return SYSERR;
- }
+ if (i != SQLITE_OK)
+ {
+ LOG_SQLITE (handle,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sqlite_getStat");
+ return SYSERR;
+ }
return ret;
}
@@ -483,47 +489,36 @@
* @param val value to set
* @return SYSERR on error, OK otherwise
*/
-static int setStat(sqliteHandle * handle,
- const char *key,
- unsigned long long val) {
+static int
+setStat (sqliteHandle * handle, const char *key, unsigned long long val)
+{
sqlite3_stmt *stmt;
- sqlite3 * dbh;
+ sqlite3 *dbh;
dbh = handle->dbh;
- if (sq_prepare(dbh,
- "DELETE FROM gn070 where hash = ?", &stmt) == SQLITE_OK) {
- sqlite3_bind_text(stmt,
- 1,
- key,
- strlen(key),
- SQLITE_STATIC);
- sqlite3_step(stmt);
- sqlite3_finalize(stmt);
- }
+ if (sq_prepare (dbh,
+ "DELETE FROM gn070 where hash = ?", &stmt) == SQLITE_OK)
+ {
+ sqlite3_bind_text (stmt, 1, key, strlen (key), SQLITE_STATIC);
+ sqlite3_step (stmt);
+ sqlite3_finalize (stmt);
+ }
- if (sq_prepare(dbh,
- "INSERT INTO gn070(hash, expire, type) VALUES (?, ?, ?)",
- &stmt) != SQLITE_OK)
+ if (sq_prepare (dbh,
+ "INSERT INTO gn070(hash, expire, type) VALUES (?, ?, ?)",
+ &stmt) != SQLITE_OK)
return SYSERR;
- sqlite3_bind_text(stmt,
- 1,
- key,
- strlen(key),
- SQLITE_STATIC);
- sqlite3_bind_int64(stmt,
- 2,
- val);
- sqlite3_bind_int(stmt,
- 3,
- RESERVED_BLOCK);
- if (sqlite3_step(stmt) != SQLITE_DONE) {
- LOG_SQLITE(handle,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_setStat");
- sqlite3_finalize(stmt);
- return SYSERR;
- }
- sqlite3_finalize(stmt);
+ sqlite3_bind_text (stmt, 1, key, strlen (key), SQLITE_STATIC);
+ sqlite3_bind_int64 (stmt, 2, val);
+ sqlite3_bind_int (stmt, 3, RESERVED_BLOCK);
+ if (sqlite3_step (stmt) != SQLITE_DONE)
+ {
+ LOG_SQLITE (handle,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sqlite_setStat");
+ sqlite3_finalize (stmt);
+ return SYSERR;
+ }
+ sqlite3_finalize (stmt);
return OK;
}
@@ -531,10 +526,10 @@
/**
* @brief write all statistics to the db
*/
-static void syncStats(sqliteHandle * handle) {
- setStat(handle,
- "PAYLOAD",
- db->payload);
+static void
+syncStats (sqliteHandle * handle)
+{
+ setStat (handle, "PAYLOAD", db->payload);
db->lastSync = 0;
}
@@ -549,192 +544,180 @@
* @param sortByPriority 0 to order by expiration, 1 to order by prio
* @return the number of items stored in the content database
*/
-static int sqlite_iterate(unsigned int type,
- Datum_Iterator iter,
- void * closure,
- int sortByPriority,
- int inverseOrder,
- int include_expired,
- int limit_nonanonymous,
- int limit_ondemand) {
- sqlite3_stmt * stmt;
+static int
+sqlite_iterate (unsigned int type,
+ Datum_Iterator iter,
+ void *closure,
+ int sortByPriority,
+ int inverseOrder,
+ int include_expired,
+ int limit_nonanonymous, int limit_ondemand)
+{
+ sqlite3_stmt *stmt;
int count;
char scratch[512];
- Datastore_Datum * datum;
+ Datastore_Datum *datum;
unsigned int lastPrio;
unsigned long long lastExp;
HashCode512 key;
- sqlite3 * dbh;
- sqliteHandle * handle;
+ sqlite3 *dbh;
+ sqliteHandle *handle;
int ret;
cron_t now;
- handle = getDBHandle();
+ handle = getDBHandle ();
dbh = handle->dbh;
/* For the rowid trick see
- http://permalink.gmane.org/gmane.network.gnunet.devel/1363 */
- strcpy(scratch,
- "SELECT size, type, prio, anonLevel, expire, hash, value FROM gn070"
- " WHERE rowid IN (SELECT rowid FROM gn070"
- " WHERE ((hash > :1 AND expire == :2 AND prio == :3) OR ");
- if (sortByPriority) {
- if (inverseOrder)
- strcat(scratch,
- "(expire < :4 AND prio == :5) OR prio < :6)");
- else
- strcat(scratch,
- "(expire > :4 AND prio == :5) OR prio > :6)");
- } else {
- if (inverseOrder)
- strcat(scratch,
- "(prio < :4 AND expire == :5) OR expire < :6)");
- else
- strcat(scratch,
- "(prio > :4 AND expire == :5) OR expire > :6)");
- }
- if (type != 0) {
- strcat(scratch, " AND type = :7");
- } else if (limit_ondemand == YES) {
- SNPRINTF(&scratch[strlen(scratch)],
- 512 - strlen(scratch),
- " AND type != %d AND type != %d",
- RESERVED_BLOCK,
- ONDEMAND_BLOCK);
- } else {
- SNPRINTF(&scratch[strlen(scratch)],
- 512 - strlen(scratch),
- " AND type != %d",
- RESERVED_BLOCK); /* otherwise we iterate over
- the stats entry, which would
- be bad */
- }
- if (NO == include_expired) {
- if (type != 0)
- strcat(scratch, " AND expire > :8");
- else
- strcat(scratch, " AND expire > :7");
- }
- if (sortByPriority) {
- if (inverseOrder)
- strcat(scratch, " ORDER BY prio DESC, expire DESC, hash ASC");
- else
- strcat(scratch, " ORDER BY prio ASC, expire ASC, hash ASC");
- } else {
- if (inverseOrder)
- strcat(scratch, " ORDER BY expire DESC, prio DESC, hash ASC");
- else
- strcat(scratch, " ORDER BY expire ASC, prio ASC, hash ASC");
- }
- strcat(scratch, " LIMIT 1)");
- if (sq_prepare(dbh,
- scratch,
- &stmt) != SQLITE_OK) {
- LOG_SQLITE(handle,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite3_prepare");
- return SYSERR;
- }
- count = 0;
- if (inverseOrder) {
- lastPrio = 0x7FFFFFFF;
- lastExp = 0x7FFFFFFFFFFFFFFFLL;
- } else {
- lastPrio = 0;
- lastExp = 0;
- }
- memset(&key, 0, sizeof(HashCode512));
- while (1) {
- sqlite3_bind_blob(stmt,
- 1,
- &key,
- sizeof(HashCode512),
- SQLITE_TRANSIENT);
- sqlite3_bind_int64(stmt,
- 2,
- lastExp);
- sqlite3_bind_int(stmt,
- 3,
- lastPrio);
- if (sortByPriority) {
- sqlite3_bind_int64(stmt,
- 4,
- lastExp);
- sqlite3_bind_int(stmt,
- 5,
- lastPrio);
- sqlite3_bind_int(stmt,
- 6,
- lastPrio);
- } else {
- sqlite3_bind_int64(stmt,
- 4,
- lastExp);
- sqlite3_bind_int(stmt,
- 5,
- lastPrio);
- sqlite3_bind_int64(stmt,
- 6,
- lastExp);
+ http://permalink.gmane.org/gmane.network.gnunet.devel/1363 */
+ strcpy (scratch,
+ "SELECT size, type, prio, anonLevel, expire, hash, value FROM gn070"
+ " WHERE rowid IN (SELECT rowid FROM gn070"
+ " WHERE ((hash > :1 AND expire == :2 AND prio == :3) OR ");
+ if (sortByPriority)
+ {
+ if (inverseOrder)
+ strcat (scratch, "(expire < :4 AND prio == :5) OR prio < :6)");
+ else
+ strcat (scratch, "(expire > :4 AND prio == :5) OR prio > :6)");
}
- if (type)
- sqlite3_bind_int(stmt,
- 7,
- type);
- if (NO == include_expired) {
- now = get_time();
- if (type)
- sqlite3_bind_int64(stmt,
- 8,
- now);
+ else
+ {
+ if (inverseOrder)
+ strcat (scratch, "(prio < :4 AND expire == :5) OR expire < :6)");
else
- sqlite3_bind_int64(stmt,
- 7,
- now);
+ strcat (scratch, "(prio > :4 AND expire == :5) OR expire > :6)");
}
- if ((ret = sqlite3_step(stmt)) == SQLITE_ROW) {
- datum = assembleDatum(handle,
- stmt);
- sqlite3_reset(stmt);
- if (datum == NULL)
- continue;
+ if (type != 0)
+ {
+ strcat (scratch, " AND type = :7");
+ }
+ else if (limit_ondemand == YES)
+ {
+ SNPRINTF (&scratch[strlen (scratch)],
+ 512 - strlen (scratch),
+ " AND type != %d AND type != %d",
+ RESERVED_BLOCK, ONDEMAND_BLOCK);
+ }
+ else
+ {
+ SNPRINTF (&scratch[strlen (scratch)], 512 - strlen (scratch), " AND type
!= %d", RESERVED_BLOCK); /* otherwise we iterate over
+
the stats entry, which would
+
be bad */
+ }
+ if (NO == include_expired)
+ {
+ if (type != 0)
+ strcat (scratch, " AND expire > :8");
+ else
+ strcat (scratch, " AND expire > :7");
+ }
+ if (sortByPriority)
+ {
+ if (inverseOrder)
+ strcat (scratch, " ORDER BY prio DESC, expire DESC, hash ASC");
+ else
+ strcat (scratch, " ORDER BY prio ASC, expire ASC, hash ASC");
+ }
+ else
+ {
+ if (inverseOrder)
+ strcat (scratch, " ORDER BY expire DESC, prio DESC, hash ASC");
+ else
+ strcat (scratch, " ORDER BY expire ASC, prio ASC, hash ASC");
+ }
+ strcat (scratch, " LIMIT 1)");
+ if (sq_prepare (dbh, scratch, &stmt) != SQLITE_OK)
+ {
+ LOG_SQLITE (handle,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sqlite3_prepare");
+ return SYSERR;
+ }
+ count = 0;
+ if (inverseOrder)
+ {
+ lastPrio = 0x7FFFFFFF;
+ lastExp = 0x7FFFFFFFFFFFFFFFLL;
+ }
+ else
+ {
+ lastPrio = 0;
+ lastExp = 0;
+ }
+ memset (&key, 0, sizeof (HashCode512));
+ while (1)
+ {
+ sqlite3_bind_blob (stmt,
+ 1, &key, sizeof (HashCode512), SQLITE_TRANSIENT);
+ sqlite3_bind_int64 (stmt, 2, lastExp);
+ sqlite3_bind_int (stmt, 3, lastPrio);
+ if (sortByPriority)
+ {
+ sqlite3_bind_int64 (stmt, 4, lastExp);
+ sqlite3_bind_int (stmt, 5, lastPrio);
+ sqlite3_bind_int (stmt, 6, lastPrio);
+ }
+ else
+ {
+ sqlite3_bind_int64 (stmt, 4, lastExp);
+ sqlite3_bind_int (stmt, 5, lastPrio);
+ sqlite3_bind_int64 (stmt, 6, lastExp);
+ }
+ if (type)
+ sqlite3_bind_int (stmt, 7, type);
+ if (NO == include_expired)
+ {
+ now = get_time ();
+ if (type)
+ sqlite3_bind_int64 (stmt, 8, now);
+ else
+ sqlite3_bind_int64 (stmt, 7, now);
+ }
+ if ((ret = sqlite3_step (stmt)) == SQLITE_ROW)
+ {
+ datum = assembleDatum (handle, stmt);
+ sqlite3_reset (stmt);
+ if (datum == NULL)
+ continue;
#if 0
- printf("FOUND %4u prio %4u exp %20llu old: %4u, %20llu\n",
- (ntohl(datum->value.size) - sizeof(Datastore_Value)),
- ntohl(datum->value.prio),
- ntohll(datum->value.expirationTime),
- lastPrio,
- lastExp);
+ printf ("FOUND %4u prio %4u exp %20llu old: %4u, %20llu\n",
+ (ntohl (datum->value.size) - sizeof (Datastore_Value)),
+ ntohl (datum->value.prio),
+ ntohll (datum->value.expirationTime), lastPrio, lastExp);
#endif
- if ( (NO == limit_nonanonymous) ||
- (ntohl(datum->value.anonymityLevel) == 0) ) {
- count++;
- if (iter != NULL) {
- if (SYSERR == iter(&datum->key,
- &datum->value,
- closure) ) {
- FREE(datum);
- count = SYSERR;
- break;
+ if ((NO == limit_nonanonymous) ||
+ (ntohl (datum->value.anonymityLevel) == 0))
+ {
+ count++;
+ if (iter != NULL)
+ {
+ if (SYSERR == iter (&datum->key, &datum->value, closure))
+ {
+ FREE (datum);
+ count = SYSERR;
+ break;
+ }
+ }
+ }
+ key = datum->key;
+ lastPrio = ntohl (datum->value.prio);
+ lastExp = ntohll (datum->value.expirationTime);
+ FREE (datum);
+ }
+ else
+ {
+ if (ret != SQLITE_DONE)
+ {
+ LOG_SQLITE (handle,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "sqlite_query");
+ sqlite3_finalize (stmt);
+ return SYSERR;
+ }
+ sqlite3_reset (stmt);
+ break;
+ }
}
- }
- }
- key = datum->key;
- lastPrio = ntohl(datum->value.prio);
- lastExp = ntohll(datum->value.expirationTime);
- FREE(datum);
- } else {
- if (ret != SQLITE_DONE) {
- LOG_SQLITE(handle,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_query");
- sqlite3_finalize(stmt);
- return SYSERR;
- }
- sqlite3_reset(stmt);
- break;
- }
- }
- sqlite3_finalize(stmt);
+ sqlite3_finalize (stmt);
return count;
}
@@ -749,10 +732,10 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateLowPriority(unsigned int type,
- Datum_Iterator iter,
- void * closure) {
- return sqlite_iterate(type, iter, closure, YES, NO, YES, NO, NO);
+static int
+iterateLowPriority (unsigned int type, Datum_Iterator iter, void *closure)
+{
+ return sqlite_iterate (type, iter, closure, YES, NO, YES, NO, NO);
}
/**
@@ -767,11 +750,11 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateNonAnonymous(unsigned int type,
- int on_demand,
- Datum_Iterator iter,
- void * closure) {
- return sqlite_iterate(0, iter, closure, NO, NO, NO, YES, on_demand);
+static int
+iterateNonAnonymous (unsigned int type,
+ int on_demand, Datum_Iterator iter, void *closure)
+{
+ return sqlite_iterate (0, iter, closure, NO, NO, NO, YES, on_demand);
}
/**
@@ -783,10 +766,10 @@
* @param data second argument to all callback calls
* @return the number of items stored in the content database
*/
-static int iterateExpirationTime(unsigned int type,
- Datum_Iterator iter,
- void * closure) {
- return sqlite_iterate(type, iter, closure, NO, NO, YES, NO, NO);
+static int
+iterateExpirationTime (unsigned int type, Datum_Iterator iter, void *closure)
+{
+ return sqlite_iterate (type, iter, closure, NO, NO, YES, NO, NO);
}
/**
@@ -797,9 +780,10 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int iterateMigrationOrder(Datum_Iterator iter,
- void * closure) {
- return sqlite_iterate(0, iter, closure, NO, YES, NO, NO, NO);
+static int
+iterateMigrationOrder (Datum_Iterator iter, void *closure)
+{
+ return sqlite_iterate (0, iter, closure, NO, YES, NO, NO, NO);
}
/**
@@ -811,105 +795,107 @@
* @param data second argument to all callback calls
* @return the number of items stored in the content database
*/
-static int iterateAllNow(Datum_Iterator iter,
- void * closure) {
- sqlite3_stmt * stmt;
+static int
+iterateAllNow (Datum_Iterator iter, void *closure)
+{
+ sqlite3_stmt *stmt;
int count;
- Datastore_Datum * datum;
- sqlite3 * dbh;
- sqliteHandle * handle;
+ Datastore_Datum *datum;
+ sqlite3 *dbh;
+ sqliteHandle *handle;
int ret;
unsigned long long payload;
payload = 0;
- handle = getDBHandle();
+ handle = getDBHandle ();
dbh = handle->dbh;
/* For the rowid trick see
- http://permalink.gmane.org/gmane.network.gnunet.devel/1363 */
- if (sq_prepare(dbh,
- "SELECT size, type, prio, anonLevel, expire, hash, value FROM gn070",
- &stmt) != SQLITE_OK) {
- LOG_SQLITE(handle,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite3_prepare");
- return SYSERR;
- }
+ http://permalink.gmane.org/gmane.network.gnunet.devel/1363 */
+ if (sq_prepare (dbh,
+ "SELECT size, type, prio, anonLevel, expire, hash, value
FROM gn070",
+ &stmt) != SQLITE_OK)
+ {
+ LOG_SQLITE (handle,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sqlite3_prepare");
+ return SYSERR;
+ }
count = 0;
- while ((ret = sqlite3_step(stmt)) == SQLITE_ROW) {
- datum = assembleDatum(handle,
- stmt);
- if (datum == NULL)
- continue;
- payload += getContentDatastoreSize(&datum->value);
- if (iter != NULL) {
- if (SYSERR == iter(&datum->key,
- &datum->value,
- closure) ) {
- FREE(datum);
- count = SYSERR;
- break;
- }
+ while ((ret = sqlite3_step (stmt)) == SQLITE_ROW)
+ {
+ datum = assembleDatum (handle, stmt);
+ if (datum == NULL)
+ continue;
+ payload += getContentDatastoreSize (&datum->value);
+ if (iter != NULL)
+ {
+ if (SYSERR == iter (&datum->key, &datum->value, closure))
+ {
+ FREE (datum);
+ count = SYSERR;
+ break;
+ }
+ }
+ FREE (datum);
+ count++;
}
- FREE(datum);
- count++;
- }
- if (ret != SQLITE_DONE) {
- LOG_SQLITE(handle,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_query");
- sqlite3_finalize(stmt);
- return SYSERR;
- }
- sqlite3_finalize(stmt);
- if (count != SYSERR) {
- /* re-computed payload! */
- GE_LOG(ectx,
- GE_INFO | GE_IMMEDIATE | GE_USER | GE_ADMIN,
- "SQLite database size recomputed. New estimate is %llu, old estimate was
%llu\n",
- payload,
- db->payload);
- db->payload = payload;
- syncStats(handle);
- }
+ if (ret != SQLITE_DONE)
+ {
+ LOG_SQLITE (handle,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sqlite_query");
+ sqlite3_finalize (stmt);
+ return SYSERR;
+ }
+ sqlite3_finalize (stmt);
+ if (count != SYSERR)
+ {
+ /* re-computed payload! */
+ GE_LOG (ectx,
+ GE_INFO | GE_IMMEDIATE | GE_USER | GE_ADMIN,
+ "SQLite database size recomputed. New estimate is %llu, old
estimate was %llu\n",
+ payload, db->payload);
+ db->payload = payload;
+ syncStats (handle);
+ }
return count;
}
-static void sqlite_shutdown() {
+static void
+sqlite_shutdown ()
+{
unsigned int idx;
#if DEBUG_SQLITE
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite: closing database\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "SQLite: closing database\n");
#endif
- if (! db)
+ if (!db)
return;
- syncStats(getDBHandle());
+ syncStats (getDBHandle ());
- for (idx = 0; idx < db->handle_count; idx++) {
- sqliteHandle * h = db->handles[idx];
+ for (idx = 0; idx < db->handle_count; idx++)
+ {
+ sqliteHandle *h = db->handles[idx];
- PTHREAD_REL_SELF(h->tid);
- sqlite3_finalize(h->countContent);
- sqlite3_finalize(h->exists);
- sqlite3_finalize(h->updPrio);
- sqlite3_finalize(h->insertContent);
- if (sqlite3_close(h->dbh) != SQLITE_OK)
- LOG_SQLITE(h,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_close");
- FREE(h);
- }
- FREE(db->handles);
+ PTHREAD_REL_SELF (h->tid);
+ sqlite3_finalize (h->countContent);
+ sqlite3_finalize (h->exists);
+ sqlite3_finalize (h->updPrio);
+ sqlite3_finalize (h->insertContent);
+ if (sqlite3_close (h->dbh) != SQLITE_OK)
+ LOG_SQLITE (h,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sqlite_close");
+ FREE (h);
+ }
+ FREE (db->handles);
db->handle_count = 0;
- MUTEX_DESTROY(db->DATABASE_Lock_);
- FREE(db->fn);
- FREE(db);
+ MUTEX_DESTROY (db->DATABASE_Lock_);
+ FREE (db->fn);
+ FREE (db);
db = NULL;
}
@@ -917,11 +903,13 @@
* Delete the database. The next operation is
* guaranteed to be unloading of the module.
*/
-static void drop() {
- char *fn = STRDUP(db->fn);
- sqlite_shutdown();
- UNLINK(fn);
- FREE(fn);
+static void
+drop ()
+{
+ char *fn = STRDUP (db->fn);
+ sqlite_shutdown ();
+ UNLINK (fn);
+ FREE (fn);
}
@@ -936,133 +924,128 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
-static int get(const HashCode512 * key,
- unsigned int type,
- Datum_Iterator iter,
- void * closure) {
+static int
+get (const HashCode512 * key,
+ unsigned int type, Datum_Iterator iter, void *closure)
+{
int ret, count = 0;
sqlite3_stmt *stmt;
char scratch[256];
int bind = 1;
Datastore_Datum *datum;
- sqlite3 * dbh;
- sqliteHandle * handle;
+ sqlite3 *dbh;
+ sqliteHandle *handle;
#if DEBUG_SQLITE
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(key,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite: retrieving content `%s'\n",
- &enc);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (key, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "SQLite: retrieving content `%s'\n", &enc);
#endif
- handle = getDBHandle();
+ handle = getDBHandle ();
dbh = handle->dbh;
- strcpy(scratch, "SELECT ");
+ strcpy (scratch, "SELECT ");
if (iter == NULL)
- strcat(scratch, "count(*)");
+ strcat (scratch, "count(*)");
else
- strcat(scratch, "size, type, prio, anonLevel, expire, hash, value");
- strcat(scratch, " FROM gn070");
+ strcat (scratch, "size, type, prio, anonLevel, expire, hash, value");
+ strcat (scratch, " FROM gn070");
- if (type || key) {
- strcat(scratch, " WHERE ");
- if (type) {
- strcat(scratch, "type = :1");
+ if (type || key)
+ {
+ strcat (scratch, " WHERE ");
+ if (type)
+ {
+ strcat (scratch, "type = :1");
+ if (key)
+ strcat (scratch, " and ");
+ }
if (key)
- strcat(scratch, " and ");
+ strcat (scratch, "hash = :2");
}
- if (key)
- strcat(scratch, "hash = :2");
- }
- strcat(scratch, " ORDER BY expire DESC");
+ strcat (scratch, " ORDER BY expire DESC");
- if (sq_prepare(dbh,
- scratch,
- &stmt) != SQLITE_OK) {
- LOG_SQLITE(handle,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_query");
- return SYSERR;
- }
+ if (sq_prepare (dbh, scratch, &stmt) != SQLITE_OK)
+ {
+ LOG_SQLITE (handle,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sqlite_query");
+ return SYSERR;
+ }
if (type)
- ret = sqlite3_bind_int(stmt,
- bind++,
- type);
+ ret = sqlite3_bind_int (stmt, bind++, type);
else
ret = SQLITE_OK;
- if (key && (ret == SQLITE_OK)) {
- ret = sqlite3_bind_blob(stmt,
- bind,
- key,
- sizeof(HashCode512),
- SQLITE_TRANSIENT);
- }
+ if (key && (ret == SQLITE_OK))
+ {
+ ret = sqlite3_bind_blob (stmt,
+ bind,
+ key, sizeof (HashCode512), SQLITE_TRANSIENT);
+ }
- if (ret == SQLITE_OK) {
- while ((ret = sqlite3_step(stmt)) == SQLITE_ROW) {
- if (iter != NULL) {
- datum = assembleDatum(handle,
- stmt);
+ if (ret == SQLITE_OK)
+ {
+ while ((ret = sqlite3_step (stmt)) == SQLITE_ROW)
+ {
+ if (iter != NULL)
+ {
+ datum = assembleDatum (handle, stmt);
- if (datum == NULL)
- continue;
- if ( (key != NULL) &&
- (0 != memcmp(&datum->key,
- key,
- sizeof(HashCode512))) ) {
- GE_BREAK(NULL, 0);
- FREE(datum);
- continue;
- }
+ if (datum == NULL)
+ continue;
+ if ((key != NULL) &&
+ (0 != memcmp (&datum->key, key, sizeof (HashCode512))))
+ {
+ GE_BREAK (NULL, 0);
+ FREE (datum);
+ continue;
+ }
#if DEBUG_SQLITE
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Found in database block with type %u.\n",
- ntohl(*(int*)&((&datum->value)[1])));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Found in database block with type %u.\n",
+ ntohl (*(int *) &((&datum->value)[1])));
#endif
- if (SYSERR == iter(&datum->key,
- &datum->value,
- closure) ) {
+ if (SYSERR == iter (&datum->key, &datum->value, closure))
+ {
- count = SYSERR;
- FREE(datum);
- ret = SQLITE_DONE;
- break;
- }
- FREE(datum);
- count++;
- } else
- count += sqlite3_column_int(stmt, 0);
+ count = SYSERR;
+ FREE (datum);
+ ret = SQLITE_DONE;
+ break;
+ }
+ FREE (datum);
+ count++;
+ }
+ else
+ count += sqlite3_column_int (stmt, 0);
+ }
+ if (ret == SQLITE_BUSY)
+ {
+ sqlite3_finalize (stmt);
+ return count;
+ }
+ if (ret != SQLITE_DONE)
+ {
+ LOG_SQLITE (handle,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "sqlite_query");
+ sqlite3_finalize (stmt);
+ return SYSERR;
+ }
+
+ sqlite3_finalize (stmt);
}
- if (ret == SQLITE_BUSY) {
- sqlite3_finalize(stmt);
- return count;
- }
- if (ret != SQLITE_DONE) {
- LOG_SQLITE(handle,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_query");
- sqlite3_finalize(stmt);
- return SYSERR;
- }
+ else
+ LOG_SQLITE (handle,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sqlite_query");
- sqlite3_finalize(stmt);
- } else
- LOG_SQLITE(handle,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_query");
-
#if DEBUG_SQLITE
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite: done reading content\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "SQLite: done reading content\n");
#endif
return count;
@@ -1074,8 +1057,9 @@
*
* @return SYSERR on error, NO on temporary error, OK if ok.
*/
-static int put(const HashCode512 * key,
- const Datastore_Value * value) {
+static int
+put (const HashCode512 * key, const Datastore_Value * value)
+{
int n;
sqlite3_stmt *stmt;
unsigned int contentSize;
@@ -1085,59 +1069,55 @@
#if DEBUG_SQLITE
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- hash2enc(key,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- "Storing in database block with type %u/key `%s'/priority %u/expiration
%llu.\n",
- ntohl(*(int*)&value[1]),
- &enc,
- ntohl(value->prio),
- ntohll(value->expirationTime));
+ IF_GELOG (ectx, GE_DEBUG | GE_BULK | GE_USER, hash2enc (key, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_BULK | GE_USER,
+ "Storing in database block with type %u/key `%s'/priority
%u/expiration %llu.\n",
+ ntohl (*(int *) &value[1]),
+ &enc, ntohl (value->prio), ntohll (value->expirationTime));
#endif
- if ( (ntohl(value->size) < sizeof(Datastore_Value)) ) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- dbh = getDBHandle();
+ if ((ntohl (value->size) < sizeof (Datastore_Value)))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ dbh = getDBHandle ();
if (db->lastSync > 1000)
- syncStats(dbh);
- contentSize = ntohl(value->size)-sizeof(Datastore_Value);
+ syncStats (dbh);
+ contentSize = ntohl (value->size) - sizeof (Datastore_Value);
stmt = dbh->insertContent;
- size = ntohl(value->size);
- type = ntohl(value->type);
- prio = ntohl(value->prio);
- anon = ntohl(value->anonymityLevel);
- expir = ntohll(value->expirationTime);
- sqlite3_bind_int(stmt, 1, size);
- sqlite3_bind_int(stmt, 2, type);
- sqlite3_bind_int(stmt, 3, prio);
- sqlite3_bind_int(stmt, 4, anon);
- sqlite3_bind_int64(stmt, 5, expir);
- sqlite3_bind_blob(stmt, 6, key, sizeof(HashCode512), SQLITE_TRANSIENT);
- sqlite3_bind_blob(stmt, 7, &value[1], contentSize, SQLITE_TRANSIENT);
- n = sqlite3_step(stmt);
- if (n != SQLITE_DONE) {
- if (n == SQLITE_BUSY) {
- sqlite3_reset(stmt);
- return NO;
+ size = ntohl (value->size);
+ type = ntohl (value->type);
+ prio = ntohl (value->prio);
+ anon = ntohl (value->anonymityLevel);
+ expir = ntohll (value->expirationTime);
+ sqlite3_bind_int (stmt, 1, size);
+ sqlite3_bind_int (stmt, 2, type);
+ sqlite3_bind_int (stmt, 3, prio);
+ sqlite3_bind_int (stmt, 4, anon);
+ sqlite3_bind_int64 (stmt, 5, expir);
+ sqlite3_bind_blob (stmt, 6, key, sizeof (HashCode512), SQLITE_TRANSIENT);
+ sqlite3_bind_blob (stmt, 7, &value[1], contentSize, SQLITE_TRANSIENT);
+ n = sqlite3_step (stmt);
+ if (n != SQLITE_DONE)
+ {
+ if (n == SQLITE_BUSY)
+ {
+ sqlite3_reset (stmt);
+ return NO;
+ }
+ LOG_SQLITE (dbh,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sqlite_query");
+ sqlite3_reset (stmt);
+ return SYSERR;
}
- LOG_SQLITE(dbh,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_query");
- sqlite3_reset(stmt);
- return SYSERR;
- }
- sqlite3_reset(stmt);
+ sqlite3_reset (stmt);
db->lastSync++;
- db->payload += getContentDatastoreSize(value);
+ db->payload += getContentDatastoreSize (value);
#if DEBUG_SQLITE
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite: done writing content\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "SQLite: done writing content\n");
#endif
return OK;
}
@@ -1150,13 +1130,14 @@
* @return the number of items deleted, 0 if
* none were found, SYSERR on errors
*/
-static int del(const HashCode512 * key,
- const Datastore_Value * value) {
+static int
+del (const HashCode512 * key, const Datastore_Value * value)
+{
size_t n;
sqlite3_stmt *stmt;
int deleted;
sqliteHandle *dbh;
- Datastore_Datum * dvalue;
+ Datastore_Datum *dvalue;
unsigned int size;
unsigned int type;
unsigned int prio;
@@ -1166,99 +1147,101 @@
#if DEBUG_SQLITE
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(key,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite: deleting block with key `%s'\n",
- &enc);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (key, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "SQLite: deleting block with key `%s'\n", &enc);
#endif
- dbh = getDBHandle();
+ dbh = getDBHandle ();
if (db->lastSync > 1000)
- syncStats(dbh);
+ syncStats (dbh);
- if (NULL == value) {
- if (sq_prepare(dbh->dbh,
- "SELECT size, type, prio, anonLevel, expire, hash, value "
- "FROM gn070 WHERE hash = ? ORDER BY prio ASC",
- &stmt) != SQLITE_OK) {
- LOG_SQLITE(dbh,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_query");
- return SYSERR;
+ if (NULL == value)
+ {
+ if (sq_prepare (dbh->dbh,
+ "SELECT size, type, prio, anonLevel, expire, hash, value
"
+ "FROM gn070 WHERE hash = ? ORDER BY prio ASC",
+ &stmt) != SQLITE_OK)
+ {
+ LOG_SQLITE (dbh,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "sqlite_query");
+ return SYSERR;
+ }
+ sqlite3_bind_blob (stmt,
+ 1, key, sizeof (HashCode512), SQLITE_TRANSIENT);
+ if (sqlite3_step (stmt) != SQLITE_ROW)
+ {
+ sqlite3_finalize (stmt);
+ return NO;
+ }
+ dvalue = assembleDatum (dbh, stmt);
+ if (dvalue == NULL)
+ {
+ sqlite3_finalize (stmt);
+ return SYSERR;
+ }
+ sqlite3_finalize (stmt);
+ value = &dvalue->value;
}
- sqlite3_bind_blob(stmt,
- 1,
- key,
- sizeof(HashCode512),
- SQLITE_TRANSIENT);
- if (sqlite3_step(stmt) != SQLITE_ROW) {
- sqlite3_finalize(stmt);
- return NO;
+ else
+ {
+ dvalue = NULL;
}
- dvalue = assembleDatum(dbh,
- stmt);
- if (dvalue == NULL) {
- sqlite3_finalize(stmt);
- return SYSERR;
+ contentSize = ntohl (value->size) - sizeof (Datastore_Value);
+ n = sq_prepare (dbh->dbh, "DELETE FROM gn070 WHERE hash = ? and " "value = ?
AND size = ? AND type = ? AND prio = ? AND anonLevel = ? " "AND expire = ?",
/* ORDER BY prio ASC LIMIT 1" -- not available in sqlite */
+ &stmt);
+ if (n == SQLITE_OK)
+ {
+ size = ntohl (value->size);
+ type = ntohl (value->type);
+ prio = ntohl (value->prio);
+ anon = ntohl (value->anonymityLevel);
+ expir = ntohll (value->expirationTime);
+
+ sqlite3_bind_blob (stmt, 1, key, sizeof (HashCode512),
+ SQLITE_TRANSIENT);
+ sqlite3_bind_blob (stmt, 2, &value[1], contentSize, SQLITE_TRANSIENT);
+ sqlite3_bind_int (stmt, 3, size);
+ sqlite3_bind_int (stmt, 4, type);
+ sqlite3_bind_int (stmt, 5, prio);
+ sqlite3_bind_int (stmt, 6, anon);
+ sqlite3_bind_int64 (stmt, 7, expir);
+ n = sqlite3_step (stmt);
+ if ((n == SQLITE_DONE) || (n == SQLITE_ROW))
+ db->payload -= getContentDatastoreSize (value);
}
- sqlite3_finalize(stmt);
- value = &dvalue->value;
- } else {
- dvalue = NULL;
- }
- contentSize = ntohl(value->size)-sizeof(Datastore_Value);
- n = sq_prepare(dbh->dbh,
- "DELETE FROM gn070 WHERE hash = ? and "
- "value = ? AND size = ? AND type = ? AND prio = ? AND anonLevel = ? "
- "AND expire = ?", /* ORDER BY prio ASC LIMIT 1" -- not available in
sqlite */
- &stmt);
- if (n == SQLITE_OK) {
- size = ntohl(value->size);
- type = ntohl(value->type);
- prio = ntohl(value->prio);
- anon = ntohl(value->anonymityLevel);
- expir = ntohll(value->expirationTime);
+ else
+ {
+ LOG_SQLITE (dbh,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sqlite3_prepare");
+ }
+ FREENONNULL (dvalue);
+ deleted = ((n == SQLITE_DONE)
+ || (n == SQLITE_ROW)) ? sqlite3_changes (dbh->dbh) : SYSERR;
+ sqlite3_finalize (stmt);
- sqlite3_bind_blob(stmt, 1, key, sizeof(HashCode512), SQLITE_TRANSIENT);
- sqlite3_bind_blob(stmt, 2, &value[1], contentSize, SQLITE_TRANSIENT);
- sqlite3_bind_int(stmt, 3, size);
- sqlite3_bind_int(stmt, 4, type);
- sqlite3_bind_int(stmt, 5, prio);
- sqlite3_bind_int(stmt, 6, anon);
- sqlite3_bind_int64(stmt, 7, expir);
- n = sqlite3_step(stmt);
- if ( (n == SQLITE_DONE) || (n == SQLITE_ROW) )
- db->payload -= getContentDatastoreSize(value);
- } else {
- LOG_SQLITE(dbh,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite3_prepare");
- }
- FREENONNULL(dvalue);
- deleted = ( (n == SQLITE_DONE) || (n == SQLITE_ROW) ) ?
sqlite3_changes(dbh->dbh) : SYSERR;
- sqlite3_finalize(stmt);
-
- if (n != SQLITE_DONE) {
- if (n != SQLITE_BUSY) {
- LOG_SQLITE(dbh,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_query");
- return SYSERR;
- } else {
- return NO;
+ if (n != SQLITE_DONE)
+ {
+ if (n != SQLITE_BUSY)
+ {
+ LOG_SQLITE (dbh,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "sqlite_query");
+ return SYSERR;
+ }
+ else
+ {
+ return NO;
+ }
}
- }
db->lastSync++;
#if DEBUG_SQLITE
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite: %d block(s) deleted\n",
- deleted);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "SQLite: %d block(s) deleted\n", deleted);
#endif
return deleted;
@@ -1268,58 +1251,38 @@
* Update the priority for a particular key
* in the datastore.
*/
-static int update(const HashCode512 * key,
- const Datastore_Value * value,
- int delta,
- cron_t expire) {
+static int
+update (const HashCode512 * key,
+ const Datastore_Value * value, int delta, cron_t expire)
+{
int n;
unsigned long contentSize;
sqliteHandle *dbh;
#if DEBUG_SQLITE
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(key,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite: updating block with key `%s'\n",
- &enc);
+ IF_GELOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, hash2enc (key, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "SQLite: updating block with key `%s'\n", &enc);
#endif
- dbh = getDBHandle();
- contentSize = ntohl(value->size)-sizeof(Datastore_Value);
- sqlite3_bind_int(dbh->updPrio,
- 1,
- delta);
- sqlite3_bind_int64(dbh->updPrio,
- 2,
- expire);
- sqlite3_bind_blob(dbh->updPrio,
- 3,
- key,
- sizeof(HashCode512),
- SQLITE_TRANSIENT);
- sqlite3_bind_blob(dbh->updPrio,
- 4,
- &value[1],
- contentSize,
- SQLITE_TRANSIENT);
- sqlite3_bind_int(dbh->updPrio,
- 5,
- delta);
- sqlite3_bind_int(dbh->updPrio,
- 6,
- MAX_PRIO);
+ dbh = getDBHandle ();
+ contentSize = ntohl (value->size) - sizeof (Datastore_Value);
+ sqlite3_bind_int (dbh->updPrio, 1, delta);
+ sqlite3_bind_int64 (dbh->updPrio, 2, expire);
+ sqlite3_bind_blob (dbh->updPrio,
+ 3, key, sizeof (HashCode512), SQLITE_TRANSIENT);
+ sqlite3_bind_blob (dbh->updPrio,
+ 4, &value[1], contentSize, SQLITE_TRANSIENT);
+ sqlite3_bind_int (dbh->updPrio, 5, delta);
+ sqlite3_bind_int (dbh->updPrio, 6, MAX_PRIO);
- n = sqlite3_step(dbh->updPrio);
- sqlite3_reset(dbh->updPrio);
+ n = sqlite3_step (dbh->updPrio);
+ sqlite3_reset (dbh->updPrio);
#if DEBUG_SQLITE
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite: block updated\n");
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, "SQLite: block updated\n");
#endif
if (n == SQLITE_BUSY)
return NO;
@@ -1327,7 +1290,8 @@
}
SQstore_ServiceAPI *
-provide_module_sqstore_sqlite(CoreAPIForApplication * capi) {
+provide_module_sqstore_sqlite (CoreAPIForApplication * capi)
+{
static SQstore_ServiceAPI api;
char *dir;
@@ -1336,63 +1300,60 @@
ectx = capi->ectx;
#if DEBUG_SQLITE
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite: initializing database\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "SQLite: initializing database\n");
#endif
- db = MALLOC(sizeof(sqliteDatabase));
- memset(db,
- 0,
- sizeof(sqliteDatabase));
+ db = MALLOC (sizeof (sqliteDatabase));
+ memset (db, 0, sizeof (sqliteDatabase));
db->payload = 0;
db->lastSync = 0;
afsdir = NULL;
- GC_get_configuration_value_filename(capi->cfg,
- "FS",
- "DIR",
- VAR_DAEMON_DIRECTORY "/data/fs/",
- &afsdir);
- dir = MALLOC(strlen(afsdir) + strlen("/content/gnunet.dat") + 2);
- strcpy(dir, afsdir);
- strcat(dir, "/content/gnunet.dat");
- FREE(afsdir);
- if (OK != disk_directory_create_for_file(ectx,
- dir)) {
- GE_BREAK(ectx, 0);
- FREE(dir);
- FREE(db);
- return NULL;
- }
- db->DATABASE_Lock_ = MUTEX_CREATE(NO);
+ GC_get_configuration_value_filename (capi->cfg,
+ "FS",
+ "DIR",
+ VAR_DAEMON_DIRECTORY "/data/fs/",
+ &afsdir);
+ dir = MALLOC (strlen (afsdir) + strlen ("/content/gnunet.dat") + 2);
+ strcpy (dir, afsdir);
+ strcat (dir, "/content/gnunet.dat");
+ FREE (afsdir);
+ if (OK != disk_directory_create_for_file (ectx, dir))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (dir);
+ FREE (db);
+ return NULL;
+ }
+ db->DATABASE_Lock_ = MUTEX_CREATE (NO);
db->fn = dir;
- dbh = getDBHandle();
- if (dbh == NULL) {
- GE_BREAK(ectx, 0);
- MUTEX_DESTROY(db->DATABASE_Lock_);
- FREE(db->fn);
- FREE(db);
- return NULL;
- }
+ dbh = getDBHandle ();
+ if (dbh == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ MUTEX_DESTROY (db->DATABASE_Lock_);
+ FREE (db->fn);
+ FREE (db);
+ return NULL;
+ }
- db->payload = getStat(dbh, "PAYLOAD");
- if (db->payload == SYSERR) {
- GE_BREAK(ectx, 0);
- LOG_SQLITE(dbh,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "sqlite_payload");
- MUTEX_DESTROY(db->DATABASE_Lock_);
- FREE(db->fn);
- FREE(db);
- return NULL;
- }
+ db->payload = getStat (dbh, "PAYLOAD");
+ if (db->payload == SYSERR)
+ {
+ GE_BREAK (ectx, 0);
+ LOG_SQLITE (dbh,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "sqlite_payload");
+ MUTEX_DESTROY (db->DATABASE_Lock_);
+ FREE (db->fn);
+ FREE (db);
+ return NULL;
+ }
coreAPI = capi;
- stats = coreAPI->requestService("stats");
+ stats = coreAPI->requestService ("stats");
if (stats)
- stat_size
- = stats->create(gettext_noop("# bytes in datastore"));
+ stat_size = stats->create (gettext_noop ("# bytes in datastore"));
api.getSize = &getSize;
api.put = &put;
@@ -1411,14 +1372,15 @@
/**
* Shutdown the module.
*/
-void release_module_sqstore_sqlite() {
+void
+release_module_sqstore_sqlite ()
+{
if (stats != NULL)
- coreAPI->releaseService(stats);
- sqlite_shutdown();
+ coreAPI->releaseService (stats);
+ sqlite_shutdown ();
#if DEBUG_SQLITE
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SQLite: database shutdown\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "SQLite: database shutdown\n");
#endif
coreAPI = NULL;
}
@@ -1430,44 +1392,45 @@
*
* Currently only makes sure that the sqlite indices are created.
*/
-void update_module_sqstore_sqlite(UpdateAPI * uapi) {
+void
+update_module_sqstore_sqlite (UpdateAPI * uapi)
+{
sqliteHandle *dbh;
char *dir;
char *afsdir;
- db = MALLOC(sizeof(sqliteDatabase));
- memset(db,
- 0,
- sizeof(sqliteDatabase));
+ db = MALLOC (sizeof (sqliteDatabase));
+ memset (db, 0, sizeof (sqliteDatabase));
db->payload = 0;
db->lastSync = 0;
afsdir = NULL;
- GC_get_configuration_value_filename(uapi->cfg,
- "FS",
- "DIR",
- VAR_DAEMON_DIRECTORY "/data/fs/",
- &afsdir);
- dir = MALLOC(strlen(afsdir) + 8 + 2); /* 8 = "content/" */
- strcpy(dir, afsdir);
- strcat(dir, "/content/");
- FREE(afsdir);
- if (OK != disk_directory_create(ectx,
- dir)) {
- FREE(dir);
- FREE(db);
- return;
- }
+ GC_get_configuration_value_filename (uapi->cfg,
+ "FS",
+ "DIR",
+ VAR_DAEMON_DIRECTORY "/data/fs/",
+ &afsdir);
+ dir = MALLOC (strlen (afsdir) + 8 + 2); /* 8 = "content/" */
+ strcpy (dir, afsdir);
+ strcat (dir, "/content/");
+ FREE (afsdir);
+ if (OK != disk_directory_create (ectx, dir))
+ {
+ FREE (dir);
+ FREE (db);
+ return;
+ }
db->fn = dir;
- db->DATABASE_Lock_ = MUTEX_CREATE(NO);
- dbh = getDBHandle();
- if (dbh == NULL) {
- MUTEX_DESTROY(db->DATABASE_Lock_);
- FREE(db->fn);
- FREE(db);
- return;
- }
- createIndices(dbh->dbh);
- sqlite_shutdown();
+ db->DATABASE_Lock_ = MUTEX_CREATE (NO);
+ dbh = getDBHandle ();
+ if (dbh == NULL)
+ {
+ MUTEX_DESTROY (db->DATABASE_Lock_);
+ FREE (db->fn);
+ FREE (db);
+ return;
+ }
+ createIndices (dbh->dbh);
+ sqlite_shutdown ();
}
/* end of sqlite.c */
Modified: GNUnet/src/applications/sqstore_sqlite/sqlitetest.c
===================================================================
--- GNUnet/src/applications/sqstore_sqlite/sqlitetest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/sqstore_sqlite/sqlitetest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -35,101 +35,104 @@
static cron_t now;
-static Datastore_Value * initValue(int i) {
- Datastore_Value * value;
+static Datastore_Value *
+initValue (int i)
+{
+ Datastore_Value *value;
- value = MALLOC(sizeof(Datastore_Value) + 8 * i);
- value->size = htonl(sizeof(Datastore_Value) + 8 * i);
- value->type = htonl(i);
- value->prio = htonl(i+1);
- value->anonymityLevel = htonl(i);
- value->expirationTime = htonll(now - i * cronSECONDS);
- memset(&value[1], i, 8*i);
+ value = MALLOC (sizeof (Datastore_Value) + 8 * i);
+ value->size = htonl (sizeof (Datastore_Value) + 8 * i);
+ value->type = htonl (i);
+ value->prio = htonl (i + 1);
+ value->anonymityLevel = htonl (i);
+ value->expirationTime = htonll (now - i * cronSECONDS);
+ memset (&value[1], i, 8 * i);
return value;
}
-static int checkValue(const HashCode512 * key,
- const Datastore_Value * val,
- void * closure) {
+static int
+checkValue (const HashCode512 * key,
+ const Datastore_Value * val, void *closure)
+{
int i;
int ret;
- Datastore_Value * value;
+ Datastore_Value *value;
- i = *(int*) closure;
- value = initValue(i);
- if ( ( value->size == val->size) &&
- (0 == memcmp(val,
- value,
- ntohl(val->size)) ) )
+ i = *(int *) closure;
+ value = initValue (i);
+ if ((value->size == val->size) &&
+ (0 == memcmp (val, value, ntohl (val->size))))
ret = OK;
- else {
- /*
- printf("Wanted: %u, %llu; got %u, %llu - %d\n",
- ntohl(value->size), ntohll(value->expirationTime),
- ntohl(val->size), ntohll(val->expirationTime),
- memcmp(val, value, ntohl(val->size))); */
- ret = SYSERR;
- }
- FREE(value);
+ else
+ {
+ /*
+ printf("Wanted: %u, %llu; got %u, %llu - %d\n",
+ ntohl(value->size), ntohll(value->expirationTime),
+ ntohl(val->size), ntohll(val->expirationTime),
+ memcmp(val, value, ntohl(val->size))); */
+ ret = SYSERR;
+ }
+ FREE (value);
return ret;
}
-static int iterateUp(const HashCode512 * key,
- const Datastore_Value * val,
- int * closure) {
+static int
+iterateUp (const HashCode512 * key, const Datastore_Value * val, int *closure)
+{
int ret;
- ret = checkValue(key, val, closure);
+ ret = checkValue (key, val, closure);
(*closure) += 2;
return ret;
}
-static int iterateDown(const HashCode512 * key,
- const Datastore_Value * val,
- int * closure) {
+static int
+iterateDown (const HashCode512 * key,
+ const Datastore_Value * val, int *closure)
+{
int ret;
(*closure) -= 2;
- ret = checkValue(key, val, closure);
+ ret = checkValue (key, val, closure);
return ret;
}
-static int iterateDelete(const HashCode512 * key,
- const Datastore_Value * val,
- SQstore_ServiceAPI * api) {
- if (1 == api->del(key, val))
- return OK;
+static int
+iterateDelete (const HashCode512 * key,
+ const Datastore_Value * val, SQstore_ServiceAPI * api)
+{
+ if (1 == api->del (key, val))
+ return OK;
else
- return SYSERR;
+ return SYSERR;
}
-static int priorityCheck(const HashCode512 * key,
- const Datastore_Value * val,
- int * closure) {
+static int
+priorityCheck (const HashCode512 * key,
+ const Datastore_Value * val, int *closure)
+{
int id;
id = (*closure);
- if (id + 1 == ntohl(val->prio))
+ if (id + 1 == ntohl (val->prio))
return OK;
else
return SYSERR;
}
-static int multipleCheck(const HashCode512 * key,
- const Datastore_Value * val,
- Datastore_Value ** last) {
- if (*last != NULL) {
- if ( ((*last)->size == val->size) &&
- (0 == memcmp(*last,
- val,
- ntohl(val->size)) ) )
- return SYSERR; /* duplicate! */
- FREE(*last);
- }
- *last = MALLOC(ntohl(val->size));
- memcpy(*last,
- val,
- ntohl(val->size));
+static int
+multipleCheck (const HashCode512 * key,
+ const Datastore_Value * val, Datastore_Value ** last)
+{
+ if (*last != NULL)
+ {
+ if (((*last)->size == val->size) &&
+ (0 == memcmp (*last, val, ntohl (val->size))))
+ return SYSERR; /* duplicate! */
+ FREE (*last);
+ }
+ *last = MALLOC (ntohl (val->size));
+ memcpy (*last, val, ntohl (val->size));
return OK;
}
@@ -137,125 +140,119 @@
/**
* Add testcode here!
*/
-static int test(SQstore_ServiceAPI * api) {
- Datastore_Value * value;
+static int
+test (SQstore_ServiceAPI * api)
+{
+ Datastore_Value *value;
HashCode512 key;
unsigned long long oldSize;
int i;
now = 1000000;
- oldSize = api->getSize();
- for (i=0;i<256;i++) {
- value = initValue(i);
- memset(&key, 256-i, sizeof(HashCode512));
- ASSERT(OK == api->put(&key, value));
- FREE(value);
- }
- ASSERT(oldSize < api->getSize());
- ASSERT(256 == api->iterateLowPriority(ANY_BLOCK,
- NULL,
- NULL));
- ASSERT(256 == api->iterateExpirationTime(ANY_BLOCK,
- NULL,
- NULL));
- for (i=255;i>=0;i--) {
- memset(&key, 256-i, sizeof(HashCode512));
- ASSERT(1 == api->get(&key, i, &checkValue, (void*) &i));
- }
+ oldSize = api->getSize ();
+ for (i = 0; i < 256; i++)
+ {
+ value = initValue (i);
+ memset (&key, 256 - i, sizeof (HashCode512));
+ ASSERT (OK == api->put (&key, value));
+ FREE (value);
+ }
+ ASSERT (oldSize < api->getSize ());
+ ASSERT (256 == api->iterateLowPriority (ANY_BLOCK, NULL, NULL));
+ ASSERT (256 == api->iterateExpirationTime (ANY_BLOCK, NULL, NULL));
+ for (i = 255; i >= 0; i--)
+ {
+ memset (&key, 256 - i, sizeof (HashCode512));
+ ASSERT (1 == api->get (&key, i, &checkValue, (void *) &i));
+ }
- oldSize = api->getSize();
- for (i=255;i>=0;i-=2) {
- memset(&key, 256-i, sizeof(HashCode512));
- value = initValue(i);
- ASSERT(1 == api->del(&key, value));
- FREE(value);
- }
- ASSERT(oldSize > api->getSize());
+ oldSize = api->getSize ();
+ for (i = 255; i >= 0; i -= 2)
+ {
+ memset (&key, 256 - i, sizeof (HashCode512));
+ value = initValue (i);
+ ASSERT (1 == api->del (&key, value));
+ FREE (value);
+ }
+ ASSERT (oldSize > api->getSize ());
i = 0;
- ASSERT(128 == api->iterateLowPriority(ANY_BLOCK,
- (Datum_Iterator) &iterateUp,
- &i));
- ASSERT(256 == i);
- ASSERT(128 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &iterateDown,
- &i));
- ASSERT(0 == i);
- ASSERT(128 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &iterateDelete,
- api));
- ASSERT(0 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &iterateDown,
- &i));
+ ASSERT (128 == api->iterateLowPriority (ANY_BLOCK,
+ (Datum_Iterator) & iterateUp, &i));
+ ASSERT (256 == i);
+ ASSERT (128 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & iterateDown,
+ &i));
+ ASSERT (0 == i);
+ ASSERT (128 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & iterateDelete,
+ api));
+ ASSERT (0 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & iterateDown,
+ &i));
i = 42;
- value = initValue(i);
- memset(&key, 256-i, sizeof(HashCode512));
- api->put(&key, value);
- ASSERT(1 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &priorityCheck,
- &i));
- api->update(&key,
- value,
- 4,
- 0);
+ value = initValue (i);
+ memset (&key, 256 - i, sizeof (HashCode512));
+ api->put (&key, value);
+ ASSERT (1 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & priorityCheck,
+ &i));
+ api->update (&key, value, 4, 0);
i += 4;
- ASSERT(1 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &priorityCheck,
- &i));
- FREE(value);
+ ASSERT (1 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & priorityCheck,
+ &i));
+ FREE (value);
/* test multiple results */
- value = initValue(i+1);
- api->put(&key, value);
- FREE(value);
+ value = initValue (i + 1);
+ api->put (&key, value);
+ FREE (value);
value = NULL;
- ASSERT(2 == api->iterateExpirationTime(ANY_BLOCK,
- (Datum_Iterator) &multipleCheck,
- &value));
- FREE(value);
- api->del(&key,
- NULL);
- api->del(&key,
- NULL);
- ASSERT(0 == api->iterateExpirationTime(ANY_BLOCK,
- NULL,
- NULL));
- api->drop();
+ ASSERT (2 == api->iterateExpirationTime (ANY_BLOCK,
+ (Datum_Iterator) & multipleCheck,
+ &value));
+ FREE (value);
+ api->del (&key, NULL);
+ api->del (&key, NULL);
+ ASSERT (0 == api->iterateExpirationTime (ANY_BLOCK, NULL, NULL));
+ api->drop ();
return OK;
- FAILURE:
- api->drop();
+FAILURE:
+ api->drop ();
return SYSERR;
}
-int main(int argc, char *argv[]) {
- SQstore_ServiceAPI * api;
+int
+main (int argc, char *argv[])
+{
+ SQstore_ServiceAPI *api;
int ok;
- struct GC_Configuration * cfg;
- struct CronManager * cron;
+ struct GC_Configuration *cfg;
+ struct CronManager *cron;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- cron = cron_create(NULL);
- initCore(NULL,
- cfg,
- cron,
- NULL);
- api = requestService("sqstore");
- if (api != NULL) {
- ok = test(api);
- releaseService(api);
- } else
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ cron = cron_create (NULL);
+ initCore (NULL, cfg, cron, NULL);
+ api = requestService ("sqstore");
+ if (api != NULL)
+ {
+ ok = test (api);
+ releaseService (api);
+ }
+ else
ok = SYSERR;
- doneCore();
- cron_destroy(cron);
- GC_free(cfg);
+ doneCore ();
+ cron_destroy (cron);
+ GC_free (cfg);
if (ok == SYSERR)
return 1;
return 0;
Modified: GNUnet/src/applications/sqstore_sqlite/sqlitetest2.c
===================================================================
--- GNUnet/src/applications/sqstore_sqlite/sqlitetest2.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/sqstore_sqlite/sqlitetest2.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -87,67 +87,65 @@
static cron_t start_time;
-static int putValue(SQstore_ServiceAPI * api,
- int i) {
- Datastore_Value * value;
+static int
+putValue (SQstore_ServiceAPI * api, int i)
+{
+ Datastore_Value *value;
size_t size;
static HashCode512 key;
static int ic;
/* most content is 32k */
- size = sizeof(Datastore_Value) + 32 * 1024;
- if (weak_randomi(16) == 0) /* but some of it is less! */
- size = sizeof(Datastore_Value) + weak_randomi(32 * 1024);
- size = size - (size & 7); /* always multiple of 8 */
+ size = sizeof (Datastore_Value) + 32 * 1024;
+ if (weak_randomi (16) == 0) /* but some of it is less! */
+ size = sizeof (Datastore_Value) + weak_randomi (32 * 1024);
+ size = size - (size & 7); /* always multiple of 8 */
/* generate random key */
- hash(&key,
- sizeof(HashCode512),
- &key);
- value = MALLOC(size);
- value->size = htonl(size);
- value->type = htonl(i);
- value->prio = htonl(weak_randomi(100));
- value->anonymityLevel = htonl(i);
- value->expirationTime = htonll(get_time() + weak_randomi(1000));
- memset(&value[1],
- i,
- size - sizeof(Datastore_Value));
- if (OK != api->put(&key, value)) {
- FREE(value);
- fprintf(stderr, "E");
- return SYSERR;
- }
+ hash (&key, sizeof (HashCode512), &key);
+ value = MALLOC (size);
+ value->size = htonl (size);
+ value->type = htonl (i);
+ value->prio = htonl (weak_randomi (100));
+ value->anonymityLevel = htonl (i);
+ value->expirationTime = htonll (get_time () + weak_randomi (1000));
+ memset (&value[1], i, size - sizeof (Datastore_Value));
+ if (OK != api->put (&key, value))
+ {
+ FREE (value);
+ fprintf (stderr, "E");
+ return SYSERR;
+ }
ic++;
#if REPORT_ID
if (ic % REP_FREQ == 0)
- fprintf(stderr, "I");
+ fprintf (stderr, "I");
#endif
- stored_bytes += ntohl(value->size);
+ stored_bytes += ntohl (value->size);
stored_ops++;
stored_entries++;
- FREE(value);
+ FREE (value);
return OK;
}
static int
-iterateDelete(const HashCode512 * key,
- const Datastore_Value * val,
- void * cls) {
- SQstore_ServiceAPI * api = cls;
+iterateDelete (const HashCode512 * key,
+ const Datastore_Value * val, void *cls)
+{
+ SQstore_ServiceAPI *api = cls;
static int dc;
- if (api->getSize() < MAX_SIZE)
+ if (api->getSize () < MAX_SIZE)
return SYSERR;
- if (GNUNET_SHUTDOWN_TEST() == YES)
+ if (GNUNET_SHUTDOWN_TEST () == YES)
return SYSERR;
dc++;
#if REPORT_ID
if (dc % REP_FREQ == 0)
- fprintf(stderr, "D");
+ fprintf (stderr, "D");
#endif
- GE_ASSERT(NULL, 1 == api->del(key, val));
- stored_bytes -= ntohl(val->size);
+ GE_ASSERT (NULL, 1 == api->del (key, val));
+ stored_bytes -= ntohl (val->size);
stored_entries--;
return OK;
}
@@ -155,7 +153,9 @@
/**
* Add testcode here!
*/
-static int test(SQstore_ServiceAPI * api) {
+static int
+test (SQstore_ServiceAPI * api)
+{
unsigned long long lops;
int i;
int j;
@@ -163,85 +163,82 @@
int have_file;
lops = 0;
- have_file = OK == disk_file_test(NULL,
- DB_NAME);
+ have_file = OK == disk_file_test (NULL, DB_NAME);
- for (i=0;i<ITERATIONS;i++) {
+ for (i = 0; i < ITERATIONS; i++)
+ {
#if REPORT_ID
- fprintf(stderr, ".");
+ fprintf (stderr, ".");
#endif
- /* insert data equivalent to 1/10th of MAX_SIZE */
- for (j=0;j<PUT_10;j++) {
- ASSERT(OK == putValue(api, j));
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
+ /* insert data equivalent to 1/10th of MAX_SIZE */
+ for (j = 0; j < PUT_10; j++)
+ {
+ ASSERT (OK == putValue (api, j));
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
- /* trim down below MAX_SIZE again */
- if ((i % 2) == 0)
- api->iterateLowPriority(0, &iterateDelete, api);
- else
- api->iterateExpirationTime(0, &iterateDelete, api);
+ /* trim down below MAX_SIZE again */
+ if ((i % 2) == 0)
+ api->iterateLowPriority (0, &iterateDelete, api);
+ else
+ api->iterateExpirationTime (0, &iterateDelete, api);
- /* every 10 iterations print status */
- size = 0;
- if (have_file)
- disk_file_size(NULL,
- DB_NAME,
- &size,
- NO);
- printf(
+ /* every 10 iterations print status */
+ size = 0;
+ if (have_file)
+ disk_file_size (NULL, DB_NAME, &size, NO);
+ printf (
#if REPORT_ID
- "\n"
+ "\n"
#endif
- "%u: Useful %llu, API %llu, disk %llu (%.2f%%) / %lluk ops / %llu
ops/s\n",
- i,
- stored_bytes / 1024, /* used size in k */
- api->getSize() / 1024, /* API-reported size in k */
- size / 1024, /* disk size in kb */
- (100.0 * size / stored_bytes) - 100, /* overhead */
- (stored_ops * 2 - stored_entries) / 1024, /* total operations (in k) */
- 1000 * ((stored_ops * 2 - stored_entries) - lops) / (1 + get_time() -
start_time)); /* operations per second */
- lops = stored_ops * 2 - stored_entries;
- start_time = get_time();
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- api->drop();
+ "%u: Useful %llu, API %llu, disk %llu (%.2f%%) / %lluk ops /
%llu ops/s\n", i, stored_bytes / 1024, /* used size in k */
+ api->getSize () / 1024, /* API-reported size in k */
+ size / 1024, /* disk size in kb */
+ (100.0 * size / stored_bytes) - 100, /* overhead */
+ (stored_ops * 2 - stored_entries) / 1024, /* total
operations (in k) */
+ 1000 * ((stored_ops * 2 - stored_entries) - lops) / (1 +
get_time () - start_time)); /* operations per second */
+ lops = stored_ops * 2 - stored_entries;
+ start_time = get_time ();
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
+ api->drop ();
return OK;
- FAILURE:
- api->drop();
+FAILURE:
+ api->drop ();
return SYSERR;
}
-int main(int argc, char *argv[]) {
- SQstore_ServiceAPI * api;
+int
+main (int argc, char *argv[])
+{
+ SQstore_ServiceAPI *api;
int ok;
- struct GC_Configuration * cfg;
- struct CronManager * cron;
+ struct GC_Configuration *cfg;
+ struct CronManager *cron;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- cron = cron_create(NULL);
- initCore(NULL,
- cfg,
- cron,
- NULL);
- api = requestService("sqstore");
- if (api != NULL) {
- start_time = get_time();
- ok = test(api);
- releaseService(api);
- } else
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ cron = cron_create (NULL);
+ initCore (NULL, cfg, cron, NULL);
+ api = requestService ("sqstore");
+ if (api != NULL)
+ {
+ start_time = get_time ();
+ ok = test (api);
+ releaseService (api);
+ }
+ else
ok = SYSERR;
- doneCore();
- cron_destroy(cron);
- GC_free(cfg);
+ doneCore ();
+ cron_destroy (cron);
+ GC_free (cfg);
if (ok == SYSERR)
return 1;
return 0;
Modified: GNUnet/src/applications/sqstore_sqlite/sqlitetest3.c
===================================================================
--- GNUnet/src/applications/sqstore_sqlite/sqlitetest3.c 2007-07-10
04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/sqstore_sqlite/sqlitetest3.c 2007-07-10
08:36:37 UTC (rev 5295)
@@ -55,146 +55,148 @@
static cron_t start_time;
-static int putValue(SQstore_ServiceAPI * api,
- int i) {
- Datastore_Value * value;
+static int
+putValue (SQstore_ServiceAPI * api, int i)
+{
+ Datastore_Value *value;
size_t size;
static HashCode512 key;
static int ic;
/* most content is 32k */
- size = sizeof(Datastore_Value) + 32 * 1024;
- if (weak_randomi(16) == 0) /* but some of it is less! */
- size = sizeof(Datastore_Value) + weak_randomi(32 * 1024);
- size = size - (size & 7); /* always multiple of 8 */
- GE_ASSERT(NULL,
- size >= sizeof(Datastore_Value));
+ size = sizeof (Datastore_Value) + 32 * 1024;
+ if (weak_randomi (16) == 0) /* but some of it is less! */
+ size = sizeof (Datastore_Value) + weak_randomi (32 * 1024);
+ size = size - (size & 7); /* always multiple of 8 */
+ GE_ASSERT (NULL, size >= sizeof (Datastore_Value));
/* generate random key */
- hash(&key,
- sizeof(HashCode512),
- &key);
- value = MALLOC(size);
- value->size = htonl(size);
- value->type = htonl(i);
- value->prio = htonl(weak_randomi(100));
- value->anonymityLevel = htonl(i);
- value->expirationTime = htonll(get_time() + 60 * cronHOURS +
weak_randomi(1000));
- memset(&value[1],
- i,
- size - sizeof(Datastore_Value));
- if (OK != api->put(&key, value)) {
- FREE(value);
- fprintf(stderr, "E");
- return SYSERR;
- }
+ hash (&key, sizeof (HashCode512), &key);
+ value = MALLOC (size);
+ value->size = htonl (size);
+ value->type = htonl (i);
+ value->prio = htonl (weak_randomi (100));
+ value->anonymityLevel = htonl (i);
+ value->expirationTime =
+ htonll (get_time () + 60 * cronHOURS + weak_randomi (1000));
+ memset (&value[1], i, size - sizeof (Datastore_Value));
+ if (OK != api->put (&key, value))
+ {
+ FREE (value);
+ fprintf (stderr, "E");
+ return SYSERR;
+ }
ic++;
#if REPORT_ID
if (ic % REP_FREQ == 0)
- fprintf(stderr, "I");
+ fprintf (stderr, "I");
#endif
- stored_bytes += ntohl(value->size);
+ stored_bytes += ntohl (value->size);
stored_ops++;
stored_entries++;
- FREE(value);
+ FREE (value);
return OK;
}
static int
-iterateDummy(const HashCode512 * key,
- const Datastore_Value * val,
- void * cls) {
- if (GNUNET_SHUTDOWN_TEST() == YES)
+iterateDummy (const HashCode512 * key, const Datastore_Value * val, void *cls)
+{
+ if (GNUNET_SHUTDOWN_TEST () == YES)
return SYSERR;
return OK;
}
-static int test(SQstore_ServiceAPI * api) {
+static int
+test (SQstore_ServiceAPI * api)
+{
int i;
int j;
cron_t start;
cron_t end;
- for (i=0;i<ITERATIONS;i++) {
- /* insert data equivalent to 1/10th of MAX_SIZE */
- start = get_time();
- for (j=0;j<PUT_10;j++) {
- if (OK != putValue(api, j))
- break;
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
+ for (i = 0; i < ITERATIONS; i++)
+ {
+ /* insert data equivalent to 1/10th of MAX_SIZE */
+ start = get_time ();
+ for (j = 0; j < PUT_10; j++)
+ {
+ if (OK != putValue (api, j))
+ break;
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ }
+ end = get_time ();
+ printf ("%3u insertion took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateLowPriority (0, &iterateDummy, api);
+ end = get_time ();
+ printf ("%3u low priority iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateExpirationTime (0, &iterateDummy, api);
+ end = get_time ();
+ printf ("%3u expiration t iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateNonAnonymous (0, NO, &iterateDummy, api);
+ end = get_time ();
+ printf ("%3u non anonymou iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateNonAnonymous (0, YES, &iterateDummy, api);
+ end = get_time ();
+ printf ("%3u non anon YES iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateMigrationOrder (&iterateDummy, api);
+ end = get_time ();
+ printf ("%3u migration or iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ start = get_time ();
+ api->iterateAllNow (&iterateDummy, api);
+ end = get_time ();
+ printf ("%3u all now iteration took %20llums\n", i, end - start);
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
}
- end = get_time();
- printf("%3u insertion took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateLowPriority(0, &iterateDummy, api);
- end = get_time();
- printf("%3u low priority iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateExpirationTime(0, &iterateDummy, api);
- end = get_time();
- printf("%3u expiration t iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateNonAnonymous(0, NO, &iterateDummy, api);
- end = get_time();
- printf("%3u non anonymou iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateNonAnonymous(0, YES, &iterateDummy, api);
- end = get_time();
- printf("%3u non anon YES iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateMigrationOrder(&iterateDummy, api);
- end = get_time();
- printf("%3u migration or iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- start = get_time();
- api->iterateAllNow(&iterateDummy, api);
- end = get_time();
- printf("%3u all now iteration took %20llums\n", i, end-start);
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- }
- api->drop();
+ api->drop ();
return OK;
}
-int main(int argc, char *argv[]) {
- SQstore_ServiceAPI * api;
+int
+main (int argc, char *argv[])
+{
+ SQstore_ServiceAPI *api;
int ok;
- struct GC_Configuration * cfg;
- struct CronManager * cron;
+ struct GC_Configuration *cfg;
+ struct CronManager *cron;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- cron = cron_create(NULL);
- initCore(NULL,
- cfg,
- cron,
- NULL);
- api = requestService("sqstore");
- if (api != NULL) {
- start_time = get_time();
- ok = test(api);
- releaseService(api);
- } else
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ cron = cron_create (NULL);
+ initCore (NULL, cfg, cron, NULL);
+ api = requestService ("sqstore");
+ if (api != NULL)
+ {
+ start_time = get_time ();
+ ok = test (api);
+ releaseService (api);
+ }
+ else
ok = SYSERR;
- doneCore();
- cron_destroy(cron);
- GC_free(cfg);
+ doneCore ();
+ cron_destroy (cron);
+ GC_free (cfg);
if (ok == SYSERR)
return 1;
return 0;
Modified: GNUnet/src/applications/state/state.c
===================================================================
--- GNUnet/src/applications/state/state.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/state/state.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -40,7 +40,7 @@
#define DIR_EXT "state.sdb"
-static char * handle;
+static char *handle;
/**
* Read the contents of a bucket to a buffer.
@@ -50,54 +50,44 @@
* (*result should be NULL, sufficient space is allocated)
* @return the number of bytes read on success, -1 on failure
*/
-static int stateReadContent(struct GE_Context * ectx,
- const char * name,
- void ** result) {
+static int
+stateReadContent (struct GE_Context *ectx, const char *name, void **result)
+{
/* open file, must exist, open read only */
- char * dbh = handle;
+ char *dbh = handle;
int fd;
int size;
- char * fil;
+ char *fil;
unsigned long long fsize;
size_t n;
- GE_ASSERT(ectx,
- handle != NULL);
+ GE_ASSERT (ectx, handle != NULL);
if (result == NULL)
return -1;
- n = strlen(dbh) + strlen(name) + 2;
- fil = MALLOC(n);
- SNPRINTF(fil,
- n,
- "%s/%s",
- dbh,
- name);
- if ( (OK != disk_file_test(ectx,
- fil)) ||
- (OK != disk_file_size(ectx,
- fil,
- &fsize,
- YES)) ||
- (fsize == 0) ||
- (-1 == (fd = disk_file_open(ectx,
- fil,
- O_RDONLY,
- S_IRUSR) )) ) {
- FREE(fil);
- return -1;
- }
- *result = MALLOC_LARGE(fsize);
- size = READ(fd,
- *result,
- fsize);
- disk_file_close(ectx,
- fil,
- fd);
- FREE(fil);
- if (size == -1) {
- FREE(*result);
- *result = NULL;
- }
+ n = strlen (dbh) + strlen (name) + 2;
+ fil = MALLOC (n);
+ SNPRINTF (fil, n, "%s/%s", dbh, name);
+ if ((OK != disk_file_test (ectx,
+ fil)) ||
+ (OK != disk_file_size (ectx,
+ fil,
+ &fsize,
+ YES)) ||
+ (fsize == 0) ||
+ (-1 == (fd = disk_file_open (ectx, fil, O_RDONLY, S_IRUSR))))
+ {
+ FREE (fil);
+ return -1;
+ }
+ *result = MALLOC_LARGE (fsize);
+ size = READ (fd, *result, fsize);
+ disk_file_close (ectx, fil, fd);
+ FREE (fil);
+ if (size == -1)
+ {
+ FREE (*result);
+ *result = NULL;
+ }
return size;
}
@@ -110,46 +100,31 @@
* @param block the data to store
* @return SYSERR on error, OK if ok.
*/
-static int stateAppendContent(struct GE_Context * ectx,
- const char * name,
- int len,
- const void * block) {
- char * dbh = handle;
- char * fil;
+static int
+stateAppendContent (struct GE_Context *ectx,
+ const char *name, int len, const void *block)
+{
+ char *dbh = handle;
+ char *fil;
int fd;
size_t n;
- GE_ASSERT(ectx,
- handle != NULL);
- n = strlen(dbh) + strlen(name) + 2;
- fil = MALLOC(n);
- SNPRINTF(fil,
- n,
- "%s/%s",
- dbh,
- name);
- fd = disk_file_open(ectx,
- fil,
- O_RDWR|O_CREAT,
- S_IRUSR|S_IWUSR);
- if (fd == -1) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- "open",
- fil);
- FREE(fil);
- return SYSERR; /* failed! */
- }
- lseek(fd,
- 0,
- SEEK_END);
- WRITE(fd,
- block,
- len);
- disk_file_close(ectx,
- fil,
- fd);
- FREE(fil);
+ GE_ASSERT (ectx, handle != NULL);
+ n = strlen (dbh) + strlen (name) + 2;
+ fil = MALLOC (n);
+ SNPRINTF (fil, n, "%s/%s", dbh, name);
+ fd = disk_file_open (ectx, fil, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
+ if (fd == -1)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_BULK | GE_USER, "open", fil);
+ FREE (fil);
+ return SYSERR; /* failed! */
+ }
+ lseek (fd, 0, SEEK_END);
+ WRITE (fd, block, len);
+ disk_file_close (ectx, fil, fd);
+ FREE (fil);
return OK;
}
@@ -161,47 +136,33 @@
* @param block the data to store
* @return SYSERR on error, OK if ok.
*/
-static int stateWriteContent(struct GE_Context * ectx,
- const char * name,
- int len,
- const void * block) {
- char * dbh = handle;
- char * fil;
+static int
+stateWriteContent (struct GE_Context *ectx,
+ const char *name, int len, const void *block)
+{
+ char *dbh = handle;
+ char *fil;
int fd;
size_t n;
- GE_ASSERT(ectx, handle != NULL);
- n = strlen(dbh) + strlen(name) + 2;
- fil = MALLOC(n);
- SNPRINTF(fil,
- n,
- "%s/%s",
- dbh,
- name);
- fd = disk_file_open(ectx,
- fil,
- O_RDWR|O_CREAT,
- S_IRUSR|S_IWUSR);
- if (fd == -1) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- "open",
- fil);
- FREE(fil);
- return SYSERR; /* failed! */
- }
- WRITE(fd,
- block,
- len);
- if (0 != ftruncate(fd, len))
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_BULK | GE_ADMIN,
- "ftruncate",
- fil);
- disk_file_close(ectx,
- fil,
- fd);
- FREE(fil);
+ GE_ASSERT (ectx, handle != NULL);
+ n = strlen (dbh) + strlen (name) + 2;
+ fil = MALLOC (n);
+ SNPRINTF (fil, n, "%s/%s", dbh, name);
+ fd = disk_file_open (ectx, fil, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
+ if (fd == -1)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_BULK | GE_USER, "open", fil);
+ FREE (fil);
+ return SYSERR; /* failed! */
+ }
+ WRITE (fd, block, len);
+ if (0 != ftruncate (fd, len))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_BULK | GE_ADMIN, "ftruncate", fil);
+ disk_file_close (ectx, fil, fd);
+ FREE (fil);
return OK;
}
@@ -210,54 +171,47 @@
* @param name the hashcode representing the name of the file
* (without directory)
*/
-static int stateUnlinkFromDB(struct GE_Context * ectx,
- const char * name) {
- char * dbh = handle;
- char * fil;
+static int
+stateUnlinkFromDB (struct GE_Context *ectx, const char *name)
+{
+ char *dbh = handle;
+ char *fil;
size_t n;
- GE_ASSERT(ectx, handle != NULL);
- n = strlen(dbh) + strlen(name) + 2;
- fil = MALLOC(n);
- SNPRINTF(fil,
- n,
- "%s/%s",
- dbh,
- name);
- UNLINK(fil);
- FREE(fil);
+ GE_ASSERT (ectx, handle != NULL);
+ n = strlen (dbh) + strlen (name) + 2;
+ fil = MALLOC (n);
+ SNPRINTF (fil, n, "%s/%s", dbh, name);
+ UNLINK (fil);
+ FREE (fil);
return OK;
}
State_ServiceAPI *
-provide_module_state(CoreAPIForApplication * capi) {
+provide_module_state (CoreAPIForApplication * capi)
+{
static State_ServiceAPI api;
- char * dbh;
+ char *dbh;
size_t n;
dbh = NULL;
- if (-1 == GC_get_configuration_value_filename(capi->cfg,
- "GNUNETD",
- "GNUNETD_HOME",
- VAR_DAEMON_DIRECTORY,
- &dbh))
+ if (-1 == GC_get_configuration_value_filename (capi->cfg,
+ "GNUNETD",
+ "GNUNETD_HOME",
+ VAR_DAEMON_DIRECTORY, &dbh))
return NULL;
- GE_ASSERT(capi->ectx, dbh != NULL);
- n = strlen(dbh) + strlen(DIR_EXT) + 5;
- handle = MALLOC(n);
- SNPRINTF(handle,
- n,
- "%s/%s/",
- dbh,
- DIR_EXT);
- FREE(dbh);
- if (SYSERR == disk_directory_create(capi->ectx,
- handle)) {
- FREE(handle);
- handle = NULL;
- return NULL;
- }
+ GE_ASSERT (capi->ectx, dbh != NULL);
+ n = strlen (dbh) + strlen (DIR_EXT) + 5;
+ handle = MALLOC (n);
+ SNPRINTF (handle, n, "%s/%s/", dbh, DIR_EXT);
+ FREE (dbh);
+ if (SYSERR == disk_directory_create (capi->ectx, handle))
+ {
+ FREE (handle);
+ handle = NULL;
+ return NULL;
+ }
api.read = &stateReadContent;
api.append = &stateAppendContent;
api.write = &stateWriteContent;
@@ -268,9 +222,11 @@
/**
* Clean shutdown of the storage module (not used at the moment)
*/
-void release_module_state() {
- GE_ASSERT(NULL, handle != NULL);
- FREE(handle);
+void
+release_module_state ()
+{
+ GE_ASSERT (NULL, handle != NULL);
+ FREE (handle);
handle = NULL;
}
Modified: GNUnet/src/applications/state/statetest.c
===================================================================
--- GNUnet/src/applications/state/statetest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/state/statetest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -10,72 +10,67 @@
/**
* Perform option parsing from the command line.
*/
-static int parseCommandLine(int argc,
- char * argv[]) {
+static int
+parseCommandLine (int argc, char *argv[])
+{
char c;
- while (1) {
- int option_index = 0;
- static struct GNoption long_options[] = {
- { "config", 1, 0, 'c' },
- { 0,0,0,0 }
- };
+ while (1)
+ {
+ int option_index = 0;
+ static struct GNoption long_options[] = {
+ {"config", 1, 0, 'c'},
+ {0, 0, 0, 0}
+ };
- c = GNgetopt_long(argc,
- argv,
- "c:",
- long_options,
- &option_index);
+ c = GNgetopt_long (argc, argv, "c:", long_options, &option_index);
- if (c == -1)
- break; /* No more flags to process */
+ if (c == -1)
+ break; /* No more flags to process */
- switch(c) {
- case 'c':
- FREENONNULL(setConfigurationString("FILES",
- "gnunet.conf",
- GNoptarg));
- break;
- } /* end of parsing commandline */
- }
- FREENONNULL(setConfigurationString("GNUNETD",
- "LOGLEVEL",
- "NOTHING"));
+ switch (c)
+ {
+ case 'c':
+ FREENONNULL (setConfigurationString ("FILES",
+ "gnunet.conf", GNoptarg));
+ break;
+ } /* end of parsing commandline */
+ }
+ FREENONNULL (setConfigurationString ("GNUNETD", "LOGLEVEL", "NOTHING"));
return OK;
}
#define TH "TestHandle"
-int testState() {
- char * testString = "Hello World";
- char * ret;
+int
+testState ()
+{
+ char *testString = "Hello World";
+ char *ret;
- stateUnlinkFromDB(TH); /* go to defined state */
- if (SYSERR == stateWriteContent(TH,
- 5,
- testString))
+ stateUnlinkFromDB (TH); /* go to defined state */
+ if (SYSERR == stateWriteContent (TH, 5, testString))
return 1;
- if (SYSERR == stateAppendContent(TH,
- 6,
- &testString[5]))
+ if (SYSERR == stateAppendContent (TH, 6, &testString[5]))
return 2;
ret = NULL;
- if (SYSERR == stateReadContent(TH,
- (void**)&ret))
+ if (SYSERR == stateReadContent (TH, (void **) &ret))
return 3;
- if (0 != strncmp(ret, testString, 11))
+ if (0 != strncmp (ret, testString, 11))
return 4;
- FREE(ret);
- if (OK != stateUnlinkFromDB(TH))
+ FREE (ret);
+ if (OK != stateUnlinkFromDB (TH))
return 5;
return 0;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int ret = 0;
- initUtil(argc, argv, &parseCommandLine);
- ret = testState();
+ initUtil (argc, argv, &parseCommandLine);
+ ret = testState ();
- doneUtil();
+ doneUtil ();
return ret;
-} /* end of main */
+} /* end of main */
Modified: GNUnet/src/applications/stats/clientapi.c
===================================================================
--- GNUnet/src/applications/stats/clientapi.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/stats/clientapi.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,100 +35,102 @@
* Return a descriptive name for a p2p message type
*/
const char *
-STATS_p2pMessageName(unsigned short type) {
+STATS_p2pMessageName (unsigned short type)
+{
const char *name = NULL;
- switch( type ) {
- case p2p_PROTO_hello :
- name = "p2p_PROTO_hello";
- break;
- case P2P_PROTO_setkey :
- name = "P2P_PROTO_setkey";
- break;
- case p2p_PROTO_PING :
- name = "p2p_PROTO_PING";
- break;
- case p2p_PROTO_PONG :
- name = "p2p_PROTO_PONG";
- break;
- case P2P_PROTO_hangup :
- name = "P2P_PROTO_hangup";
- break;
- case P2P_PROTO_fragment :
- name = "P2P_PROTO_fragment";
- break;
- case P2P_PROTO_noise :
- name = "P2P_PROTO_noise";
- break;
+ switch (type)
+ {
+ case p2p_PROTO_hello:
+ name = "p2p_PROTO_hello";
+ break;
+ case P2P_PROTO_setkey:
+ name = "P2P_PROTO_setkey";
+ break;
+ case p2p_PROTO_PING:
+ name = "p2p_PROTO_PING";
+ break;
+ case p2p_PROTO_PONG:
+ name = "p2p_PROTO_PONG";
+ break;
+ case P2P_PROTO_hangup:
+ name = "P2P_PROTO_hangup";
+ break;
+ case P2P_PROTO_fragment:
+ name = "P2P_PROTO_fragment";
+ break;
+ case P2P_PROTO_noise:
+ name = "P2P_PROTO_noise";
+ break;
- case P2P_PROTO_gap_QUERY :
- name = "P2P_PROTO_gap_QUERY";
- break;
- case P2P_PROTO_gap_RESULT :
- name = "P2P_PROTO_gap_RESULT";
- break;
+ case P2P_PROTO_gap_QUERY:
+ name = "P2P_PROTO_gap_QUERY";
+ break;
+ case P2P_PROTO_gap_RESULT:
+ name = "P2P_PROTO_gap_RESULT";
+ break;
- case P2P_PROTO_chat_MSG :
- name = "P2P_PROTO_chat_MSG";
- break;
+ case P2P_PROTO_chat_MSG:
+ name = "P2P_PROTO_chat_MSG";
+ break;
- case P2P_PROTO_tracekit_PROBE :
- name = "P2P_PROTO_tracekit_PROBE";
- break;
- case P2P_PROTO_tracekit_REPLY :
- name = "P2P_PROTO_tracekit_REPLY";
- break;
+ case P2P_PROTO_tracekit_PROBE:
+ name = "P2P_PROTO_tracekit_PROBE";
+ break;
+ case P2P_PROTO_tracekit_REPLY:
+ name = "P2P_PROTO_tracekit_REPLY";
+ break;
- case P2P_PROTO_tbench_REQUEST :
- name = "P2P_PROTO_tbench_REQUEST";
- break;
- case P2P_PROTO_tbench_REPLY :
- name = "P2P_PROTO_tbench_REPLY";
- break;
+ case P2P_PROTO_tbench_REQUEST:
+ name = "P2P_PROTO_tbench_REQUEST";
+ break;
+ case P2P_PROTO_tbench_REPLY:
+ name = "P2P_PROTO_tbench_REPLY";
+ break;
- case P2P_PROTO_rpc_REQ :
- name = "P2P_PROTO_rpc_REQ";
- break;
- case P2P_PROTO_rpc_RES :
- name = "P2P_PROTO_rpc_RES";
- break;
- case P2P_PROTO_rpc_ACK :
- name = "P2P_PROTO_rpc_ACK";
- break;
+ case P2P_PROTO_rpc_REQ:
+ name = "P2P_PROTO_rpc_REQ";
+ break;
+ case P2P_PROTO_rpc_RES:
+ name = "P2P_PROTO_rpc_RES";
+ break;
+ case P2P_PROTO_rpc_ACK:
+ name = "P2P_PROTO_rpc_ACK";
+ break;
- case P2P_PROTO_DHT_DISCOVERY :
- name = "P2P_PROTO_DHT_DISCOVERY";
- break;
- case P2P_PROTO_DHT_ASK_HELLO :
- name = "P2P_PROTO_DHT_ASK_HELLO";
- break;
- case P2P_PROTO_DHT_GET :
- name = "P2P_PROTO_DHT_GET";
- break;
- case P2P_PROTO_DHT_PUT :
- name = "P2P_PROTO_DHT_PUT";
- break;
- case P2P_PROTO_DHT_RESULT :
- name = "P2P_PROTO_DHT_RESULT";
- break;
+ case P2P_PROTO_DHT_DISCOVERY:
+ name = "P2P_PROTO_DHT_DISCOVERY";
+ break;
+ case P2P_PROTO_DHT_ASK_HELLO:
+ name = "P2P_PROTO_DHT_ASK_HELLO";
+ break;
+ case P2P_PROTO_DHT_GET:
+ name = "P2P_PROTO_DHT_GET";
+ break;
+ case P2P_PROTO_DHT_PUT:
+ name = "P2P_PROTO_DHT_PUT";
+ break;
+ case P2P_PROTO_DHT_RESULT:
+ name = "P2P_PROTO_DHT_RESULT";
+ break;
- case P2P_PROTO_aip_IP :
- name = "P2P_PROTO_aip_IP";
- break;
- case P2P_PROTO_aip_ROUTE :
- name = "P2P_PROTO_aip_ROUTE";
- break;
- case P2P_PROTO_aip_ROUTES :
- name = "P2P_PROTO_aip_ROUTES";
- break;
- case P2P_PROTO_aip_GETROUTE :
- name = "P2P_PROTO_aip_GETROUTE";
- break;
+ case P2P_PROTO_aip_IP:
+ name = "P2P_PROTO_aip_IP";
+ break;
+ case P2P_PROTO_aip_ROUTE:
+ name = "P2P_PROTO_aip_ROUTE";
+ break;
+ case P2P_PROTO_aip_ROUTES:
+ name = "P2P_PROTO_aip_ROUTES";
+ break;
+ case P2P_PROTO_aip_GETROUTE:
+ name = "P2P_PROTO_aip_GETROUTE";
+ break;
- default:
- name = NULL;
- break;
- }
+ default:
+ name = NULL;
+ break;
+ }
return name;
}
@@ -137,145 +139,147 @@
* Return a descriptive name for a client server message type
*/
const char *
-STATS_csMessageName(unsigned short type) {
+STATS_csMessageName (unsigned short type)
+{
const char *name = NULL;
- switch( type ) {
- case CS_PROTO_RETURN_VALUE :
- name = "CS_PROTO_RETURN_VALUE";
- break;
- case CS_PROTO_SHUTDOWN_REQUEST :
- name = "CS_PROTO_SHUTDOWN_REQUEST";
- break;
- case CS_PROTO_GET_OPTION_REQUEST :
- name = "CS_PROTO_GET_OPTION_REQUEST";
- break;
- case CS_PROTO_GET_OPTION_REPLY :
- name = "CS_PROTO_GET_OPTION_REPLY";
- break;
- case CS_PROTO_RETURN_ERROR :
- name = "CS_PROTO_RETURN_ERROR";
- break;
+ switch (type)
+ {
+ case CS_PROTO_RETURN_VALUE:
+ name = "CS_PROTO_RETURN_VALUE";
+ break;
+ case CS_PROTO_SHUTDOWN_REQUEST:
+ name = "CS_PROTO_SHUTDOWN_REQUEST";
+ break;
+ case CS_PROTO_GET_OPTION_REQUEST:
+ name = "CS_PROTO_GET_OPTION_REQUEST";
+ break;
+ case CS_PROTO_GET_OPTION_REPLY:
+ name = "CS_PROTO_GET_OPTION_REPLY";
+ break;
+ case CS_PROTO_RETURN_ERROR:
+ name = "CS_PROTO_RETURN_ERROR";
+ break;
- case CS_PROTO_gap_QUERY_START :
- name = "CS_PROTO_gap_QUERY_START";
- break;
- case CS_PROTO_gap_QUERY_STOP :
- /* case CS_PROTO_gap_RESULT : */
- name = "CS_PROTO_gap_QUERY_STOP or CS_PROTO_gap_RESULT";
- break;
- case CS_PROTO_gap_INSERT :
- name = "CS_PROTO_gap_INSERT";
- break;
- case CS_PROTO_gap_INDEX :
- name = "CS_PROTO_gap_INDEX";
- break;
- case CS_PROTO_gap_DELETE :
- name = "CS_PROTO_gap_DELETE";
- break;
- case CS_PROTO_gap_UNINDEX :
- name = "CS_PROTO_gap_UNINDEX";
- break;
- case CS_PROTO_gap_TESTINDEX :
- name = "CS_PROTO_gap_TESTINDEX";
- break;
- case CS_PROTO_gap_GET_AVG_PRIORITY :
- name = "CS_PROTO_gap_GET_AVG_PRIORITY";
- break;
- case CS_PROTO_gap_INIT_INDEX :
- name = "CS_PROTO_gap_INIT_INDEX";
- break;
+ case CS_PROTO_gap_QUERY_START:
+ name = "CS_PROTO_gap_QUERY_START";
+ break;
+ case CS_PROTO_gap_QUERY_STOP:
+ /* case CS_PROTO_gap_RESULT : */
+ name = "CS_PROTO_gap_QUERY_STOP or CS_PROTO_gap_RESULT";
+ break;
+ case CS_PROTO_gap_INSERT:
+ name = "CS_PROTO_gap_INSERT";
+ break;
+ case CS_PROTO_gap_INDEX:
+ name = "CS_PROTO_gap_INDEX";
+ break;
+ case CS_PROTO_gap_DELETE:
+ name = "CS_PROTO_gap_DELETE";
+ break;
+ case CS_PROTO_gap_UNINDEX:
+ name = "CS_PROTO_gap_UNINDEX";
+ break;
+ case CS_PROTO_gap_TESTINDEX:
+ name = "CS_PROTO_gap_TESTINDEX";
+ break;
+ case CS_PROTO_gap_GET_AVG_PRIORITY:
+ name = "CS_PROTO_gap_GET_AVG_PRIORITY";
+ break;
+ case CS_PROTO_gap_INIT_INDEX:
+ name = "CS_PROTO_gap_INIT_INDEX";
+ break;
- case CS_PROTO_traffic_COUNT :
- name = "CS_PROTO_traffic_COUNT";
- break;
- case CS_PROTO_traffic_QUERY :
- name = "CS_PROTO_traffic_QUERY";
- break;
- case CS_PROTO_traffic_INFO :
- name = "CS_PROTO_traffic_INFO";
- break;
+ case CS_PROTO_traffic_COUNT:
+ name = "CS_PROTO_traffic_COUNT";
+ break;
+ case CS_PROTO_traffic_QUERY:
+ name = "CS_PROTO_traffic_QUERY";
+ break;
+ case CS_PROTO_traffic_INFO:
+ name = "CS_PROTO_traffic_INFO";
+ break;
- case CS_PROTO_stats_GET_STATISTICS :
- name = "CS_PROTO_stats_GET_STATISTICS";
- break;
- case CS_PROTO_stats_STATISTICS :
- name = "CS_PROTO_stats_STATISTICS";
- break;
- case CS_PROTO_stats_GET_CS_MESSAGE_SUPPORTED :
- name = "CS_PROTO_stats_GET_CS_MESSAGE_SUPPORTED";
- break;
- case CS_PROTO_stats_GET_P2P_MESSAGE_SUPPORTED :
- name = "CS_PROTO_stats_GET_P2P_MESSAGE_SUPPORTED";
- break;
+ case CS_PROTO_stats_GET_STATISTICS:
+ name = "CS_PROTO_stats_GET_STATISTICS";
+ break;
+ case CS_PROTO_stats_STATISTICS:
+ name = "CS_PROTO_stats_STATISTICS";
+ break;
+ case CS_PROTO_stats_GET_CS_MESSAGE_SUPPORTED:
+ name = "CS_PROTO_stats_GET_CS_MESSAGE_SUPPORTED";
+ break;
+ case CS_PROTO_stats_GET_P2P_MESSAGE_SUPPORTED:
+ name = "CS_PROTO_stats_GET_P2P_MESSAGE_SUPPORTED";
+ break;
- case CS_PROTO_tbench_REQUEST :
- name = "CS_PROTO_tbench_REQUEST";
- break;
- case CS_PROTO_tbench_REPLY :
- name = "CS_PROTO_tbench_REPLY";
- break;
+ case CS_PROTO_tbench_REQUEST:
+ name = "CS_PROTO_tbench_REQUEST";
+ break;
+ case CS_PROTO_tbench_REPLY:
+ name = "CS_PROTO_tbench_REPLY";
+ break;
- case CS_PROTO_tracekit_PROBE :
- name = "CS_PROTO_tracekit_PROBE";
- break;
- case CS_PROTO_tracekit_REPLY :
- name = "CS_PROTO_tracekit_REPLY";
- break;
+ case CS_PROTO_tracekit_PROBE:
+ name = "CS_PROTO_tracekit_PROBE";
+ break;
+ case CS_PROTO_tracekit_REPLY:
+ name = "CS_PROTO_tracekit_REPLY";
+ break;
- case CS_PROTO_chat_MSG :
- name = "CS_PROTO_chat_MSG";
- break;
+ case CS_PROTO_chat_MSG:
+ name = "CS_PROTO_chat_MSG";
+ break;
- case CS_PROTO_dht_REQUEST_GET :
- name = "CS_PROTO_dht_REQUEST_GET";
- break;
- case CS_PROTO_dht_REQUEST_PUT :
- name = "CS_PROTO_dht_REQUEST_PUT";
- break;
+ case CS_PROTO_dht_REQUEST_GET:
+ name = "CS_PROTO_dht_REQUEST_GET";
+ break;
+ case CS_PROTO_dht_REQUEST_PUT:
+ name = "CS_PROTO_dht_REQUEST_PUT";
+ break;
- case CS_PROTO_testbed_REQUEST :
- name = "CS_PROTO_testbed_REQUEST";
- break;
- case CS_PROTO_testbed_REPLY :
- name = "CS_PROTO_testbed_REPLY";
- break;
+ case CS_PROTO_testbed_REQUEST:
+ name = "CS_PROTO_testbed_REQUEST";
+ break;
+ case CS_PROTO_testbed_REPLY:
+ name = "CS_PROTO_testbed_REPLY";
+ break;
- case CS_PROTO_VPN_MSG :
- name = "CS_PROTO_VPN_MSG";
- break;
- case CS_PROTO_VPN_REPLY :
- name = "CS_PROTO_VPN_REPLY";
- break;
- case CS_PROTO_VPN_DEBUGOFF :
- name = "CS_PROTO_VPN_DEBUGOFF";
- break;
- case CS_PROTO_VPN_TUNNELS :
- name = "CS_PROTO_VPN_TUNNELS";
- break;
- case CS_PROTO_VPN_ROUTES :
- name = "CS_PROTO_VPN_ROUTES";
- break;
- case CS_PROTO_VPN_REALISED :
- name = "CS_PROTO_VPN_REALISED";
- break;
- case CS_PROTO_VPN_RESET :
- name = "CS_PROTO_VPN_RESET";
- break;
- case CS_PROTO_VPN_REALISE :
- name = "CS_PROTO_VPN_REALISE";
- break;
- case CS_PROTO_VPN_ADD :
- name = "CS_PROTO_VPN_ADD";
- break;
- case CS_PROTO_VPN_TRUST :
- name = "CS_PROTO_VPN_TRUST";
- break;
+ case CS_PROTO_VPN_MSG:
+ name = "CS_PROTO_VPN_MSG";
+ break;
+ case CS_PROTO_VPN_REPLY:
+ name = "CS_PROTO_VPN_REPLY";
+ break;
+ case CS_PROTO_VPN_DEBUGOFF:
+ name = "CS_PROTO_VPN_DEBUGOFF";
+ break;
+ case CS_PROTO_VPN_TUNNELS:
+ name = "CS_PROTO_VPN_TUNNELS";
+ break;
+ case CS_PROTO_VPN_ROUTES:
+ name = "CS_PROTO_VPN_ROUTES";
+ break;
+ case CS_PROTO_VPN_REALISED:
+ name = "CS_PROTO_VPN_REALISED";
+ break;
+ case CS_PROTO_VPN_RESET:
+ name = "CS_PROTO_VPN_RESET";
+ break;
+ case CS_PROTO_VPN_REALISE:
+ name = "CS_PROTO_VPN_REALISE";
+ break;
+ case CS_PROTO_VPN_ADD:
+ name = "CS_PROTO_VPN_ADD";
+ break;
+ case CS_PROTO_VPN_TRUST:
+ name = "CS_PROTO_VPN_TRUST";
+ break;
- default:
- name = NULL;
- break;
- }
+ default:
+ name = NULL;
+ break;
+ }
return name;
}
@@ -285,11 +289,12 @@
* @param processor function to call on each value
* @return OK on success, SYSERR on error
*/
-int STATS_getStatistics(struct GE_Context * ectx,
- struct ClientServerConnection * sock,
- STATS_StatProcessor processor,
- void * cls) {
- CS_stats_reply_MESSAGE * statMsg;
+int
+STATS_getStatistics (struct GE_Context *ectx,
+ struct ClientServerConnection *sock,
+ STATS_StatProcessor processor, void *cls)
+{
+ CS_stats_reply_MESSAGE *statMsg;
MESSAGE_HEADER csHdr;
unsigned int count;
unsigned int i;
@@ -297,56 +302,68 @@
int ret;
ret = OK;
- csHdr.size
- = htons(sizeof(MESSAGE_HEADER));
- csHdr.type
- = htons(CS_PROTO_stats_GET_STATISTICS);
- if (SYSERR == connection_write(sock,
- &csHdr))
+ csHdr.size = htons (sizeof (MESSAGE_HEADER));
+ csHdr.type = htons (CS_PROTO_stats_GET_STATISTICS);
+ if (SYSERR == connection_write (sock, &csHdr))
return SYSERR;
- statMsg
- = MALLOC(sizeof(CS_stats_reply_MESSAGE));
- statMsg->totalCounters
- = htonl(1); /* to ensure we enter the loop */
+ statMsg = MALLOC (sizeof (CS_stats_reply_MESSAGE));
+ statMsg->totalCounters = htonl (1); /* to ensure we enter the loop */
count = 0;
- while ( count < ntohl(statMsg->totalCounters) ) {
- FREE(statMsg);
- statMsg = NULL;
- /* printf("reading from socket starting %u of %d\n",
- count, ntohl(statMsg->totalCounters) );*/
- if (SYSERR == connection_read(sock,
- (MESSAGE_HEADER**)&statMsg))
- return SYSERR;
- if ( (ntohs(statMsg->header.size) < sizeof(CS_stats_reply_MESSAGE)) ||
- (((char*)statMsg)[ntohs(statMsg->header.size)-1] != '\0') ) {
- GE_BREAK(ectx, 0);
- ret = SYSERR;
- break;
- }
- mpos = sizeof(unsigned long long) * ntohl(statMsg->statCounters);
- if (count == 0) {
- ret = processor(_("Uptime (seconds)"),
- (unsigned long long)
- ((get_time() - ntohll(statMsg->startTime))/cronSECONDS),
- cls);
- }
- for (i=0;i<ntohl(statMsg->statCounters);i++) {
- if
(mpos+strlen(&((char*)(((CS_stats_reply_MESSAGE_GENERIC*)statMsg)->values))[mpos])+1
>
- ntohs(statMsg->header.size) - sizeof(CS_stats_reply_MESSAGE)) {
- GE_BREAK(ectx, 0);
- ret = SYSERR;
- break; /* out of bounds! */
- }
- if (ret != SYSERR) {
- ret =
processor(&((char*)(((CS_stats_reply_MESSAGE_GENERIC*)statMsg)->values))[mpos],
- ntohll(((CS_stats_reply_MESSAGE_GENERIC*)statMsg)->values[i]),
- cls);
- }
- mpos +=
strlen(&((char*)(((CS_stats_reply_MESSAGE_GENERIC*)statMsg)->values))[mpos])+1;
- }
- count += ntohl(statMsg->statCounters);
- } /* end while */
- FREE(statMsg);
+ while (count < ntohl (statMsg->totalCounters))
+ {
+ FREE (statMsg);
+ statMsg = NULL;
+ /* printf("reading from socket starting %u of %d\n",
+ count, ntohl(statMsg->totalCounters) ); */
+ if (SYSERR == connection_read (sock, (MESSAGE_HEADER **) & statMsg))
+ return SYSERR;
+ if ((ntohs (statMsg->header.size) < sizeof (CS_stats_reply_MESSAGE)) ||
+ (((char *) statMsg)[ntohs (statMsg->header.size) - 1] != '\0'))
+ {
+ GE_BREAK (ectx, 0);
+ ret = SYSERR;
+ break;
+ }
+ mpos = sizeof (unsigned long long) * ntohl (statMsg->statCounters);
+ if (count == 0)
+ {
+ ret = processor (_("Uptime (seconds)"),
+ (unsigned long long)
+ ((get_time () -
+ ntohll (statMsg->startTime)) / cronSECONDS),
+ cls);
+ }
+ for (i = 0; i < ntohl (statMsg->statCounters); i++)
+ {
+ if (mpos +
+ strlen (&
+ ((char
+ *) (((CS_stats_reply_MESSAGE_GENERIC *) statMsg)->
+ values))[mpos]) + 1 >
+ ntohs (statMsg->header.size) - sizeof (CS_stats_reply_MESSAGE))
+ {
+ GE_BREAK (ectx, 0);
+ ret = SYSERR;
+ break; /* out of bounds! */
+ }
+ if (ret != SYSERR)
+ {
+ ret =
+ processor (&
+ ((char
+ *) (((CS_stats_reply_MESSAGE_GENERIC *)
+ statMsg)->values))[mpos],
+ ntohll (((CS_stats_reply_MESSAGE_GENERIC *)
+ statMsg)->values[i]), cls);
+ }
+ mpos +=
+ strlen (&
+ ((char *) (((CS_stats_reply_MESSAGE_GENERIC *) statMsg)->
+ values))[mpos]) + 1;
+ }
+ count += ntohl (statMsg->statCounters);
+ } /* end while */
+ FREE (statMsg);
return ret;
}
@@ -357,10 +374,11 @@
* @param processor function to call on each value
* @return OK on success, SYSERR on error
*/
-int STATS_getAvailableProtocols(struct GE_Context * ectx,
- struct ClientServerConnection * sock,
- STATS_ProtocolProcessor processor,
- void * cls) {
+int
+STATS_getAvailableProtocols (struct GE_Context *ectx,
+ struct ClientServerConnection *sock,
+ STATS_ProtocolProcessor processor, void *cls)
+{
CS_stats_get_supported_MESSAGE csStatMsg;
unsigned short i;
unsigned short j;
@@ -368,29 +386,26 @@
int ret;
ret = OK;
- csStatMsg.header.size
- = htons(sizeof(CS_stats_get_supported_MESSAGE));
- csStatMsg.header.type
- = htons(CS_PROTO_stats_GET_P2P_MESSAGE_SUPPORTED);
- for (j=2;j<4;j++) {
- csStatMsg.handlerType = htons(j);
- for (i=0;i<65535;i++) {
- csStatMsg.type = htons(i);
- if (SYSERR == connection_write(sock,
- &csStatMsg.header))
- return SYSERR;
- if (SYSERR == connection_read_result(sock,
- &supported))
- return SYSERR;
- if (supported == YES) {
- ret = processor(i,
- (j == 2) ? YES : NO,
- cls);
- if (ret != OK)
- break;
- }
+ csStatMsg.header.size = htons (sizeof (CS_stats_get_supported_MESSAGE));
+ csStatMsg.header.type = htons (CS_PROTO_stats_GET_P2P_MESSAGE_SUPPORTED);
+ for (j = 2; j < 4; j++)
+ {
+ csStatMsg.handlerType = htons (j);
+ for (i = 0; i < 65535; i++)
+ {
+ csStatMsg.type = htons (i);
+ if (SYSERR == connection_write (sock, &csStatMsg.header))
+ return SYSERR;
+ if (SYSERR == connection_read_result (sock, &supported))
+ return SYSERR;
+ if (supported == YES)
+ {
+ ret = processor (i, (j == 2) ? YES : NO, cls);
+ if (ret != OK)
+ break;
+ }
+ }
}
- }
return OK;
}
Modified: GNUnet/src/applications/stats/gnunet-stats.c
===================================================================
--- GNUnet/src/applications/stats/gnunet-stats.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/stats/gnunet-stats.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -32,9 +32,9 @@
#include "gnunet_stats_lib.h"
#include "statistics.h"
-static int lastIp2p = 42; /* not YES or NO */
+static int lastIp2p = 42; /* not YES or NO */
-static char * cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
+static char *cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
/**
* Print statistics received.
@@ -42,46 +42,37 @@
* @param stream where to print the statistics
* @return OK on success, SYSERR on error
*/
-static int printStatistics(const char * name,
- unsigned long long value,
- void * cls) {
- FILE * stream = cls;
- FPRINTF(stream,
- "%-60s: %16llu\n",
- dgettext("GNUnet", name),
- value);
+static int
+printStatistics (const char *name, unsigned long long value, void *cls)
+{
+ FILE *stream = cls;
+ FPRINTF (stream, "%-60s: %16llu\n", dgettext ("GNUnet", name), value);
return OK;
}
-static int printProtocols(unsigned short type,
- int isP2P,
- void * cls) {
- FILE * stream = cls;
+static int
+printProtocols (unsigned short type, int isP2P, void *cls)
+{
+ FILE *stream = cls;
const char *name = NULL;
- if (isP2P != lastIp2p) {
- if (isP2P)
- fprintf(stream,
- _("Supported peer-to-peer messages:\n"));
+ if (isP2P != lastIp2p)
+ {
+ if (isP2P)
+ fprintf (stream, _("Supported peer-to-peer messages:\n"));
- else
- fprintf(stream,
- _("Supported client-server messages:\n"));
- lastIp2p = isP2P;
- }
+ else
+ fprintf (stream, _("Supported client-server messages:\n"));
+ lastIp2p = isP2P;
+ }
if (isP2P)
- name = STATS_p2pMessageName(type);
+ name = STATS_p2pMessageName (type);
else
- name = STATS_csMessageName(type);
+ name = STATS_csMessageName (type);
if (name == NULL)
- fprintf(stream,
- "\t%d\n",
- type);
+ fprintf (stream, "\t%d\n", type);
else
- fprintf(stream,
- "\t%d\t(%s)\n",
- type,
- name);
+ fprintf (stream, "\t%d\t(%s)\n", type, name);
return OK;
}
@@ -89,14 +80,14 @@
* All gnunet-transport-check command line options
*/
static struct CommandLineOption gnunetstatsOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- COMMAND_LINE_OPTION_HELP(gettext_noop("Print statistics about GNUnet
operations.")), /* -h */
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Print statistics about GNUnet
operations.")), /* -h */
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'p', "protocols", NULL,
- gettext_noop("prints supported protocol messages"),
- 0, &gnunet_getopt_configure_set_option, "STATS:PRINT-PROTOCOLS=YES" },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'p', "protocols", NULL,
+ gettext_noop ("prints supported protocol messages"),
+ 0, &gnunet_getopt_configure_set_option, "STATS:PRINT-PROTOCOLS=YES"},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_END,
};
@@ -108,50 +99,41 @@
* @param argv command line arguments
* @return 0 ok, 1 on error
*/
-int main(int argc,
- char * const * argv) {
+int
+main (int argc, char *const *argv)
+{
int res;
- struct ClientServerConnection * sock;
- struct GC_Configuration * cfg;
- struct GE_Context * ectx;
+ struct ClientServerConnection *sock;
+ struct GC_Configuration *cfg;
+ struct GE_Context *ectx;
- res = GNUNET_init(argc,
- argv,
- "gnunet-stats",
- &cfgFilename,
- gnunetstatsOptions,
- &ectx,
- &cfg);
- if (res == -1) {
- GNUNET_fini(ectx, cfg);
- return -1;
- }
- sock = client_connection_create(ectx,
- cfg);
- if (sock == NULL) {
- fprintf(stderr,
- _("Error establishing connection with gnunetd.\n"));
- return 1;
- }
- res = STATS_getStatistics(ectx,
- sock,
- &printStatistics,
- stdout);
- if ( (YES == GC_get_configuration_value_yesno(cfg,
- "STATS",
- "PRINT-PROTOCOLS",
- NO)) &&
- (res == OK) ) {
- res = STATS_getAvailableProtocols(ectx,
- sock,
- &printProtocols,
- stdout);
- }
+ res = GNUNET_init (argc,
+ argv,
+ "gnunet-stats",
+ &cfgFilename, gnunetstatsOptions, &ectx, &cfg);
+ if (res == -1)
+ {
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
+ sock = client_connection_create (ectx, cfg);
+ if (sock == NULL)
+ {
+ fprintf (stderr, _("Error establishing connection with gnunetd.\n"));
+ return 1;
+ }
+ res = STATS_getStatistics (ectx, sock, &printStatistics, stdout);
+ if ((YES == GC_get_configuration_value_yesno (cfg,
+ "STATS",
+ "PRINT-PROTOCOLS",
+ NO)) && (res == OK))
+ {
+ res = STATS_getAvailableProtocols (ectx, sock, &printProtocols, stdout);
+ }
if (res != OK)
- fprintf(stderr,
- _("Error reading information from gnunetd.\n"));
- connection_destroy(sock);
- GNUNET_fini(ectx, cfg);
+ fprintf (stderr, _("Error reading information from gnunetd.\n"));
+ connection_destroy (sock);
+ GNUNET_fini (ectx, cfg);
return (res == OK) ? 0 : 1;
}
Modified: GNUnet/src/applications/stats/sqstats.c
===================================================================
--- GNUnet/src/applications/stats/sqstats.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/stats/sqstats.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -27,7 +27,7 @@
#include "gnunet_sqstore_service.h"
#include "gnunet_protocols.h"
-static SQstore_ServiceAPI * sq;
+static SQstore_ServiceAPI *sq;
/* block types */
static int stat_block[8];
@@ -38,7 +38,8 @@
/* anonymity */
static int stat_anon[3];
-struct CD {
+struct CD
+{
/* block types */
unsigned long long stat_block[8];
/* expiration */
@@ -49,63 +50,66 @@
unsigned long long stat_anon[3];
};
-static int iter(const HashCode512 * key,
- const Datastore_Value * value,
- void * cls) {
- struct CD * data = cls;
+static int
+iter (const HashCode512 * key, const Datastore_Value * value, void *cls)
+{
+ struct CD *data = cls;
cron_t expire;
cron_t now;
- switch (ntohl(value->type)) {
- case ANY_BLOCK:
- data->stat_block[0]++;
- break;
- case D_BLOCK:
- data->stat_block[1]++;
- break;
- case S_BLOCK:
- data->stat_block[2]++;
- break;
- case K_BLOCK:
- data->stat_block[3]++;
- break;
- case N_BLOCK:
- data->stat_block[4]++;
- break;
- case KN_BLOCK:
- data->stat_block[5]++;
- break;
- case ONDEMAND_BLOCK:
- data->stat_block[6]++;
- break;
- default:
- data->stat_block[7]++;
- break;
- }
- switch (ntohl(value->anonymityLevel)) {
- case 0:
- data->stat_anon[0]++;
- break;
- case 1:
- data->stat_anon[1]++;
- break;
- default:
- data->stat_anon[2]++;
- break;
- }
- switch (ntohl(value->prio)) {
- case 0:
- data->stat_prio[0]++;
- break;
- case 1:
- data->stat_prio[1]++;
- break;
- default:
- data->stat_prio[2]++;
- break;
- }
- expire = ntohll(value->expirationTime);
- now = get_time();
+ switch (ntohl (value->type))
+ {
+ case ANY_BLOCK:
+ data->stat_block[0]++;
+ break;
+ case D_BLOCK:
+ data->stat_block[1]++;
+ break;
+ case S_BLOCK:
+ data->stat_block[2]++;
+ break;
+ case K_BLOCK:
+ data->stat_block[3]++;
+ break;
+ case N_BLOCK:
+ data->stat_block[4]++;
+ break;
+ case KN_BLOCK:
+ data->stat_block[5]++;
+ break;
+ case ONDEMAND_BLOCK:
+ data->stat_block[6]++;
+ break;
+ default:
+ data->stat_block[7]++;
+ break;
+ }
+ switch (ntohl (value->anonymityLevel))
+ {
+ case 0:
+ data->stat_anon[0]++;
+ break;
+ case 1:
+ data->stat_anon[1]++;
+ break;
+ default:
+ data->stat_anon[2]++;
+ break;
+ }
+ switch (ntohl (value->prio))
+ {
+ case 0:
+ data->stat_prio[0]++;
+ break;
+ case 1:
+ data->stat_prio[1]++;
+ break;
+ default:
+ data->stat_prio[2]++;
+ break;
+ }
+ expire = ntohll (value->expirationTime);
+ now = get_time ();
if (expire <= now)
data->stat_expire[0]++;
else if (expire <= now + 1 * cronHOURS)
@@ -119,77 +123,57 @@
return OK;
}
-static void update_sqstore_stats() {
+static void
+update_sqstore_stats ()
+{
struct CD data;
int i;
- memset(&data,
- 0,
- sizeof(struct CD));
- sq->iterateAllNow(&iter,
- &data);
- for (i=0;i<8;i++)
- stats->set(stat_block[i],
- data.stat_block[i]);
- for (i=0;i<5;i++)
- stats->set(stat_expire[i],
- data.stat_expire[i]);
- for (i=0;i<6;i++)
- stats->set(stat_prio[i],
- data.stat_prio[i]);
- for (i=0;i<3;i++)
- stats->set(stat_anon[i],
- data.stat_anon[i]);
+ memset (&data, 0, sizeof (struct CD));
+ sq->iterateAllNow (&iter, &data);
+ for (i = 0; i < 8; i++)
+ stats->set (stat_block[i], data.stat_block[i]);
+ for (i = 0; i < 5; i++)
+ stats->set (stat_expire[i], data.stat_expire[i]);
+ for (i = 0; i < 6; i++)
+ stats->set (stat_prio[i], data.stat_prio[i]);
+ for (i = 0; i < 3; i++)
+ stats->set (stat_anon[i], data.stat_anon[i]);
}
-static int init_sqstore_stats() {
- sq = myCoreAPI->requestService("sqstore");
+static int
+init_sqstore_stats ()
+{
+ sq = myCoreAPI->requestService ("sqstore");
if (sq == NULL)
return SYSERR;
- stat_block[0]
- = stats->create(gettext_noop("# Any-Blocks"));
- stat_block[1]
- = stats->create(gettext_noop("# DBlocks"));
- stat_block[2]
- = stats->create(gettext_noop("# SBlocks"));
- stat_block[3]
- = stats->create(gettext_noop("# KBlocks"));
- stat_block[4]
- = stats->create(gettext_noop("# NBlocks"));
- stat_block[5]
- = stats->create(gettext_noop("# KNBlocks"));
- stat_block[6]
- = stats->create(gettext_noop("# OnDemand-Blocks"));
- stat_block[7]
- = stats->create(gettext_noop("# Unknown-Blocks"));
- stat_expire[0]
- = stats->create(gettext_noop("# expired"));
- stat_expire[1]
- = stats->create(gettext_noop("# expire in 1h"));
- stat_expire[2]
- = stats->create(gettext_noop("# expire in 24h"));
- stat_expire[3]
- = stats->create(gettext_noop("# expire in 1 week"));
- stat_expire[4]
- = stats->create(gettext_noop("# expire in 1 month"));
- stat_prio[0]
- = stats->create(gettext_noop("# zero priority"));
- stat_prio[1]
- = stats->create(gettext_noop("# priority one"));
- stat_prio[2]
- = stats->create(gettext_noop("# priority larger than one"));
- stat_anon[3]
- = stats->create(gettext_noop("# no anonymity"));
- stat_anon[1]
- = stats->create(gettext_noop("# anonymity one"));
- stat_anon[2]
- = stats->create(gettext_noop("# anonymity larger than one"));
+ stat_block[0] = stats->create (gettext_noop ("# Any-Blocks"));
+ stat_block[1] = stats->create (gettext_noop ("# DBlocks"));
+ stat_block[2] = stats->create (gettext_noop ("# SBlocks"));
+ stat_block[3] = stats->create (gettext_noop ("# KBlocks"));
+ stat_block[4] = stats->create (gettext_noop ("# NBlocks"));
+ stat_block[5] = stats->create (gettext_noop ("# KNBlocks"));
+ stat_block[6] = stats->create (gettext_noop ("# OnDemand-Blocks"));
+ stat_block[7] = stats->create (gettext_noop ("# Unknown-Blocks"));
+ stat_expire[0] = stats->create (gettext_noop ("# expired"));
+ stat_expire[1] = stats->create (gettext_noop ("# expire in 1h"));
+ stat_expire[2] = stats->create (gettext_noop ("# expire in 24h"));
+ stat_expire[3] = stats->create (gettext_noop ("# expire in 1 week"));
+ stat_expire[4] = stats->create (gettext_noop ("# expire in 1 month"));
+ stat_prio[0] = stats->create (gettext_noop ("# zero priority"));
+ stat_prio[1] = stats->create (gettext_noop ("# priority one"));
+ stat_prio[2] = stats->create (gettext_noop ("# priority larger than one"));
+ stat_anon[3] = stats->create (gettext_noop ("# no anonymity"));
+ stat_anon[1] = stats->create (gettext_noop ("# anonymity one"));
+ stat_anon[2] = stats->create (gettext_noop ("# anonymity larger than one"));
return OK;
}
-static void done_sqstore_stats() {
+static void
+done_sqstore_stats ()
+{
if (sq == NULL)
return;
- myCoreAPI->releaseService(sq);
+ myCoreAPI->releaseService (sq);
sq = NULL;
}
Modified: GNUnet/src/applications/stats/statistics.c
===================================================================
--- GNUnet/src/applications/stats/statistics.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/stats/statistics.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -55,13 +55,14 @@
*/
static cron_t startTime;
-struct StatEntry {
+struct StatEntry
+{
unsigned long long value;
- char * description;
+ char *description;
unsigned int descStrLen;
};
-static struct StatEntry * entries;
+static struct StatEntry *entries;
/**
* Size of the entries array
@@ -71,12 +72,12 @@
/**
* lock for the stat module
*/
-static struct MUTEX * statLock;
+static struct MUTEX *statLock;
/**
* The core API.
*/
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
/**
* Get a handle to a statistical entity.
@@ -84,23 +85,24 @@
* @param name a description of the entity
* @return a handle for updating the associated value
*/
-static int statHandle(const char * name) {
+static int
+statHandle (const char *name)
+{
int i;
- GE_ASSERT(NULL, name != NULL);
- MUTEX_LOCK(statLock);
- for (i=0;i<statCounters;i++)
- if (0 == strcmp(entries[i].description, name)) {
- MUTEX_UNLOCK(statLock);
- return i;
- }
- GROW(entries,
- statCounters,
- statCounters+1);
- entries[statCounters-1].description = STRDUP(name);
- entries[statCounters-1].descStrLen = strlen(name);
- entries[statCounters-1].value = 0;
- MUTEX_UNLOCK(statLock);
- return statCounters-1;
+ GE_ASSERT (NULL, name != NULL);
+ MUTEX_LOCK (statLock);
+ for (i = 0; i < statCounters; i++)
+ if (0 == strcmp (entries[i].description, name))
+ {
+ MUTEX_UNLOCK (statLock);
+ return i;
+ }
+ GROW (entries, statCounters, statCounters + 1);
+ entries[statCounters - 1].description = STRDUP (name);
+ entries[statCounters - 1].descStrLen = strlen (name);
+ entries[statCounters - 1].value = 0;
+ MUTEX_UNLOCK (statLock);
+ return statCounters - 1;
}
/**
@@ -110,30 +112,33 @@
* @param handle the handle for the value to change
* @param value to what the value should be set
*/
-static void statSet(const int handle,
- const unsigned long long value) {
- MUTEX_LOCK(statLock);
- if ( (handle < 0) ||
- (handle >= statCounters) ) {
- GE_BREAK(NULL, 0);
- MUTEX_UNLOCK(statLock);
- return;
- }
+static void
+statSet (const int handle, const unsigned long long value)
+{
+ MUTEX_LOCK (statLock);
+ if ((handle < 0) || (handle >= statCounters))
+ {
+ GE_BREAK (NULL, 0);
+ MUTEX_UNLOCK (statLock);
+ return;
+ }
entries[handle].value = value;
- MUTEX_UNLOCK(statLock);
+ MUTEX_UNLOCK (statLock);
}
-static unsigned long long statGet(const int handle) {
+static unsigned long long
+statGet (const int handle)
+{
unsigned long long ret;
- MUTEX_LOCK(statLock);
- if ( (handle < 0) ||
- (handle >= statCounters) ) {
- GE_BREAK(NULL, 0);
- MUTEX_UNLOCK(statLock);
- return -1;
- }
+ MUTEX_LOCK (statLock);
+ if ((handle < 0) || (handle >= statCounters))
+ {
+ GE_BREAK (NULL, 0);
+ MUTEX_UNLOCK (statLock);
+ return -1;
+ }
ret = entries[handle].value;
- MUTEX_UNLOCK(statLock);
+ MUTEX_UNLOCK (statLock);
return ret;
}
@@ -144,32 +149,33 @@
* @param handle the handle for the value to change
* @param delta by how much should the value be changed
*/
-static void statChange(const int handle,
- const int delta) {
- MUTEX_LOCK(statLock);
- if ( (handle < 0) ||
- (handle >= statCounters) ) {
- GE_BREAK(NULL, 0);
- MUTEX_UNLOCK(statLock);
- return;
- }
+static void
+statChange (const int handle, const int delta)
+{
+ MUTEX_LOCK (statLock);
+ if ((handle < 0) || (handle >= statCounters))
+ {
+ GE_BREAK (NULL, 0);
+ MUTEX_UNLOCK (statLock);
+ return;
+ }
entries[handle].value += delta;
- MUTEX_UNLOCK(statLock);
+ MUTEX_UNLOCK (statLock);
}
/**
* Shutdown the statistics module.
*/
-void release_module_stats() {
+void
+release_module_stats ()
+{
int i;
- MUTEX_DESTROY(statLock);
- for (i=0;i<statCounters;i++)
- FREE(entries[i].description);
- GROW(entries,
- statCounters,
- 0);
+ MUTEX_DESTROY (statLock);
+ for (i = 0; i < statCounters; i++)
+ FREE (entries[i].description);
+ GROW (entries, statCounters, 0);
}
@@ -177,7 +183,8 @@
* Initialize the statistics module.
*/
Stats_ServiceAPI *
-provide_module_stats(CoreAPIForApplication * capi) {
+provide_module_stats (CoreAPIForApplication * capi)
+{
static Stats_ServiceAPI api;
coreAPI = capi;
@@ -185,8 +192,8 @@
api.set = &statSet;
api.change = &statChange;
api.get = &statGet;
- startTime = get_time();
- statLock = MUTEX_CREATE(YES);
+ startTime = get_time ();
+ statLock = MUTEX_CREATE (YES);
return &api;
}
@@ -202,60 +209,52 @@
static int stat_handle_io_load;
static int stat_bytes_noise_received;
static int stat_connected;
-static Stats_ServiceAPI * stats;
-static CoreAPIForApplication * myCoreAPI;
+static Stats_ServiceAPI *stats;
+static CoreAPIForApplication *myCoreAPI;
#if HAVE_SQSTATS
#include "sqstats.c"
#endif
-static void initializeStats() {
+static void
+initializeStats ()
+{
stat_handle_network_load_up
- = statHandle(gettext_noop("% of allowed network load (up)"));
+ = statHandle (gettext_noop ("% of allowed network load (up)"));
stat_handle_network_load_down
- = statHandle(gettext_noop("% of allowed network load (down)"));
- stat_handle_cpu_load
- = statHandle(gettext_noop("% of allowed cpu load"));
- stat_handle_io_load
- = statHandle(gettext_noop("% of allowed io load"));
- stat_connected
- = statHandle(gettext_noop("# of connected peers"));
+ = statHandle (gettext_noop ("% of allowed network load (down)"));
+ stat_handle_cpu_load = statHandle (gettext_noop ("% of allowed cpu load"));
+ stat_handle_io_load = statHandle (gettext_noop ("% of allowed io load"));
+ stat_connected = statHandle (gettext_noop ("# of connected peers"));
stat_bytes_noise_received
- = statHandle(gettext_noop("# bytes of noise received"));
+ = statHandle (gettext_noop ("# bytes of noise received"));
}
-static void immediateUpdates() {
+static void
+immediateUpdates ()
+{
int load;
#if HAVE_SQSTATS
- update_sqstore_stats();
+ update_sqstore_stats ();
#endif
- load = os_cpu_get_load(coreAPI->ectx,
- coreAPI->cfg);
+ load = os_cpu_get_load (coreAPI->ectx, coreAPI->cfg);
if (load == -1)
load = 0;
- statSet(stat_handle_cpu_load,
- load);
- load = os_disk_get_load(coreAPI->ectx,
- coreAPI->cfg);
+ statSet (stat_handle_cpu_load, load);
+ load = os_disk_get_load (coreAPI->ectx, coreAPI->cfg);
if (load == -1)
load = 0;
- statSet(stat_handle_io_load,
- load);
- load = os_network_monitor_get_load(coreAPI->load_monitor,
- Upload);
+ statSet (stat_handle_io_load, load);
+ load = os_network_monitor_get_load (coreAPI->load_monitor, Upload);
if (load == -1)
load = 0;
- statSet(stat_handle_network_load_up,
- load);
- load = os_network_monitor_get_load(coreAPI->load_monitor,
- Download);
+ statSet (stat_handle_network_load_up, load);
+ load = os_network_monitor_get_load (coreAPI->load_monitor, Download);
if (load == -1)
load = 0;
- statSet(stat_handle_network_load_down,
- load);
- statSet(stat_connected,
- coreAPI->forAllConnectedNodes(NULL, NULL));
+ statSet (stat_handle_network_load_down, load);
+ statSet (stat_connected, coreAPI->forAllConnectedNodes (NULL, NULL));
}
@@ -265,85 +264,91 @@
*
* @param originalRequestMessage ignored at this point.
*/
-static int sendStatistics(struct ClientHandle * sock,
- const MESSAGE_HEADER * originalRequestMessage) {
- CS_stats_reply_MESSAGE * statMsg;
- int pos; /* position in the values-descriptions */
+static int
+sendStatistics (struct ClientHandle *sock,
+ const MESSAGE_HEADER * originalRequestMessage)
+{
+ CS_stats_reply_MESSAGE *statMsg;
+ int pos; /* position in the values-descriptions */
int start;
int end;
- int mpos; /* postion in the message */
+ int mpos; /* postion in the message */
- immediateUpdates();
- statMsg = MALLOC(MAX_BUFFER_SIZE);
- statMsg->header.type
- = htons(CS_PROTO_stats_STATISTICS);
- statMsg->totalCounters
- = htonl(statCounters);
- statMsg->statCounters
- = htons(0);
- statMsg->startTime
- = htonll(startTime);
+ immediateUpdates ();
+ statMsg = MALLOC (MAX_BUFFER_SIZE);
+ statMsg->header.type = htons (CS_PROTO_stats_STATISTICS);
+ statMsg->totalCounters = htonl (statCounters);
+ statMsg->statCounters = htons (0);
+ statMsg->startTime = htonll (startTime);
start = 0;
- while (start < statCounters) {
- pos = start;
- /* first pass: gauge how many statistic numbers
- and their descriptions we can send in one message */
- mpos = 0;
- while ( (pos < statCounters) &&
- (mpos + sizeof(unsigned long long)
- + entries[pos].descStrLen + 1
- < MAX_BUFFER_SIZE - sizeof(CS_stats_reply_MESSAGE)) ) {
- mpos += sizeof(unsigned long long); /* value */
- mpos += entries[pos].descStrLen + 1;
- pos++;
+ while (start < statCounters)
+ {
+ pos = start;
+ /* first pass: gauge how many statistic numbers
+ and their descriptions we can send in one message */
+ mpos = 0;
+ while ((pos < statCounters) &&
+ (mpos + sizeof (unsigned long long)
+ + entries[pos].descStrLen + 1
+ < MAX_BUFFER_SIZE - sizeof (CS_stats_reply_MESSAGE)))
+ {
+ mpos += sizeof (unsigned long long); /* value */
+ mpos += entries[pos].descStrLen + 1;
+ pos++;
+ }
+ end = pos;
+ /* second pass: copy values and messages to message */
+ for (pos = start; pos < end; pos++)
+ ((CS_stats_reply_MESSAGE_GENERIC *) statMsg)->values[pos - start] =
+ htonll (entries[pos].value);
+ mpos = sizeof (unsigned long long) * (end - start);
+ for (pos = start; pos < end; pos++)
+ {
+ memcpy (&
+ ((char *) (((CS_stats_reply_MESSAGE_GENERIC *) statMsg))->
+ values)[mpos], entries[pos].description,
+ entries[pos].descStrLen + 1);
+ mpos += entries[pos].descStrLen + 1;
+ }
+ statMsg->statCounters = htonl (end - start);
+ GE_ASSERT (NULL,
+ mpos + sizeof (CS_stats_reply_MESSAGE) < MAX_BUFFER_SIZE);
+
+ statMsg->header.size = htons (mpos + sizeof (CS_stats_reply_MESSAGE));
+ /* printf("writing message of size %d with stats %d to %d out of %d to
socket\n",
+ ntohs(statMsg->header.size),
+ start, end, statCounters); */
+ if (SYSERR == coreAPI->sendToClient (sock, &statMsg->header))
+ break; /* abort, socket error! */
+ start = end;
}
- end = pos;
- /* second pass: copy values and messages to message */
- for (pos=start;pos<end;pos++)
- ((CS_stats_reply_MESSAGE_GENERIC*)statMsg)->values[pos-start] =
htonll(entries[pos].value);
- mpos = sizeof(unsigned long long) * (end - start);
- for (pos=start;pos<end;pos++) {
-
memcpy(&((char*)(((CS_stats_reply_MESSAGE_GENERIC*)statMsg))->values)[mpos],
- entries[pos].description,
- entries[pos].descStrLen+1);
- mpos += entries[pos].descStrLen+1;
- }
- statMsg->statCounters = htonl(end - start);
- GE_ASSERT(NULL, mpos + sizeof(CS_stats_reply_MESSAGE) < MAX_BUFFER_SIZE);
-
- statMsg->header.size = htons(mpos + sizeof(CS_stats_reply_MESSAGE));
- /* printf("writing message of size %d with stats %d to %d out of %d to
socket\n",
- ntohs(statMsg->header.size),
- start, end, statCounters);*/
- if (SYSERR == coreAPI->sendToClient(sock,
- &statMsg->header))
- break; /* abort, socket error! */
- start = end;
- }
- FREE(statMsg);
+ FREE (statMsg);
return OK;
}
/**
* Handle a request to see if a particular p2p message is supported.
*/
-static int handleMessageSupported(struct ClientHandle * sock,
- const MESSAGE_HEADER * message) {
+static int
+handleMessageSupported (struct ClientHandle *sock,
+ const MESSAGE_HEADER * message)
+{
unsigned short type;
unsigned short htype;
int supported;
- CS_stats_get_supported_MESSAGE * cmsg;
+ CS_stats_get_supported_MESSAGE *cmsg;
- if (ntohs(message->size) != sizeof(CS_stats_get_supported_MESSAGE)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
+ if (ntohs (message->size) != sizeof (CS_stats_get_supported_MESSAGE))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
cmsg = (CS_stats_get_supported_MESSAGE *) message;
- type = ntohs(cmsg->type);
- htype = ntohs(cmsg->handlerType);
- supported = coreAPI->isHandlerRegistered(type, htype);
- return coreAPI->sendValueToClient(sock, supported);
+ type = ntohs (cmsg->type);
+ htype = ntohs (cmsg->handlerType);
+ supported = coreAPI->isHandlerRegistered (type, htype);
+ return coreAPI->sendValueToClient (sock, supported);
}
/**
@@ -354,86 +359,90 @@
* @param msg the request from the client
* @returns OK if ok, SYSERR if not.
*/
-static int processGetConnectionCountRequest(struct ClientHandle * client,
- const MESSAGE_HEADER * msg) {
- if (ntohs(msg->size) != sizeof(MESSAGE_HEADER)) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
+static int
+processGetConnectionCountRequest (struct ClientHandle *client,
+ const MESSAGE_HEADER * msg)
+{
+ if (ntohs (msg->size) != sizeof (MESSAGE_HEADER))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
return coreAPI->sendValueToClient
- (client,
- coreAPI->forAllConnectedNodes(NULL, NULL));
+ (client, coreAPI->forAllConnectedNodes (NULL, NULL));
}
/**
* Handler for processing noise.
*/
-static int processNoise(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg) {
- statChange(stat_bytes_noise_received,
- ntohs(msg->size));
+static int
+processNoise (const PeerIdentity * sender, const MESSAGE_HEADER * msg)
+{
+ statChange (stat_bytes_noise_received, ntohs (msg->size));
return OK;
}
-int initialize_module_stats(CoreAPIForApplication * capi) {
- GE_ASSERT(capi->ectx,
- myCoreAPI == NULL);
+int
+initialize_module_stats (CoreAPIForApplication * capi)
+{
+ GE_ASSERT (capi->ectx, myCoreAPI == NULL);
myCoreAPI = capi;
- stats = capi->requestService("stats");
- if (stats == NULL) {
- GE_BREAK(capi->ectx, 0);
- myCoreAPI = NULL;
- return SYSERR;
- }
- initializeStats();
- GE_LOG(capi->ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- _("`%s' registering client handlers %d %d %d and p2p handler %d\n"),
- "stats",
- CS_PROTO_traffic_COUNT,
- CS_PROTO_stats_GET_STATISTICS,
- CS_PROTO_stats_GET_P2P_MESSAGE_SUPPORTED,
- P2P_PROTO_noise);
- capi->registerClientHandler(CS_PROTO_stats_GET_STATISTICS,
- &sendStatistics);
- capi->registerClientHandler(CS_PROTO_stats_GET_P2P_MESSAGE_SUPPORTED,
- &handleMessageSupported);
- capi->registerClientHandler(CS_PROTO_stats_GET_CS_MESSAGE_SUPPORTED,
- &handleMessageSupported);
- capi->registerClientHandler(CS_PROTO_traffic_COUNT,
- &processGetConnectionCountRequest);
- capi->registerHandler(P2P_PROTO_noise,
- &processNoise);
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "stats",
- gettext_noop("keeps statistics about
gnunetd's operation")));
+ stats = capi->requestService ("stats");
+ if (stats == NULL)
+ {
+ GE_BREAK (capi->ectx, 0);
+ myCoreAPI = NULL;
+ return SYSERR;
+ }
+ initializeStats ();
+ GE_LOG (capi->ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ _("`%s' registering client handlers %d %d %d and p2p handler %d\n"),
+ "stats",
+ CS_PROTO_traffic_COUNT,
+ CS_PROTO_stats_GET_STATISTICS,
+ CS_PROTO_stats_GET_P2P_MESSAGE_SUPPORTED, P2P_PROTO_noise);
+ capi->registerClientHandler (CS_PROTO_stats_GET_STATISTICS,
+ &sendStatistics);
+ capi->registerClientHandler (CS_PROTO_stats_GET_P2P_MESSAGE_SUPPORTED,
+ &handleMessageSupported);
+ capi->registerClientHandler (CS_PROTO_stats_GET_CS_MESSAGE_SUPPORTED,
+ &handleMessageSupported);
+ capi->registerClientHandler (CS_PROTO_traffic_COUNT,
+ &processGetConnectionCountRequest);
+ capi->registerHandler (P2P_PROTO_noise, &processNoise);
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "stats",
+ gettext_noop
+ ("keeps statistics about
gnunetd's operation")));
#if HAVE_SQSTATS
- init_sqstore_stats();
+ init_sqstore_stats ();
#endif
- immediateUpdates();
+ immediateUpdates ();
return OK;
}
-int done_module_stats() {
+int
+done_module_stats ()
+{
#if HAVE_SQSTATS
- done_sqstore_stats();
+ done_sqstore_stats ();
#endif
- GE_ASSERT(NULL, myCoreAPI != NULL);
- coreAPI->unregisterClientHandler(CS_PROTO_stats_GET_STATISTICS,
- &sendStatistics);
- coreAPI->unregisterClientHandler(CS_PROTO_stats_GET_P2P_MESSAGE_SUPPORTED,
- &handleMessageSupported);
- coreAPI->unregisterClientHandler(CS_PROTO_stats_GET_CS_MESSAGE_SUPPORTED,
- &handleMessageSupported);
- coreAPI->unregisterClientHandler(CS_PROTO_traffic_COUNT,
- &processGetConnectionCountRequest);
- coreAPI->unregisterHandler(P2P_PROTO_noise,
- &processNoise);
- myCoreAPI->releaseService(stats);
+ GE_ASSERT (NULL, myCoreAPI != NULL);
+ coreAPI->unregisterClientHandler (CS_PROTO_stats_GET_STATISTICS,
+ &sendStatistics);
+ coreAPI->unregisterClientHandler (CS_PROTO_stats_GET_P2P_MESSAGE_SUPPORTED,
+ &handleMessageSupported);
+ coreAPI->unregisterClientHandler (CS_PROTO_stats_GET_CS_MESSAGE_SUPPORTED,
+ &handleMessageSupported);
+ coreAPI->unregisterClientHandler (CS_PROTO_traffic_COUNT,
+ &processGetConnectionCountRequest);
+ coreAPI->unregisterHandler (P2P_PROTO_noise, &processNoise);
+ myCoreAPI->releaseService (stats);
stats = NULL;
myCoreAPI = NULL;
return OK;
Modified: GNUnet/src/applications/stats/statistics.h
===================================================================
--- GNUnet/src/applications/stats/statistics.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/stats/statistics.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -32,13 +32,14 @@
* (bounded by the maximum CS message size!) number of statistical
* numbers. If needed, several messages are used.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
* For 64-bit alignment...
*/
int reserved;
- /* timestamp (network byte order)*/
+ /* timestamp (network byte order) */
cron_t startTime;
/* total number of statistical counters */
int totalCounters;
@@ -51,7 +52,8 @@
* Generic version of CS_stats_reply_MESSAGE with field for finding the end
* of the struct. Use the other version for allocation.
*/
-typedef struct {
+typedef struct
+{
CS_stats_reply_MESSAGE stats_cs_message;
/* values[statCounters] */
@@ -68,7 +70,8 @@
* Query protocol supported message. Contains the type of
* the message we are requesting the status of.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
Modified: GNUnet/src/applications/tbench/gnunet-tbench.c
===================================================================
--- GNUnet/src/applications/tbench/gnunet-tbench.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/tbench/gnunet-tbench.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -40,55 +40,56 @@
static unsigned long long messageSize = DEFAULT_MESSAGE_SIZE;
-static unsigned long long messageCnt = 1;
+static unsigned long long messageCnt = 1;
-static char * messageReceiver;
+static char *messageReceiver;
static unsigned long long messageIterations = 1;
-static unsigned long long messageTrainSize = 1;
+static unsigned long long messageTrainSize = 1;
-static cron_t messageTimeOut = DEFAULT_TIMEOUT;
+static cron_t messageTimeOut = DEFAULT_TIMEOUT;
-static cron_t messageSpacing = DEFAULT_SPACING;
+static cron_t messageSpacing = DEFAULT_SPACING;
-static int outputFormat = OF_HUMAN_READABLE;
+static int outputFormat = OF_HUMAN_READABLE;
-static char * cfgFilename;
+static char *cfgFilename;
/**
* All gnunet-tbench command line options
*/
static struct CommandLineOption gnunettbenchOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- COMMAND_LINE_OPTION_HELP(gettext_noop("Start GNUnet transport benchmarking
tool.")), /* -h */
- { 'g', "gnuplot", NULL,
- gettext_noop("output in gnuplot format"), 0,
- &gnunet_getopt_configure_set_one, &outputFormat },
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Start GNUnet transport benchmarking
tool.")), /* -h */
+ {'g', "gnuplot", NULL,
+ gettext_noop ("output in gnuplot format"), 0,
+ &gnunet_getopt_configure_set_one, &outputFormat},
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- { 'i', "iterations", "ITER",
- gettext_noop("number of iterations"), 1,
- &gnunet_getopt_configure_set_ulong, &messageIterations },
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'n', "msg", "MESSAGES",
- gettext_noop("number of messages to use per iteration"), 1,
- &gnunet_getopt_configure_set_ulong, &messageCnt },
- { 'r', "rec", "RECEIVER",
- gettext_noop("receiver host identifier (ENC file name)"), 1,
- &gnunet_getopt_configure_set_string, &messageReceiver },
- { 's', "size", "SIZE",
- gettext_noop("message size"), 1,
- &gnunet_getopt_configure_set_ulong, &messageSize },
- { 'S', "space", "SPACE",
- gettext_noop("sleep for SPACE ms after each a message block"), 1,
- &gnunet_getopt_configure_set_ulong, &messageSpacing },
- { 't', "timeout", "TIMEOUT",
- gettext_noop("time to wait for the completion of an iteration (in ms)"), 1,
- &gnunet_getopt_configure_set_ulong, &messageTimeOut },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
- { 'X', "xspace", "COUNT",
- gettext_noop("number of messages in a message block"), 1,
- &gnunet_getopt_configure_set_ulong, &messageTrainSize },
+ {'i', "iterations", "ITER",
+ gettext_noop ("number of iterations"), 1,
+ &gnunet_getopt_configure_set_ulong, &messageIterations},
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'n', "msg", "MESSAGES",
+ gettext_noop ("number of messages to use per iteration"), 1,
+ &gnunet_getopt_configure_set_ulong, &messageCnt},
+ {'r', "rec", "RECEIVER",
+ gettext_noop ("receiver host identifier (ENC file name)"), 1,
+ &gnunet_getopt_configure_set_string, &messageReceiver},
+ {'s', "size", "SIZE",
+ gettext_noop ("message size"), 1,
+ &gnunet_getopt_configure_set_ulong, &messageSize},
+ {'S', "space", "SPACE",
+ gettext_noop ("sleep for SPACE ms after each a message block"), 1,
+ &gnunet_getopt_configure_set_ulong, &messageSpacing},
+ {'t', "timeout", "TIMEOUT",
+ gettext_noop ("time to wait for the completion of an iteration (in ms)"),
+ 1,
+ &gnunet_getopt_configure_set_ulong, &messageTimeOut},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
+ {'X', "xspace", "COUNT",
+ gettext_noop ("number of messages in a message block"), 1,
+ &gnunet_getopt_configure_set_ulong, &messageTrainSize},
COMMAND_LINE_OPTION_END,
};
@@ -100,119 +101,115 @@
* @param argv command line arguments
* @return return value from gnunetsearch: 0: ok, -1: error
*/
-int main(int argc,
- char * const * argv) {
- struct ClientServerConnection * sock;
+int
+main (int argc, char *const *argv)
+{
+ struct ClientServerConnection *sock;
CS_tbench_request_MESSAGE msg;
- CS_tbench_reply_MESSAGE * buffer;
+ CS_tbench_reply_MESSAGE *buffer;
float messagesPercentLoss;
- struct GE_Context * ectx;
- struct GC_Configuration * cfg;
+ struct GE_Context *ectx;
+ struct GC_Configuration *cfg;
int res;
- res = GNUNET_init(argc,
- argv,
- "gnunet-tbench",
- &cfgFilename,
- gnunettbenchOptions,
- &ectx,
- &cfg);
- if (res == -1) {
- GNUNET_fini(ectx, cfg);
- return -1;
- }
- sock = client_connection_create(ectx,
- cfg);
- if (sock == NULL) {
- fprintf(stderr,
- _("Error establishing connection with gnunetd.\n"));
- GNUNET_fini(ectx, cfg);
- return 1;
- }
+ res = GNUNET_init (argc,
+ argv,
+ "gnunet-tbench",
+ &cfgFilename, gnunettbenchOptions, &ectx, &cfg);
+ if (res == -1)
+ {
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
+ sock = client_connection_create (ectx, cfg);
+ if (sock == NULL)
+ {
+ fprintf (stderr, _("Error establishing connection with gnunetd.\n"));
+ GNUNET_fini (ectx, cfg);
+ return 1;
+ }
- msg.header.size = htons(sizeof(CS_tbench_request_MESSAGE));
- msg.header.type = htons(CS_PROTO_tbench_REQUEST);
- msg.msgSize = htonl(messageSize);
- msg.msgCnt = htonl(messageCnt);
- msg.iterations = htonl(messageIterations);
- msg.intPktSpace = htonll(messageSpacing);
- msg.trainSize = htonl(messageTrainSize);
- msg.timeOut = htonll(messageTimeOut);
- msg.priority = htonl(5);
- if (messageReceiver == NULL) {
- fprintf(stderr,
- _("You must specify a receiver!\n"));
- connection_destroy(sock);
- GNUNET_fini(ectx, cfg);
- return 1;
- }
- if (OK != enc2hash(messageReceiver,
- &msg.receiverId.hashPubKey)) {
- fprintf(stderr,
- _("Invalid receiver peer ID specified (`%s' is not valid name).\n"),
- messageReceiver);
- FREE(messageReceiver);
- connection_destroy(sock);
- GNUNET_fini(ectx, cfg);
- return 1;
- }
- FREE(messageReceiver);
+ msg.header.size = htons (sizeof (CS_tbench_request_MESSAGE));
+ msg.header.type = htons (CS_PROTO_tbench_REQUEST);
+ msg.msgSize = htonl (messageSize);
+ msg.msgCnt = htonl (messageCnt);
+ msg.iterations = htonl (messageIterations);
+ msg.intPktSpace = htonll (messageSpacing);
+ msg.trainSize = htonl (messageTrainSize);
+ msg.timeOut = htonll (messageTimeOut);
+ msg.priority = htonl (5);
+ if (messageReceiver == NULL)
+ {
+ fprintf (stderr, _("You must specify a receiver!\n"));
+ connection_destroy (sock);
+ GNUNET_fini (ectx, cfg);
+ return 1;
+ }
+ if (OK != enc2hash (messageReceiver, &msg.receiverId.hashPubKey))
+ {
+ fprintf (stderr,
+ _
+ ("Invalid receiver peer ID specified (`%s' is not valid
name).\n"),
+ messageReceiver);
+ FREE (messageReceiver);
+ connection_destroy (sock);
+ GNUNET_fini (ectx, cfg);
+ return 1;
+ }
+ FREE (messageReceiver);
- if (SYSERR == connection_write(sock,
- &msg.header)) {
- connection_destroy(sock);
- GNUNET_fini(ectx, cfg);
- return -1;
- }
+ if (SYSERR == connection_write (sock, &msg.header))
+ {
+ connection_destroy (sock);
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
buffer = NULL;
- if (OK == connection_read(sock,
- (MESSAGE_HEADER**)&buffer)) {
- GE_ASSERT(ectx,
- ntohs(buffer->header.size) ==
- sizeof(CS_tbench_reply_MESSAGE));
- if ((float)buffer->mean_loss < 0){
- GE_BREAK(ectx, 0);
- messagesPercentLoss = 0.0;
- } else {
- messagesPercentLoss = (buffer->mean_loss/((float)htons(msg.msgCnt)));
- }
- switch (outputFormat) {
- case OF_HUMAN_READABLE:
- printf(_("Time:\n"));
- PRINTF(_("\tmax %llums\n"),
- ntohll(buffer->max_time));
- PRINTF(_("\tmin %llums\n"),
- ntohll(buffer->min_time));
- printf(_("\tmean %8.4fms\n"),
- buffer->mean_time);
- printf(_("\tvariance %8.4fms\n"),
- buffer->variance_time);
+ if (OK == connection_read (sock, (MESSAGE_HEADER **) & buffer))
+ {
+ GE_ASSERT (ectx,
+ ntohs (buffer->header.size) ==
+ sizeof (CS_tbench_reply_MESSAGE));
+ if ((float) buffer->mean_loss < 0)
+ {
+ GE_BREAK (ectx, 0);
+ messagesPercentLoss = 0.0;
+ }
+ else
+ {
+ messagesPercentLoss =
+ (buffer->mean_loss / ((float) htons (msg.msgCnt)));
+ }
+ switch (outputFormat)
+ {
+ case OF_HUMAN_READABLE:
+ printf (_("Time:\n"));
+ PRINTF (_("\tmax %llums\n"), ntohll (buffer->max_time));
+ PRINTF (_("\tmin %llums\n"), ntohll (buffer->min_time));
+ printf (_("\tmean %8.4fms\n"), buffer->mean_time);
+ printf (_("\tvariance %8.4fms\n"), buffer->variance_time);
- printf(_("Loss:\n"));
- printf(_("\tmax %u\n"),
- ntohl(buffer->max_loss));
- printf(_("\tmin %u\n"),
- ntohl(buffer->min_loss));
- printf(_("\tmean %8.4f\n"),
- buffer->mean_loss);
- printf(_("\tvariance %8.4f\n"),
- buffer->variance_loss);
- break;
- case OF_GNUPLOT_INPUT:
- printf("%f %f\n",
- buffer->mean_time,
- 1.0-messagesPercentLoss);
- break;
- default:
- printf(_("Output format not known, this should not happen.\n"));
+ printf (_("Loss:\n"));
+ printf (_("\tmax %u\n"), ntohl (buffer->max_loss));
+ printf (_("\tmin %u\n"), ntohl (buffer->min_loss));
+ printf (_("\tmean %8.4f\n"), buffer->mean_loss);
+ printf (_("\tvariance %8.4f\n"), buffer->variance_loss);
+ break;
+ case OF_GNUPLOT_INPUT:
+ printf ("%f %f\n", buffer->mean_time, 1.0 - messagesPercentLoss);
+ break;
+ default:
+ printf (_("Output format not known, this should not happen.\n"));
+ }
+ FREE (buffer);
}
- FREE(buffer);
- } else
- printf(_("\nDid not receive the message from gnunetd. Is gnunetd
running?\n"));
+ else
+ printf (_
+ ("\nDid not receive the message from gnunetd. Is gnunetd
running?\n"));
- connection_destroy(sock);
- GNUNET_fini(ectx, cfg);
+ connection_destroy (sock);
+ GNUNET_fini (ectx, cfg);
return 0;
}
Modified: GNUnet/src/applications/tbench/tbench.c
===================================================================
--- GNUnet/src/applications/tbench/tbench.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/tbench/tbench.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,9 +30,10 @@
#define DEBUG_TBENCH NO
-typedef struct {
+typedef struct
+{
cron_t totalTime;
- unsigned char * packetsReceived;
+ unsigned char *packetsReceived;
unsigned int maxPacketNumber;
unsigned int lossCount;
unsigned int duplicateCount;
@@ -42,7 +43,8 @@
* Message exchanged between peers for profiling
* transport performance.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
unsigned int iterationNum;
unsigned int packetNum;
@@ -54,9 +56,9 @@
/**
* Lock for access to semaphores.
*/
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-static struct SEMAPHORE * postsem;
+static struct SEMAPHORE *postsem;
/**
* What is the current iteration counter? (Used to verify
@@ -71,11 +73,11 @@
*/
static int timeoutOccured;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static IterationData * results;
+static IterationData *results;
/**
* Did we receive the last response for the current iteration
@@ -88,124 +90,132 @@
* Another peer send us a tbench request. Just turn
* around and send it back.
*/
-static int handleTBenchReq(const PeerIdentity * sender,
- const MESSAGE_HEADER * message) {
- MESSAGE_HEADER * reply;
- const P2P_tbench_MESSAGE * msg;
+static int
+handleTBenchReq (const PeerIdentity * sender, const MESSAGE_HEADER * message)
+{
+ MESSAGE_HEADER *reply;
+ const P2P_tbench_MESSAGE *msg;
#if DEBUG_TBENCH
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- "Received tbench request\n");
+ GE_LOG (ectx, GE_DEBUG | GE_BULK | GE_USER, "Received tbench request\n");
#endif
- if ( ntohs(message->size) < sizeof(P2P_tbench_MESSAGE)) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- msg = (const P2P_tbench_MESSAGE*) message;
- if (crc32N(&msg[1],
- ntohs(message->size) - sizeof(P2P_tbench_MESSAGE))
- != ntohl(msg->crc)) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ if (ntohs (message->size) < sizeof (P2P_tbench_MESSAGE))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ msg = (const P2P_tbench_MESSAGE *) message;
+ if (crc32N (&msg[1],
+ ntohs (message->size) - sizeof (P2P_tbench_MESSAGE))
+ != ntohl (msg->crc))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
#if DEBUG_TBENCH
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- "Received request %u from iteration %u/%u\n",
- htonl(msg->packetNum),
- htonl(msg->iterationNum),
- htonl(msg->nounce));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_BULK | GE_USER,
+ "Received request %u from iteration %u/%u\n",
+ htonl (msg->packetNum),
+ htonl (msg->iterationNum), htonl (msg->nounce));
#endif
- reply = MALLOC(ntohs(message->size));
- memcpy(reply,
- message,
- ntohs(message->size));
- reply->type = htons(P2P_PROTO_tbench_REPLY);
- coreAPI->unicast(sender,
- reply,
- ntohl(msg->priority),
- 0); /* no delay */
- FREE(reply);
+ reply = MALLOC (ntohs (message->size));
+ memcpy (reply, message, ntohs (message->size));
+ reply->type = htons (P2P_PROTO_tbench_REPLY);
+ coreAPI->unicast (sender, reply, ntohl (msg->priority), 0); /* no delay */
+ FREE (reply);
return OK;
}
/**
* We received a tbench-reply. Check and count stats.
*/
-static int handleTBenchReply(const PeerIdentity * sender,
- const MESSAGE_HEADER * message) {
- const P2P_tbench_MESSAGE * pmsg;
+static int
+handleTBenchReply (const PeerIdentity * sender,
+ const MESSAGE_HEADER * message)
+{
+ const P2P_tbench_MESSAGE *pmsg;
unsigned int lastPacketNumber;
- IterationData * res;
+ IterationData *res;
- if (ntohs(message->size) < sizeof(P2P_tbench_MESSAGE)) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- pmsg = (const P2P_tbench_MESSAGE*) message;
- if (crc32N(&pmsg[1],
- ntohs(message->size) - sizeof(P2P_tbench_MESSAGE))
- != ntohl(pmsg->crc)) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- MUTEX_LOCK(lock);
- if ( (timeoutOccured == NO) &&
- (postsem != NULL) &&
- (htonl(pmsg->iterationNum) == currIteration) &&
- (htonl(pmsg->nounce) == currNounce) ) {
- res = &results[currIteration];
- lastPacketNumber = ntohl(pmsg->packetNum);
- if (lastPacketNumber <= res->maxPacketNumber) {
- if (0 == res->packetsReceived[lastPacketNumber]++) {
- res->lossCount--;
- if (res->lossCount == 0)
- earlyEnd = get_time();
- } else {
- res->duplicateCount++;
- }
+ if (ntohs (message->size) < sizeof (P2P_tbench_MESSAGE))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
}
+ pmsg = (const P2P_tbench_MESSAGE *) message;
+ if (crc32N (&pmsg[1],
+ ntohs (message->size) - sizeof (P2P_tbench_MESSAGE))
+ != ntohl (pmsg->crc))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ MUTEX_LOCK (lock);
+ if ((timeoutOccured == NO) &&
+ (postsem != NULL) &&
+ (htonl (pmsg->iterationNum) == currIteration) &&
+ (htonl (pmsg->nounce) == currNounce))
+ {
+ res = &results[currIteration];
+ lastPacketNumber = ntohl (pmsg->packetNum);
+ if (lastPacketNumber <= res->maxPacketNumber)
+ {
+ if (0 == res->packetsReceived[lastPacketNumber]++)
+ {
+ res->lossCount--;
+ if (res->lossCount == 0)
+ earlyEnd = get_time ();
+ }
+ else
+ {
+ res->duplicateCount++;
+ }
+ }
#if DEBUG_TBENCH
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- "Received response %u from iteration %u/%u on time!\n",
- htonl(pmsg->packetNum),
- htonl(pmsg->iterationNum),
- htonl(pmsg->nounce));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_BULK | GE_USER,
+ "Received response %u from iteration %u/%u on time!\n",
+ htonl (pmsg->packetNum),
+ htonl (pmsg->iterationNum), htonl (pmsg->nounce));
#endif
- } else {
+ }
+ else
+ {
#if DEBUG_TBENCH
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- "Received message %u from iteration %u too late (now at iteration %u)\n",
- ntohl(pmsg->packetNum),
- ntohl(pmsg->iterationNum),
- currIteration);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_BULK | GE_USER,
+ "Received message %u from iteration %u too late (now at
iteration %u)\n",
+ ntohl (pmsg->packetNum),
+ ntohl (pmsg->iterationNum), currIteration);
#endif
- }
- MUTEX_UNLOCK(lock);
+ }
+ MUTEX_UNLOCK (lock);
return OK;
}
/**
* Cron-job helper function to signal timeout.
*/
-static void semaUp(void * cls) {
- struct SEMAPHORE * sem = cls;
+static void
+semaUp (void *cls)
+{
+ struct SEMAPHORE *sem = cls;
timeoutOccured = YES;
- SEMAPHORE_UP(sem);
+ SEMAPHORE_UP (sem);
}
/**
* Handle client request (main function)
*/
-static int csHandleTBenchRequest(struct ClientHandle * client,
- const MESSAGE_HEADER * message) {
- CS_tbench_request_MESSAGE * msg;
+static int
+csHandleTBenchRequest (struct ClientHandle *client,
+ const MESSAGE_HEADER * message)
+{
+ CS_tbench_request_MESSAGE *msg;
CS_tbench_reply_MESSAGE reply;
- P2P_tbench_MESSAGE * p2p;
+ P2P_tbench_MESSAGE *p2p;
unsigned short size;
unsigned int iteration;
unsigned int packetNum;
@@ -225,122 +235,99 @@
unsigned int iterations;
#if DEBUG_TBENCH
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Tbench received request from client.\n",
- msgCnt,
- size,
- iterations);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "Tbench received request from client.\n", msgCnt, size, iterations);
#endif
- if ( ntohs(message->size) != sizeof(CS_tbench_request_MESSAGE) )
+ if (ntohs (message->size) != sizeof (CS_tbench_request_MESSAGE))
return SYSERR;
- msg = (CS_tbench_request_MESSAGE*) message;
- size = sizeof(P2P_tbench_MESSAGE) + ntohl(msg->msgSize);
- if (size < sizeof(P2P_tbench_MESSAGE))
+ msg = (CS_tbench_request_MESSAGE *) message;
+ size = sizeof (P2P_tbench_MESSAGE) + ntohl (msg->msgSize);
+ if (size < sizeof (P2P_tbench_MESSAGE))
return SYSERR;
- delay = ntohll(msg->intPktSpace);
- iterations = ntohl(msg->iterations);
- msgCnt = ntohl(msg->msgCnt);
+ delay = ntohll (msg->intPktSpace);
+ iterations = ntohl (msg->iterations);
+ msgCnt = ntohl (msg->msgCnt);
#if DEBUG_TBENCH
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- "Tbench runs %u test messages of size %u in %u iterations.\n",
- msgCnt,
- size,
- iterations);
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ "Tbench runs %u test messages of size %u in %u iterations.\n",
+ msgCnt, size, iterations);
#endif
- MUTEX_LOCK(lock);
- if (results != NULL) {
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_IMMEDIATE,
- "Cannot run multiple tbench sessions at the same time!\n");
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- results = MALLOC(sizeof(IterationData) * iterations);
+ MUTEX_LOCK (lock);
+ if (results != NULL)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_IMMEDIATE,
+ "Cannot run multiple tbench sessions at the same time!\n");
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ results = MALLOC (sizeof (IterationData) * iterations);
- p2p = MALLOC(size);
- memset(p2p,
- 0,
- size);
- p2p->header.size = htons(size);
- p2p->header.type = htons(P2P_PROTO_tbench_REQUEST);
+ p2p = MALLOC (size);
+ memset (p2p, 0, size);
+ p2p->header.size = htons (size);
+ p2p->header.type = htons (P2P_PROTO_tbench_REQUEST);
p2p->priority = msg->priority;
- for (iteration=0;iteration<iterations;iteration++) {
- results[iteration].maxPacketNumber = msgCnt;
- results[iteration].packetsReceived = MALLOC(msgCnt);
- memset(results[iteration].packetsReceived,
- 0,
- msgCnt);
- results[iteration].lossCount = msgCnt;
- results[iteration].duplicateCount = 0;
+ for (iteration = 0; iteration < iterations; iteration++)
+ {
+ results[iteration].maxPacketNumber = msgCnt;
+ results[iteration].packetsReceived = MALLOC (msgCnt);
+ memset (results[iteration].packetsReceived, 0, msgCnt);
+ results[iteration].lossCount = msgCnt;
+ results[iteration].duplicateCount = 0;
- earlyEnd = 0;
- postsem = SEMAPHORE_CREATE(0);
- currNounce = weak_randomi(0xFFFFFF);
- p2p->nounce
- = htonl(currNounce);
- currIteration = iteration;
- p2p->iterationNum
- = htonl(currIteration);
- memset(&p2p[1],
- weak_randomi(256),
- size - sizeof(P2P_tbench_MESSAGE));
- p2p->crc
- = htonl(crc32N(&p2p[1],
- size - sizeof(P2P_tbench_MESSAGE)));
- MUTEX_UNLOCK(lock); /* allow receiving */
+ earlyEnd = 0;
+ postsem = SEMAPHORE_CREATE (0);
+ currNounce = weak_randomi (0xFFFFFF);
+ p2p->nounce = htonl (currNounce);
+ currIteration = iteration;
+ p2p->iterationNum = htonl (currIteration);
+ memset (&p2p[1],
+ weak_randomi (256), size - sizeof (P2P_tbench_MESSAGE));
+ p2p->crc = htonl (crc32N (&p2p[1], size - sizeof (P2P_tbench_MESSAGE)));
+ MUTEX_UNLOCK (lock); /* allow receiving */
- startTime = get_time();
- endTime = startTime + ntohll(msg->timeOut);
+ startTime = get_time ();
+ endTime = startTime + ntohll (msg->timeOut);
- timeoutOccured = NO;
- cron_add_job(coreAPI->cron,
- &semaUp,
- ntohll(msg->timeOut) * cronMILLIS,
- 0,
- postsem);
- for (packetNum=0;packetNum<msgCnt;packetNum++){
- now = get_time();
- p2p->packetNum = htonl(packetNum);
+ timeoutOccured = NO;
+ cron_add_job (coreAPI->cron,
+ &semaUp, ntohll (msg->timeOut) * cronMILLIS, 0, postsem);
+ for (packetNum = 0; packetNum < msgCnt; packetNum++)
+ {
+ now = get_time ();
+ p2p->packetNum = htonl (packetNum);
#if DEBUG_TBENCH
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- "Sending message %u of size %u in iteration %u\n",
- packetNum,
- size,
- iteration);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_BULK | GE_USER,
+ "Sending message %u of size %u in iteration %u\n",
+ packetNum, size, iteration);
#endif
- coreAPI->unicast(&msg->receiverId,
- &p2p->header,
- ntohl(msg->priority),
- 0); /* no delay */
- if ( (delay != 0) &&
- (htonl(msg->trainSize) != 0) &&
- (packetNum % htonl(msg->trainSize)) == 0)
- PTHREAD_SLEEP(delay);
+ coreAPI->unicast (&msg->receiverId, &p2p->header, ntohl
(msg->priority), 0); /* no delay */
+ if ((delay != 0) &&
+ (htonl (msg->trainSize) != 0) &&
+ (packetNum % htonl (msg->trainSize)) == 0)
+ PTHREAD_SLEEP (delay);
+ }
+ SEMAPHORE_DOWN (postsem, YES);
+ MUTEX_LOCK (lock);
+ if (earlyEnd == 0)
+ earlyEnd = get_time ();
+ results[iteration].totalTime = earlyEnd - startTime;
+ FREE (results[iteration].packetsReceived);
+ SEMAPHORE_DESTROY (postsem);
+ postsem = NULL;
}
- SEMAPHORE_DOWN(postsem, YES);
- MUTEX_LOCK(lock);
- if (earlyEnd == 0)
- earlyEnd = get_time();
- results[iteration].totalTime
- = earlyEnd - startTime;
- FREE(results[iteration].packetsReceived);
- SEMAPHORE_DESTROY(postsem);
- postsem = NULL;
- }
- MUTEX_UNLOCK(lock);
- FREE(p2p);
+ MUTEX_UNLOCK (lock);
+ FREE (p2p);
#if DEBUG_TBENCH
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- "Done waiting for response.\n",
- packetNum,
- size,
- iteration);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_BULK | GE_USER,
+ "Done waiting for response.\n", packetNum, size, iteration);
#endif
sum_loss = 0;
@@ -350,46 +337,47 @@
min_time = 1 * cronYEARS;
max_time = 0;
/* data post-processing */
- for (iteration=0;iteration<iterations;iteration++) {
- sum_loss += results[iteration].lossCount;
- sum_time += results[iteration].totalTime;
+ for (iteration = 0; iteration < iterations; iteration++)
+ {
+ sum_loss += results[iteration].lossCount;
+ sum_time += results[iteration].totalTime;
- if (results[iteration].lossCount > max_loss)
- max_loss = results[iteration].lossCount;
- if (results[iteration].lossCount < min_loss)
- min_loss = results[iteration].lossCount;
- if (results[iteration].totalTime > max_time)
- max_time = results[iteration].totalTime;
- if (results[iteration].totalTime < min_time)
- min_time = results[iteration].totalTime;
- }
+ if (results[iteration].lossCount > max_loss)
+ max_loss = results[iteration].lossCount;
+ if (results[iteration].lossCount < min_loss)
+ min_loss = results[iteration].lossCount;
+ if (results[iteration].totalTime > max_time)
+ max_time = results[iteration].totalTime;
+ if (results[iteration].totalTime < min_time)
+ min_time = results[iteration].totalTime;
+ }
sum_variance_time = 0.0;
sum_variance_loss = 0.0;
- for(iteration = 0; iteration <iterations; iteration++){
- sum_variance_time +=
- (results[iteration].totalTime - sum_time/iterations) *
- (results[iteration].totalTime - sum_time/iterations);
- sum_variance_loss +=
- (results[iteration].lossCount - sum_loss/iterations) *
- (results[iteration].lossCount - sum_loss/iterations);
- }
+ for (iteration = 0; iteration < iterations; iteration++)
+ {
+ sum_variance_time +=
+ (results[iteration].totalTime - sum_time / iterations) *
+ (results[iteration].totalTime - sum_time / iterations);
+ sum_variance_loss +=
+ (results[iteration].lossCount - sum_loss / iterations) *
+ (results[iteration].lossCount - sum_loss / iterations);
+ }
/* send collected stats back to client */
- reply.header.size = htons(sizeof(CS_tbench_reply_MESSAGE));
- reply.header.type = htons(CS_PROTO_tbench_REPLY);
- reply.max_loss = htonl(max_loss);
- reply.min_loss = htonl(min_loss);
- reply.mean_loss = ((float)sum_loss/(float)iterations);
- reply.mean_time = ((float)sum_time/(float)iterations);
- reply.max_time = htonll(max_time);
- reply.min_time = htonll(min_time);
- reply.variance_time = sum_variance_time/(iterations-1);
- reply.variance_loss = sum_variance_loss/(iterations-1);
- FREE(results);
+ reply.header.size = htons (sizeof (CS_tbench_reply_MESSAGE));
+ reply.header.type = htons (CS_PROTO_tbench_REPLY);
+ reply.max_loss = htonl (max_loss);
+ reply.min_loss = htonl (min_loss);
+ reply.mean_loss = ((float) sum_loss / (float) iterations);
+ reply.mean_time = ((float) sum_time / (float) iterations);
+ reply.max_time = htonll (max_time);
+ reply.min_time = htonll (min_time);
+ reply.variance_time = sum_variance_time / (iterations - 1);
+ reply.variance_loss = sum_variance_loss / (iterations - 1);
+ FREE (results);
results = NULL;
- return coreAPI->sendToClient(client,
- &reply.header);
+ return coreAPI->sendToClient (client, &reply.header);
}
/**
@@ -397,40 +385,43 @@
* the library name (libgnunet_XXX => initialize_XXX).
* @return SYSERR on errors
*/
-int initialize_module_tbench(CoreAPIForApplication * capi) {
+int
+initialize_module_tbench (CoreAPIForApplication * capi)
+{
int ok = OK;
ectx = capi->ectx;
- lock = MUTEX_CREATE(NO);
+ lock = MUTEX_CREATE (NO);
coreAPI = capi;
- if (SYSERR == capi->registerHandler(P2P_PROTO_tbench_REPLY,
- &handleTBenchReply))
+ if (SYSERR == capi->registerHandler (P2P_PROTO_tbench_REPLY,
+ &handleTBenchReply))
ok = SYSERR;
- if (SYSERR == capi->registerHandler(P2P_PROTO_tbench_REQUEST,
- &handleTBenchReq))
+ if (SYSERR == capi->registerHandler (P2P_PROTO_tbench_REQUEST,
+ &handleTBenchReq))
ok = SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_tbench_REQUEST,
- &csHandleTBenchRequest))
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_tbench_REQUEST,
+ &csHandleTBenchRequest))
ok = SYSERR;
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "tbench",
- gettext_noop("allows profiling of
direct "
- "peer-to-peer
connections")));
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "tbench",
+ gettext_noop
+ ("allows profiling of
direct "
+ "peer-to-peer
connections")));
return ok;
}
-void done_module_tbench() {
- coreAPI->unregisterHandler(P2P_PROTO_tbench_REQUEST,
- &handleTBenchReq);
- coreAPI->unregisterHandler(P2P_PROTO_tbench_REPLY,
- &handleTBenchReply);
- coreAPI->unregisterClientHandler(CS_PROTO_tbench_REQUEST,
- &csHandleTBenchRequest);
- MUTEX_DESTROY(lock);
+void
+done_module_tbench ()
+{
+ coreAPI->unregisterHandler (P2P_PROTO_tbench_REQUEST, &handleTBenchReq);
+ coreAPI->unregisterHandler (P2P_PROTO_tbench_REPLY, &handleTBenchReply);
+ coreAPI->unregisterClientHandler (CS_PROTO_tbench_REQUEST,
+ &csHandleTBenchRequest);
+ MUTEX_DESTROY (lock);
lock = NULL;
coreAPI = NULL;
}
Modified: GNUnet/src/applications/tbench/tbench.h
===================================================================
--- GNUnet/src/applications/tbench/tbench.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/tbench/tbench.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,7 +30,8 @@
/**
* Client requests peer to perform some profiling.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
* How big is each message (plus headers).
@@ -59,7 +60,7 @@
* Time to wait for the arrival of all repies
* in one iteration.
*/
- cron_t timeOut;
+ cron_t timeOut;
/**
* intPktSpace delay is only introduced every
* trainSize messages.
@@ -74,7 +75,8 @@
/**
* Response from server with statistics.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
unsigned int max_loss;
unsigned int min_loss;
Modified: GNUnet/src/applications/tbench/tbenchtest.c
===================================================================
--- GNUnet/src/applications/tbench/tbenchtest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/tbench/tbenchtest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -38,60 +38,63 @@
static PeerIdentity peer1;
static PeerIdentity peer2;
-static int test(struct ClientServerConnection * sock,
- unsigned int messageSize,
- unsigned int messageCnt,
- unsigned int messageIterations,
- cron_t messageSpacing,
- unsigned int messageTrainSize,
- cron_t messageTimeOut /* in milli-seconds */) {
+static int
+test (struct ClientServerConnection *sock,
+ unsigned int messageSize,
+ unsigned int messageCnt,
+ unsigned int messageIterations,
+ cron_t messageSpacing,
+ unsigned int messageTrainSize,
+ cron_t messageTimeOut /* in milli-seconds */ )
+{
int ret;
CS_tbench_request_MESSAGE msg;
- CS_tbench_reply_MESSAGE * buffer;
+ CS_tbench_reply_MESSAGE *buffer;
float messagesPercentLoss;
- printf(_("Using %u messages of size %u for %u times.\n"),
- messageCnt,
- messageSize,
- messageIterations);
- msg.header.size = htons(sizeof(CS_tbench_request_MESSAGE));
- msg.header.type = htons(CS_PROTO_tbench_REQUEST);
- msg.msgSize = htonl(messageSize);
- msg.msgCnt = htonl(messageCnt);
- msg.iterations = htonl(messageIterations);
- msg.intPktSpace = htonll(messageSpacing);
- msg.trainSize = htonl(messageTrainSize);
- msg.timeOut = htonll(messageTimeOut);
- msg.priority = htonl(5);
- msg.receiverId = peer2;
+ printf (_("Using %u messages of size %u for %u times.\n"),
+ messageCnt, messageSize, messageIterations);
+ msg.header.size = htons (sizeof (CS_tbench_request_MESSAGE));
+ msg.header.type = htons (CS_PROTO_tbench_REQUEST);
+ msg.msgSize = htonl (messageSize);
+ msg.msgCnt = htonl (messageCnt);
+ msg.iterations = htonl (messageIterations);
+ msg.intPktSpace = htonll (messageSpacing);
+ msg.trainSize = htonl (messageTrainSize);
+ msg.timeOut = htonll (messageTimeOut);
+ msg.priority = htonl (5);
+ msg.receiverId = peer2;
- if (SYSERR == connection_write(sock,
- &msg.header))
+ if (SYSERR == connection_write (sock, &msg.header))
return -1;
ret = 0;
buffer = NULL;
- if (OK == connection_read(sock, (MESSAGE_HEADER**)&buffer)) {
- if ((float)buffer->mean_loss <= 0){
- messagesPercentLoss = 0.0;
- } else {
- messagesPercentLoss = (buffer->mean_loss/((float)htons(msg.msgCnt)));
+ if (OK == connection_read (sock, (MESSAGE_HEADER **) & buffer))
+ {
+ if ((float) buffer->mean_loss <= 0)
+ {
+ messagesPercentLoss = 0.0;
+ }
+ else
+ {
+ messagesPercentLoss =
+ (buffer->mean_loss / ((float) htons (msg.msgCnt)));
+ }
+ printf (_
+ ("Times: max %16llu min %16llu mean %12.3f variance
%12.3f\n"),
+ ntohll (buffer->max_time), ntohll (buffer->min_time),
+ buffer->mean_time, buffer->variance_time);
+ printf (_("Loss: max %16u min %16u mean %12.3f variance %12.3f\n"),
+ ntohl (buffer->max_loss), ntohl (buffer->min_loss),
+ buffer->mean_loss, buffer->variance_loss);
}
- printf(_("Times: max %16llu min %16llu mean %12.3f variance %12.3f\n"),
- ntohll(buffer->max_time),
- ntohll(buffer->min_time),
- buffer->mean_time,
- buffer->variance_time);
- printf(_("Loss: max %16u min %16u mean %12.3f variance %12.3f\n"),
- ntohl(buffer->max_loss),
- ntohl(buffer->min_loss),
- buffer->mean_loss,
- buffer->variance_loss);
- } else {
- printf(_("\nFailed to receive reply from gnunetd.\n"));
- ret = -1;
- }
- FREENONNULL(buffer);
+ else
+ {
+ printf (_("\nFailed to receive reply from gnunetd.\n"));
+ ret = -1;
+ }
+ FREENONNULL (buffer);
return ret;
}
@@ -103,66 +106,69 @@
* @param argv command line arguments
* @return 0: ok, -1: error
*/
-int main(int argc, char ** argv) {
+int
+main (int argc, char **argv)
+{
#if START_PEERS
- struct DaemonContext * peers;
+ struct DaemonContext *peers;
#endif
int i;
int ok;
int ret;
- struct ClientServerConnection * sock;
- struct GC_Configuration * cfg;
+ struct ClientServerConnection *sock;
+ struct GC_Configuration *cfg;
ret = 0;
ok = 1;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
#if START_PEERS
- peers = gnunet_testing_start_daemons(NULL == strstr(argv[0], "_udp") ? "tcp"
: "udp",
- "advertising tbench topology stats",
- "/tmp/gnunet-tbench-test",
- 2087,
- 10000,
- 2);
- if (peers == NULL) {
- GC_free(cfg);
- return -1;
- }
+ peers =
+ gnunet_testing_start_daemons (NULL ==
+ strstr (argv[0], "_udp") ? "tcp" : "udp",
+ "advertising tbench topology stats",
+ "/tmp/gnunet-tbench-test", 2087, 10000, 2);
+ if (peers == NULL)
+ {
+ GC_free (cfg);
+ return -1;
+ }
#endif
peer1 = peers->peer;
peer2 = peers->next->peer;
- if (OK != gnunet_testing_connect_daemons(2087,
- 12087)) {
- gnunet_testing_stop_daemons(peers);
- fprintf(stderr,
- "Failed to connect the peers!\n");
- GC_free(cfg);
- return -1;
- }
- sock = client_connection_create(NULL,
- cfg);
- printf(_("Running benchmark...\n"));
+ if (OK != gnunet_testing_connect_daemons (2087, 12087))
+ {
+ gnunet_testing_stop_daemons (peers);
+ fprintf (stderr, "Failed to connect the peers!\n");
+ GC_free (cfg);
+ return -1;
+ }
+ sock = client_connection_create (NULL, cfg);
+ printf (_("Running benchmark...\n"));
/* 'slow' pass: wait for bandwidth negotiation! */
if (ret == 0)
- ret = test(sock, 64, 100, 4, 50 * cronMILLIS, 1, 5 * cronSECONDS);
+ ret = test (sock, 64, 100, 4, 50 * cronMILLIS, 1, 5 * cronSECONDS);
/* 'blast' pass: hit bandwidth limits! */
- for (i=8;i<60000;i*=2) {
- if (ret == 0)
- ret = test(sock, i, 1+1024/i, 4, 10 * cronMILLIS, 2, 2 * cronSECONDS);
- }
- ret = test(sock, 32768, 10, 10, 500 * cronMILLIS, 1, 10 * cronSECONDS);
- connection_destroy(sock);
+ for (i = 8; i < 60000; i *= 2)
+ {
+ if (ret == 0)
+ ret =
+ test (sock, i, 1 + 1024 / i, 4, 10 * cronMILLIS, 2,
+ 2 * cronSECONDS);
+ }
+ ret = test (sock, 32768, 10, 10, 500 * cronMILLIS, 1, 10 * cronSECONDS);
+ connection_destroy (sock);
#if START_PEERS
- gnunet_testing_stop_daemons(peers);
+ gnunet_testing_stop_daemons (peers);
#endif
if (ok == 0)
ret = 1;
- GC_free(cfg);
+ GC_free (cfg);
return ret;
}
Modified: GNUnet/src/applications/template/gnunet-template.c
===================================================================
--- GNUnet/src/applications/template/gnunet-template.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/template/gnunet-template.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -31,33 +31,35 @@
#define TEMPLATE_VERSION "0.0.0"
-static struct SEMAPHORE * doneSem;
+static struct SEMAPHORE *doneSem;
-static char * cfgFilename;
+static char *cfgFilename;
/**
* All gnunetd command line options
*/
static struct CommandLineOption gnunettemplateOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- COMMAND_LINE_OPTION_HELP(gettext_noop("Template description.")), /* -h */
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Template description.")), /* -h
*/
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_END,
};
-static void * receiveThread(void * cls) {
- struct ClientServerConnection * sock = cls;
- void * buffer;
+static void *
+receiveThread (void *cls)
+{
+ struct ClientServerConnection *sock = cls;
+ void *buffer;
- buffer = MALLOC(MAX_BUFFER_SIZE);
- while (OK == connection_read(sock,
- (MESSAGE_HEADER**)&buffer)) {
- /* process */
- }
- FREE(buffer);
- SEMAPHORE_UP(doneSem);
+ buffer = MALLOC (MAX_BUFFER_SIZE);
+ while (OK == connection_read (sock, (MESSAGE_HEADER **) & buffer))
+ {
+ /* process */
+ }
+ FREE (buffer);
+ SEMAPHORE_UP (doneSem);
return NULL;
}
@@ -66,52 +68,49 @@
* @param argv command line arguments
* @return return value from gnunet-template: 0: ok, -1: error
*/
-int main(int argc,
- char * const * argv) {
- struct ClientServerConnection * sock;
- struct PTHREAD * messageReceiveThread;
- void * unused;
- struct GE_Context * ectx;
- struct GC_Configuration * cfg;
+int
+main (int argc, char *const *argv)
+{
+ struct ClientServerConnection *sock;
+ struct PTHREAD *messageReceiveThread;
+ void *unused;
+ struct GE_Context *ectx;
+ struct GC_Configuration *cfg;
int i;
- i = GNUNET_init(argc,
- argv,
- "gnunet-template",
- &cfgFilename,
- gnunettemplateOptions,
- &ectx,
- &cfg);
- if (-1 == i) {
- GNUNET_fini(ectx, cfg);
- return -1;
- }
+ i = GNUNET_init (argc,
+ argv,
+ "gnunet-template",
+ &cfgFilename, gnunettemplateOptions, &ectx, &cfg);
+ if (-1 == i)
+ {
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
- sock = client_connection_create(ectx,
- cfg);
- if (sock == NULL) {
- fprintf(stderr,
- _("Error establishing connection with gnunetd.\n"));
- GNUNET_fini(ectx, cfg);
- return 1;
- }
- messageReceiveThread = PTHREAD_CREATE(&receiveThread,
- sock,
- 128 * 1024);
- if (messageReceiveThread == NULL) {
- GE_DIE_STRERROR(ectx,
- GE_IMMEDIATE | GE_FATAL | GE_USER | GE_ADMIN,
- "pthread_create");
- }
+ sock = client_connection_create (ectx, cfg);
+ if (sock == NULL)
+ {
+ fprintf (stderr, _("Error establishing connection with gnunetd.\n"));
+ GNUNET_fini (ectx, cfg);
+ return 1;
+ }
+ messageReceiveThread = PTHREAD_CREATE (&receiveThread, sock, 128 * 1024);
+ if (messageReceiveThread == NULL)
+ {
+ GE_DIE_STRERROR (ectx,
+ GE_IMMEDIATE | GE_FATAL | GE_USER | GE_ADMIN,
+ "pthread_create");
+ }
/* wait for shutdown... */
- connection_close_forever(sock);
- SEMAPHORE_DOWN(doneSem, YES);
- SEMAPHORE_DESTROY(doneSem);
- PTHREAD_JOIN(messageReceiveThread, &unused);
- connection_destroy(sock);
- GNUNET_fini(ectx, cfg);
+ connection_close_forever (sock);
+ SEMAPHORE_DOWN (doneSem, YES);
+ SEMAPHORE_DESTROY (doneSem);
+ PTHREAD_JOIN (messageReceiveThread, &unused);
+ connection_destroy (sock);
+ GNUNET_fini (ectx, cfg);
return 0;
}
Modified: GNUnet/src/applications/template/template.c
===================================================================
--- GNUnet/src/applications/template/template.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/template/template.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -29,58 +29,60 @@
#include "gnunet_core.h"
#include "gnunet_protocols.h"
-static CoreAPIForApplication * coreAPI = NULL;
-static struct ClientHandle * client;
-static struct MUTEX * lock;
+static CoreAPIForApplication *coreAPI = NULL;
+static struct ClientHandle *client;
+static struct MUTEX *lock;
-static int handlep2pMSG(const PeerIdentity * sender,
- const MESSAGE_HEADER * message) {
+static int
+handlep2pMSG (const PeerIdentity * sender, const MESSAGE_HEADER * message)
+{
return OK;
}
-static int csHandle(struct ClientHandle * client,
- const MESSAGE_HEADER * message) {
+static int
+csHandle (struct ClientHandle *client, const MESSAGE_HEADER * message)
+{
return OK;
}
-static void clientExitHandler(struct ClientHandle * c) {
- MUTEX_LOCK(lock);
+static void
+clientExitHandler (struct ClientHandle *c)
+{
+ MUTEX_LOCK (lock);
if (c == client)
client = NULL;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
-int initialize_module_template(CoreAPIForApplication * capi) {
+int
+initialize_module_template (CoreAPIForApplication * capi)
+{
int ok = OK;
- lock = MUTEX_CREATE(NO);
+ lock = MUTEX_CREATE (NO);
client = NULL;
coreAPI = capi;
- GE_LOG(capi->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _("`%s' registering client handler %d and %d\n"),
- "template",
- CS_PROTO_MAX_USED,
- P2P_PROTO_MAX_USED);
- if (SYSERR == capi->registerHandler(P2P_PROTO_MAX_USED,
- &handlep2pMSG))
+ GE_LOG (capi->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ _("`%s' registering client handler %d and %d\n"),
+ "template", CS_PROTO_MAX_USED, P2P_PROTO_MAX_USED);
+ if (SYSERR == capi->registerHandler (P2P_PROTO_MAX_USED, &handlep2pMSG))
ok = SYSERR;
- if (SYSERR == capi->registerClientExitHandler(&clientExitHandler))
+ if (SYSERR == capi->registerClientExitHandler (&clientExitHandler))
ok = SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_MAX_USED,
- &csHandle))
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_MAX_USED, &csHandle))
ok = SYSERR;
return ok;
}
-void done_module_template() {
- coreAPI->unregisterHandler(P2P_PROTO_MAX_USED,
- &handlep2pMSG);
- coreAPI->unregisterClientExitHandler(&clientExitHandler);
- coreAPI->unregisterClientHandler(CS_PROTO_MAX_USED,
- &csHandle);
- MUTEX_DESTROY(lock);
+void
+done_module_template ()
+{
+ coreAPI->unregisterHandler (P2P_PROTO_MAX_USED, &handlep2pMSG);
+ coreAPI->unregisterClientExitHandler (&clientExitHandler);
+ coreAPI->unregisterClientHandler (CS_PROTO_MAX_USED, &csHandle);
+ MUTEX_DESTROY (lock);
coreAPI = NULL;
}
Modified: GNUnet/src/applications/testbed/commands.c
===================================================================
--- GNUnet/src/applications/testbed/commands.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/testbed/commands.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -43,17 +43,18 @@
/**
* @brief struct keeping per-peer information for the testbed
*/
-typedef struct {
+typedef struct
+{
/** IP address of the peer */
- IPaddr ip;
+ IPaddr ip;
/** CS port of the peer */
- unsigned short port;
+ unsigned short port;
/** string describing the peer address */
- char * ips;
+ char *ips;
/** socket to communicate with the peer */
struct ClientServerConnection sock;
/** hello message identifying the peer in the network */
- P2P_hello_MESSAGE * helo;
+ P2P_hello_MESSAGE *helo;
/** if we're using ssh, what is the PID of the
ssh process? (-1 for unencrypted direct connections) */
pid_t ssh;
@@ -62,7 +63,7 @@
/**
* List of nodes known to the testbed.
*/
-static NODE_INFO * nodes = NULL;
+static NODE_INFO *nodes = NULL;
/**
* Number of known nodes, size of the nodes array.
@@ -102,37 +103,29 @@
* Send a message to peer 'peer' of type 'msgType'
* the given size and data.
*/
-static int sendMessage(unsigned msgType,
- int peer,
- unsigned short argSize,
- void *arg) {
- TESTBED_CS_MESSAGE * msg;
+static int
+sendMessage (unsigned msgType, int peer, unsigned short argSize, void *arg)
+{
+ TESTBED_CS_MESSAGE *msg;
int msgsz;
/* Assume peer value is valid. */
- if (argSize + sizeof(TESTBED_CS_MESSAGE) > 65535)
- errexit("Message body too big for sendMessage: %s\n",
- argSize);
+ if (argSize + sizeof (TESTBED_CS_MESSAGE) > 65535)
+ errexit ("Message body too big for sendMessage: %s\n", argSize);
- msgsz = sizeof(TESTBED_CS_MESSAGE)+argSize;
- msg = MALLOC(msgsz);
- msg->header.size
- = htons(msgsz);
- msg->header.type
- = htons(CS_PROTO_testbed_REQUEST);
- msg->msgType
- = htonl(msgType);
- memcpy(&((TESTBED_CS_MESSAGE_GENERIC*)msg)->data[0],
- arg,
- argSize);
- msgsz = connection_write(&nodes[peer].sock,
- &msg->header);
- FREE(msg);
- if (msgsz == SYSERR) {
- XPRINTF(" Could not send message to peer %s.\n",
- nodes[peer].ips);
- return SYSERR;
- }
+ msgsz = sizeof (TESTBED_CS_MESSAGE) + argSize;
+ msg = MALLOC (msgsz);
+ msg->header.size = htons (msgsz);
+ msg->header.type = htons (CS_PROTO_testbed_REQUEST);
+ msg->msgType = htonl (msgType);
+ memcpy (&((TESTBED_CS_MESSAGE_GENERIC *) msg)->data[0], arg, argSize);
+ msgsz = connection_write (&nodes[peer].sock, &msg->header);
+ FREE (msg);
+ if (msgsz == SYSERR)
+ {
+ XPRINTF (" Could not send message to peer %s.\n", nodes[peer].ips);
+ return SYSERR;
+ }
return OK;
}
@@ -142,14 +135,14 @@
*
* @return OK on success, SYSERR on error
*/
-static int readResult(int peer,
- int * result) {
- if (OK != connection_read_result(&nodes[peer].sock,
- result)) {
- XPRINTF(" peer %s is not responding.\n",
- nodes[peer].ips);
- return SYSERR;
- }
+static int
+readResult (int peer, int *result)
+{
+ if (OK != connection_read_result (&nodes[peer].sock, result))
+ {
+ XPRINTF (" peer %s is not responding.\n", nodes[peer].ips);
+ return SYSERR;
+ }
return OK;
}
@@ -160,97 +153,101 @@
* Add a node to the configuration.
* Arguments must be IP PORT of the peer.
*/
-static int addNode(int argc, char * argv[]) {
+static int
+addNode (int argc, char *argv[])
+{
int currindex;
- TESTBED_hello_MESSAGE * hdr;
+ TESTBED_hello_MESSAGE *hdr;
TESTBED_GET_hello_MESSAGE req;
int port;
int i;
- if (argc != 2) {
- XPRINTF("Syntax: add-node IP PORT.\n");
- return -1;
- }
- port = atoi(argv[1]);
- for (i=0;i<nnodes;i++) {
- if ( (0 == strcmp(argv[0],
- nodes[i].ips)) &&
- (port == nodes[i].port) ) {
- XPRINTF("Node already in use!\n");
+ if (argc != 2)
+ {
+ XPRINTF ("Syntax: add-node IP PORT.\n");
return -1;
}
- }
+ port = atoi (argv[1]);
+ for (i = 0; i < nnodes; i++)
+ {
+ if ((0 == strcmp (argv[0], nodes[i].ips)) && (port == nodes[i].port))
+ {
+ XPRINTF ("Node already in use!\n");
+ return -1;
+ }
+ }
req.proto = 0;
req.reserved = 0;
/* connect */
currindex = nnodes;
- GROW(nodes, nnodes, nnodes+1);
- nodes[currindex].ips = STRDUP(argv[0]);
- nodes[currindex].port = atoi(argv[1]);
+ GROW (nodes, nnodes, nnodes + 1);
+ nodes[currindex].ips = STRDUP (argv[0]);
+ nodes[currindex].port = atoi (argv[1]);
nodes[currindex].ssh = -1;
#ifndef MINGW
- inet_aton(argv[0], (struct in_addr*) &nodes[currindex].ip);
+ inet_aton (argv[0], (struct in_addr *) &nodes[currindex].ip);
#else
- nodes[currindex].ip.addr.S_un.S_addr = inet_addr(argv[0]);
+ nodes[currindex].ip.addr.S_un.S_addr = inet_addr (argv[0]);
#endif
- if (SYSERR == initGNUnetClientSocket(nodes[currindex].port,
- nodes[currindex].ips,
- &nodes[currindex].sock)) {
- XPRINTF(" could not connect to %s:%d.\n",
- nodes[currindex].ips,
- nodes[currindex].port);
- return -1;
- }
+ if (SYSERR == initGNUnetClientSocket (nodes[currindex].port,
+ nodes[currindex].ips,
+ &nodes[currindex].sock))
+ {
+ XPRINTF (" could not connect to %s:%d.\n",
+ nodes[currindex].ips, nodes[currindex].port);
+ return -1;
+ }
/* request hello */
- if (OK != sendMessage(TESTBED_GET_hello,
- currindex,
- sizeof(TESTBED_GET_hello_MESSAGE)-sizeof(TESTBED_CS_MESSAGE),
- &req.proto)) {
- /* send message already printed an error message */
- destroySocket(&nodes[currindex].sock);
- FREE(nodes[currindex].ips);
- GROW(nodes,
- nnodes,
- nnodes-1);
- return -1;
- }
+ if (OK != sendMessage (TESTBED_GET_hello,
+ currindex,
+ sizeof (TESTBED_GET_hello_MESSAGE) -
+ sizeof (TESTBED_CS_MESSAGE), &req.proto))
+ {
+ /* send message already printed an error message */
+ destroySocket (&nodes[currindex].sock);
+ FREE (nodes[currindex].ips);
+ GROW (nodes, nnodes, nnodes - 1);
+ return -1;
+ }
hdr = NULL;
- if (SYSERR == connection_read(&nodes[currindex].sock,
- (CS_MESSAGE_HEADER**)&hdr)) {
- XPRINTF(" peer %s is not responding.\n",
- nodes[currindex].ips);
- destroySocket(&nodes[currindex].sock);
- FREE(nodes[currindex].ips);
- GROW(nodes, nnodes, nnodes-1);
- return -1;
- }
- if ( (ntohs(hdr->header.header.type) == CS_PROTO_testbed_REPLY) &&
- (ntohs(hdr->header.header.size) >= sizeof(TESTBED_hello_MESSAGE)) &&
- (ntohl(hdr->header.msgType) == TESTBED_hello_RESPONSE) &&
- (ntohs(hdr->header.header.size) - sizeof(TESTBED_CS_MESSAGE) >=
sizeof(P2P_hello_MESSAGE)) &&
- (ntohs(hdr->header.header.size) - sizeof(TESTBED_CS_MESSAGE) ==
P2P_hello_MESSAGE_size(&hdr->helo)) ) {
- nodes[currindex].helo
- = MALLOC(P2P_hello_MESSAGE_size(&hdr->helo));
- memcpy(nodes[currindex].helo,
- &hdr->helo,
- P2P_hello_MESSAGE_size(&hdr->helo));
- } else {
- FREE(hdr);
- destroySocket(&nodes[currindex].sock);
- XPRINTF(" peer %s did not respond with proper hello.\n",
- nodes[currindex].ips);
- FREE(nodes[currindex].ips);
- GROW(nodes, nnodes, nnodes-1);
- return -1;
- }
- FREE(hdr);
- XPRINTF("%d\n",
- currindex);
+ if (SYSERR == connection_read (&nodes[currindex].sock,
+ (CS_MESSAGE_HEADER **) & hdr))
+ {
+ XPRINTF (" peer %s is not responding.\n", nodes[currindex].ips);
+ destroySocket (&nodes[currindex].sock);
+ FREE (nodes[currindex].ips);
+ GROW (nodes, nnodes, nnodes - 1);
+ return -1;
+ }
+ if ((ntohs (hdr->header.header.type) == CS_PROTO_testbed_REPLY) &&
+ (ntohs (hdr->header.header.size) >= sizeof (TESTBED_hello_MESSAGE)) &&
+ (ntohl (hdr->header.msgType) == TESTBED_hello_RESPONSE) &&
+ (ntohs (hdr->header.header.size) - sizeof (TESTBED_CS_MESSAGE) >=
+ sizeof (P2P_hello_MESSAGE))
+ && (ntohs (hdr->header.header.size) - sizeof (TESTBED_CS_MESSAGE) ==
+ P2P_hello_MESSAGE_size (&hdr->helo)))
+ {
+ nodes[currindex].helo = MALLOC (P2P_hello_MESSAGE_size (&hdr->helo));
+ memcpy (nodes[currindex].helo,
+ &hdr->helo, P2P_hello_MESSAGE_size (&hdr->helo));
+ }
+ else
+ {
+ FREE (hdr);
+ destroySocket (&nodes[currindex].sock);
+ XPRINTF (" peer %s did not respond with proper hello.\n",
+ nodes[currindex].ips);
+ FREE (nodes[currindex].ips);
+ GROW (nodes, nnodes, nnodes - 1);
+ return -1;
+ }
+ FREE (hdr);
+ XPRINTF ("%d\n", currindex);
return 0;
}
@@ -261,9 +258,11 @@
* Arguments must be LOGIN, IP PORT of the peer. Sshd must
* be running on the default port.
*/
-static int addSshNode(int argc, char * argv[]) {
+static int
+addSshNode (int argc, char *argv[])
+{
int currindex;
- TESTBED_hello_MESSAGE * hdr;
+ TESTBED_hello_MESSAGE *hdr;
TESTBED_GET_hello_MESSAGE req;
int port;
int i;
@@ -273,193 +272,177 @@
int ret;
int status;
- if (argc != 3) {
- XPRINTF("Syntax: add-ssh-node LOGIN IP PORT.\n");
- return -1;
- }
- port = atoi(argv[2]);
- for (i=0;i<nnodes;i++) {
- if ( (0 == strcmp(argv[1],
- nodes[i].ips)) &&
- (port == nodes[i].port) ) {
- XPRINTF("Node already in use!\n");
+ if (argc != 3)
+ {
+ XPRINTF ("Syntax: add-ssh-node LOGIN IP PORT.\n");
return -1;
}
- }
+ port = atoi (argv[2]);
+ for (i = 0; i < nnodes; i++)
+ {
+ if ((0 == strcmp (argv[1], nodes[i].ips)) && (port == nodes[i].port))
+ {
+ XPRINTF ("Node already in use!\n");
+ return -1;
+ }
+ }
/* find available local port to bind to */
- for (lport=10000;lport<65535;lport++) {
- struct sockaddr_in addr;
- int s;
- const int on = 1;
+ for (lport = 10000; lport < 65535; lport++)
+ {
+ struct sockaddr_in addr;
+ int s;
+ const int on = 1;
- s = SOCKET(PF_INET, SOCK_STREAM, 0);
- if (s == -1) {
- XPRINTF("Cannot open socket: %s\n",
- STRERROR(errno));
+ s = SOCKET (PF_INET, SOCK_STREAM, 0);
+ if (s == -1)
+ {
+ XPRINTF ("Cannot open socket: %s\n", STRERROR (errno));
+ return -1;
+ }
+ if (SETSOCKOPT (s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0)
+ perror ("setsockopt");
+ memset (&addr, 0, sizeof (addr));
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = htonl (INADDR_ANY);
+ addr.sin_port = htons (lport);
+ if (0 == BIND (s,
+ (const struct sockaddr *) &addr,
+ sizeof (struct sockaddr_in)))
+ {
+ closefile (s);
+ break; /* found port! */
+ }
+ else
+ {
+ closefile (s); /* not available, try another one... */
+ }
+ }
+ if (lport == 65535)
+ {
+ XPRINTF (" Cannot find available local port!\n");
return -1;
}
- if ( SETSOCKOPT(s,
- SOL_SOCKET,
- SO_REUSEADDR,
- &on, sizeof(on)) < 0 )
- perror("setsockopt");
- memset(&addr,
- 0,
- sizeof(addr));
- addr.sin_family
- = AF_INET;
- addr.sin_addr.s_addr
- = htonl(INADDR_ANY);
- addr.sin_port
- = htons(lport);
- if (0 == BIND(s,
- (const struct sockaddr *) &addr,
- sizeof(struct sockaddr_in))) {
- closefile(s);
- break; /* found port! */
- } else {
- closefile(s); /* not available, try another one... */
+
+ pid = fork ();
+ if (pid == 0)
+ {
+ char *sargv[7];
+ char pohopo[64];
+ sargv[0] = "ssh";
+ sargv[1] = "-l";
+ sargv[2] = argv[0]; /* login */
+ sargv[3] = "-L";
+ SNPRINTF (pohopo, 64, "%d:%s:%d", lport, /* local port */
+ "localhost", /* loopback on remote host */
+ port /* remote port */ );
+ sargv[4] = pohopo;
+ sargv[5] = argv[1]; /* remote hostname */
+ sargv[6] = NULL; /* last argument */
+ execvp ("ssh", sargv);
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ " execvp failed: %s\n", STRERROR (errno));
+ exit (-1);
}
- }
- if (lport == 65535) {
- XPRINTF(" Cannot find available local port!\n");
- return -1;
- }
+ if (pid == -1)
+ {
+ XPRINTF ("Failed to fork: %s\n", STRERROR (errno));
+ return -1;
+ }
- pid = fork();
- if (pid == 0) {
- char * sargv[7];
- char pohopo[64];
- sargv[0] = "ssh";
- sargv[1] = "-l";
- sargv[2] = argv[0]; /* login */
- sargv[3] = "-L";
- SNPRINTF(pohopo,
- 64,
- "%d:%s:%d",
- lport, /* local port */
- "localhost", /* loopback on remote host */
- port /* remote port */);
- sargv[4] = pohopo;
- sargv[5] = argv[1]; /* remote hostname */
- sargv[6] = NULL; /* last argument */
- execvp("ssh",
- sargv);
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- " execvp failed: %s\n",
- STRERROR(errno));
- exit(-1);
- }
- if (pid == -1) {
- XPRINTF("Failed to fork: %s\n",
- STRERROR(errno));
- return -1;
- }
-
req.proto = 0;
req.reserved = 0;
/* connect */
currindex = nnodes;
- GROW(nodes, nnodes, nnodes+1);
- nodes[currindex].ips = STRDUP("localhost");
+ GROW (nodes, nnodes, nnodes + 1);
+ nodes[currindex].ips = STRDUP ("localhost");
nodes[currindex].port = lport;
nodes[currindex].ssh = pid;
#ifndef MINGW
- inet_aton(argv[0], (struct in_addr*) &nodes[currindex].ip);
+ inet_aton (argv[0], (struct in_addr *) &nodes[currindex].ip);
#else
- nodes[currindex].ip.addr.S_un.S_addr = inet_addr(argv[0]);
+ nodes[currindex].ip.addr.S_un.S_addr = inet_addr (argv[0]);
#endif
/* FIXME: wait a bit to give ssh a chance to connect... */
- rtc = 0; /* number of retries */
- while (rtc < 5) {
- ret = initGNUnetClientSocket(nodes[currindex].port,
- nodes[currindex].ips,
- &nodes[currindex].sock);
- if (ret == OK)
- break;
- rtc++;
- PTHREAD_SLEEP(cronSECONDS);
- }
- if (ret == SYSERR) {
- XPRINTF(" could not connect to %s:%d.\n",
- nodes[currindex].ips,
- nodes[currindex].port);
- kill(nodes[currindex].ssh,
- SIGTERM);
- waitpid(nodes[currindex].ssh,
- &status,
- 0);
- GROW(nodes, nnodes, nnodes-1);
- return -1;
- }
+ rtc = 0; /* number of retries */
+ while (rtc < 5)
+ {
+ ret = initGNUnetClientSocket (nodes[currindex].port,
+ nodes[currindex].ips,
+ &nodes[currindex].sock);
+ if (ret == OK)
+ break;
+ rtc++;
+ PTHREAD_SLEEP (cronSECONDS);
+ }
+ if (ret == SYSERR)
+ {
+ XPRINTF (" could not connect to %s:%d.\n",
+ nodes[currindex].ips, nodes[currindex].port);
+ kill (nodes[currindex].ssh, SIGTERM);
+ waitpid (nodes[currindex].ssh, &status, 0);
+ GROW (nodes, nnodes, nnodes - 1);
+ return -1;
+ }
/* request hello */
- if (OK != sendMessage(TESTBED_GET_hello,
- currindex,
- sizeof(TESTBED_GET_hello_MESSAGE)-sizeof(TESTBED_CS_MESSAGE),
- &req.proto)) {
- /* send message already printed an error message */
- destroySocket(&nodes[currindex].sock);
- FREE(nodes[currindex].ips);
- /* fixme: check error conditions on kill/waidpid! */
- kill(nodes[currindex].ssh,
- SIGTERM);
- waitpid(nodes[currindex].ssh,
- &status,
- 0);
- GROW(nodes,
- nnodes,
- nnodes-1);
- return -1;
- }
+ if (OK != sendMessage (TESTBED_GET_hello,
+ currindex,
+ sizeof (TESTBED_GET_hello_MESSAGE) -
+ sizeof (TESTBED_CS_MESSAGE), &req.proto))
+ {
+ /* send message already printed an error message */
+ destroySocket (&nodes[currindex].sock);
+ FREE (nodes[currindex].ips);
+ /* fixme: check error conditions on kill/waidpid! */
+ kill (nodes[currindex].ssh, SIGTERM);
+ waitpid (nodes[currindex].ssh, &status, 0);
+ GROW (nodes, nnodes, nnodes - 1);
+ return -1;
+ }
hdr = NULL;
- if (SYSERR == connection_read(&nodes[currindex].sock,
- (CS_MESSAGE_HEADER**)&hdr)) {
- XPRINTF(" peer %s is not responding.\n",
- nodes[currindex].ips);
- destroySocket(&nodes[currindex].sock);
- FREE(nodes[currindex].ips);
- /* fixme: check error conditions on kill/waidpid! */
- kill(nodes[currindex].ssh,
- SIGTERM);
- waitpid(nodes[currindex].ssh,
- &status,
- 0);
- GROW(nodes, nnodes, nnodes-1);
- return -1;
- }
- if ( (ntohs(hdr->header.header.type) == CS_PROTO_testbed_REPLY) &&
- (ntohs(hdr->header.header.size) >= sizeof(TESTBED_hello_MESSAGE)) &&
- (ntohl(hdr->header.msgType) == TESTBED_hello_RESPONSE) &&
- (ntohs(hdr->header.header.size) - sizeof(TESTBED_CS_MESSAGE) >=
sizeof(P2P_hello_MESSAGE)) &&
- (ntohs(hdr->header.header.size) - sizeof(TESTBED_CS_MESSAGE) ==
P2P_hello_MESSAGE_size(&hdr->helo)) ) {
- nodes[currindex].helo
- = MALLOC(P2P_hello_MESSAGE_size(&hdr->helo));
- memcpy(nodes[currindex].helo,
- &hdr->helo,
- P2P_hello_MESSAGE_size(&hdr->helo));
- } else {
- FREE(hdr);
- destroySocket(&nodes[currindex].sock);
- XPRINTF(" peer %s did not respond with proper hello.\n",
- nodes[currindex].ips);
- FREE(nodes[currindex].ips);
- /* fixme: check error conditions on kill/waidpid! */
- kill(nodes[currindex].ssh,
- SIGTERM);
- waitpid(nodes[currindex].ssh,
- &status,
- 0);
- GROW(nodes, nnodes, nnodes-1);
- return -1;
- }
- FREE(hdr);
- XPRINTF("%d\n",
- currindex);
+ if (SYSERR == connection_read (&nodes[currindex].sock,
+ (CS_MESSAGE_HEADER **) & hdr))
+ {
+ XPRINTF (" peer %s is not responding.\n", nodes[currindex].ips);
+ destroySocket (&nodes[currindex].sock);
+ FREE (nodes[currindex].ips);
+ /* fixme: check error conditions on kill/waidpid! */
+ kill (nodes[currindex].ssh, SIGTERM);
+ waitpid (nodes[currindex].ssh, &status, 0);
+ GROW (nodes, nnodes, nnodes - 1);
+ return -1;
+ }
+ if ((ntohs (hdr->header.header.type) == CS_PROTO_testbed_REPLY) &&
+ (ntohs (hdr->header.header.size) >= sizeof (TESTBED_hello_MESSAGE)) &&
+ (ntohl (hdr->header.msgType) == TESTBED_hello_RESPONSE) &&
+ (ntohs (hdr->header.header.size) - sizeof (TESTBED_CS_MESSAGE) >=
+ sizeof (P2P_hello_MESSAGE))
+ && (ntohs (hdr->header.header.size) - sizeof (TESTBED_CS_MESSAGE) ==
+ P2P_hello_MESSAGE_size (&hdr->helo)))
+ {
+ nodes[currindex].helo = MALLOC (P2P_hello_MESSAGE_size (&hdr->helo));
+ memcpy (nodes[currindex].helo,
+ &hdr->helo, P2P_hello_MESSAGE_size (&hdr->helo));
+ }
+ else
+ {
+ FREE (hdr);
+ destroySocket (&nodes[currindex].sock);
+ XPRINTF (" peer %s did not respond with proper hello.\n",
+ nodes[currindex].ips);
+ FREE (nodes[currindex].ips);
+ /* fixme: check error conditions on kill/waidpid! */
+ kill (nodes[currindex].ssh, SIGTERM);
+ waitpid (nodes[currindex].ssh, &status, 0);
+ GROW (nodes, nnodes, nnodes - 1);
+ return -1;
+ }
+ FREE (hdr);
+ XPRINTF ("%d\n", currindex);
return 0;
}
@@ -467,381 +450,416 @@
/**
* Tear down the connection between two peers.
*/
-static int delConnection(int argc,
- char * argv[]) {
+static int
+delConnection (int argc, char *argv[])
+{
int src, dst, ack;
- if (argc != 2) {
- XPRINTF("Syntax: disconnect PEERID PEERID\n");
+ if (argc != 2)
+ {
+ XPRINTF ("Syntax: disconnect PEERID PEERID\n");
+ return -1;
+ }
+ CHECK_SRC_DST (src, dst, argv[0], argv[1]);
+ if (OK != sendMessage (TESTBED_DEL_PEER,
+ src,
+ sizeof (PeerIdentity),
+ &nodes[dst].helo->senderIdentity))
return -1;
- }
- CHECK_SRC_DST(src, dst, argv[0], argv[1]);
- if (OK != sendMessage(TESTBED_DEL_PEER,
- src,
- sizeof(PeerIdentity),
- &nodes[dst].helo->senderIdentity))
+ if (OK != readResult (src, &ack))
return -1;
- if (OK != readResult(src,
- &ack))
- return -1;
- if (ack == OK) {
- XPRINTF("OK.\n");
- return 0;
- } else {
- XPRINTF(" Connection NOT deleted.\n");
- return -1;
- }
+ if (ack == OK)
+ {
+ XPRINTF ("OK.\n");
+ return 0;
+ }
+ else
+ {
+ XPRINTF (" Connection NOT deleted.\n");
+ return -1;
+ }
}
/**
* Tear down all connections of a peer.
*/
-static int delAllConnections(int argc,
- char * argv[]) {
+static int
+delAllConnections (int argc, char *argv[])
+{
int dst, ack;
- if (argc != 1) {
- XPRINTF("Syntax: disconnect-all PEERID\n");
+ if (argc != 1)
+ {
+ XPRINTF ("Syntax: disconnect-all PEERID\n");
+ return -1;
+ }
+ CHECK_PEER (dst, argv[0]);
+ if (OK != sendMessage (TESTBED_DEL_ALL_PEERS, dst, 0, NULL))
return -1;
- }
- CHECK_PEER(dst, argv[0]);
- if (OK != sendMessage(TESTBED_DEL_ALL_PEERS,
- dst,
- 0,
- NULL))
+ if (OK != readResult (dst, &ack))
return -1;
- if (OK != readResult(dst,
- &ack))
- return -1;
- if (ack == OK) {
- XPRINTF("OK.\n");
- return 0;
- } else {
- XPRINTF(" Connections NOT deleted.\n");
- return -1;
- }
+ if (ack == OK)
+ {
+ XPRINTF ("OK.\n");
+ return 0;
+ }
+ else
+ {
+ XPRINTF (" Connections NOT deleted.\n");
+ return -1;
+ }
}
/**
* Add a connection between two peers.
*/
-static int addConnection(int argc,
- char * argv[]) {
+static int
+addConnection (int argc, char *argv[])
+{
int src, dst, ack;
- if (argc != 2) {
- XPRINTF("Syntax: connect PEERID PEERID\n");
+ if (argc != 2)
+ {
+ XPRINTF ("Syntax: connect PEERID PEERID\n");
+ return -1;
+ }
+ CHECK_SRC_DST (src, dst, argv[0], argv[1]);
+ if (SYSERR == sendMessage (TESTBED_ADD_PEER,
+ src,
+ P2P_hello_MESSAGE_size (nodes[dst].helo),
+ nodes[dst].helo))
return -1;
- }
- CHECK_SRC_DST(src, dst, argv[0], argv[1]);
- if (SYSERR == sendMessage(TESTBED_ADD_PEER,
- src,
- P2P_hello_MESSAGE_size(nodes[dst].helo),
- nodes[dst].helo))
+ if (OK != readResult (src, &ack))
return -1;
- if (OK != readResult(src,
- &ack))
- return -1;
- if (ack == OK) {
- XPRINTF("OK.\n");
- return 0;
- } else {
- XPRINTF(" peer cannot connect.\n");
- return -1;
- }
+ if (ack == OK)
+ {
+ XPRINTF ("OK.\n");
+ return 0;
+ }
+ else
+ {
+ XPRINTF (" peer cannot connect.\n");
+ return -1;
+ }
}
/**
* Set the level of trust that one peer has in
* another.
*/
-static int setTrust(int argc, char * argv[]) {
+static int
+setTrust (int argc, char *argv[])
+{
int src, dst, value, ack;
TESTBED_SET_TVALUE_MESSAGE msg;
- if (argc != 3) {
- XPRINTF("Syntax: set-trust PEERID PEERID TRUST\n");
+ if (argc != 3)
+ {
+ XPRINTF ("Syntax: set-trust PEERID PEERID TRUST\n");
+ return -1;
+ }
+ CHECK_SRC_DST (src, dst, argv[0], argv[1]);
+ value = atoi (argv[2]);
+ msg.trust = htonl (value);
+ memcpy (&msg.otherPeer,
+ &nodes[dst].helo->senderIdentity, sizeof (PeerIdentity));
+ if (SYSERR == sendMessage (TESTBED_SET_TVALUE,
+ src,
+ sizeof (PeerIdentity) + sizeof (unsigned int),
+ &msg.otherPeer))
return -1;
- }
- CHECK_SRC_DST(src, dst, argv[0], argv[1]);
- value = atoi(argv[2]);
- msg.trust = htonl(value);
- memcpy(&msg.otherPeer,
- &nodes[dst].helo->senderIdentity,
- sizeof(PeerIdentity));
- if (SYSERR == sendMessage(TESTBED_SET_TVALUE,
- src,
- sizeof(PeerIdentity)+sizeof(unsigned int),
- &msg.otherPeer))
+ if (OK != readResult (src, &ack))
return -1;
- if (OK != readResult(src,
- &ack))
- return -1;
- if (htonl(ack) != OK) {
- XPRINTF(" peer could not set trust value.\n");
- return -1;
- } else {
- XPRINTF("OK.\n");
- return 0;
- }
+ if (htonl (ack) != OK)
+ {
+ XPRINTF (" peer could not set trust value.\n");
+ return -1;
+ }
+ else
+ {
+ XPRINTF ("OK.\n");
+ return 0;
+ }
}
/**
* Get the amount of trust that A has in B.
*/
-static int getTrust(int argc, char *argv[]) {
+static int
+getTrust (int argc, char *argv[])
+{
int src, dst, value;
- if (argc != 2) {
- XPRINTF("Syntax: get-trust PEERID PEERID\n");
+ if (argc != 2)
+ {
+ XPRINTF ("Syntax: get-trust PEERID PEERID\n");
+ return -1;
+ }
+ CHECK_SRC_DST (src, dst, argv[0], argv[1]);
+ if (SYSERR == sendMessage (TESTBED_GET_TVALUE,
+ src,
+ sizeof (PeerIdentity),
+ &nodes[dst].helo->senderIdentity))
return -1;
- }
- CHECK_SRC_DST(src, dst, argv[0], argv[1]);
- if (SYSERR == sendMessage(TESTBED_GET_TVALUE,
- src,
- sizeof(PeerIdentity),
- &nodes[dst].helo->senderIdentity))
+ if (SYSERR == readResult (src, &value))
return -1;
- if (SYSERR == readResult(src, &value))
- return -1;
- if (value < 0) {
- XPRINTF(" could not get trust value.\n");
- return -1;
- } else {
- XPRINTF("%d\n",
- value);
- return 0;
- }
+ if (value < 0)
+ {
+ XPRINTF (" could not get trust value.\n");
+ return -1;
+ }
+ else
+ {
+ XPRINTF ("%d\n", value);
+ return 0;
+ }
}
/**
* Disable hello at a peer.
*/
-static int disablehello(int argc, char *argv[]) {
+static int
+disablehello (int argc, char *argv[])
+{
int dst, value;
- if (argc != 1) {
- XPRINTF("Syntax: helo-disable PEERID\n");
+ if (argc != 1)
+ {
+ XPRINTF ("Syntax: helo-disable PEERID\n");
+ return -1;
+ }
+ CHECK_PEER (dst, argv[0]);
+ if (SYSERR == sendMessage (TESTBED_DISABLE_hello, dst, 0, NULL))
return -1;
- }
- CHECK_PEER(dst, argv[0]);
- if (SYSERR == sendMessage(TESTBED_DISABLE_hello,
- dst,
- 0,
- NULL))
+ if (SYSERR == readResult (dst, &value))
return -1;
- if (SYSERR == readResult(dst, &value))
- return -1;
- if (value != OK) {
- XPRINTF(" could disable hello\n");
- return -1;
- } else {
- XPRINTF("OK.\n");
- return 0;
- }
+ if (value != OK)
+ {
+ XPRINTF (" could disable hello\n");
+ return -1;
+ }
+ else
+ {
+ XPRINTF ("OK.\n");
+ return 0;
+ }
}
/**
* Enable hello at a peer.
*/
-static int enablehello(int argc, char *argv[]) {
+static int
+enablehello (int argc, char *argv[])
+{
int dst, value;
- if (argc != 1) {
- XPRINTF("Syntax: helo-enable PEERID\n");
+ if (argc != 1)
+ {
+ XPRINTF ("Syntax: helo-enable PEERID\n");
+ return -1;
+ }
+ CHECK_PEER (dst, argv[0]);
+ if (SYSERR == sendMessage (TESTBED_ENABLE_hello, dst, 0, NULL))
return -1;
- }
- CHECK_PEER(dst, argv[0]);
- if (SYSERR == sendMessage(TESTBED_ENABLE_hello,
- dst,
- 0,
- NULL))
+ if (SYSERR == readResult (dst, &value))
return -1;
- if (SYSERR == readResult(dst, &value))
- return -1;
- if (value != OK) {
- XPRINTF(" could enable hello\n");
- return -1;
- } else {
- XPRINTF("OK.\n");
- return 0;
- }
+ if (value != OK)
+ {
+ XPRINTF (" could enable hello\n");
+ return -1;
+ }
+ else
+ {
+ XPRINTF ("OK.\n");
+ return 0;
+ }
}
/**
* Disable AUTOCONNECT at a peer.
*/
-static int disableAUTOCONNECT(int argc, char *argv[]) {
+static int
+disableAUTOCONNECT (int argc, char *argv[])
+{
int dst, value;
- if (argc != 1) {
- XPRINTF("Syntax: autoconnect-disable PEERID\n");
+ if (argc != 1)
+ {
+ XPRINTF ("Syntax: autoconnect-disable PEERID\n");
+ return -1;
+ }
+ CHECK_PEER (dst, argv[0]);
+ if (SYSERR == sendMessage (TESTBED_DISABLE_AUTOCONNECT, dst, 0, NULL))
return -1;
- }
- CHECK_PEER(dst, argv[0]);
- if (SYSERR == sendMessage(TESTBED_DISABLE_AUTOCONNECT,
- dst,
- 0,
- NULL))
+ if (SYSERR == readResult (dst, &value))
return -1;
- if (SYSERR == readResult(dst, &value))
- return -1;
- if (value != OK) {
- XPRINTF(" could disable AUTOCONNECT\n");
- return -1;
- } else {
- XPRINTF("OK.\n");
- return 0;
- }
+ if (value != OK)
+ {
+ XPRINTF (" could disable AUTOCONNECT\n");
+ return -1;
+ }
+ else
+ {
+ XPRINTF ("OK.\n");
+ return 0;
+ }
}
/**
* Enable AUTOCONNECT at a peer.
*/
-static int enableAUTOCONNECT(int argc, char *argv[]) {
+static int
+enableAUTOCONNECT (int argc, char *argv[])
+{
int dst, value;
- if (argc != 1) {
- XPRINTF("Syntax: autoconnect-enable PEERID\n");
+ if (argc != 1)
+ {
+ XPRINTF ("Syntax: autoconnect-enable PEERID\n");
+ return -1;
+ }
+ CHECK_PEER (dst, argv[0]);
+ if (SYSERR == sendMessage (TESTBED_ENABLE_AUTOCONNECT, dst, 0, NULL))
return -1;
- }
- CHECK_PEER(dst, argv[0]);
- if (SYSERR == sendMessage(TESTBED_ENABLE_AUTOCONNECT,
- dst,
- 0,
- NULL))
+ if (SYSERR == readResult (dst, &value))
return -1;
- if (SYSERR == readResult(dst, &value))
- return -1;
- if (value != OK) {
- XPRINTF(" could enable AUTOCONNECT\n");
- return -1;
- } else {
- XPRINTF("OK.\n");
- return 0;
- }
+ if (value != OK)
+ {
+ XPRINTF (" could enable AUTOCONNECT\n");
+ return -1;
+ }
+ else
+ {
+ XPRINTF ("OK.\n");
+ return 0;
+ }
}
-static int allowDenyConnectHelper(unsigned int argc,
- char * argv[],
- int type) {
+static int
+allowDenyConnectHelper (unsigned int argc, char *argv[], int type)
+{
int dst, value;
- PeerIdentity * list;
+ PeerIdentity *list;
int i;
int idx = 0;
- CHECK_PEER(dst, argv[0]);
- if (argc > (65532 - sizeof(TESTBED_CS_MESSAGE)) / sizeof(PeerIdentity)) {
- XPRINTF("Too many peers specified. Ask a wizard to enlarge limit.\n");
- return -1;
- }
+ CHECK_PEER (dst, argv[0]);
+ if (argc > (65532 - sizeof (TESTBED_CS_MESSAGE)) / sizeof (PeerIdentity))
+ {
+ XPRINTF ("Too many peers specified. Ask a wizard to enlarge limit.\n");
+ return -1;
+ }
list = NULL;
- for (i=1;i<argc;i++)
- CHECK_PEER(idx, argv[i]); /* may return, do before MALLOC! */
+ for (i = 1; i < argc; i++)
+ CHECK_PEER (idx, argv[i]); /* may return, do before MALLOC! */
if (argc > 1)
- list = MALLOC(sizeof(PeerIdentity)*(argc-1));
- for (i=1;i<argc;i++) {
- CHECK_PEER(idx, argv[i]);
- memcpy(&list[i-1],
- &nodes[idx].helo->senderIdentity,
- sizeof(PeerIdentity));
- }
- if (SYSERR == sendMessage(type,
- dst,
- sizeof(PeerIdentity)*(argc-1),
- list)) {
- FREENONNULL(list);
+ list = MALLOC (sizeof (PeerIdentity) * (argc - 1));
+ for (i = 1; i < argc; i++)
+ {
+ CHECK_PEER (idx, argv[i]);
+ memcpy (&list[i - 1],
+ &nodes[idx].helo->senderIdentity, sizeof (PeerIdentity));
+ }
+ if (SYSERR == sendMessage (type,
+ dst, sizeof (PeerIdentity) * (argc - 1), list))
+ {
+ FREENONNULL (list);
+ return -1;
+ }
+ FREENONNULL (list);
+ if (SYSERR == readResult (dst, &value))
return -1;
- }
- FREENONNULL(list);
- if (SYSERR == readResult(dst, &value))
- return -1;
- if (value != OK) {
- XPRINTF(" could change setting.\n");
- return -1;
- } else {
- XPRINTF("OK.\n");
- return 0;
- }
+ if (value != OK)
+ {
+ XPRINTF (" could change setting.\n");
+ return -1;
+ }
+ else
+ {
+ XPRINTF ("OK.\n");
+ return 0;
+ }
}
/**
* Deny connections to certain peers at a peer.
*/
-static int denyConnect(int argc, char *argv[]) {
- if (argc < 1) {
- XPRINTF("Syntax: connect-deny PEERID [PEERID]*\n");
- return -1;
- }
- return allowDenyConnectHelper(argc, argv,
- TESTBED_DENY_CONNECT);
+static int
+denyConnect (int argc, char *argv[])
+{
+ if (argc < 1)
+ {
+ XPRINTF ("Syntax: connect-deny PEERID [PEERID]*\n");
+ return -1;
+ }
+ return allowDenyConnectHelper (argc, argv, TESTBED_DENY_CONNECT);
}
/**
* Allow connections to certain peers at a peer.
*/
-static int allowConnect(int argc, char *argv[]) {
- if (argc < 1) {
- XPRINTF("Syntax: connect-allow PEERID [PEERID]*\n");
- return -1;
- }
- return allowDenyConnectHelper(argc, argv,
- TESTBED_ALLOW_CONNECT);
+static int
+allowConnect (int argc, char *argv[])
+{
+ if (argc < 1)
+ {
+ XPRINTF ("Syntax: connect-allow PEERID [PEERID]*\n");
+ return -1;
+ }
+ return allowDenyConnectHelper (argc, argv, TESTBED_ALLOW_CONNECT);
}
/**
* Helper function for (un)loadModule.
* @param type load or unload requested?
*/
-static int loadModuleHelper(unsigned short type,
- char * peerId,
- char * modulename) {
+static int
+loadModuleHelper (unsigned short type, char *peerId, char *modulename)
+{
int ok, dst;
- CHECK_PEER(dst, peerId);
- if (OK != sendMessage(type,
- dst,
- strlen(modulename),
- modulename))
+ CHECK_PEER (dst, peerId);
+ if (OK != sendMessage (type, dst, strlen (modulename), modulename))
return -1;
- if (OK != readResult(dst,
- &ok))
+ if (OK != readResult (dst, &ok))
return -1;
- if (ok != OK) {
- XPRINTF(" peer %s refused.\n",
- nodes[dst].ips);
- return -1;
- }
- XPRINTF("OK.\n");
+ if (ok != OK)
+ {
+ XPRINTF (" peer %s refused.\n", nodes[dst].ips);
+ return -1;
+ }
+ XPRINTF ("OK.\n");
return 0;
}
/**
* Load an application module at the given peer.
*/
-static int loadModule(int argc, char *argv[]) {
- if (argc != 2) {
- XPRINTF("Syntax: load-module PEERID MODULENAME\n");
- return -1;
- }
- return loadModuleHelper(TESTBED_LOAD_MODULE,
- argv[0],
- argv[1]);
+static int
+loadModule (int argc, char *argv[])
+{
+ if (argc != 2)
+ {
+ XPRINTF ("Syntax: load-module PEERID MODULENAME\n");
+ return -1;
+ }
+ return loadModuleHelper (TESTBED_LOAD_MODULE, argv[0], argv[1]);
}
/**
* Unload an application module.
*/
-static int unloadModule(int argc, char *argv[]) {
- if (argc != 2) {
- XPRINTF("Syntax: unload-module PEERID MODULENAME\n");
- return -1;
- }
- return loadModuleHelper(TESTBED_UNLOAD_MODULE,
- argv[0],
- argv[1]);
+static int
+unloadModule (int argc, char *argv[])
+{
+ if (argc != 2)
+ {
+ XPRINTF ("Syntax: unload-module PEERID MODULENAME\n");
+ return -1;
+ }
+ return loadModuleHelper (TESTBED_UNLOAD_MODULE, argv[0], argv[1]);
}
/**
@@ -849,51 +867,51 @@
* available via process-output. The client can be killed
* using process-signal. The process identifier is printed.
*/
-static int startProcess(int argc,
- char *argv[]) {
- char * cmdLine;
+static int
+startProcess (int argc, char *argv[])
+{
+ char *cmdLine;
int size;
int i;
int dst;
int ack;
int pos;
- if (argc < 2) {
- XPRINTF("Syntax: process-start PEERID COMMAND [ARGUMENTS]\n");
- return -1;
- }
- CHECK_PEER(dst, argv[0]);
+ if (argc < 2)
+ {
+ XPRINTF ("Syntax: process-start PEERID COMMAND [ARGUMENTS]\n");
+ return -1;
+ }
+ CHECK_PEER (dst, argv[0]);
size = 0;
- for (i=1;i<argc;i++)
- size += 1 + strlen(argv[i]);
- cmdLine = MALLOC(size);
+ for (i = 1; i < argc; i++)
+ size += 1 + strlen (argv[i]);
+ cmdLine = MALLOC (size);
pos = 0;
- for (i=1;i<argc;i++) {
- memcpy(&cmdLine[pos],
- argv[i],
- strlen(argv[i])+1);
- pos += strlen(argv[i])+1;
- }
+ for (i = 1; i < argc; i++)
+ {
+ memcpy (&cmdLine[pos], argv[i], strlen (argv[i]) + 1);
+ pos += strlen (argv[i]) + 1;
+ }
- if (OK != sendMessage(TESTBED_EXEC,
- dst,
- size,
- cmdLine)) {
- FREE(cmdLine);
+ if (OK != sendMessage (TESTBED_EXEC, dst, size, cmdLine))
+ {
+ FREE (cmdLine);
+ return -1;
+ }
+ FREE (cmdLine);
+ if (OK != readResult (dst, &ack))
return -1;
- }
- FREE(cmdLine);
- if (OK != readResult(dst,
- &ack))
- return -1;
- if (ack != SYSERR) {
- XPRINTF("%d\n",
- ack);
- return 0;
- } else {
- XPRINTF(" Peer could not fork process.\n");
- return -1;
- }
+ if (ack != SYSERR)
+ {
+ XPRINTF ("%d\n", ack);
+ return 0;
+ }
+ else
+ {
+ XPRINTF (" Peer could not fork process.\n");
+ return -1;
+ }
}
/**
@@ -906,175 +924,193 @@
* is still running, -1 is returned (which can then
* NOT be distinguished from the process returning -1)
*/
-static int signalProcess(int argc, char *argv[]) {
+static int
+signalProcess (int argc, char *argv[])
+{
int dst;
int ack;
TESTBED_SIGNAL_MESSAGE msg;
- if (argc != 3) {
- XPRINTF("Syntax: process-signal PEERID PROCESSID SIGNAL\n");
+ if (argc != 3)
+ {
+ XPRINTF ("Syntax: process-signal PEERID PROCESSID SIGNAL\n");
+ return -1;
+ }
+ CHECK_PEER (dst, argv[0]);
+ msg.pid = htonl (atoi (argv[1]));
+ msg.signal = htonl (atoi (argv[2]));
+ if (OK != sendMessage (TESTBED_SIGNAL,
+ dst,
+ sizeof (TESTBED_SIGNAL_MESSAGE) -
+ sizeof (TESTBED_CS_MESSAGE), &msg.pid))
return -1;
- }
- CHECK_PEER(dst, argv[0]);
- msg.pid = htonl(atoi(argv[1]));
- msg.signal = htonl(atoi(argv[2]));
- if (OK != sendMessage(TESTBED_SIGNAL,
- dst,
- sizeof(TESTBED_SIGNAL_MESSAGE) - sizeof(TESTBED_CS_MESSAGE),
- &msg.pid))
+ if (OK != readResult (dst, &ack))
return -1;
- if (OK != readResult(dst,
- &ack))
- return -1;
- if (ntohl(msg.signal) == -1) {
- XPRINTF("%d\n", ack);
- return 0;
- }
- if (ack == OK) {
- XPRINTF("OK.\n");
- return 0;
- } else {
- XPRINTF(" Peer could not signal process.\n");
- return -1;
- }
+ if (ntohl (msg.signal) == -1)
+ {
+ XPRINTF ("%d\n", ack);
+ return 0;
+ }
+ if (ack == OK)
+ {
+ XPRINTF ("OK.\n");
+ return 0;
+ }
+ else
+ {
+ XPRINTF (" Peer could not signal process.\n");
+ return -1;
+ }
}
/**
* Get the recorded output of a process.
*/
-static int dumpProcessOutput(int argc,
- char * argv[]) {
+static int
+dumpProcessOutput (int argc, char *argv[])
+{
int dst;
int pid;
unsigned int ack;
- if (argc != 2) {
- XPRINTF("Syntax: process-output PEERID PROCESSID\n");
+ if (argc != 2)
+ {
+ XPRINTF ("Syntax: process-output PEERID PROCESSID\n");
+ return -1;
+ }
+ CHECK_PEER (dst, argv[0]);
+ pid = htonl (atoi (argv[1]));
+ if (OK != sendMessage (TESTBED_GET_OUTPUT, dst, sizeof (int), &pid))
return -1;
- }
- CHECK_PEER(dst, argv[0]);
- pid = htonl(atoi(argv[1]));
- if (OK != sendMessage(TESTBED_GET_OUTPUT,
- dst,
- sizeof(int),
- &pid))
+ if (OK != readResult (dst, (int *) &ack))
return -1;
- if (OK != readResult(dst,
- (int*) &ack))
- return -1;
- if (ack != SYSERR) {
- char * tmp;
- unsigned int pos = 0;
- while (pos < ack) {
- unsigned short size;
- TESTBED_OUTPUT_REPLY_MESSAGE * reply;
+ if (ack != SYSERR)
+ {
+ char *tmp;
+ unsigned int pos = 0;
+ while (pos < ack)
+ {
+ unsigned short size;
+ TESTBED_OUTPUT_REPLY_MESSAGE *reply;
- reply = NULL;
- if (SYSERR == connection_read(&nodes[dst].sock,
- (CS_MESSAGE_HEADER**)&reply)) {
- XPRINTF(" peer %s is not responding after %d of %d bytes.\n",
- nodes[dst].ips,
- pos,
- ack);
- return -1;
- }
- /* FIXME: check that this is the correct reply format */
- size = ntohs(reply->header.header.size) -
sizeof(TESTBED_OUTPUT_REPLY_MESSAGE);
- tmp = MALLOC(size+1);
- memcpy(tmp,
- &((TESTBED_OUTPUT_REPLY_MESSAGE_GENERIC*)reply)->data[0],
- size);
- tmp[size] = '\0';
- XPRINTF("%s",
- tmp);
- FREE(tmp);
- FREE(reply);
- pos += size;
+ reply = NULL;
+ if (SYSERR == connection_read (&nodes[dst].sock,
+ (CS_MESSAGE_HEADER **) & reply))
+ {
+ XPRINTF (" peer %s is not responding after %d of %d bytes.\n",
+ nodes[dst].ips, pos, ack);
+ return -1;
+ }
+ /* FIXME: check that this is the correct reply format */
+ size =
+ ntohs (reply->header.header.size) -
+ sizeof (TESTBED_OUTPUT_REPLY_MESSAGE);
+ tmp = MALLOC (size + 1);
+ memcpy (tmp,
+ &((TESTBED_OUTPUT_REPLY_MESSAGE_GENERIC *) reply)->data[0],
+ size);
+ tmp[size] = '\0';
+ XPRINTF ("%s", tmp);
+ FREE (tmp);
+ FREE (reply);
+ pos += size;
+ }
+ return 0;
}
- return 0;
- } else {
- XPRINTF(" Peer could not return process output.\n");
- return -1;
- }
+ else
+ {
+ XPRINTF (" Peer could not return process output.\n");
+ return -1;
+ }
}
/**
* Set bandwidth limitations for a peer.
*/
-static int setBW(int argc, char * argv[]) {
+static int
+setBW (int argc, char *argv[])
+{
TESTBED_SET_BW_MESSAGE msg;
int dst, in, out, ack;
- if (argc != 3) {
- XPRINTF("Syntax: set-bw PEERID DOWN-BPS UP-BPS\n");
+ if (argc != 3)
+ {
+ XPRINTF ("Syntax: set-bw PEERID DOWN-BPS UP-BPS\n");
+ return -1;
+ }
+ CHECK_PEER (dst, argv[0]);
+ in = atoi (argv[1]);
+ out = atoi (argv[2]);
+ if ((in < 0) || (out < 0))
+ {
+ XPRINTF (" Invalid bandwidth specification.\n");
+ return -1;
+ }
+ msg.in_bw = htonl (in);
+ msg.out_bw = htonl (out);
+ if (SYSERR == sendMessage (TESTBED_SET_BW,
+ dst,
+ sizeof (TESTBED_SET_BW_MESSAGE) -
+ sizeof (TESTBED_CS_MESSAGE), &msg.in_bw))
return -1;
- }
- CHECK_PEER(dst, argv[0]);
- in = atoi(argv[1]);
- out = atoi(argv[2]);
- if ((in < 0) || (out < 0)) {
- XPRINTF(" Invalid bandwidth specification.\n");
+ if (OK != readResult (dst, &ack))
return -1;
- }
- msg.in_bw = htonl(in);
- msg.out_bw = htonl(out);
- if (SYSERR == sendMessage(TESTBED_SET_BW,
- dst,
- sizeof(TESTBED_SET_BW_MESSAGE) - sizeof(TESTBED_CS_MESSAGE),
- &msg.in_bw))
- return -1;
- if (OK != readResult(dst, &ack))
- return -1;
- if (ack != OK) {
- XPRINTF(" peer could not set the specified bandwith.\n");
- return -1;
- } else {
- XPRINTF("OK.\n");
- return 0;
- }
+ if (ack != OK)
+ {
+ XPRINTF (" peer could not set the specified bandwith.\n");
+ return -1;
+ }
+ else
+ {
+ XPRINTF ("OK.\n");
+ return 0;
+ }
}
/**
* Set artifical message loss rates for a peer.
*/
-static int setLoss(int argc, char * argv[]) {
+static int
+setLoss (int argc, char *argv[])
+{
int dst;
int ack;
TESTBED_SET_LOSS_RATE_MESSAGE msg;
- if (argc != 3) {
- XPRINTF("Syntax: set-loss PEERID DOWN-LOSS UP-LOSS\n");
- return -1;
- }
- CHECK_PEER(dst, argv[0]);
- msg.percentageLossInbound
- = htonl(atoi(argv[1]));
- msg.percentageLossOutbound
- = htonl(atoi(argv[2]));
+ if (argc != 3)
+ {
+ XPRINTF ("Syntax: set-loss PEERID DOWN-LOSS UP-LOSS\n");
+ return -1;
+ }
+ CHECK_PEER (dst, argv[0]);
+ msg.percentageLossInbound = htonl (atoi (argv[1]));
+ msg.percentageLossOutbound = htonl (atoi (argv[2]));
- if (SYSERR == sendMessage(TESTBED_SET_LOSS_RATE,
- dst,
- sizeof(TESTBED_SET_LOSS_RATE_MESSAGE) -
sizeof(TESTBED_CS_MESSAGE),
- &msg.percentageLossInbound))
+ if (SYSERR == sendMessage (TESTBED_SET_LOSS_RATE,
+ dst,
+ sizeof (TESTBED_SET_LOSS_RATE_MESSAGE) -
+ sizeof (TESTBED_CS_MESSAGE),
+ &msg.percentageLossInbound))
return -1;
- if (OK != readResult(dst, &ack))
+ if (OK != readResult (dst, &ack))
return -1;
- if (ack != OK) {
- XPRINTF(" peer could not set the specified loss rates.\n");
- return -1;
- } else {
- XPRINTF("OK.\n");
- return 0;
- }
+ if (ack != OK)
+ {
+ XPRINTF (" peer could not set the specified loss rates.\n");
+ return -1;
+ }
+ else
+ {
+ XPRINTF ("OK.\n");
+ return 0;
+ }
}
-static int printStatistic(const char * name,
- unsigned long long value,
- const char * arg) {
- if (0 == strcmp(name,
- arg))
- XPRINTF("%llu\n",
- value);
+static int
+printStatistic (const char *name, unsigned long long value, const char *arg)
+{
+ if (0 == strcmp (name, arg))
+ XPRINTF ("%llu\n", value);
return OK;
}
@@ -1085,18 +1121,20 @@
* @param argv command line arguments
* @return 0 ok, 1 on error
*/
-static int getStat(int argc, char ** argv) {
+static int
+getStat (int argc, char **argv)
+{
int res, peer, printProtocols;
printProtocols = NO;
- if (argc != 2) {
- XPRINTF("Syntax: get-stat PEERID STATID\n");
- return -1;
- }
- CHECK_PEER(peer, argv[0]);
- res = requestStatistics(&nodes[peer].sock,
- (StatisticsProcessor) &printStatistic,
- argv[1]);
+ if (argc != 2)
+ {
+ XPRINTF ("Syntax: get-stat PEERID STATID\n");
+ return -1;
+ }
+ CHECK_PEER (peer, argv[0]);
+ res = requestStatistics (&nodes[peer].sock,
+ (StatisticsProcessor) & printStatistic, argv[1]);
if (res == OK)
return 0;
else
@@ -1109,40 +1147,36 @@
* @param stream where to print the statistics
* @return OK on success, SYSERR on error
*/
-static int printStatistics(const char * name,
- unsigned long long value,
- void * unused) {
- XPRINTF("%-60s: %16llu\n",
- name,
- value);
+static int
+printStatistics (const char *name, unsigned long long value, void *unused)
+{
+ XPRINTF ("%-60s: %16llu\n", name, value);
return OK;
}
static int lastIp2p;
-static int printProtocols(unsigned short type,
- int isP2P,
- void * unused) {
+static int
+printProtocols (unsigned short type, int isP2P, void *unused)
+{
const char *name = NULL;
- if (isP2P != lastIp2p) {
- if (isP2P)
- XPRINTF(_("Supported peer-to-peer messages:\n"));
- else
- XPRINTF(_("Supported client-server messages:\n"));
- lastIp2p = isP2P;
- }
+ if (isP2P != lastIp2p)
+ {
+ if (isP2P)
+ XPRINTF (_("Supported peer-to-peer messages:\n"));
+ else
+ XPRINTF (_("Supported client-server messages:\n"));
+ lastIp2p = isP2P;
+ }
if (isP2P)
- name = p2pMessageName(type);
+ name = p2pMessageName (type);
else
- name = csMessageName(type);
+ name = csMessageName (type);
if (name == NULL)
- XPRINTF("\t%d\n",
- type);
+ XPRINTF ("\t%d\n", type);
else
- XPRINTF("\t%d\t(%s)\n",
- type,
- name);
+ XPRINTF ("\t%d\t(%s)\n", type, name);
return OK;
}
@@ -1153,32 +1187,38 @@
* @param argv command line arguments
* @return 0 ok, 1 on error
*/
-static int getStats(int argc, char ** argv) {
+static int
+getStats (int argc, char **argv)
+{
int res, peer, printProtocolsOpt;
printProtocolsOpt = NO;
- if (argc == 2) {
- if (strcmp(argv[0], "-P")) {
- XPRINTF("Syntax: get-stats [-P] PEERID\n");
+ if (argc == 2)
+ {
+ if (strcmp (argv[0], "-P"))
+ {
+ XPRINTF ("Syntax: get-stats [-P] PEERID\n");
+ return -1;
+ }
+ printProtocolsOpt = YES;
+ CHECK_PEER (peer, argv[1]);
+ }
+ else if (argc != 1)
+ {
+ XPRINTF ("Syntax: get-stats [-P] PEERID\n");
return -1;
}
- printProtocolsOpt = YES;
- CHECK_PEER(peer, argv[1]);
- } else if (argc != 1) {
- XPRINTF("Syntax: get-stats [-P] PEERID\n");
- return -1;
- } else
- CHECK_PEER(peer, argv[0]);
- res = requestStatistics(&nodes[peer].sock,
- (StatisticsProcessor) &printStatistics,
- NULL);
- if ( (printProtocolsOpt == YES) &&
- (res == OK)) {
- lastIp2p = 42; /* not YES or NO */
- res = requestAvailableProtocols(&nodes[peer].sock,
- (ProtocolProcessor) &printProtocols,
- NULL);
- }
+ else
+ CHECK_PEER (peer, argv[0]);
+ res = requestStatistics (&nodes[peer].sock,
+ (StatisticsProcessor) & printStatistics, NULL);
+ if ((printProtocolsOpt == YES) && (res == OK))
+ {
+ lastIp2p = 42; /* not YES or NO */
+ res = requestAvailableProtocols (&nodes[peer].sock,
+ (ProtocolProcessor) & printProtocols,
+ NULL);
+ }
if (res == OK)
return 0;
else
@@ -1193,26 +1233,26 @@
* @param argv command line arguments
* @return 0 ok, 1 on error
*/
-static int getOption(int argc, char ** argv) {
+static int
+getOption (int argc, char **argv)
+{
int peer;
- char * opt;
+ char *opt;
- if (argc != 3) {
- XPRINTF("Syntax: get-option PEERID SECTION OPTION\n");
- return -1;
- }
- CHECK_PEER(peer, argv[0]);
- opt = getConfigurationOptionValue(&nodes[peer].sock,
- argv[1],
- argv[2]);
- if (opt == NULL) {
- XPRINTF("Error sending request to peer %d\n",
- peer);
- return -1;
- }
- XPRINTF("%s\n",
- opt);
- FREE(opt);
+ if (argc != 3)
+ {
+ XPRINTF ("Syntax: get-option PEERID SECTION OPTION\n");
+ return -1;
+ }
+ CHECK_PEER (peer, argv[0]);
+ opt = getConfigurationOptionValue (&nodes[peer].sock, argv[1], argv[2]);
+ if (opt == NULL)
+ {
+ XPRINTF ("Error sending request to peer %d\n", peer);
+ return -1;
+ }
+ XPRINTF ("%s\n", opt);
+ FREE (opt);
return 0;
}
@@ -1220,217 +1260,199 @@
/**
* Upload a file to a peer.
*/
-static int uploadFile(int argc,
- char *argv[]) {
+static int
+uploadFile (int argc, char *argv[])
+{
int peer, nbytes, flen, ack;
- char * buf;
- FILE * infile;
- TESTBED_UPLOAD_FILE_MESSAGE * msg;
+ char *buf;
+ FILE *infile;
+ TESTBED_UPLOAD_FILE_MESSAGE *msg;
- if (argc != 3) {
- XPRINTF("Syntax: load-file PEERID LOCAL_FILENAME DEST_FILENAME\n");
- return -1;
- }
- CHECK_PEER(peer, argv[0]);
- infile = FOPEN(argv[1], "r");
- if (infile == NULL) {
- XPRINTF(" Could not open file %s\n",
- argv[1]);
- return -1;
- }
- flen = strlen(argv[2]) + 1; /* '\0' added in the flen */
- if (flen > TESTBED_FILE_BLK_SIZE) {
- XPRINTF(" destination file name too long (%d characters, limit %d).\n",
- flen-1,
- TESTBED_FILE_BLK_SIZE);
- return -1;
- }
+ if (argc != 3)
+ {
+ XPRINTF ("Syntax: load-file PEERID LOCAL_FILENAME DEST_FILENAME\n");
+ return -1;
+ }
+ CHECK_PEER (peer, argv[0]);
+ infile = FOPEN (argv[1], "r");
+ if (infile == NULL)
+ {
+ XPRINTF (" Could not open file %s\n", argv[1]);
+ return -1;
+ }
+ flen = strlen (argv[2]) + 1; /* '\0' added in the flen */
+ if (flen > TESTBED_FILE_BLK_SIZE)
+ {
+ XPRINTF (" destination file name too long (%d characters, limit %d).\n",
+ flen - 1, TESTBED_FILE_BLK_SIZE);
+ return -1;
+ }
- msg = MALLOC(sizeof(TESTBED_UPLOAD_FILE_MESSAGE) + TESTBED_FILE_BLK_SIZE);
+ msg = MALLOC (sizeof (TESTBED_UPLOAD_FILE_MESSAGE) + TESTBED_FILE_BLK_SIZE);
msg->header.header.size
- = htons(sizeof(TESTBED_UPLOAD_FILE_MESSAGE)+flen);
- msg->header.header.type
- = htons(CS_PROTO_testbed_REQUEST);
- msg->header.msgType
- = htonl(TESTBED_UPLOAD_FILE);
- msg->type
- = htonl(TESTBED_FILE_DELETE);
- memcpy(((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC*)msg)->buf, argv[2], flen);
+ = htons (sizeof (TESTBED_UPLOAD_FILE_MESSAGE) + flen);
+ msg->header.header.type = htons (CS_PROTO_testbed_REQUEST);
+ msg->header.msgType = htonl (TESTBED_UPLOAD_FILE);
+ msg->type = htonl (TESTBED_FILE_DELETE);
+ memcpy (((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC *) msg)->buf, argv[2], flen);
- if (SYSERR == connection_write(&nodes[peer].sock,
- &msg->header.header)) {
- fclose(infile);
- FREE(msg);
- XPRINTF(" Could not send message to peer %s.\n",
- nodes[peer].ips);
- return -1;
- }
+ if (SYSERR == connection_write (&nodes[peer].sock, &msg->header.header))
+ {
+ fclose (infile);
+ FREE (msg);
+ XPRINTF (" Could not send message to peer %s.\n", nodes[peer].ips);
+ return -1;
+ }
/* Read ack from the peer */
- if (OK != connection_read_result(&nodes[peer].sock, &ack)) {
- fclose(infile);
- FREE(msg);
- XPRINTF("Peer is not responding\n");
- return -1;
- }
- if (ack != OK) {
- fclose(infile);
- FREE(msg);
- XPRINTF(" Peer returned error (delete existing file).\n");
- return -1;
- }
- msg->type = htonl(TESTBED_FILE_APPEND);
- buf = ((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC*)msg)->buf + flen;
- while ((nbytes = GN_FREAD(buf, 1,
- (TESTBED_FILE_BLK_SIZE -
- sizeof(TESTBED_UPLOAD_FILE_MESSAGE) - flen),
- infile)) > 0) {
- if (ferror(infile))
- break;
- msg->header.header.size = htons(sizeof(TESTBED_UPLOAD_FILE_MESSAGE) +
- nbytes + flen);
- if (SYSERR == connection_write(&nodes[peer].sock, &msg->header.header)) {
- fclose(infile);
- FREE(msg);
- XPRINTF(" could not send file to node %s.\n",
- nodes[peer].ips);
+ if (OK != connection_read_result (&nodes[peer].sock, &ack))
+ {
+ fclose (infile);
+ FREE (msg);
+ XPRINTF ("Peer is not responding\n");
return -1;
}
- if (OK != readResult(peer, &ack)) {
- fclose(infile);
- FREE(msg);
+ if (ack != OK)
+ {
+ fclose (infile);
+ FREE (msg);
+ XPRINTF (" Peer returned error (delete existing file).\n");
return -1;
}
- if (ack != OK) {
- fclose(infile);
- FREE(msg);
- XPRINTF(" peer returned error.\n");
+ msg->type = htonl (TESTBED_FILE_APPEND);
+ buf = ((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC *) msg)->buf + flen;
+ while ((nbytes = GN_FREAD (buf, 1,
+ (TESTBED_FILE_BLK_SIZE -
+ sizeof (TESTBED_UPLOAD_FILE_MESSAGE) - flen),
+ infile)) > 0)
+ {
+ if (ferror (infile))
+ break;
+ msg->header.header.size = htons (sizeof (TESTBED_UPLOAD_FILE_MESSAGE) +
+ nbytes + flen);
+ if (SYSERR == connection_write (&nodes[peer].sock, &msg->header.header))
+ {
+ fclose (infile);
+ FREE (msg);
+ XPRINTF (" could not send file to node %s.\n", nodes[peer].ips);
+ return -1;
+ }
+ if (OK != readResult (peer, &ack))
+ {
+ fclose (infile);
+ FREE (msg);
+ return -1;
+ }
+ if (ack != OK)
+ {
+ fclose (infile);
+ FREE (msg);
+ XPRINTF (" peer returned error.\n");
+ return -1;
+ }
+ }
+ if (ferror (infile))
+ {
+ fclose (infile);
+ FREE (msg);
+ XPRINTF (" could not read source file. Transmission aborted.\n");
return -1;
}
- }
- if (ferror(infile)) {
- fclose(infile);
- FREE(msg);
- XPRINTF(" could not read source file. Transmission aborted.\n");
- return -1;
- }
- fclose(infile);
- FREE(msg);
- XPRINTF("OK.\n");
+ fclose (infile);
+ FREE (msg);
+ XPRINTF ("OK.\n");
return 0;
}
/**
* Print the list of commands.
*/
-static int printOnlineHelp(int argc,
- char * argv[]) {
+static int
+printOnlineHelp (int argc, char *argv[])
+{
int i;
i = 0;
- while (commands[i].command != NULL) {
- XPRINTF("%-30s%s\n",
- commands[i].command,
- commands[i].help);
- i++;
- }
+ while (commands[i].command != NULL)
+ {
+ XPRINTF ("%-30s%s\n", commands[i].command, commands[i].help);
+ i++;
+ }
return 0;
}
-static int processCommands(char * buffer,
- unsigned int * available) {
+static int
+processCommands (char *buffer, unsigned int *available)
+{
int ip[4];
int port;
unsigned int end;
unsigned int start;
- char * up;
+ char *up;
int err;
err = 0;
end = 0;
start = 0;
- while (end < *available) {
- while ( (buffer[end] != '\n') &&
- (end < *available) )
+ while (end < *available)
+ {
+ while ((buffer[end] != '\n') && (end < *available))
+ end++;
+ if (buffer[end] != '\n')
+ {
+ if (start == 0)
+ {
+ XPRINTF ("Received invalid response from HTTP server!\n");
+ return -1;
+ }
+ else
+ {
+ memmove (buffer, &buffer[start], *available - start);
+ *available -= start;
+ return 0;
+ }
+ }
+ up = MALLOC (end - start + 1);
+ memcpy (up, &buffer[start], end - start);
+ up[end - start] = '\0';
+ port = 2087; /* default port */
+ if (4 <= sscanf (up,
+ "add-node %d %d %d %d %d",
+ &ip[0], &ip[1], &ip[2], &ip[3], &port))
+ {
+ char ports[12];
+ char ips[128];
+ char *argv[2];
+ SNPRINTF (ports, 12, "%d", port);
+ SNPRINTF (ips, 128, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
+ argv[0] = ips;
+ argv[1] = ports;
+ if (0 != addNode (2, argv))
+ err = 2;
+ }
+ else
+ {
+ char *login;
+ login = MALLOC (64);
+ if (5 <= sscanf (up,
+ "add-node %63s %d %d %d %d %d",
+ login, &ip[0], &ip[1], &ip[2], &ip[3], &port))
+ {
+ char ports[12];
+ char ips[128];
+ char *argv[3];
+ SNPRINTF (ports, 12, "%d", port);
+ SNPRINTF (ips, 128, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
+ argv[0] = login;
+ argv[1] = ips;
+ argv[2] = ports;
+ if (0 != addSshNode (3, argv))
+ err = 2;
+ }
+ FREE (login);
+ }
+ FREE (up);
end++;
- if (buffer[end] != '\n') {
- if (start == 0) {
- XPRINTF("Received invalid response from HTTP server!\n");
- return -1;
- } else {
- memmove(buffer,
- &buffer[start],
- *available - start);
- *available -= start;
- return 0;
- }
+ start = end;
}
- up = MALLOC(end-start+1);
- memcpy(up,
- &buffer[start],
- end - start);
- up[end-start] = '\0';
- port = 2087; /* default port */
- if (4 <= sscanf(up,
- "add-node %d %d %d %d %d",
- &ip[0],
- &ip[1],
- &ip[2],
- &ip[3],
- &port)) {
- char ports[12];
- char ips[128];
- char * argv[2];
- SNPRINTF(ports,
- 12,
- "%d",
- port);
- SNPRINTF(ips,
- 128,
- "%u.%u.%u.%u",
- ip[0],
- ip[1],
- ip[2],
- ip[3]);
- argv[0] = ips;
- argv[1] = ports;
- if (0 != addNode(2, argv))
- err = 2;
- } else {
- char * login;
- login = MALLOC(64);
- if (5 <= sscanf(up,
- "add-node %63s %d %d %d %d %d",
- login,
- &ip[0],
- &ip[1],
- &ip[2],
- &ip[3],
- &port)) {
- char ports[12];
- char ips[128];
- char * argv[3];
- SNPRINTF(ports,
- 12,
- "%d",
- port);
- SNPRINTF(ips,
- 128,
- "%u.%u.%u.%u",
- ip[0],
- ip[1],
- ip[2],
- ip[3]);
- argv[0] = login;
- argv[1] = ips;
- argv[2] = ports;
- if (0 != addSshNode(3, argv))
- err = 2;
- }
- FREE(login);
- }
- FREE(up);
- end++;
- start = end;
- }
return err;
}
@@ -1444,19 +1466,20 @@
* URL of the registry (by default we use the
* value from the configuration file value).
*/
-static int addAvailable(int argc,
- char * argv[]) {
- char * reg = NULL;
+static int
+addAvailable (int argc, char *argv[])
+{
+ char *reg = NULL;
long int port;
- char * hostname;
+ char *hostname;
unsigned int curpos;
struct sockaddr_in soaddr;
int sock;
size_t ret;
- char * command;
+ char *command;
cron_t start;
char c;
- char * buffer;
+ char *buffer;
int i;
int j;
int k;
@@ -1465,267 +1488,262 @@
IPaddr ip;
size_t n;
- if (argc == 0) {
- reg = getConfigurationString("GNUNET-TESTBED",
- "REGISTERURL");
- if (reg == NULL) {
- XPRINTF(" no testbed registration URL given.\n");
- return -1;
+ if (argc == 0)
+ {
+ reg = getConfigurationString ("GNUNET-TESTBED", "REGISTERURL");
+ if (reg == NULL)
+ {
+ XPRINTF (" no testbed registration URL given.\n");
+ return -1;
+ }
}
- } else
- reg = STRDUP(argv[0]);
+ else
+ reg = STRDUP (argv[0]);
- proxy = getConfigurationString("GNUNETD",
- "HTTP-PROXY");
- if (proxy != NULL) {
- if (OK != get_host_by_name(ectx, proxy,
- &ip)) {
- XPRINTF(" Couldn't resolve name of HTTP proxy '%s'\n",
- proxy);
+ proxy = getConfigurationString ("GNUNETD", "HTTP-PROXY");
+ if (proxy != NULL)
+ {
+ if (OK != get_host_by_name (ectx, proxy, &ip))
+ {
+ XPRINTF (" Couldn't resolve name of HTTP proxy '%s'\n", proxy);
+ theProxy.sin_addr.s_addr = 0;
+ }
+ else
+ {
+ memcpy (&theProxy.sin_addr.s_addr, &ip, sizeof (IPaddr));
+ proxyPort = getConfigurationString ("GNUNETD", "HTTP-PROXY-PORT");
+ if (proxyPort == NULL)
+ {
+ theProxy.sin_port = htons (8080);
+ }
+ else
+ {
+ theProxy.sin_port = htons (atoi (proxyPort));
+ FREE (proxyPort);
+ }
+ }
+ FREE (proxy);
+ }
+ else
+ {
theProxy.sin_addr.s_addr = 0;
- } else {
- memcpy(&theProxy.sin_addr.s_addr,
- &ip,
- sizeof(IPaddr));
- proxyPort = getConfigurationString("GNUNETD",
- "HTTP-PROXY-PORT");
- if (proxyPort == NULL) {
- theProxy.sin_port = htons(8080);
- } else {
- theProxy.sin_port = htons(atoi(proxyPort));
- FREE(proxyPort);
- }
}
- FREE(proxy);
- } else {
- theProxy.sin_addr.s_addr = 0;
- }
- if (0 != strncmp(HTTP_URL,
- reg,
- strlen(HTTP_URL)) ) {
- XPRINTF(" invalid URL %s (must begin with %s)\n",
- reg,
- HTTP_URL);
- return -1;
- }
- port = 80; /* default http port */
+ if (0 != strncmp (HTTP_URL, reg, strlen (HTTP_URL)))
+ {
+ XPRINTF (" invalid URL %s (must begin with %s)\n", reg, HTTP_URL);
+ return -1;
+ }
+ port = 80; /* default http port */
- hostname = STRDUP(®[strlen(HTTP_URL)]);
+ hostname = STRDUP (®[strlen (HTTP_URL)]);
buffer = NULL;
j = -1;
k = -1;
- for (i=0;i<strlen(hostname);i++) {
- if (hostname[i] == ':')
- j = i;
- if (hostname[i] == '/') {
- k = i;
- if (j == -1)
- j = i;
- break;
+ for (i = 0; i < strlen (hostname); i++)
+ {
+ if (hostname[i] == ':')
+ j = i;
+ if (hostname[i] == '/')
+ {
+ k = i;
+ if (j == -1)
+ j = i;
+ break;
+ }
}
- }
- if ( (j != -1) && (j < k) ) {
- char * pstring;
- if (k == -1) {
- pstring = MALLOC(strlen(hostname)-j+1);
- memcpy(pstring,
- &hostname[j],
- strlen(hostname)-j+1);
- pstring[strlen(hostname)-j] = '\0';
- } else {
- pstring = MALLOC(k-j+1);
- memcpy(pstring,
- &hostname[j],
- k-j);
- pstring[k-j] = '\0';
+ if ((j != -1) && (j < k))
+ {
+ char *pstring;
+ if (k == -1)
+ {
+ pstring = MALLOC (strlen (hostname) - j + 1);
+ memcpy (pstring, &hostname[j], strlen (hostname) - j + 1);
+ pstring[strlen (hostname) - j] = '\0';
+ }
+ else
+ {
+ pstring = MALLOC (k - j + 1);
+ memcpy (pstring, &hostname[j], k - j);
+ pstring[k - j] = '\0';
+ }
+ port = strtol (pstring, &buffer, 10);
+ if ((port < 0) || (port > 65536))
+ {
+ XPRINTF (" malformed http URL: %s at %s.\n", reg, buffer);
+ FREE (hostname);
+ FREE (reg);
+ FREE (pstring);
+ return -1;
+ }
+ FREE (pstring);
}
- port = strtol(pstring, &buffer, 10);
- if ( (port < 0) || (port > 65536) ) {
- XPRINTF(" malformed http URL: %s at %s.\n",
- reg,
- buffer);
- FREE(hostname);
- FREE(reg);
- FREE(pstring);
- return -1;
- }
- FREE(pstring);
- }
hostname[k] = '\0';
#if DEBUG_TESTBED
- GE_LOG(ectx, GE_INFO | GE_REQUEST | GE_USER,
- " Trying to download a hostlist from %s\n",
- reg);
+ GE_LOG (ectx, GE_INFO | GE_REQUEST | GE_USER,
+ " Trying to download a hostlist from %s\n", reg);
#endif
- sock = SOCKET(PF_INET,
- SOCK_STREAM,
- 0);
- if (sock < 0) {
- XPRINTF(" could not open socket for hostlist download (%s).\n",
- STRERROR(errno));
- FREE(hostname);
- FREE(reg);
- return -1;
- }
+ sock = SOCKET (PF_INET, SOCK_STREAM, 0);
+ if (sock < 0)
+ {
+ XPRINTF (" could not open socket for hostlist download (%s).\n",
+ STRERROR (errno));
+ FREE (hostname);
+ FREE (reg);
+ return -1;
+ }
/* Do we need to connect through a proxy? */
- if (theProxy.sin_addr.s_addr == 0) {
- /* no proxy */
- if (OK != get_host_by_name(ectx, hostname,
- &ip)) {
- XPRINTF(" could not download hostlist, host '%s' unknown\n",
- hostname);
- FREE(reg);
- FREE(hostname);
+ if (theProxy.sin_addr.s_addr == 0)
+ {
+ /* no proxy */
+ if (OK != get_host_by_name (ectx, hostname, &ip))
+ {
+ XPRINTF (" could not download hostlist, host '%s' unknown\n",
+ hostname);
+ FREE (reg);
+ FREE (hostname);
+ return -1;
+ }
+ memcpy (&soaddr.sin_addr.s_addr, &ip, sizeof (IPaddr));
+ soaddr.sin_port = htons ((unsigned short) port);
+ }
+ else
+ {
+ /* proxy */
+ soaddr.sin_addr.s_addr = theProxy.sin_addr.s_addr;
+ soaddr.sin_port = theProxy.sin_port;
+ }
+ soaddr.sin_family = AF_INET;
+ if (CONNECT (sock,
+ (struct sockaddr *) &soaddr,
+ sizeof (soaddr)) < 0 && errno != EWOULDBLOCK)
+ {
+ XPRINTF (" failed to send HTTP request to host %s: %s\n",
+ hostname, STRERROR (errno));
+ FREE (reg);
+ FREE (hostname);
+ closefile (sock);
return -1;
}
- memcpy(&soaddr.sin_addr.s_addr,
- &ip,
- sizeof(IPaddr));
- soaddr.sin_port
- = htons((unsigned short)port);
- } else {
- /* proxy */
- soaddr.sin_addr.s_addr
- = theProxy.sin_addr.s_addr;
- soaddr.sin_port
- = theProxy.sin_port;
- }
- soaddr.sin_family = AF_INET;
- if (CONNECT(sock,
- (struct sockaddr*)&soaddr,
- sizeof(soaddr)) < 0 && errno != EWOULDBLOCK) {
- XPRINTF(" failed to send HTTP request to host %s: %s\n",
- hostname,
- STRERROR(errno));
- FREE(reg);
- FREE(hostname);
- closefile(sock);
- return -1;
- }
- n = strlen(GET_COMMAND) + strlen(reg);
- command = MALLOC(n);
- SNPRINTF(command,
- n,
- GET_COMMAND,
- reg);
- FREE(reg);
- curpos = strlen(command)+1;
- curpos = SEND_BLOCKING_ALL(sock,
- command,
- curpos);
- if (SYSERR == (int)curpos) {
- XPRINTF(" failed so send HTTP request %s to host %s (%u - %d) - %s\n",
- command,
- hostname,
- curpos,
- sock,
- STRERROR(errno));
- FREE(command);
- FREE(hostname);
- closefile(sock);
- return -1;
- }
- FREE(command);
- FREE(hostname);
- cronTime(&start);
+ n = strlen (GET_COMMAND) + strlen (reg);
+ command = MALLOC (n);
+ SNPRINTF (command, n, GET_COMMAND, reg);
+ FREE (reg);
+ curpos = strlen (command) + 1;
+ curpos = SEND_BLOCKING_ALL (sock, command, curpos);
+ if (SYSERR == (int) curpos)
+ {
+ XPRINTF (" failed so send HTTP request %s to host %s (%u - %d) - %s\n",
+ command, hostname, curpos, sock, STRERROR (errno));
+ FREE (command);
+ FREE (hostname);
+ closefile (sock);
+ return -1;
+ }
+ FREE (command);
+ FREE (hostname);
+ cronTime (&start);
- /* we first have to read out the http_response*/
+ /* we first have to read out the http_response */
/* it ends with four line delimiters: "\r\n\r\n" */
curpos = 0;
- while (curpos < 4) {
- int success;
+ while (curpos < 4)
+ {
+ int success;
- if (start + 5 * cronMINUTES < get_time())
- break; /* exit after 5m */
- success = RECV_NONBLOCKING(sock,
- &c,
- sizeof(c),
- &ret);
- if ( success == NO ) {
- PTHREAD_SLEEP(100 * cronMILLIS);
- continue;
+ if (start + 5 * cronMINUTES < get_time ())
+ break; /* exit after 5m */
+ success = RECV_NONBLOCKING (sock, &c, sizeof (c), &ret);
+ if (success == NO)
+ {
+ PTHREAD_SLEEP (100 * cronMILLIS);
+ continue;
+ }
+ if ((ret == 0) || (ret == (size_t) - 1))
+ break; /* end of transmission or error */
+ if ((c == '\r') || (c == '\n'))
+ curpos += ret;
+ else
+ curpos = 0;
}
- if ( (ret == 0) || (ret == (size_t)-1) )
- break; /* end of transmission or error */
- if ((c=='\r') || (c=='\n'))
- curpos += ret;
- else
- curpos=0;
- }
- if (curpos < 4) { /* invalid response */
- XPRINTF(" exit register (error: no http response read)\n");
- closefile(sock);
- return -1;
- }
+ if (curpos < 4)
+ { /* invalid response */
+ XPRINTF (" exit register (error: no http response read)\n");
+ closefile (sock);
+ return -1;
+ }
/* now read peer list */
- buffer = MALLOC(65536);
+ buffer = MALLOC (65536);
- while (1) {
- int success;
+ while (1)
+ {
+ int success;
- if (start + 300 * cronSECONDS < get_time())
- break; /* exit after 300s */
- curpos = 0;
- while (curpos < 65536) {
- if (start + 300 * cronSECONDS < get_time())
- break; /* exit after 300s */
- success = RECV_NONBLOCKING(sock,
- &buffer[curpos],
- 65536-curpos,
- &ret);
- if ( success == NO ) {
- PTHREAD_SLEEP(20);
- continue;
- }
- if ( (ret == 0) || (ret == (size_t)-1) )
- break; /* end of file or error*/
- curpos += ret;
+ if (start + 300 * cronSECONDS < get_time ())
+ break; /* exit after 300s */
+ curpos = 0;
+ while (curpos < 65536)
+ {
+ if (start + 300 * cronSECONDS < get_time ())
+ break; /* exit after 300s */
+ success = RECV_NONBLOCKING (sock,
+ &buffer[curpos], 65536 - curpos, &ret);
+ if (success == NO)
+ {
+ PTHREAD_SLEEP (20);
+ continue;
+ }
+ if ((ret == 0) || (ret == (size_t) - 1))
+ break; /* end of file or error */
+ curpos += ret;
- if (0 != processCommands(buffer, &curpos)) {
- FREE(buffer);
- closefile(sock);
- return -1;
- }
+ if (0 != processCommands (buffer, &curpos))
+ {
+ FREE (buffer);
+ closefile (sock);
+ return -1;
+ }
+ }
}
- }
- if (0 != processCommands(buffer, &curpos)) {
- FREE(buffer);
- closefile(sock);
- return -1;
- }
- FREE(buffer);
- closefile(sock);
+ if (0 != processCommands (buffer, &curpos))
+ {
+ FREE (buffer);
+ closefile (sock);
+ return -1;
+ }
+ FREE (buffer);
+ closefile (sock);
return 0;
}
/**
* Print the list of available peers.
*/
-static int listPeers(int argc, char * argv[]) {
+static int
+listPeers (int argc, char *argv[])
+{
int i;
- for (i=0;i<nnodes;i++)
- XPRINTF("%4d - %s:%d\n",
- i,
- nodes[i].ips,
- nodes[i].port);
+ for (i = 0; i < nnodes; i++)
+ XPRINTF ("%4d - %s:%d\n", i, nodes[i].ips, nodes[i].port);
return 0;
}
/**
* Exit gnunet-testbed shell.
*/
-static int doExit(int argc, char * argv[]) {
+static int
+doExit (int argc, char *argv[])
+{
do_quit = YES;
return 0;
}
@@ -1733,77 +1751,106 @@
/* ****************** command set ****************** */
CMD_ENTRY commands[] = {
- { "help",
- "print this help text",
- &printOnlineHelp },
- { "get-trust",
- "",
- &getTrust },
- { "set-bw",
- "",
- &setBW },
- { "set-trust",
- "",
- &setTrust },
- { "add-node",
- "add node to testbed, arguments: IP PORT",
- &addNode },
- { "add-ssh-node",
- "add node to testbed, arguments: LOGIN IP PORT",
- &addSshNode },
- { "connect",
- "connect two peers",
- &addConnection },
- { "disconnect",
- "disconnect two peers",
- &delConnection },
- { "disconnect-all",
- "destroy all connections between peers",
- &delAllConnections },
- { "helo-disable",
- "disable hello advertisements",
- &disablehello },
- { "helo-enable",
- "enable hello advertisements",
- &enablehello },
- { "autoconnect-disable", "", &disableAUTOCONNECT },
- { "autoconnect-enable", "", &enableAUTOCONNECT },
- { "process-start",
- "Start a process on a given peer. Prints the process-ID on success.",
- &startProcess },
- { "process-signal",
- "Send a signal to a process running at a peer. Use signal 0 to test if
the process is still running. Use -1 to obtain the exit code of a process that
terminated.",
- &signalProcess },
- { "process-output",
- "Obtain the process output from a process at a peer.",
- &dumpProcessOutput },
- { "exit",
- "exit the testbed shell",
- &doExit },
- { "list-peers", "", &listPeers},
- { "set-loss", "", &setLoss} ,
- { "get-stats",
- "get all stats values from peer",
- &getStats },
- { "get-stat",
- "get one specific stats value from peer",
- &getStat },
- { "get-option",
- "Get configuration value from peer.",
- &getOption },
- { "load-module", "", &loadModule },
- { "unload-module", "", &unloadModule },
- { "add-available",
- "Check http server for available testbed peers and add"
- " all available nodes. An optional argument can be"
- " passed to specify the URL of the http server.",
- &addAvailable },
- { "upload",
- "",
- &uploadFile },
- { "connect-deny", "", &denyConnect },
- { "connect-allow", "", &allowConnect },
- { NULL, NULL }, /* termination */
+ {"help",
+ "print this help text",
+ &printOnlineHelp}
+ ,
+ {"get-trust",
+ "",
+ &getTrust}
+ ,
+ {"set-bw",
+ "",
+ &setBW}
+ ,
+ {"set-trust",
+ "",
+ &setTrust}
+ ,
+ {"add-node",
+ "add node to testbed, arguments: IP PORT",
+ &addNode}
+ ,
+ {"add-ssh-node",
+ "add node to testbed, arguments: LOGIN IP PORT",
+ &addSshNode}
+ ,
+ {"connect",
+ "connect two peers",
+ &addConnection}
+ ,
+ {"disconnect",
+ "disconnect two peers",
+ &delConnection}
+ ,
+ {"disconnect-all",
+ "destroy all connections between peers",
+ &delAllConnections}
+ ,
+ {"helo-disable",
+ "disable hello advertisements",
+ &disablehello}
+ ,
+ {"helo-enable",
+ "enable hello advertisements",
+ &enablehello}
+ ,
+ {"autoconnect-disable", "", &disableAUTOCONNECT}
+ ,
+ {"autoconnect-enable", "", &enableAUTOCONNECT}
+ ,
+ {"process-start",
+ "Start a process on a given peer. Prints the process-ID on success.",
+ &startProcess}
+ ,
+ {"process-signal",
+ "Send a signal to a process running at a peer. Use signal 0 to test if the
process is still running. Use -1 to obtain the exit code of a process that
terminated.",
+ &signalProcess}
+ ,
+ {"process-output",
+ "Obtain the process output from a process at a peer.",
+ &dumpProcessOutput}
+ ,
+ {"exit",
+ "exit the testbed shell",
+ &doExit}
+ ,
+ {"list-peers", "", &listPeers}
+ ,
+ {"set-loss", "", &setLoss}
+ ,
+ {"get-stats",
+ "get all stats values from peer",
+ &getStats}
+ ,
+ {"get-stat",
+ "get one specific stats value from peer",
+ &getStat}
+ ,
+ {"get-option",
+ "Get configuration value from peer.",
+ &getOption}
+ ,
+ {"load-module", "", &loadModule}
+ ,
+ {"unload-module", "", &unloadModule}
+ ,
+ {"add-available",
+ "Check http server for available testbed peers and add"
+ " all available nodes. An optional argument can be"
+ " passed to specify the URL of the http server.",
+ &addAvailable}
+ ,
+ {"upload",
+ "",
+ &uploadFile}
+ ,
+ {"connect-deny", "", &denyConnect}
+ ,
+ {"connect-allow", "", &allowConnect}
+ ,
+ {NULL, NULL}
+ , /* termination */
};
Modified: GNUnet/src/applications/testbed/commands.h
===================================================================
--- GNUnet/src/applications/testbed/commands.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/testbed/commands.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,15 +30,15 @@
/**
* Signature of a command -- just like main()!
*/
-typedef int (*CommandHandler)(int argc,
- char * argv[]);
+typedef int (*CommandHandler) (int argc, char *argv[]);
-typedef struct CMD_ENTRY_ {
+typedef struct CMD_ENTRY_
+{
/* the name of the command (what the user enters
in the shell */
- char * command;
+ char *command;
/* help text */
- char * help;
+ char *help;
/* the function to run */
CommandHandler handler;
} CMD_ENTRY;
Modified: GNUnet/src/applications/testbed/gnunet-testbed.c
===================================================================
--- GNUnet/src/applications/testbed/gnunet-testbed.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/testbed/gnunet-testbed.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -42,7 +42,7 @@
#include <signal.h>
#ifndef sighandler_t
-typedef void (*sighandler_t)(int);
+typedef void (*sighandler_t) (int);
#endif
#define TESTBED_VERSION "0.0.5"
@@ -64,12 +64,12 @@
/**
* Name of gnunet-testbed binary.
*/
-static char * testbedArg0;
+static char *testbedArg0;
/* ****************** scriptability *************** */
-#ifndef MINGW /* FIXME MINGW */
+#ifndef MINGW /* FIXME MINGW */
@@ -80,55 +80,51 @@
* @param argv the option list (including keywords)
* @return OK on error, SYSERR if we should exit
*/
-static int helperParseOptions(int argc, char *argv[]) {
+static int
+helperParseOptions (int argc, char *argv[])
+{
int c, option_index;
- FREENONNULL(setConfigurationString("GNUNETD",
- "LOGFILE",
- NULL));
- while (1) {
- static struct GNoption long_options[] = {
- LONG_DEFAULT_OPTIONS,
- { 0,0,0,0 }
- };
-
- option_index = 0;
- c = GNgetopt_long(argc,
- argv,
- "vhdc:L:",
- long_options,
- &option_index);
- if (c == -1)
- break; /* No more flags to process */
- if (YES == parseDefaultOptions(c, GNoptarg))
- continue;
- switch(c) {
- case 'v':
- printf("GNUnet v%s, gnunet-testbed v%s\n",
- VERSION,
- TESTBED_VERSION);
- return SYSERR;
- case 'h': {
- static Help help[] = {
- HELP_CONFIG,
- HELP_HELP,
- HELP_LOGLEVEL,
- HELP_VERSION,
- HELP_END,
+ FREENONNULL (setConfigurationString ("GNUNETD", "LOGFILE", NULL));
+ while (1)
+ {
+ static struct GNoption long_options[] = {
+ LONG_DEFAULT_OPTIONS,
+ {0, 0, 0, 0}
};
- formatHelp("gnunet-testbed ==HELPER== [OPTIONS] [COMMAND]",
- _("Start GNUnet-testbed helper."),
- help);
- return SYSERR;
- }
- default:
- GE_LOG(ectx, GE_ERROR | GE_IMMEDIATE | GE_USER,
- _("Use --help to get a list of options.\n"));
- return -1;
- } /* end of parsing commandline */
- } /* while (1) */
- setConfigurationStringList(&argv[GNoptind],
- argc - GNoptind);
+
+ option_index = 0;
+ c = GNgetopt_long (argc, argv, "vhdc:L:", long_options, &option_index);
+ if (c == -1)
+ break; /* No more flags to process */
+ if (YES == parseDefaultOptions (c, GNoptarg))
+ continue;
+ switch (c)
+ {
+ case 'v':
+ printf ("GNUnet v%s, gnunet-testbed v%s\n",
+ VERSION, TESTBED_VERSION);
+ return SYSERR;
+ case 'h':
+ {
+ static Help help[] = {
+ HELP_CONFIG,
+ HELP_HELP,
+ HELP_LOGLEVEL,
+ HELP_VERSION,
+ HELP_END,
+ };
+ formatHelp ("gnunet-testbed ==HELPER== [OPTIONS] [COMMAND]",
+ _("Start GNUnet-testbed helper."), help);
+ return SYSERR;
+ }
+ default:
+ GE_LOG (ectx, GE_ERROR | GE_IMMEDIATE | GE_USER,
+ _("Use --help to get a list of options.\n"));
+ return -1;
+ } /* end of parsing commandline */
+ } /* while (1) */
+ setConfigurationStringList (&argv[GNoptind], argc - GNoptind);
return OK;
}
@@ -141,87 +137,72 @@
* retrieves there result and outputs he result back
* to bash.
*/
-static int helper_main(int argc,
- char * argv[]) {
+static int
+helper_main (int argc, char *argv[])
+{
int i;
int retVal;
unsigned int len;
int res;
- char *buf;
+ char *buf;
struct sockaddr_in soaddr;
- if (SYSERR == initUtil(argc,
- argv,
- &helperParseOptions))
+ if (SYSERR == initUtil (argc, argv, &helperParseOptions))
return -1;
- argc = getConfigurationStringList(&argv);
+ argc = getConfigurationStringList (&argv);
- if (argc == 0) {
- fprintf(stderr,
- " must have at least one argument!\n");
- return -1;
- }
- sock = SOCKET(PF_INET,
- SOCK_STREAM,
- 6); /* 6: TCP */
- if (sock == -1) {
- LOG_STRERROR(LOG_FAILURE, "socket");
- return SYSERR;
- }
- soaddr.sin_family
- = AF_INET;
- soaddr.sin_addr.s_addr
- = htonl(INADDR_LOOPBACK);
- soaddr.sin_port
- = htons(PORT);
- res = CONNECT(sock,
- (struct sockaddr*)&soaddr,
- sizeof(soaddr));
- if ( (res < 0) &&
- (errno != EINPROGRESS) && (errno != EWOULDBLOCK) ) {
- GE_LOG(ectx, GE_INFO | GE_REQUEST | GE_USER,
- _("Cannot connect to LOOPBACK port %d: %s\n"),
- PORT,
- STRERROR(errno));
- closefile(sock);
- sock = -1;
- return SYSERR;
- }
+ if (argc == 0)
+ {
+ fprintf (stderr, " must have at least one argument!\n");
+ return -1;
+ }
+ sock = SOCKET (PF_INET, SOCK_STREAM, 6); /* 6: TCP */
+ if (sock == -1)
+ {
+ LOG_STRERROR (LOG_FAILURE, "socket");
+ return SYSERR;
+ }
+ soaddr.sin_family = AF_INET;
+ soaddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+ soaddr.sin_port = htons (PORT);
+ res = CONNECT (sock, (struct sockaddr *) &soaddr, sizeof (soaddr));
+ if ((res < 0) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK))
+ {
+ GE_LOG (ectx, GE_INFO | GE_REQUEST | GE_USER,
+ _("Cannot connect to LOOPBACK port %d: %s\n"),
+ PORT, STRERROR (errno));
+ closefile (sock);
+ sock = -1;
+ return SYSERR;
+ }
/* write command to socket */
- socketSend(strlen(argv[0]),
- SOCKET_BEGIN_COMMAND,
- argv[0]);
- FREE(argv[0]);
+ socketSend (strlen (argv[0]), SOCKET_BEGIN_COMMAND, argv[0]);
+ FREE (argv[0]);
/* write args to socket */
- for (i=1;i<argc;i++) {
- socketSend(strlen(argv[i]),
- SOCKET_ADD_ARGUMENT,
- argv[i]);
- FREE(argv[i]);
- }
- FREE(argv);
- socketSend(0,
- SOCKET_END_COMMAND,
- NULL);
+ for (i = 1; i < argc; i++)
+ {
+ socketSend (strlen (argv[i]), SOCKET_ADD_ARGUMENT, argv[i]);
+ FREE (argv[i]);
+ }
+ FREE (argv);
+ socketSend (0, SOCKET_END_COMMAND, NULL);
/* read result from socket, print to stderr, obtain retVal */
i = SOCKET_PRINTF;
buf = NULL;
- while (i == SOCKET_PRINTF) {
- FREENONNULL(buf);
- buf = NULL;
- i = readSocket(&buf, &len);
- if (i == SOCKET_PRINTF)
- fprintf(stdout,
- "%.*s",
- (int) len,
- buf);
- }
- retVal = *(int*)buf;
- FREE(buf);
- closefile(sock);
+ while (i == SOCKET_PRINTF)
+ {
+ FREENONNULL (buf);
+ buf = NULL;
+ i = readSocket (&buf, &len);
+ if (i == SOCKET_PRINTF)
+ fprintf (stdout, "%.*s", (int) len, buf);
+ }
+ retVal = *(int *) buf;
+ FREE (buf);
+ closefile (sock);
return retVal;
}
@@ -229,9 +210,9 @@
* A child (the shell) has quit. So we exit,
* too.
*/
-static void sigChildHandler(int signal,
- siginfo_t * info,
- void * extra) {
+static void
+sigChildHandler (int signal, siginfo_t * info, void *extra)
+{
do_quit = YES;
}
@@ -239,63 +220,63 @@
* This is the "bash" process. Execs bash.
* @returns never
*/
-static void bash_main() {
- int i;
+static void
+bash_main ()
+{
+ int i;
FILE *aliases;
- char * configFile;
+ char *configFile;
char *argv[] = {
- NULL, /* replaced by SHELL */
+ NULL, /* replaced by SHELL */
"--init-file",
TB_ALIASES,
"-i",
NULL,
};
- configFile = getConfigurationString("FILES",
- "gnunet.conf");
- GE_ASSERT(ectx, configFile != NULL);
+ configFile = getConfigurationString ("FILES", "gnunet.conf");
+ GE_ASSERT (ectx, configFile != NULL);
argv[0] = SHELL;
- aliases = FOPEN(TB_ALIASES, "w+");
- fprintf(aliases,
- "export PS1=\"[GTB]%% \"\n");
- i=0;
- while (commands[i].command != NULL) {
- if (0 == strcmp("exit", commands[i].command)) {
- fprintf(aliases,
- "alias exit=\"%s ==HELPER== -c %s exit ; exit\"\n",
- testbedArg0,
- configFile);
- } else {
- fprintf(aliases,
- "alias %s=\"%s ==HELPER== -c %s %s\"\n",
- commands[i].command,
- testbedArg0,
- configFile,
- commands[i].command);
+ aliases = FOPEN (TB_ALIASES, "w+");
+ fprintf (aliases, "export PS1=\"[GTB]%% \"\n");
+ i = 0;
+ while (commands[i].command != NULL)
+ {
+ if (0 == strcmp ("exit", commands[i].command))
+ {
+ fprintf (aliases,
+ "alias exit=\"%s ==HELPER== -c %s exit ; exit\"\n",
+ testbedArg0, configFile);
+ }
+ else
+ {
+ fprintf (aliases,
+ "alias %s=\"%s ==HELPER== -c %s %s\"\n",
+ commands[i].command,
+ testbedArg0, configFile, commands[i].command);
+ }
+ i++;
}
- i++;
- }
- FREE(configFile);
- fclose(aliases);
- doneUtil();
- execvp(SHELL, argv);
- fprintf(stderr,
- _("Could not execute `%s': %s\n"),
- SHELL,
- STRERROR(errno));
+ FREE (configFile);
+ fclose (aliases);
+ doneUtil ();
+ execvp (SHELL, argv);
+ fprintf (stderr,
+ _("Could not execute `%s': %s\n"), SHELL, STRERROR (errno));
}
/**
* Configuration...
*/
-static struct CIDRNetwork * trustedNetworks_ = NULL;
+static struct CIDRNetwork *trustedNetworks_ = NULL;
/**
* Is this IP labeled as trusted for CS connections?
*/
-static int isWhitelisted(IPaddr ip) {
- return checkIPListed(trustedNetworks_,
- ip);
+static int
+isWhitelisted (IPaddr ip)
+{
+ return checkIPListed (trustedNetworks_, ip);
}
/**
@@ -306,10 +287,12 @@
*
* @param bash_pid the process ID of the child that is bash
*/
-static int server_main(pid_t bash_pid) {
- int i, status, ssock;
+static int
+server_main (pid_t bash_pid)
+{
+ int i, status, ssock;
socklen_t lenOfIncomingAddr;
- int secs = 5;
+ int secs = 5;
const int on = 1;
struct sockaddr_in serverAddr, clientAddr;
struct sigaction oldAct;
@@ -319,172 +302,150 @@
/* create the socket */
- CREATE_SOCKET:
- while ( (ssock = SOCKET(PF_INET, SOCK_STREAM, 0)) < 0) {
- LOG_STRERROR(LOG_ERROR, "socket");
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("No client service started. Trying again in 30 seconds.\n"));
- sleep(30);
- }
+CREATE_SOCKET:
+ while ((ssock = SOCKET (PF_INET, SOCK_STREAM, 0)) < 0)
+ {
+ LOG_STRERROR (LOG_ERROR, "socket");
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("No client service started. Trying again in 30 seconds.\n"));
+ sleep (30);
+ }
- serverAddr.sin_family
- = AF_INET;
- serverAddr.sin_addr.s_addr
- = htonl(INADDR_ANY);
- serverAddr.sin_port
- = htons(PORT);
+ serverAddr.sin_family = AF_INET;
+ serverAddr.sin_addr.s_addr = htonl (INADDR_ANY);
+ serverAddr.sin_port = htons (PORT);
- if (SETSOCKOPT(ssock,
- SOL_SOCKET,
- SO_REUSEADDR,
- &on,
- sizeof(on)) < 0)
- LOG_STRERROR(LOG_ERROR, "setsockopt");
+ if (SETSOCKOPT (ssock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0)
+ LOG_STRERROR (LOG_ERROR, "setsockopt");
/* bind the socket */
- if (BIND(ssock,
- (struct sockaddr*)&serverAddr,
- sizeof(serverAddr)) < 0) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Error (%s) binding the TCP listener to "
- "port %d. No proxy service started.\nTrying "
- "again in %d seconds...\n"),
- STRERROR(errno),
- PORT,
- secs);
- sleep(secs);
- secs += 5; /* slow progression... */
- closefile(ssock);
- goto CREATE_SOCKET;
- }
+ if (BIND (ssock, (struct sockaddr *) &serverAddr, sizeof (serverAddr)) < 0)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Error (%s) binding the TCP listener to "
+ "port %d. No proxy service started.\nTrying "
+ "again in %d seconds...\n"), STRERROR (errno), PORT, secs);
+ sleep (secs);
+ secs += 5; /* slow progression... */
+ closefile (ssock);
+ goto CREATE_SOCKET;
+ }
do_quit = NO;
/* signal handler is needed if the child did exit
(e.g. with CTRL-D and not with the command 'exit') */
newAct.sa_sigaction = &sigChildHandler;
- sigfillset(&newAct.sa_mask);
+ sigfillset (&newAct.sa_mask);
newAct.sa_flags = SA_NOCLDSTOP | SA_SIGINFO | SA_RESTART;
- if (0 != sigaction(SIGCHLD,
- &newAct,
- &oldAct))
- DIE_STRERROR("sigaction");
- sigemptyset(&set);
- sigaddset(&set, SIGCHLD);
- if (0 != sigprocmask(SIG_UNBLOCK,
- &set,
- &oset))
- DIE_STRERROR("sigprocmask");
- LISTEN(ssock, 5);
- while ( (do_quit == NO) &&
- (0 == waitpid(bash_pid,
- &status,
- WNOHANG)) ) {
- unsigned int argc;
- char *command;
- char **args;
- char *buf;
- unsigned int len;
- fd_set rset;
- fd_set wset;
- fd_set eset;
- IPaddr ipaddr;
+ if (0 != sigaction (SIGCHLD, &newAct, &oldAct))
+ DIE_STRERROR ("sigaction");
+ sigemptyset (&set);
+ sigaddset (&set, SIGCHLD);
+ if (0 != sigprocmask (SIG_UNBLOCK, &set, &oset))
+ DIE_STRERROR ("sigprocmask");
+ LISTEN (ssock, 5);
+ while ((do_quit == NO) && (0 == waitpid (bash_pid, &status, WNOHANG)))
+ {
+ unsigned int argc;
+ char *command;
+ char **args;
+ char *buf;
+ unsigned int len;
+ fd_set rset;
+ fd_set wset;
+ fd_set eset;
+ IPaddr ipaddr;
- lenOfIncomingAddr = sizeof(clientAddr);
- /* accept is not interrupted by SIGCHLD,
- so we must do a select first; yuck. */
- FD_ZERO(&rset);
- FD_ZERO(&wset);
- FD_ZERO(&eset);
- FD_SET(ssock, &rset);
- sock = SELECT(ssock+1, &rset, &wset, &eset, NULL);
- if (sock == -1)
- continue;
- sock = ACCEPT(ssock,
- (struct sockaddr *)&clientAddr,
- &lenOfIncomingAddr);
- if (sock < 0) {
- LOG_STRERROR(LOG_ERROR, "accept");
- continue;
- }
- /* access control! */
- GE_ASSERT(ectx, sizeof(struct in_addr) == sizeof(IPaddr));
- memcpy(&ipaddr,
- &clientAddr.sin_addr,
- sizeof(struct in_addr));
- if (NO == isWhitelisted(ipaddr)) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Rejected unauthorized connection from %u.%u.%u.%u.\n"),
- PRIP(ntohl(*(int*)&clientAddr.sin_addr)));
- closefile(sock);
- continue;
- }
+ lenOfIncomingAddr = sizeof (clientAddr);
+ /* accept is not interrupted by SIGCHLD,
+ so we must do a select first; yuck. */
+ FD_ZERO (&rset);
+ FD_ZERO (&wset);
+ FD_ZERO (&eset);
+ FD_SET (ssock, &rset);
+ sock = SELECT (ssock + 1, &rset, &wset, &eset, NULL);
+ if (sock == -1)
+ continue;
+ sock = ACCEPT (ssock,
+ (struct sockaddr *) &clientAddr, &lenOfIncomingAddr);
+ if (sock < 0)
+ {
+ LOG_STRERROR (LOG_ERROR, "accept");
+ continue;
+ }
+ /* access control! */
+ GE_ASSERT (ectx, sizeof (struct in_addr) == sizeof (IPaddr));
+ memcpy (&ipaddr, &clientAddr.sin_addr, sizeof (struct in_addr));
+ if (NO == isWhitelisted (ipaddr))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Rejected unauthorized connection from %u.%u.%u.%u.\n"),
+ PRIP (ntohl (*(int *) &clientAddr.sin_addr)));
+ closefile (sock);
+ continue;
+ }
- /* read from socket, run reaction,
- return result value and stdout value;
- possibly set doExit to 1 to exit */
- buf = NULL;
- if (SOCKET_BEGIN_COMMAND != readSocket(&buf, &len)) {
- fprintf(stderr,
- _("Protocol violation on socket. "
- "Expected command.\n"));
- return -1;
- }
- command = MALLOC(len+1);
- memcpy(command, buf, len);
- command[len] = '\0';
- argc = 0;
- args = NULL;
- FREE(buf);
- buf = NULL;
- while (SOCKET_ADD_ARGUMENT == readSocket(&buf, &len)) {
- GROW(args, argc, argc+1);
- args[argc-1] = MALLOC(len+1);
- memcpy(args[argc-1], buf, len);
- args[argc-1][len] = '\0';
- FREE(buf);
+ /* read from socket, run reaction,
+ return result value and stdout value;
+ possibly set doExit to 1 to exit */
buf = NULL;
+ if (SOCKET_BEGIN_COMMAND != readSocket (&buf, &len))
+ {
+ fprintf (stderr,
+ _("Protocol violation on socket. " "Expected command.\n"));
+ return -1;
+ }
+ command = MALLOC (len + 1);
+ memcpy (command, buf, len);
+ command[len] = '\0';
+ argc = 0;
+ args = NULL;
+ FREE (buf);
+ buf = NULL;
+ while (SOCKET_ADD_ARGUMENT == readSocket (&buf, &len))
+ {
+ GROW (args, argc, argc + 1);
+ args[argc - 1] = MALLOC (len + 1);
+ memcpy (args[argc - 1], buf, len);
+ args[argc - 1][len] = '\0';
+ FREE (buf);
+ buf = NULL;
+ }
+ FREENONNULL (buf);
+ i = 0;
+ while (commands[i].command != NULL)
+ {
+ if (0 == strcmp (commands[i].command, command))
+ {
+ int ret;
+ ret = commands[i].handler (argc, args);
+ socketSend (sizeof (unsigned int), SOCKET_RETVAL, &ret);
+ break;
+ }
+ i++;
+ }
+ for (i = 0; i < argc; i++)
+ FREE (args[i]);
+ GROW (args, argc, 0);
+ if (commands[i].command == NULL)
+ {
+ /* should never happen unless the user
+ plays by hand with the aliases... */
+ i = -1;
+ PRINTF (_("Command `%s' not found!\n"), command);
+ socketSend (sizeof (unsigned int), SOCKET_RETVAL, &i);
+ }
+ FREE (command);
+ closefile (sock);
+ sock = -1;
}
- FREENONNULL(buf);
- i = 0;
- while (commands[i].command != NULL) {
- if (0 == strcmp(commands[i].command, command)) {
- int ret;
- ret = commands[i].handler(argc, args);
- socketSend(sizeof(unsigned int),
- SOCKET_RETVAL,
- &ret);
- break;
- }
- i++;
- }
- for (i=0;i<argc;i++)
- FREE(args[i]);
- GROW(args, argc, 0);
- if (commands[i].command == NULL) {
- /* should never happen unless the user
- plays by hand with the aliases... */
- i = -1;
- PRINTF(_("Command `%s' not found!\n"),
- command);
- socketSend(sizeof(unsigned int),
- SOCKET_RETVAL,
- &i);
- }
- FREE(command);
- closefile(sock);
- sock = -1;
- }
/* just to be certain, we could have
left the main loop due to doExit... */
- waitpid(bash_pid,
- &status,
- WNOHANG);
+ waitpid (bash_pid, &status, WNOHANG);
/* restore... */
- if (0 != sigaction(SIGCHLD,
- &oldAct,
- &newAct))
- LOG_STRERROR(LOG_WARNING, "sigaction");
+ if (0 != sigaction (SIGCHLD, &oldAct, &newAct))
+ LOG_STRERROR (LOG_WARNING, "sigaction");
return status;
}
@@ -500,54 +461,51 @@
* @param argv the option list (including keywords)
* @return OK on error, SYSERR if we should exit
*/
-static int parseOptions(int argc, char *argv[]) {
+static int
+parseOptions (int argc, char *argv[])
+{
int c, option_index;
- FREENONNULL(setConfigurationString("GNUNETD",
- "LOGFILE",
- NULL));
- while (1) {
- static struct GNoption long_options[] = {
- LONG_DEFAULT_OPTIONS,
- { 0,0,0,0 }
- };
+ FREENONNULL (setConfigurationString ("GNUNETD", "LOGFILE", NULL));
+ while (1)
+ {
+ static struct GNoption long_options[] = {
+ LONG_DEFAULT_OPTIONS,
+ {0, 0, 0, 0}
+ };
- option_index = 0;
- c = GNgetopt_long(argc,
- argv,
- "vhdc:L:",
- long_options,
- &option_index);
- if (c == -1)
- break; /* No more flags to process */
- if (YES == parseDefaultOptions(c, GNoptarg))
- continue;
- switch(c) {
- case 'v':
- printf("GNUnet v%s, gnunet-testbed v%s\n",
- VERSION,
- TESTBED_VERSION);
- return SYSERR;
+ option_index = 0;
+ c = GNgetopt_long (argc, argv, "vhdc:L:", long_options, &option_index);
+ if (c == -1)
+ break; /* No more flags to process */
+ if (YES == parseDefaultOptions (c, GNoptarg))
+ continue;
+ switch (c)
+ {
+ case 'v':
+ printf ("GNUnet v%s, gnunet-testbed v%s\n",
+ VERSION, TESTBED_VERSION);
+ return SYSERR;
- case 'h': {
- static Help help[] = {
- HELP_CONFIG,
- HELP_HELP,
- HELP_LOGLEVEL,
- HELP_VERSION,
- HELP_END,
- };
- formatHelp("gnunet-testbed [OPTIONS]",
- _("Start GNUnet testbed controller."),
- help);
- return SYSERR;
- }
- default:
- GE_LOG(ectx, GE_ERROR | GE_IMMEDIATE | GE_USER,
- _("Use --help to get a list of options.\n"));
- return -1;
- } /* end of parsing commandline */
- } /* while (1) */
+ case 'h':
+ {
+ static Help help[] = {
+ HELP_CONFIG,
+ HELP_HELP,
+ HELP_LOGLEVEL,
+ HELP_VERSION,
+ HELP_END,
+ };
+ formatHelp ("gnunet-testbed [OPTIONS]",
+ _("Start GNUnet testbed controller."), help);
+ return SYSERR;
+ }
+ default:
+ GE_LOG (ectx, GE_ERROR | GE_IMMEDIATE | GE_USER,
+ _("Use --help to get a list of options.\n"));
+ return -1;
+ } /* end of parsing commandline */
+ } /* while (1) */
return OK;
}
@@ -566,62 +524,70 @@
* @param argv command line arguments
* @return 0 on success, -1 on error
*/
-int main(int argc, char *argv[]) {
-#ifndef MINGW /* FIXME MINGW */
+int
+main (int argc, char *argv[])
+{
+#ifndef MINGW /* FIXME MINGW */
pid_t pid;
- char * ch;
+ char *ch;
- testbedArg0 = expandFileName(argv[0]);
+ testbedArg0 = expandFileName (argv[0]);
/* first, evaluate if we are the special
helper process. If so, eat HELPER
argument and run helper_main */
- if (argc > 1) {
- if (strcmp(argv[1], HELPER) == 0) {
- argv[1] = argv[0];
- return helper_main(argc -1, &argv[1]);
+ if (argc > 1)
+ {
+ if (strcmp (argv[1], HELPER) == 0)
+ {
+ argv[1] = argv[0];
+ return helper_main (argc - 1, &argv[1]);
+ }
}
- }
- if (SYSERR == initUtil(argc, argv, &parseOptions))
+ if (SYSERR == initUtil (argc, argv, &parseOptions))
return -1;
- ch = getConfigurationString("GNUNET-TESTBED",
- "TRUSTED");
- if (ch == NULL) {
- trustedNetworks_ = parseRoutes("127.0.0.0/8;"); /* by default, trust
localhost only */
- } else {
- trustedNetworks_ = parseRoutes(ch);
- if (trustedNetworks_ == NULL)
- errexit(_("Malformed entry in the configuration in section %s under %s:
%s\n"),
- "GNUNET-TESTBED",
- "TRUSTED",
- ch);
- FREE(ch);
- }
+ ch = getConfigurationString ("GNUNET-TESTBED", "TRUSTED");
+ if (ch == NULL)
+ {
+ trustedNetworks_ = parseRoutes ("127.0.0.0/8;"); /* by default, trust
localhost only */
+ }
+ else
+ {
+ trustedNetworks_ = parseRoutes (ch);
+ if (trustedNetworks_ == NULL)
+ errexit (_
+ ("Malformed entry in the configuration in section %s under
%s: %s\n"),
+ "GNUNET-TESTBED", "TRUSTED", ch);
+ FREE (ch);
+ }
/* we are the main testbed process. Fork of
a shell and start processing from the socket */
- pid = fork();
+ pid = fork ();
if (pid < 0)
- DIE_STRERROR("fork");
- if (pid == 0) {
- FREE(trustedNetworks_);
- bash_main();
- return 0; /* unreached */
- } else {
- int ret;
- /* run actual main loop */
- ret = server_main(pid);
- /* just to be certain */
- kill(pid, SIGHUP);
- /* proper shutdown... */
- doneUtil();
- FREE(trustedNetworks_);
- UNLINK(TB_ALIASES);
- FREE(testbedArg0);
- return ret;
- }
+ DIE_STRERROR ("fork");
+ if (pid == 0)
+ {
+ FREE (trustedNetworks_);
+ bash_main ();
+ return 0; /* unreached */
+ }
+ else
+ {
+ int ret;
+ /* run actual main loop */
+ ret = server_main (pid);
+ /* just to be certain */
+ kill (pid, SIGHUP);
+ /* proper shutdown... */
+ doneUtil ();
+ FREE (trustedNetworks_);
+ UNLINK (TB_ALIASES);
+ FREE (testbedArg0);
+ return ret;
+ }
#endif
}
Modified: GNUnet/src/applications/testbed/socket.c
===================================================================
--- GNUnet/src/applications/testbed/socket.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/testbed/socket.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -36,65 +36,68 @@
int sock = -1;
-static void writeAll(int fd,
- char * data,
- unsigned int len) {
+static void
+writeAll (int fd, char *data, unsigned int len)
+{
unsigned int pos;
int ret;
pos = 0;
ret = 42;
- while ( (ret > 0) && (pos < len) ) {
- ret = WRITE(sock, &data[pos], len-pos);
- if (ret > 0)
- pos += ret;
- else
- LOG_STRERROR(LOG_WARNING, "write");
- }
+ while ((ret > 0) && (pos < len))
+ {
+ ret = WRITE (sock, &data[pos], len - pos);
+ if (ret > 0)
+ pos += ret;
+ else
+ LOG_STRERROR (LOG_WARNING, "write");
+ }
}
/* ************** socket operations (IPC) ************* */
-typedef struct {
+typedef struct
+{
unsigned int size;
unsigned int type;
char data[0];
} ExchangeBuffer;
-void socketSend(unsigned int len,
- unsigned int type,
- void * data) {
- ExchangeBuffer * buf;
+void
+socketSend (unsigned int len, unsigned int type, void *data)
+{
+ ExchangeBuffer *buf;
unsigned int tlen;
#if DEBUG
unsigned int i;
#endif
- tlen = len + sizeof(ExchangeBuffer);
- buf = MALLOC(tlen);
+ tlen = len + sizeof (ExchangeBuffer);
+ buf = MALLOC (tlen);
if (len > 0)
- memcpy(&buf->data[0], data, len);
- buf->size = htonl(tlen);
- buf->type = htonl(type);
+ memcpy (&buf->data[0], data, len);
+ buf->size = htonl (tlen);
+ buf->type = htonl (type);
#if DEBUG
- printf("Sending %u bytes: ", tlen);
- for (i=0;i<tlen;i++)
- printf("%d ", ((char*)buf)[i]);
- printf("\n");
+ printf ("Sending %u bytes: ", tlen);
+ for (i = 0; i < tlen; i++)
+ printf ("%d ", ((char *) buf)[i]);
+ printf ("\n");
#endif
- writeAll(sock, (void*)buf, tlen);
- FREE(buf);
+ writeAll (sock, (void *) buf, tlen);
+ FREE (buf);
}
/**
* Read a message from the socket.
* @return the type of the message
*/
-unsigned int readSocket(char ** rbuf,
- unsigned int * len) {
+unsigned int
+readSocket (char **rbuf, unsigned int *len)
+{
unsigned int type;
- ExchangeBuffer * buf;
+ ExchangeBuffer *buf;
unsigned int pos;
int ret;
unsigned int mlen;
@@ -105,68 +108,73 @@
pos = 0;
ret = 42;
- while ( (pos < sizeof(unsigned int)) && (ret >= 0) ) {
- ret = READ(sock, &((char*)&mlen)[pos], sizeof(unsigned int)-pos);
- if (ret >= 0)
- pos += ret;
- else
- DIE_STRERROR("read");
- }
- mlen = ntohl(mlen);
+ while ((pos < sizeof (unsigned int)) && (ret >= 0))
+ {
+ ret = READ (sock, &((char *) &mlen)[pos], sizeof (unsigned int) - pos);
+ if (ret >= 0)
+ pos += ret;
+ else
+ DIE_STRERROR ("read");
+ }
+ mlen = ntohl (mlen);
- buf = MALLOC(mlen);
- while ( (pos < mlen) && (ret >= 0) ) {
- ret = READ(sock, &((char*)buf)[pos], mlen-pos);
- if (ret >= 0)
- pos += ret;
- else
- DIE_STRERROR("read");
- }
+ buf = MALLOC (mlen);
+ while ((pos < mlen) && (ret >= 0))
+ {
+ ret = READ (sock, &((char *) buf)[pos], mlen - pos);
+ if (ret >= 0)
+ pos += ret;
+ else
+ DIE_STRERROR ("read");
+ }
#if DEBUG
- buf->size = htonl(mlen);
- printf("Reading %u bytes: ", mlen);
- for (i=0;i<mlen;i++)
- printf("%d ", ((char*)buf)[i]);
- printf("\n");
+ buf->size = htonl (mlen);
+ printf ("Reading %u bytes: ", mlen);
+ for (i = 0; i < mlen; i++)
+ printf ("%d ", ((char *) buf)[i]);
+ printf ("\n");
#endif
- type = ntohl(buf->type);
- *rbuf = MALLOC(mlen - sizeof(ExchangeBuffer));
- memcpy(*rbuf, &buf->data[0], mlen - sizeof(ExchangeBuffer));
- FREE(buf);
- *len = mlen - sizeof(ExchangeBuffer);
+ type = ntohl (buf->type);
+ *rbuf = MALLOC (mlen - sizeof (ExchangeBuffer));
+ memcpy (*rbuf, &buf->data[0], mlen - sizeof (ExchangeBuffer));
+ FREE (buf);
+ *len = mlen - sizeof (ExchangeBuffer);
return type;
}
/**
* Print a message in the testbed-shell.
*/
-void XPRINTF(const char * fmt,
- ...) {
- va_list args;
+void
+XPRINTF (const char *fmt, ...)
+{
+ va_list args;
int n;
unsigned int size = 1024;
- char * p;
+ char *p;
- p = MALLOC(size);
- while (1) {
- /* Try to print in the allocated space. */
- va_start(args, fmt);
- n = vsnprintf(p, size, fmt, args);
- va_end(args);
- /* If that worked, return the string. */
- if ( (n > -1) && (n < size) ) {
- socketSend(n, SOCKET_PRINTF, p);
- FREE(p);
- return;
+ p = MALLOC (size);
+ while (1)
+ {
+ /* Try to print in the allocated space. */
+ va_start (args, fmt);
+ n = vsnprintf (p, size, fmt, args);
+ va_end (args);
+ /* If that worked, return the string. */
+ if ((n > -1) && (n < size))
+ {
+ socketSend (n, SOCKET_PRINTF, p);
+ FREE (p);
+ return;
+ }
+ /* Else try again with more space. */
+ if (n > -1) /* glibc 2.1 */
+ GROW (p, size, (unsigned int) n + 1); /* precisely what is needed */
+ else /* glibc 2.0 */
+ GROW (p, size, size * 2); /* twice the old size */
}
- /* Else try again with more space. */
- if (n > -1) /* glibc 2.1 */
- GROW(p, size, (unsigned int) n+1); /* precisely what is needed */
- else /* glibc 2.0 */
- GROW(p, size, size*2); /* twice the old size */
- }
}
/* end of socket communication primitives */
Modified: GNUnet/src/applications/testbed/socket.h
===================================================================
--- GNUnet/src/applications/testbed/socket.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/testbed/socket.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -40,18 +40,14 @@
#define SOCKET_ADD_ARGUMENT 3
#define SOCKET_END_COMMAND 4
-void socketSend(unsigned int len,
- unsigned int type,
- void * data);
+void socketSend (unsigned int len, unsigned int type, void *data);
/**
* Read a message from the socket.
* @return the type of the message
*/
-unsigned int readSocket(char ** rbuf,
- unsigned int * len);
+unsigned int readSocket (char **rbuf, unsigned int *len);
-void XPRINTF(const char * fmt,
- ...);
+void XPRINTF (const char *fmt, ...);
#endif
Modified: GNUnet/src/applications/testbed/testbed.c
===================================================================
--- GNUnet/src/applications/testbed/testbed.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/testbed/testbed.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -39,245 +39,243 @@
#define HTTP_URL "http://"
/* */
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
-static void sendAcknowledgement(ClientHandle client,
- int ack) {
- if (OK != coreAPI->sendValueToClient(client, ack)) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Could not send acknowledgement back to client.\n"));
- }
+static void
+sendAcknowledgement (ClientHandle client, int ack)
+{
+ if (OK != coreAPI->sendValueToClient (client, ack))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Could not send acknowledgement back to client.\n"));
+ }
}
/**
* Handler that is called for "message not understood" cases.
*/
-static void tb_undefined(ClientHandle client,
- TESTBED_CS_MESSAGE * msg) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Received unknown testbed message of type %u.\n"),
- ntohl(msg->msgType));
+static void
+tb_undefined (ClientHandle client, TESTBED_CS_MESSAGE * msg)
+{
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Received unknown testbed message of type %u.\n"),
+ ntohl (msg->msgType));
}
/**
* Connect to another peer.
*/
-static void tb_ADD_PEER(ClientHandle client,
- TESTBED_CS_MESSAGE * msg) {
+static void
+tb_ADD_PEER (ClientHandle client, TESTBED_CS_MESSAGE * msg)
+{
MESSAGE_HEADER noise;
- TESTBED_ADD_PEER_MESSAGE * hm
- = (TESTBED_ADD_PEER_MESSAGE*) msg;
+ TESTBED_ADD_PEER_MESSAGE *hm = (TESTBED_ADD_PEER_MESSAGE *) msg;
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- " tb_ADD_PEER\n");
- if (sizeof(TESTBED_ADD_PEER_MESSAGE) >
- ntohs(msg->header.size) ) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("size of `%s' message is too short. Ignoring.\n"),
- "ADD_PEER");
- return;
- }
- if (P2P_hello_MESSAGE_size(&hm->helo) !=
- ntohs(msg->header.size) - sizeof(TESTBED_CS_MESSAGE) ) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("size of `%s' message is wrong. Ignoring.\n"),
- "_ADD_PEER");
- return;
- }
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, " tb_ADD_PEER\n");
+ if (sizeof (TESTBED_ADD_PEER_MESSAGE) > ntohs (msg->header.size))
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("size of `%s' message is too short. Ignoring.\n"),
+ "ADD_PEER");
+ return;
+ }
+ if (P2P_hello_MESSAGE_size (&hm->helo) !=
+ ntohs (msg->header.size) - sizeof (TESTBED_CS_MESSAGE))
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("size of `%s' message is wrong. Ignoring.\n"), "_ADD_PEER");
+ return;
+ }
- identity->addHost(&hm->helo);
- noise.size = htons(sizeof(MESSAGE_HEADER));
- noise.type = htons(P2P_PROTO_noise);
- coreAPI->unicast(&hm->helo.senderIdentity,
- &noise,
- EXTREME_PRIORITY,
- 0);
- sendAcknowledgement(client, OK);
+ identity->addHost (&hm->helo);
+ noise.size = htons (sizeof (MESSAGE_HEADER));
+ noise.type = htons (P2P_PROTO_noise);
+ coreAPI->unicast (&hm->helo.senderIdentity, &noise, EXTREME_PRIORITY, 0);
+ sendAcknowledgement (client, OK);
}
/**
* Disconnect from another peer.
*/
-static void tb_DEL_PEER(ClientHandle client,
- TESTBED_DEL_PEER_MESSAGE * msg) {
- coreAPI->disconnectFromPeer(&msg->host);
- sendAcknowledgement(client, OK);
+static void
+tb_DEL_PEER (ClientHandle client, TESTBED_DEL_PEER_MESSAGE * msg)
+{
+ coreAPI->disconnectFromPeer (&msg->host);
+ sendAcknowledgement (client, OK);
}
-static void doDisconnect(const PeerIdentity * id,
- void * unused) {
- coreAPI->disconnectFromPeer(id);
+static void
+doDisconnect (const PeerIdentity * id, void *unused)
+{
+ coreAPI->disconnectFromPeer (id);
}
/**
* Disconnect from all other peers.
*/
-static void tb_DEL_ALL_PEERS(ClientHandle client,
- TESTBED_DEL_ALL_PEERS_MESSAGE * msg) {
- coreAPI->forAllConnectedNodes(&doDisconnect,
- NULL);
- sendAcknowledgement(client, OK);
+static void
+tb_DEL_ALL_PEERS (ClientHandle client, TESTBED_DEL_ALL_PEERS_MESSAGE * msg)
+{
+ coreAPI->forAllConnectedNodes (&doDisconnect, NULL);
+ sendAcknowledgement (client, OK);
}
/**
* Get a hello message for this peer.
*/
-static void tb_GET_hello(ClientHandle client,
- TESTBED_GET_hello_MESSAGE * msg) {
- P2P_hello_MESSAGE * helo;
- unsigned int proto = ntohs(msg->proto);
+static void
+tb_GET_hello (ClientHandle client, TESTBED_GET_hello_MESSAGE * msg)
+{
+ P2P_hello_MESSAGE *helo;
+ unsigned int proto = ntohs (msg->proto);
- helo = identity->identity2Helo(coreAPI->myIdentity,
- proto,
- NO);
- if (NULL == helo) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("TESTBED could not generate hello message for protocol %u\n"),
- proto);
- sendAcknowledgement(client, SYSERR);
- } else {
- TESTBED_hello_MESSAGE * reply
- = MALLOC(ntohs(helo->header.size) + sizeof(TESTBED_CS_MESSAGE));
- reply->header.header.size
- = htons(ntohs(helo->header.size) + sizeof(TESTBED_CS_MESSAGE));
- reply->header.header.type
- = htons(CS_PROTO_testbed_REPLY);
- reply->header.msgType
- = htonl(TESTBED_hello_RESPONSE);
- memcpy(&reply->helo,
- helo,
- ntohs(helo->header.size));
- coreAPI->sendToClient(client,
- &reply->header.header);
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "%s: returning from sendToClient\n",
- __FUNCTION__);
- FREE(helo);
- FREE(reply);
- }
+ helo = identity->identity2Helo (coreAPI->myIdentity, proto, NO);
+ if (NULL == helo)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("TESTBED could not generate hello message for protocol %u\n"),
+ proto);
+ sendAcknowledgement (client, SYSERR);
+ }
+ else
+ {
+ TESTBED_hello_MESSAGE *reply
+ = MALLOC (ntohs (helo->header.size) + sizeof (TESTBED_CS_MESSAGE));
+ reply->header.header.size
+ = htons (ntohs (helo->header.size) + sizeof (TESTBED_CS_MESSAGE));
+ reply->header.header.type = htons (CS_PROTO_testbed_REPLY);
+ reply->header.msgType = htonl (TESTBED_hello_RESPONSE);
+ memcpy (&reply->helo, helo, ntohs (helo->header.size));
+ coreAPI->sendToClient (client, &reply->header.header);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "%s: returning from sendToClient\n", __FUNCTION__);
+ FREE (helo);
+ FREE (reply);
+ }
}
/**
* Set a trust value.
*/
-static void tb_SET_TVALUE(ClientHandle client,
- TESTBED_SET_TVALUE_MESSAGE * msg) {
+static void
+tb_SET_TVALUE (ClientHandle client, TESTBED_SET_TVALUE_MESSAGE * msg)
+{
int trust;
- trust = ntohl(msg->trust);
- identity->changeHostTrust(&msg->otherPeer,
- trust);
- sendAcknowledgement(client, OK);
+ trust = ntohl (msg->trust);
+ identity->changeHostTrust (&msg->otherPeer, trust);
+ sendAcknowledgement (client, OK);
}
-
+
/**
* Get a trust value.
*/
-static void tb_GET_TVALUE(ClientHandle client,
- TESTBED_GET_TVALUE_MESSAGE * msg) {
+static void
+tb_GET_TVALUE (ClientHandle client, TESTBED_GET_TVALUE_MESSAGE * msg)
+{
unsigned int trust;
- trust = identity->getHostTrust(&msg->otherPeer);
- sendAcknowledgement(client, trust);
+ trust = identity->getHostTrust (&msg->otherPeer);
+ sendAcknowledgement (client, trust);
}
/**
* Change the bandwidth limitations.
*/
-static void tb_SET_BW(ClientHandle client,
- TESTBED_SET_BW_MESSAGE * msg) {
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "gnunet-testbed: tb_SET_BW\n");
- setConfigurationInt("LOAD",
- "MAXNETDOWNBPSTOTAL",
- ntohl(msg->in_bw));
- setConfigurationInt("LOAD",
- "MAXNETUPBPSTOTAL",
- ntohl(msg->out_bw));
- triggerGlobalConfigurationRefresh();
- sendAcknowledgement(client, OK);
-}
+static void
+tb_SET_BW (ClientHandle client, TESTBED_SET_BW_MESSAGE * msg)
+{
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "gnunet-testbed: tb_SET_BW\n");
+ setConfigurationInt ("LOAD", "MAXNETDOWNBPSTOTAL", ntohl (msg->in_bw));
+ setConfigurationInt ("LOAD", "MAXNETUPBPSTOTAL", ntohl (msg->out_bw));
+ triggerGlobalConfigurationRefresh ();
+ sendAcknowledgement (client, OK);
+}
/**
* Load an application module.
*/
-static void tb_LOAD_MODULE(ClientHandle client,
- TESTBED_CS_MESSAGE * msg) {
+static void
+tb_LOAD_MODULE (ClientHandle client, TESTBED_CS_MESSAGE * msg)
+{
unsigned short size;
- char * name;
+ char *name;
int ok;
- size = ntohs(msg->header.size);
- if (size <= sizeof(TESTBED_CS_MESSAGE) ) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("received invalid `%s' message\n"),
- "LOAD_MODULE");
- return;
- }
+ size = ntohs (msg->header.size);
+ if (size <= sizeof (TESTBED_CS_MESSAGE))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("received invalid `%s' message\n"), "LOAD_MODULE");
+ return;
+ }
- if (! testConfigurationString("TESTBED",
- "ALLOW_MODULE_LOADING",
- "YES")) {
- sendAcknowledgement(client, SYSERR);
- return;
- }
+ if (!testConfigurationString ("TESTBED", "ALLOW_MODULE_LOADING", "YES"))
+ {
+ sendAcknowledgement (client, SYSERR);
+ return;
+ }
- name = STRNDUP(&((TESTBED_LOAD_MODULE_MESSAGE_GENERIC*)msg)->modulename[0],
- size - sizeof(TESTBED_CS_MESSAGE));
- if (strlen(name) == 0) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("received invalid `%s' message (empty module name)\n"),
- "LOAD_MODULE");
- return;
- }
- ok = coreAPI->loadApplicationModule(name);
+ name =
+ STRNDUP (&((TESTBED_LOAD_MODULE_MESSAGE_GENERIC *) msg)->modulename[0],
+ size - sizeof (TESTBED_CS_MESSAGE));
+ if (strlen (name) == 0)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("received invalid `%s' message (empty module name)\n"),
+ "LOAD_MODULE");
+ return;
+ }
+ ok = coreAPI->loadApplicationModule (name);
if (ok != OK)
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("loading module `%s' failed. Notifying client.\n"),
- name);
- FREE(name);
- sendAcknowledgement(client, ok);
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("loading module `%s' failed. Notifying client.\n"), name);
+ FREE (name);
+ sendAcknowledgement (client, ok);
}
/**
* Unload an application module.
*/
-static void tb_UNLOAD_MODULE(ClientHandle client,
- TESTBED_CS_MESSAGE * msg) {
+static void
+tb_UNLOAD_MODULE (ClientHandle client, TESTBED_CS_MESSAGE * msg)
+{
unsigned short size;
- char * name;
+ char *name;
int ok;
- size = ntohs(msg->header.size);
- if (size <= sizeof(TESTBED_CS_MESSAGE) ) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("received invalid `%s' message\n"),
- "UNLOAD_MODULE");
- return;
- }
- if (! testConfigurationString("TESTBED",
- "ALLOW_MODULE_LOADING",
- "YES")) {
- sendAcknowledgement(client, SYSERR);
- return;
- }
+ size = ntohs (msg->header.size);
+ if (size <= sizeof (TESTBED_CS_MESSAGE))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("received invalid `%s' message\n"), "UNLOAD_MODULE");
+ return;
+ }
+ if (!testConfigurationString ("TESTBED", "ALLOW_MODULE_LOADING", "YES"))
+ {
+ sendAcknowledgement (client, SYSERR);
+ return;
+ }
- name = STRNDUP(&((TESTBED_UNLOAD_MODULE_MESSAGE_GENERIC*)msg)->modulename[0],
- size - sizeof(TESTBED_CS_MESSAGE));
- if (strlen(name) == 0) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("received invalid `%s' message (empty module name)\n"),
- "UNLOAD_MODULE");
- return;
- }
- ok = coreAPI->unloadApplicationModule(name);
+ name =
+ STRNDUP (&((TESTBED_UNLOAD_MODULE_MESSAGE_GENERIC *) msg)->modulename[0],
+ size - sizeof (TESTBED_CS_MESSAGE));
+ if (strlen (name) == 0)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("received invalid `%s' message (empty module name)\n"),
+ "UNLOAD_MODULE");
+ return;
+ }
+ ok = coreAPI->unloadApplicationModule (name);
if (ok != OK)
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("unloading module failed. Notifying client.\n"));
- FREE(name);
- sendAcknowledgement(client, ok);
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("unloading module failed. Notifying client.\n"));
+ FREE (name);
+ sendAcknowledgement (client, ok);
}
/**
@@ -285,13 +283,14 @@
* peer (by making it drop a certain percentage of the messages at
* random).
*/
-static void tb_DISABLE_AUTOCONNECT(ClientHandle client,
- TESTBED_DISABLE_AUTOCONNECT_MESSAGE * msg) {
- FREENONNULL(setConfigurationString("GNUNETD",
- "DISABLE-AUTOCONNECT",
- "YES"));
- triggerGlobalConfigurationRefresh();
- sendAcknowledgement(client, OK);
+static void
+tb_DISABLE_AUTOCONNECT (ClientHandle client,
+ TESTBED_DISABLE_AUTOCONNECT_MESSAGE * msg)
+{
+ FREENONNULL (setConfigurationString ("GNUNETD",
+ "DISABLE-AUTOCONNECT", "YES"));
+ triggerGlobalConfigurationRefresh ();
+ sendAcknowledgement (client, OK);
}
/**
@@ -299,13 +298,14 @@
* peer (by making it drop a certain percentage of the messages at
* random).
*/
-static void tb_ENABLE_AUTOCONNECT(ClientHandle client,
- TESTBED_ENABLE_AUTOCONNECT_MESSAGE * msg) {
- FREENONNULL(setConfigurationString("GNUNETD",
- "DISABLE-AUTOCONNECT",
- "NO"));
- triggerGlobalConfigurationRefresh();
- sendAcknowledgement(client, OK);
+static void
+tb_ENABLE_AUTOCONNECT (ClientHandle client,
+ TESTBED_ENABLE_AUTOCONNECT_MESSAGE * msg)
+{
+ FREENONNULL (setConfigurationString ("GNUNETD",
+ "DISABLE-AUTOCONNECT", "NO"));
+ triggerGlobalConfigurationRefresh ();
+ sendAcknowledgement (client, OK);
}
/**
@@ -313,16 +313,14 @@
* peer (by making it drop a certain percentage of the messages at
* random).
*/
-static void tb_DISABLE_hello(ClientHandle client,
- TESTBED_DISABLE_hello_MESSAGE * msg) {
- FREENONNULL(setConfigurationString("NETWORK",
- "DISABLE-ADVERTISEMENTS",
- "YES"));
- FREENONNULL(setConfigurationString("NETWORK",
- "HELLOEXCHANGE",
- "NO"));
- triggerGlobalConfigurationRefresh();
- sendAcknowledgement(client, OK);
+static void
+tb_DISABLE_hello (ClientHandle client, TESTBED_DISABLE_hello_MESSAGE * msg)
+{
+ FREENONNULL (setConfigurationString ("NETWORK",
+ "DISABLE-ADVERTISEMENTS", "YES"));
+ FREENONNULL (setConfigurationString ("NETWORK", "HELLOEXCHANGE", "NO"));
+ triggerGlobalConfigurationRefresh ();
+ sendAcknowledgement (client, OK);
}
/**
@@ -330,110 +328,115 @@
* peer (by making it drop a certain percentage of the messages at
* random).
*/
-static void tb_ENABLE_hello(ClientHandle client,
- TESTBED_ENABLE_hello_MESSAGE * msg) {
- FREENONNULL(setConfigurationString("NETWORK",
- "DISABLE-ADVERTISEMENTS",
- "NO"));
- FREENONNULL(setConfigurationString("NETWORK",
- "HELLOEXCHANGE",
- "YES"));
- triggerGlobalConfigurationRefresh();
- sendAcknowledgement(client, OK);
+static void
+tb_ENABLE_hello (ClientHandle client, TESTBED_ENABLE_hello_MESSAGE * msg)
+{
+ FREENONNULL (setConfigurationString ("NETWORK",
+ "DISABLE-ADVERTISEMENTS", "NO"));
+ FREENONNULL (setConfigurationString ("NETWORK", "HELLOEXCHANGE", "YES"));
+ triggerGlobalConfigurationRefresh ();
+ sendAcknowledgement (client, OK);
}
/**
* Allow only certain peers to connect.
*/
-static void tb_ALLOW_CONNECT(ClientHandle client,
- TESTBED_ALLOW_CONNECT_MESSAGE * msg) {
- char * value;
+static void
+tb_ALLOW_CONNECT (ClientHandle client, TESTBED_ALLOW_CONNECT_MESSAGE * msg)
+{
+ char *value;
unsigned short size;
unsigned int count;
unsigned int i;
EncName enc;
- size = ntohs(msg->header.header.size);
- if (size <= sizeof(TESTBED_CS_MESSAGE) ) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("received invalid `%s' message\n"),
- "ALLOW_CONNECT");
- return;
- }
- count = (size - sizeof(TESTBED_CS_MESSAGE)) / sizeof(PeerIdentity);
- if (count * sizeof(PeerIdentity) + sizeof(TESTBED_CS_MESSAGE) != size) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("received invalid `%s' message\n"),
- "ALLOW_CONNECT");
- return;
- }
- if (count == 0) {
- value = NULL;
- } else {
- value = MALLOC(count * sizeof(EncName) + 1);
- value[0] = '\0';
- for (i=0;i<count;i++) {
-
hash2enc(&((TESTBED_ALLOW_CONNECT_MESSAGE_GENERIC*)msg)->peers[i].hashPubKey,
- &enc);
- strcat(value, (char*)&enc);
+ size = ntohs (msg->header.header.size);
+ if (size <= sizeof (TESTBED_CS_MESSAGE))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("received invalid `%s' message\n"), "ALLOW_CONNECT");
+ return;
}
- }
- FREENONNULL(setConfigurationString("GNUNETD",
- "LIMIT-ALLOW",
- value));
- FREENONNULL(value);
- triggerGlobalConfigurationRefresh();
- sendAcknowledgement(client, OK);
+ count = (size - sizeof (TESTBED_CS_MESSAGE)) / sizeof (PeerIdentity);
+ if (count * sizeof (PeerIdentity) + sizeof (TESTBED_CS_MESSAGE) != size)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("received invalid `%s' message\n"), "ALLOW_CONNECT");
+ return;
+ }
+ if (count == 0)
+ {
+ value = NULL;
+ }
+ else
+ {
+ value = MALLOC (count * sizeof (EncName) + 1);
+ value[0] = '\0';
+ for (i = 0; i < count; i++)
+ {
+ hash2enc (&((TESTBED_ALLOW_CONNECT_MESSAGE_GENERIC *) msg)->
+ peers[i].hashPubKey, &enc);
+ strcat (value, (char *) &enc);
+ }
+ }
+ FREENONNULL (setConfigurationString ("GNUNETD", "LIMIT-ALLOW", value));
+ FREENONNULL (value);
+ triggerGlobalConfigurationRefresh ();
+ sendAcknowledgement (client, OK);
}
/**
* Deny certain peers the right to connect.
*/
-static void tb_DENY_CONNECT(ClientHandle client,
- TESTBED_DENY_CONNECT_MESSAGE * msg) {
- char * value;
+static void
+tb_DENY_CONNECT (ClientHandle client, TESTBED_DENY_CONNECT_MESSAGE * msg)
+{
+ char *value;
unsigned short size;
unsigned int count;
unsigned int i;
EncName enc;
- size = ntohs(msg->header.header.size);
- if (size <= sizeof(TESTBED_CS_MESSAGE) ) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("received invalid `%s' message\n"),
- "DENY_CONNECT");
- return;
- }
- count = (size - sizeof(TESTBED_CS_MESSAGE)) / sizeof(PeerIdentity);
- if (count * sizeof(PeerIdentity) + sizeof(TESTBED_CS_MESSAGE) != size) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("received invalid `%s' message\n"),
- "DENY_CONNECT");
- return;
- }
- if (count == 0) {
- value = NULL;
- } else {
- value = MALLOC(count * sizeof(EncName) + 1);
- value[0] = '\0';
- for (i=0;i<count;i++) {
-
hash2enc(&((TESTBED_DENY_CONNECT_MESSAGE_GENERIC*)msg)->peers[i].hashPubKey,
- &enc);
- strcat(value, (char*)&enc);
+ size = ntohs (msg->header.header.size);
+ if (size <= sizeof (TESTBED_CS_MESSAGE))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("received invalid `%s' message\n"), "DENY_CONNECT");
+ return;
}
- }
- FREENONNULL(setConfigurationString("GNUNETD",
- "LIMIT-DENY",
- value));
- FREENONNULL(value);
- triggerGlobalConfigurationRefresh();
- sendAcknowledgement(client, OK);
+ count = (size - sizeof (TESTBED_CS_MESSAGE)) / sizeof (PeerIdentity);
+ if (count * sizeof (PeerIdentity) + sizeof (TESTBED_CS_MESSAGE) != size)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("received invalid `%s' message\n"), "DENY_CONNECT");
+ return;
+ }
+ if (count == 0)
+ {
+ value = NULL;
+ }
+ else
+ {
+ value = MALLOC (count * sizeof (EncName) + 1);
+ value[0] = '\0';
+ for (i = 0; i < count; i++)
+ {
+ hash2enc (&((TESTBED_DENY_CONNECT_MESSAGE_GENERIC *) msg)->peers[i].
+ hashPubKey, &enc);
+ strcat (value, (char *) &enc);
+ }
+ }
+ FREENONNULL (setConfigurationString ("GNUNETD", "LIMIT-DENY", value));
+ FREENONNULL (value);
+ triggerGlobalConfigurationRefresh ();
+ sendAcknowledgement (client, OK);
}
/**
* Information about processes that we have forked off.
*/
-typedef struct {
+typedef struct
+{
/** the unique identifier of the PI */
unsigned int uid;
/** errno after fork */
@@ -447,19 +450,19 @@
/** how many bytes of output did the process produce? */
unsigned int outputSize;
/** the output of the process */
- char * output;
+ char *output;
/** did the process exit? (YES/NO) */
int hasExited;
/** if the process did exit, what was the status? (or errno of execve) */
int exitStatus;
/** semaphore used to communicate thread-start */
- Semaphore * sem;
+ Semaphore *sem;
/** Client responsible for this process
(if that client disconnects, the process
will be killed!) */
ClientHandle client;
/** arguments for exec */
- char ** argv;
+ char **argv;
int argc;
} ProcessInfo;
@@ -468,7 +471,7 @@
/**
* The process table.
*/
-static ProcessInfo ** pt = NULL;
+static ProcessInfo **pt = NULL;
/**
* Number of entries in the process table.
@@ -484,75 +487,73 @@
* Thread that captures the output from a child-process
* and stores it in the process info.
*/
-static int pipeReaderThread(ProcessInfo * pi) {
+static int
+pipeReaderThread (ProcessInfo * pi)
+{
int ret = 1;
- char * buffer;
+ char *buffer;
int pos;
int fd[2];
int i;
- char * dir;
- char * tmp;
+ char *dir;
+ char *tmp;
- if (0 != PIPE(fd)) {
- LOG_STRERROR(LOG_WARNING, "pipe");
- pi->pid = SYSERR;
- SEMAPHORE_UP(pi->sem);
- MUTEX_UNLOCK(&lock);
- return -1;
- }
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "exec'ing: %s with %d arguments\n",
- pi->argv[0],
- pi->argc-1);
- for (i=1;i<pi->argc;i++)
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "exec argument %d is %s\n",
- i, pi->argv[i]);
- tmp = getConfigurationString("TESTBED",
- "UPLOAD-DIR");
+ if (0 != PIPE (fd))
+ {
+ LOG_STRERROR (LOG_WARNING, "pipe");
+ pi->pid = SYSERR;
+ SEMAPHORE_UP (pi->sem);
+ MUTEX_UNLOCK (&lock);
+ return -1;
+ }
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "exec'ing: %s with %d arguments\n", pi->argv[0], pi->argc - 1);
+ for (i = 1; i < pi->argc; i++)
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "exec argument %d is %s\n", i, pi->argv[i]);
+ tmp = getConfigurationString ("TESTBED", "UPLOAD-DIR");
if (tmp == NULL)
- tmp = STRDUP(DIR_SEPARATOR_STR);
- dir = expandFileName(tmp);
- disk_directory_create(ectx, dir);
- FREE(tmp);
+ tmp = STRDUP (DIR_SEPARATOR_STR);
+ dir = expandFileName (tmp);
+ disk_directory_create (ectx, dir);
+ FREE (tmp);
- MUTEX_LOCK(&lock);
- pi->pid = fork();
+ MUTEX_LOCK (&lock);
+ pi->pid = fork ();
pi->errno_ = errno;
- if (pi->pid == 0) {
- /* make pipe stdout/stderr */
+ if (pi->pid == 0)
+ {
+ /* make pipe stdout/stderr */
- closefile(fd[0]);
- closefile(1);
- closefile(2);
- if (-1 == dup2(fd[1], 1))
- LOG_STRERROR(LOG_ERROR, "dup2");
- if (-1 == dup2(fd[1], 2))
- LOG_STRERROR(LOG_ERROR, "dup2");
- closefile(fd[1]);
- CHDIR(dir);
- FREE(dir);
- execvp(pi->argv[0],
- &pi->argv[0]);
- GE_LOG_STRERROR_FILE(ectx,LOG_ERROR, "execvp", pi->argv[0]);
- fprintf(stderr,
- _("`%s' %s failed: %s\n"),
- "execvp",
- pi->argv[0],
- STRERROR(errno));
- exit(errno);
- } /* end pi->pid == 0 */
- FREE(dir);
- closefile(fd[1]);
- for (pos=0;pos<pi->argc;pos++)
- FREE(pi->argv[pos]);
- FREE(pi->argv);
- if (pi->pid == -1) {
- closefile(fd[0]);
- SEMAPHORE_UP(pi->sem);
- MUTEX_UNLOCK(&lock);
- return -1;
- }
+ closefile (fd[0]);
+ closefile (1);
+ closefile (2);
+ if (-1 == dup2 (fd[1], 1))
+ LOG_STRERROR (LOG_ERROR, "dup2");
+ if (-1 == dup2 (fd[1], 2))
+ LOG_STRERROR (LOG_ERROR, "dup2");
+ closefile (fd[1]);
+ CHDIR (dir);
+ FREE (dir);
+ execvp (pi->argv[0], &pi->argv[0]);
+ GE_LOG_STRERROR_FILE (ectx, LOG_ERROR, "execvp", pi->argv[0]);
+ fprintf (stderr,
+ _("`%s' %s failed: %s\n"),
+ "execvp", pi->argv[0], STRERROR (errno));
+ exit (errno);
+ } /* end pi->pid == 0 */
+ FREE (dir);
+ closefile (fd[1]);
+ for (pos = 0; pos < pi->argc; pos++)
+ FREE (pi->argv[pos]);
+ FREE (pi->argv);
+ if (pi->pid == -1)
+ {
+ closefile (fd[0]);
+ SEMAPHORE_UP (pi->sem);
+ MUTEX_UNLOCK (&lock);
+ return -1;
+ }
pi->uid = uidCounter++;
pi->outputPipe = fd[0];
pi->outputSize = 0;
@@ -560,363 +561,367 @@
pi->hasExited = NO;
pi->exitStatus = 0;
- GROW(pt,
- ptSize,
- ptSize+1);
- pt[ptSize-1] = pi;
- SEMAPHORE_UP(pi->sem);
- MUTEX_UNLOCK(&lock);
+ GROW (pt, ptSize, ptSize + 1);
+ pt[ptSize - 1] = pi;
+ SEMAPHORE_UP (pi->sem);
+ MUTEX_UNLOCK (&lock);
#define PRT_BUFSIZE 65536
- buffer = MALLOC(PRT_BUFSIZE);
- while (ret > 0) {
- ret = READ(pi->outputPipe,
- buffer,
- PRT_BUFSIZE);
- if (ret <= 0)
- break;
- MUTEX_LOCK(&lock);
- if (pi->outputSize == -1) {
- MUTEX_UNLOCK(&lock);
- break;
+ buffer = MALLOC (PRT_BUFSIZE);
+ while (ret > 0)
+ {
+ ret = READ (pi->outputPipe, buffer, PRT_BUFSIZE);
+ if (ret <= 0)
+ break;
+ MUTEX_LOCK (&lock);
+ if (pi->outputSize == -1)
+ {
+ MUTEX_UNLOCK (&lock);
+ break;
+ }
+ GROW (pi->output, pi->outputSize, pi->outputSize + ret);
+ memcpy (&pi->output[pi->outputSize - ret], buffer, ret);
+ MUTEX_UNLOCK (&lock);
}
- GROW(pi->output,
- pi->outputSize,
- pi->outputSize + ret);
- memcpy(&pi->output[pi->outputSize-ret],
- buffer,
- ret);
- MUTEX_UNLOCK(&lock);
- }
- closefile(pi->outputPipe);
- MUTEX_LOCK(&lock);
+ closefile (pi->outputPipe);
+ MUTEX_LOCK (&lock);
- ret = waitpid(pi->pid,
- &pi->exitStatus,
- 0);
- if (ret != pi->pid) {
- LOG_STRERROR(LOG_WARNING, "waitpid");
- pi->exitStatus = errno;
- }
+ ret = waitpid (pi->pid, &pi->exitStatus, 0);
+ if (ret != pi->pid)
+ {
+ LOG_STRERROR (LOG_WARNING, "waitpid");
+ pi->exitStatus = errno;
+ }
pi->hasExited = YES;
- MUTEX_UNLOCK(&lock);
+ MUTEX_UNLOCK (&lock);
return 0;
}
/**
* Execute a command.
*/
-static void tb_EXEC(ClientHandle client,
- TESTBED_CS_MESSAGE * msg) {
+static void
+tb_EXEC (ClientHandle client, TESTBED_CS_MESSAGE * msg)
+{
int argc2;
unsigned short size;
unsigned int uid;
int pos;
- TESTBED_EXEC_MESSAGE * emsg;
- ProcessInfo * pi;
- char * clientConfig;
- char * mainName;
+ TESTBED_EXEC_MESSAGE *emsg;
+ ProcessInfo *pi;
+ char *clientConfig;
+ char *mainName;
- emsg = (TESTBED_EXEC_MESSAGE*)msg;
- size = htons(msg->header.size);
- if ( (size <= sizeof(TESTBED_CS_MESSAGE)) ||
-
(((TESTBED_EXEC_MESSAGE_GENERIC*)emsg)->commandLine[size-sizeof(TESTBED_CS_MESSAGE)-1]
!= '\0') ) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("received invalid `%s' message: %s.\n"),
- "EXEC",
- (size <= sizeof(TESTBED_CS_MESSAGE))
- ? "size smaller or equal than TESTBED_CS_MESSAGE"
- : "last character in command line is not zero-terminator");
- sendAcknowledgement(client, SYSERR);
- return;
- }
- size -= sizeof(TESTBED_CS_MESSAGE);
- pi = MALLOC(sizeof(ProcessInfo));
+ emsg = (TESTBED_EXEC_MESSAGE *) msg;
+ size = htons (msg->header.size);
+ if ((size <= sizeof (TESTBED_CS_MESSAGE)) ||
+ (((TESTBED_EXEC_MESSAGE_GENERIC *) emsg)->
+ commandLine[size - sizeof (TESTBED_CS_MESSAGE) - 1] != '\0'))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("received invalid `%s' message: %s.\n"),
+ "EXEC",
+ (size <= sizeof (TESTBED_CS_MESSAGE))
+ ? "size smaller or equal than TESTBED_CS_MESSAGE"
+ : "last character in command line is not zero-terminator");
+ sendAcknowledgement (client, SYSERR);
+ return;
+ }
+ size -= sizeof (TESTBED_CS_MESSAGE);
+ pi = MALLOC (sizeof (ProcessInfo));
pi->argc = 0;
- for (pos=0;pos<size;pos++)
- if (((TESTBED_EXEC_MESSAGE_GENERIC*)emsg)->commandLine[pos] == '\0')
+ for (pos = 0; pos < size; pos++)
+ if (((TESTBED_EXEC_MESSAGE_GENERIC *) emsg)->commandLine[pos] == '\0')
pi->argc++;
- mainName = STRDUP(&((TESTBED_EXEC_MESSAGE_GENERIC*)emsg)->commandLine[0]);
+ mainName =
+ STRDUP (&((TESTBED_EXEC_MESSAGE_GENERIC *) emsg)->commandLine[0]);
clientConfig = NULL;
- if (0 == strncmp("gnunet",
- mainName,
- strlen("gnunet")))
- clientConfig = getConfigurationString("TESTBED",
- "CLIENTCONFIG");
+ if (0 == strncmp ("gnunet", mainName, strlen ("gnunet")))
+ clientConfig = getConfigurationString ("TESTBED", "CLIENTCONFIG");
if (clientConfig != NULL)
- pi->argc +=2;
+ pi->argc += 2;
argc2 = pi->argc;
- pi->argv = MALLOC(sizeof(char*)*(pi->argc+1));
+ pi->argv = MALLOC (sizeof (char *) * (pi->argc + 1));
pi->argv[0] = mainName;
- pi->argv[pi->argc] = NULL; /* termination! */
- for (pos=size-2;pos>=0;pos--)
- if (((TESTBED_EXEC_MESSAGE_GENERIC*)emsg)->commandLine[pos] == '\0')
- pi->argv[--argc2] =
STRDUP(&((TESTBED_EXEC_MESSAGE_GENERIC*)emsg)->commandLine[pos+1]);
- if (clientConfig != NULL) {
- pi->argv[--argc2] = clientConfig;
- pi->argv[--argc2] = STRDUP("-c");
- }
- MUTEX_LOCK(&lock);
+ pi->argv[pi->argc] = NULL; /* termination! */
+ for (pos = size - 2; pos >= 0; pos--)
+ if (((TESTBED_EXEC_MESSAGE_GENERIC *) emsg)->commandLine[pos] == '\0')
+ pi->argv[--argc2] =
+ STRDUP (&((TESTBED_EXEC_MESSAGE_GENERIC *) emsg)->
+ commandLine[pos + 1]);
+ if (clientConfig != NULL)
+ {
+ pi->argv[--argc2] = clientConfig;
+ pi->argv[--argc2] = STRDUP ("-c");
+ }
+ MUTEX_LOCK (&lock);
- pi->sem = SEMAPHORE_CREATE(0);
- if (0 != PTHREAD_CREATE(&pi->reader,
- (PThreadMain) &pipeReaderThread,
- pi,
- 8*1024)) {
- LOG_STRERROR(LOG_WARNING, "pthread_create");
- SEMAPHORE_DESTROY(pi->sem);
- MUTEX_UNLOCK(&lock);
- FREE(pi);
- sendAcknowledgement(client, SYSERR);
- return;
- }
- MUTEX_UNLOCK(&lock);
- SEMAPHORE_DOWN(pi->sem);
- SEMAPHORE_DESTROY(pi->sem);
+ pi->sem = SEMAPHORE_CREATE (0);
+ if (0 != PTHREAD_CREATE (&pi->reader,
+ (PThreadMain) & pipeReaderThread, pi, 8 * 1024))
+ {
+ LOG_STRERROR (LOG_WARNING, "pthread_create");
+ SEMAPHORE_DESTROY (pi->sem);
+ MUTEX_UNLOCK (&lock);
+ FREE (pi);
+ sendAcknowledgement (client, SYSERR);
+ return;
+ }
+ MUTEX_UNLOCK (&lock);
+ SEMAPHORE_DOWN (pi->sem);
+ SEMAPHORE_DESTROY (pi->sem);
uid = pi->uid;
- if (uid == -1) {
- errno = pi->errno_;
- LOG_STRERROR(LOG_WARNING, "fork");
- FREE(pi);
- uid = SYSERR;
- }
- sendAcknowledgement(client, uid);
+ if (uid == -1)
+ {
+ errno = pi->errno_;
+ LOG_STRERROR (LOG_WARNING, "fork");
+ FREE (pi);
+ uid = SYSERR;
+ }
+ sendAcknowledgement (client, uid);
}
/**
* Send a signal to a process or obtain the status of the
* process on exit.
*/
-static void tb_SIGNAL(ClientHandle client,
- TESTBED_SIGNAL_MESSAGE * msg) {
+static void
+tb_SIGNAL (ClientHandle client, TESTBED_SIGNAL_MESSAGE * msg)
+{
int ret;
int i;
unsigned int uid;
int sig;
- void * unused;
- ProcessInfo * pi;
+ void *unused;
+ ProcessInfo *pi;
ret = SYSERR;
- uid = ntohl(msg->pid);
- sig = ntohl(msg->signal);
- MUTEX_LOCK(&lock);
- for (i=0;i<ptSize;i++) {
- pi = pt[i];
- if (pi->uid != uid)
- continue;
- if (sig == -1) {
- if (pi->hasExited == NO) {
- ret = SYSERR;
- } else {
- ret = WEXITSTATUS(pi->exitStatus);
- /* free resources... */
- GROW(pi->output,
- pi->outputSize,
- 0);
- PTHREAD_JOIN(&pi->reader,
- &unused);
- FREE(pi);
- pt[i] = pt[ptSize-1];
- GROW(pt,
- ptSize,
- ptSize-1);
- }
- } else {
- if (pi->hasExited == NO) {
- if (0 == kill(pi->pid,
- ntohl(msg->signal)))
- ret = OK;
- else
- LOG_STRERROR(LOG_WARNING, "kill");
- }
+ uid = ntohl (msg->pid);
+ sig = ntohl (msg->signal);
+ MUTEX_LOCK (&lock);
+ for (i = 0; i < ptSize; i++)
+ {
+ pi = pt[i];
+ if (pi->uid != uid)
+ continue;
+ if (sig == -1)
+ {
+ if (pi->hasExited == NO)
+ {
+ ret = SYSERR;
+ }
+ else
+ {
+ ret = WEXITSTATUS (pi->exitStatus);
+ /* free resources... */
+ GROW (pi->output, pi->outputSize, 0);
+ PTHREAD_JOIN (&pi->reader, &unused);
+ FREE (pi);
+ pt[i] = pt[ptSize - 1];
+ GROW (pt, ptSize, ptSize - 1);
+ }
+ }
+ else
+ {
+ if (pi->hasExited == NO)
+ {
+ if (0 == kill (pi->pid, ntohl (msg->signal)))
+ ret = OK;
+ else
+ LOG_STRERROR (LOG_WARNING, "kill");
+ }
+ }
+ break;
}
- break;
- }
- MUTEX_UNLOCK(&lock);
- sendAcknowledgement(client, ret);
+ MUTEX_UNLOCK (&lock);
+ sendAcknowledgement (client, ret);
}
/**
* Get the output of a process.
*/
-static void tb_GET_OUTPUT(ClientHandle client,
- TESTBED_GET_OUTPUT_MESSAGE * msg) {
+static void
+tb_GET_OUTPUT (ClientHandle client, TESTBED_GET_OUTPUT_MESSAGE * msg)
+{
int i;
unsigned int uid;
- uid = ntohl(msg->pid);
- MUTEX_LOCK(&lock);
- for (i=0;i<ptSize;i++) {
- ProcessInfo * pi;
+ uid = ntohl (msg->pid);
+ MUTEX_LOCK (&lock);
+ for (i = 0; i < ptSize; i++)
+ {
+ ProcessInfo *pi;
- pi = pt[i];
- if (pi->uid == uid) {
- unsigned int pos;
- TESTBED_OUTPUT_REPLY_MESSAGE * msg;
+ pi = pt[i];
+ if (pi->uid == uid)
+ {
+ unsigned int pos;
+ TESTBED_OUTPUT_REPLY_MESSAGE *msg;
- msg = MALLOC(65532);
- msg->header.header.type
- = htons(CS_PROTO_testbed_REPLY);
- msg->header.msgType
- = htonl(TESTBED_OUTPUT_RESPONSE);
+ msg = MALLOC (65532);
+ msg->header.header.type = htons (CS_PROTO_testbed_REPLY);
+ msg->header.msgType = htonl (TESTBED_OUTPUT_RESPONSE);
- sendAcknowledgement(client, pi->outputSize);
- pos = 0;
- while (pos < pi->outputSize) {
- unsigned int run = pi->outputSize - pos;
- if (run > 65532 - sizeof(TESTBED_OUTPUT_REPLY_MESSAGE))
- run = 65532 - sizeof(TESTBED_OUTPUT_REPLY_MESSAGE);
- msg->header.header.size
- = htons(run+sizeof(TESTBED_OUTPUT_REPLY_MESSAGE));
- memcpy(&((TESTBED_OUTPUT_REPLY_MESSAGE_GENERIC*)msg)->data[0],
- &pi->output[pos],
- run);
- coreAPI->sendToClient(client,
- &msg->header.header);
- pos += run;
- }
- FREE(msg);
- /* reset output buffer */
- GROW(pi->output,
- pi->outputSize,
- 0);
- MUTEX_UNLOCK(&lock);
- return;
+ sendAcknowledgement (client, pi->outputSize);
+ pos = 0;
+ while (pos < pi->outputSize)
+ {
+ unsigned int run = pi->outputSize - pos;
+ if (run > 65532 - sizeof (TESTBED_OUTPUT_REPLY_MESSAGE))
+ run = 65532 - sizeof (TESTBED_OUTPUT_REPLY_MESSAGE);
+ msg->header.header.size
+ = htons (run + sizeof (TESTBED_OUTPUT_REPLY_MESSAGE));
+ memcpy (&((TESTBED_OUTPUT_REPLY_MESSAGE_GENERIC *) msg)->
+ data[0], &pi->output[pos], run);
+ coreAPI->sendToClient (client, &msg->header.header);
+ pos += run;
+ }
+ FREE (msg);
+ /* reset output buffer */
+ GROW (pi->output, pi->outputSize, 0);
+ MUTEX_UNLOCK (&lock);
+ return;
+ }
}
- }
- MUTEX_UNLOCK(&lock);
- sendAcknowledgement(client, SYSERR);
+ MUTEX_UNLOCK (&lock);
+ sendAcknowledgement (client, SYSERR);
}
/**
* The client is uploading a file to this peer.
*/
-static void tb_UPLOAD_FILE(ClientHandle client,
- TESTBED_UPLOAD_FILE_MESSAGE * msg) {
+static void
+tb_UPLOAD_FILE (ClientHandle client, TESTBED_UPLOAD_FILE_MESSAGE * msg)
+{
int ack;
unsigned int size;
- char * filename, *gnHome, *s;
- char * end;
- char * tmp;
+ char *filename, *gnHome, *s;
+ char *end;
+ char *tmp;
FILE *outfile;
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "tb_UPLOAD_FILE\n");
- if (sizeof(TESTBED_UPLOAD_FILE_MESSAGE) > ntohs(msg->header.header.size)) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("size of `%s' message is too short. Ignoring.\n"),
- "UPLOAD_FILE");
- sendAcknowledgement(client, SYSERR);
- return;
- }
- end = &((char*)msg)[ntohs(msg->header.header.size)];
- s = filename = ((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC*)msg)->buf;
- while ( (*s) && (s != end) ) {
- if (*s == '.' && *(s+1) == '.') {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("\'..\' is not allowed in file name (%s).\n"),
- filename);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, "tb_UPLOAD_FILE\n");
+ if (sizeof (TESTBED_UPLOAD_FILE_MESSAGE) > ntohs (msg->header.header.size))
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("size of `%s' message is too short. Ignoring.\n"),
+ "UPLOAD_FILE");
+ sendAcknowledgement (client, SYSERR);
return;
}
- s++;
- }
- if (s == filename) {
- /* filename empty, not allowed! */
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Empty filename for UPLOAD_FILE message is invalid!\n"));
- sendAcknowledgement(client, SYSERR);
- return;
- }
- if (s == end) {
- /* filename empty, not allowed! */
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Filename for UPLOAD_FILE message is not null-terminated (invalid!)\n"));
- sendAcknowledgement(client, SYSERR);
- return;
- }
- tmp = getConfigurationString("TESTBED",
- "UPLOAD-DIR");
- if (tmp == NULL) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Upload refused!"));
- sendAcknowledgement(client, SYSERR);
- return;
- }
- gnHome = expandFileName(tmp);
- FREE(tmp);
- disk_directory_create(ectx, gnHome);
+ end = &((char *) msg)[ntohs (msg->header.header.size)];
+ s = filename = ((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC *) msg)->buf;
+ while ((*s) && (s != end))
+ {
+ if (*s == '.' && *(s + 1) == '.')
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("\'..\' is not allowed in file name (%s).\n"), filename);
+ return;
+ }
+ s++;
+ }
+ if (s == filename)
+ {
+ /* filename empty, not allowed! */
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Empty filename for UPLOAD_FILE message is invalid!\n"));
+ sendAcknowledgement (client, SYSERR);
+ return;
+ }
+ if (s == end)
+ {
+ /* filename empty, not allowed! */
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("Filename for UPLOAD_FILE message is not null-terminated
(invalid!)\n"));
+ sendAcknowledgement (client, SYSERR);
+ return;
+ }
+ tmp = getConfigurationString ("TESTBED", "UPLOAD-DIR");
+ if (tmp == NULL)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER, _("Upload refused!"));
+ sendAcknowledgement (client, SYSERR);
+ return;
+ }
+ gnHome = expandFileName (tmp);
+ FREE (tmp);
+ disk_directory_create (ectx, gnHome);
- filename = MALLOC(strlen(filename) + strlen(gnHome) + 2); /*2: /, \0 */
- strcpy(filename, gnHome);
- strcat(filename, DIR_SEPARATOR_STR);
- strncat(filename,
- ((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC*)msg)->buf,
- end - ((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC*)msg)->buf);
- if (htonl(msg->type) == TESTBED_FILE_DELETE) {
- if (REMOVE(filename) && errno != ENOENT) {
- GE_LOG_STRERROR_FILE(ectx,LOG_WARNING, "remove", filename);
- ack = SYSERR;
- } else
- ack = OK;
- FREE(filename);
- sendAcknowledgement(client, ack);
- return;
- }
- if (htonl(msg->type) != TESTBED_FILE_APPEND) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Invalid message received at %s:%d."),
- __FILE__,
- __LINE__);
- FREE(filename);
- return;
- }
- outfile = FOPEN(filename, "ab");
- if (outfile == NULL) {
- /* Send nack back to control point. */
- GE_LOG_STRERROR_FILE(ectx,LOG_ERROR, "fopen", filename);
- sendAcknowledgement(client, SYSERR);
- FREE(filename);
- return;
- }
- FREE(filename);
- s = ((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC*)msg)->buf
- + strlen(((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC*)msg)->buf) + 1; /* \0
added */
- size = ntohs(msg->header.header.size) -
- sizeof(TESTBED_UPLOAD_FILE_MESSAGE) -
- (strlen(((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC*)msg)->buf)+1);
- if (GN_FWRITE(s, 1, size, outfile) != size)
+ filename = MALLOC (strlen (filename) + strlen (gnHome) + 2); /*2: /, \0 */
+ strcpy (filename, gnHome);
+ strcat (filename, DIR_SEPARATOR_STR);
+ strncat (filename,
+ ((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC *) msg)->buf,
+ end - ((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC *) msg)->buf);
+ if (htonl (msg->type) == TESTBED_FILE_DELETE)
+ {
+ if (REMOVE (filename) && errno != ENOENT)
+ {
+ GE_LOG_STRERROR_FILE (ectx, LOG_WARNING, "remove", filename);
+ ack = SYSERR;
+ }
+ else
+ ack = OK;
+ FREE (filename);
+ sendAcknowledgement (client, ack);
+ return;
+ }
+ if (htonl (msg->type) != TESTBED_FILE_APPEND)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Invalid message received at %s:%d."), __FILE__, __LINE__);
+ FREE (filename);
+ return;
+ }
+ outfile = FOPEN (filename, "ab");
+ if (outfile == NULL)
+ {
+ /* Send nack back to control point. */
+ GE_LOG_STRERROR_FILE (ectx, LOG_ERROR, "fopen", filename);
+ sendAcknowledgement (client, SYSERR);
+ FREE (filename);
+ return;
+ }
+ FREE (filename);
+ s = ((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC *) msg)->buf + strlen
(((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC *) msg)->buf) + 1; /* \0 added */
+ size = ntohs (msg->header.header.size) -
+ sizeof (TESTBED_UPLOAD_FILE_MESSAGE) -
+ (strlen (((TESTBED_UPLOAD_FILE_MESSAGE_GENERIC *) msg)->buf) + 1);
+ if (GN_FWRITE (s, 1, size, outfile) != size)
ack = SYSERR;
else
ack = OK;
- fclose(outfile);
- sendAcknowledgement(client, ack);
+ fclose (outfile);
+ sendAcknowledgement (client, ack);
}
/**
* General type of a message handler.
- */
-typedef void (*THandler)(ClientHandle client,
- TESTBED_CS_MESSAGE * msg);
+ */
+typedef void (*THandler) (ClientHandle client, TESTBED_CS_MESSAGE * msg);
/**
* @brief Entry in the handlers array that describes a testbed message handler.
*/
-typedef struct HD_ {
+typedef struct HD_
+{
/**
* function that handles these types of messages
*/
- THandler handler;
+ THandler handler;
/**
* Expected size of messages for this handler. Checked by caller. Use
* 0 for variable size, in that case, the handler must check.
*/
- unsigned short expectedSize;
+ unsigned short expectedSize;
/**
* Textual description of the handler for debugging
*/
- char * description;
+ char *description;
/**
* The message-ID of the handler. Used only for checking that
@@ -924,7 +929,7 @@
* Must be equal to the index in the handler array that yields
* this entry.
*/
- unsigned int msgId;
+ unsigned int msgId;
} HD;
/* some macros to make initializing the handlers array extremely brief. */
@@ -937,31 +942,31 @@
* The array of message handlers. Add new handlers here.
*/
static HD handlers[] = {
- TBSENTRY(undefined), /* For IDs that should never be received */
- TBDENTRY(ADD_PEER), /* RF: Why was this as TBDENTRY? Because hello is
variable size! */
- TBSENTRY(DEL_PEER),
- TBSENTRY(DEL_ALL_PEERS),
- TBSENTRY(GET_hello),
- TBSENTRY(SET_TVALUE),
- TBSENTRY(GET_TVALUE),
- TBSENTRY(undefined),
- TBSENTRY(SET_BW),
- TBDENTRY(LOAD_MODULE),
- TBDENTRY(UNLOAD_MODULE),
- TBDENTRY(UPLOAD_FILE),
- TBSENTRY(DISABLE_hello),
- TBSENTRY(ENABLE_hello),
- TBSENTRY(DISABLE_AUTOCONNECT),
- TBSENTRY(ENABLE_AUTOCONNECT),
- TBDENTRY(ALLOW_CONNECT),
- TBDENTRY(DENY_CONNECT),
- TBDENTRY(EXEC),
- TBSENTRY(SIGNAL),
- TBSENTRY(GET_OUTPUT),
- { NULL, 0, NULL, 0 }, /* this entry is used to ensure that
- a wrong TESTBED_MAX_MSG will abort
- insted of possibly segfaulting.
- This must always be the LAST entry. */
+ TBSENTRY (undefined), /* For IDs that should never be received */
+ TBDENTRY (ADD_PEER), /* RF: Why was this as TBDENTRY? Because hello
is variable size! */
+ TBSENTRY (DEL_PEER),
+ TBSENTRY (DEL_ALL_PEERS),
+ TBSENTRY (GET_hello),
+ TBSENTRY (SET_TVALUE),
+ TBSENTRY (GET_TVALUE),
+ TBSENTRY (undefined),
+ TBSENTRY (SET_BW),
+ TBDENTRY (LOAD_MODULE),
+ TBDENTRY (UNLOAD_MODULE),
+ TBDENTRY (UPLOAD_FILE),
+ TBSENTRY (DISABLE_hello),
+ TBSENTRY (ENABLE_hello),
+ TBSENTRY (DISABLE_AUTOCONNECT),
+ TBSENTRY (ENABLE_AUTOCONNECT),
+ TBDENTRY (ALLOW_CONNECT),
+ TBDENTRY (DENY_CONNECT),
+ TBDENTRY (EXEC),
+ TBSENTRY (SIGNAL),
+ TBSENTRY (GET_OUTPUT),
+ {NULL, 0, NULL, 0}, /* this entry is used to ensure that
+ a wrong TESTBED_MAX_MSG will abort
+ insted of possibly segfaulting.
+ This must always be the LAST entry. */
};
@@ -969,44 +974,49 @@
* Global handler called by the GNUnet core. Does the demultiplexing
* on the testbed-message type.
*/
-static void csHandleTestbedRequest(ClientHandle client,
- CS_MESSAGE_HEADER * message) {
- TESTBED_CS_MESSAGE * msg;
+static void
+csHandleTestbedRequest (ClientHandle client, CS_MESSAGE_HEADER * message)
+{
+ TESTBED_CS_MESSAGE *msg;
unsigned short size;
unsigned int id;
#if DEBUG_TESTBED
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "TESTBED handleTestbedRequest\n");
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "TESTBED handleTestbedRequest\n");
#endif
- size = ntohs(message->size);
- if (size < sizeof(TESTBED_CS_MESSAGE)) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("received invalid testbed message of size %u\n"),
- size);
- return;
- }
- msg = (TESTBED_CS_MESSAGE *)message;
- id = ntohl(msg->msgType);
- if (id < TESTBED_MAX_MSG) {
- if ( (handlers[id].expectedSize == 0) ||
- (handlers[id].expectedSize == size) ) {
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "TESTBED received message of type %u.\n",
- id);
+ size = ntohs (message->size);
+ if (size < sizeof (TESTBED_CS_MESSAGE))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("received invalid testbed message of size %u\n"), size);
+ return;
+ }
+ msg = (TESTBED_CS_MESSAGE *) message;
+ id = ntohl (msg->msgType);
+ if (id < TESTBED_MAX_MSG)
+ {
+ if ((handlers[id].expectedSize == 0) ||
+ (handlers[id].expectedSize == size))
+ {
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "TESTBED received message of type %u.\n", id);
- handlers[id].handler(client, msg);
+ handlers[id].handler (client, msg);
- } else {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Received testbed message of type %u but unexpected size %u, expected
%u\n"),
- id,
- size,
- handlers[id].expectedSize);
+ }
+ else
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("Received testbed message of type %u but unexpected size
%u, expected %u\n"),
+ id, size, handlers[id].expectedSize);
+ }
}
- } else {
- tb_undefined(client, msg);
- }
+ else
+ {
+ tb_undefined (client, msg);
+ }
}
/**
@@ -1014,23 +1024,25 @@
* Yes, the testbed has a central server. There's nothing wrong
* with that. It's a testbed.
*/
-static void httpRegister(char * cmd) {
- char * reg;
+static void
+httpRegister (char *cmd)
+{
+ char *reg;
long int port;
- char * hostname;
+ char *hostname;
unsigned int curpos;
IPaddr ip_info;
struct sockaddr_in soaddr;
int sock;
size_t ret;
- char * command;
- char * secure;
- char * trusted;
+ char *command;
+ char *secure;
+ char *trusted;
unsigned short tport;
char sport[6];
cron_t start;
char c;
- char * buffer;
+ char *buffer;
int i;
int j;
int k;
@@ -1038,291 +1050,279 @@
char *proxy, *proxyPort;
size_t n;
- reg = getConfigurationString("TESTBED",
- "REGISTERURL");
- if (reg == NULL) {
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- _("No testbed URL given, not registered.\n"));
- return;
- }
+ reg = getConfigurationString ("TESTBED", "REGISTERURL");
+ if (reg == NULL)
+ {
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ _("No testbed URL given, not registered.\n"));
+ return;
+ }
- proxy = getConfigurationString("GNUNETD",
- "HTTP-PROXY");
- if (proxy != NULL) {
- if (OK != get_host_by_name(ectx, proxy, &ip_info)) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Could not resolve name of HTTP proxy `%s'.\n"),
- proxy);
+ proxy = getConfigurationString ("GNUNETD", "HTTP-PROXY");
+ if (proxy != NULL)
+ {
+ if (OK != get_host_by_name (ectx, proxy, &ip_info))
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Could not resolve name of HTTP proxy `%s'.\n"), proxy);
+ theProxy.sin_addr.s_addr = 0;
+ }
+ else
+ {
+ memcpy (&theProxy.sin_addr.s_addr, &ip_info, sizeof (IPaddr));
+ proxyPort = getConfigurationString ("GNUNETD", "HTTP-PROXY-PORT");
+ if (proxyPort == NULL)
+ {
+ theProxy.sin_port = htons (8080);
+ }
+ else
+ {
+ theProxy.sin_port = htons (atoi (proxyPort));
+ FREE (proxyPort);
+ }
+ }
+ FREE (proxy);
+ }
+ else
+ {
theProxy.sin_addr.s_addr = 0;
- } else {
- memcpy(&theProxy.sin_addr.s_addr,
- &ip_info,
- sizeof(IPaddr));
- proxyPort = getConfigurationString("GNUNETD",
- "HTTP-PROXY-PORT");
- if (proxyPort == NULL) {
- theProxy.sin_port = htons(8080);
- } else {
- theProxy.sin_port = htons(atoi(proxyPort));
- FREE(proxyPort);
- }
}
- FREE(proxy);
- } else {
- theProxy.sin_addr.s_addr = 0;
- }
- if (0 != strncmp(HTTP_URL,
- reg,
- strlen(HTTP_URL)) ) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Invalid URL `%s' (must begin with `%s')\n"),
- reg,
- HTTP_URL);
- return;
- }
- port = 80; /* default http port */
+ if (0 != strncmp (HTTP_URL, reg, strlen (HTTP_URL)))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Invalid URL `%s' (must begin with `%s')\n"), reg, HTTP_URL);
+ return;
+ }
+ port = 80; /* default http port */
- hostname = STRDUP(®[strlen(HTTP_URL)]);
+ hostname = STRDUP (®[strlen (HTTP_URL)]);
buffer = NULL;
j = -1;
k = -1;
- for (i=0;i<strlen(hostname);i++) {
- if (hostname[i] == ':')
- j = i;
- if (hostname[i] == '/') {
- k = i;
- if (j == -1)
- j = i;
- break;
+ for (i = 0; i < strlen (hostname); i++)
+ {
+ if (hostname[i] == ':')
+ j = i;
+ if (hostname[i] == '/')
+ {
+ k = i;
+ if (j == -1)
+ j = i;
+ break;
+ }
}
- }
- if ( (j != -1) && (j < k) ) {
- char * pstring;
- if (k == -1) {
- pstring = MALLOC(strlen(hostname)-j+1);
- memcpy(pstring,
- &hostname[j],
- strlen(hostname)-j+1);
- pstring[strlen(hostname)-j] = '\0';
- } else {
- pstring = MALLOC(k-j+1);
- memcpy(pstring,
- &hostname[j],
- k-j);
- pstring[k-j] = '\0';
+ if ((j != -1) && (j < k))
+ {
+ char *pstring;
+ if (k == -1)
+ {
+ pstring = MALLOC (strlen (hostname) - j + 1);
+ memcpy (pstring, &hostname[j], strlen (hostname) - j + 1);
+ pstring[strlen (hostname) - j] = '\0';
+ }
+ else
+ {
+ pstring = MALLOC (k - j + 1);
+ memcpy (pstring, &hostname[j], k - j);
+ pstring[k - j] = '\0';
+ }
+ port = strtol (pstring, &buffer, 10);
+ if ((port < 0) || (port > 65536))
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("Malformed http URL: `%s' at `%s'. Testbed-client not
registered.\n"),
+ reg, buffer);
+ FREE (hostname);
+ FREE (reg);
+ FREE (pstring);
+ return;
+ }
+ FREE (pstring);
}
- port = strtol(pstring, &buffer, 10);
- if ( (port < 0) || (port > 65536) ) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Malformed http URL: `%s' at `%s'. Testbed-client not registered.\n"),
- reg,
- buffer);
- FREE(hostname);
- FREE(reg);
- FREE(pstring);
- return;
- }
- FREE(pstring);
- }
hostname[k] = '\0';
#if DEBUG_TESTBED
- GE_LOG(ectx, GE_INFO | GE_REQUEST | GE_USER,
- "Trying to (un)register testbed client at %s\n",
- reg);
+ GE_LOG (ectx, GE_INFO | GE_REQUEST | GE_USER,
+ "Trying to (un)register testbed client at %s\n", reg);
#endif
- sock = SOCKET(PF_INET,
- SOCK_STREAM,
- 0);
- if (sock < 0) {
- LOG_STRERROR(LOG_ERROR, "socket");
- FREE(hostname);
- FREE(reg);
- return;
- }
+ sock = SOCKET (PF_INET, SOCK_STREAM, 0);
+ if (sock < 0)
+ {
+ LOG_STRERROR (LOG_ERROR, "socket");
+ FREE (hostname);
+ FREE (reg);
+ return;
+ }
/* Do we need to connect through a proxy? */
- if (theProxy.sin_addr.s_addr == 0) {
- /* no proxy */
- if (OK != get_host_by_name(ectx, hostname,
- &ip_info)) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Could not register testbed, host `%s' unknown\n"),
- hostname);
- FREE(reg);
- FREE(hostname);
+ if (theProxy.sin_addr.s_addr == 0)
+ {
+ /* no proxy */
+ if (OK != get_host_by_name (ectx, hostname, &ip_info))
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Could not register testbed, host `%s' unknown\n"),
+ hostname);
+ FREE (reg);
+ FREE (hostname);
+ return;
+ }
+ memcpy (&soaddr.sin_addr.s_addr, &ip_info, sizeof (IPaddr));
+ soaddr.sin_port = htons ((unsigned short) port);
+ }
+ else
+ {
+ /* proxy */
+ soaddr.sin_addr.s_addr = theProxy.sin_addr.s_addr;
+ soaddr.sin_port = theProxy.sin_port;
+ }
+ soaddr.sin_family = AF_INET;
+ if (CONNECT (sock,
+ (struct sockaddr *) &soaddr,
+ sizeof (soaddr)) < 0 && errno != EWOULDBLOCK)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Failed to send HTTP request to host `%s': %s\n"),
+ hostname, STRERROR (errno));
+ FREE (reg);
+ FREE (hostname);
+ closefile (sock);
return;
}
- memcpy(&soaddr.sin_addr.s_addr,
- &ip_info,
- sizeof(IPaddr));
- soaddr.sin_port
- = htons((unsigned short)port);
- } else {
- /* proxy */
- soaddr.sin_addr.s_addr
- = theProxy.sin_addr.s_addr;
- soaddr.sin_port
- = theProxy.sin_port;
- }
- soaddr.sin_family = AF_INET;
- if (CONNECT(sock,
- (struct sockaddr*)&soaddr,
- sizeof(soaddr)) < 0 && errno != EWOULDBLOCK) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Failed to send HTTP request to host `%s': %s\n"),
- hostname,
- STRERROR(errno));
- FREE(reg);
- FREE(hostname);
- closefile(sock);
- return;
- }
- trusted = getConfigurationString("NETWORK",
- "TRUSTED");
+ trusted = getConfigurationString ("NETWORK", "TRUSTED");
if (trusted == NULL)
- trusted = STRDUP("127.0.0.0/8;");
+ trusted = STRDUP ("127.0.0.0/8;");
i = 0;
- while (trusted[i] != '\0') {
- if (trusted[i] == ';')
- trusted[i] = '@';
- i++;
- }
- tport = getGNUnetPort();
- SNPRINTF(sport,
- 6,
- "%u",
- tport);
- secure = getConfigurationString("TESTBED",
- "LOGIN");
+ while (trusted[i] != '\0')
+ {
+ if (trusted[i] == ';')
+ trusted[i] = '@';
+ i++;
+ }
+ tport = getGNUnetPort ();
+ SNPRINTF (sport, 6, "%u", tport);
+ secure = getConfigurationString ("TESTBED", "LOGIN");
if (secure == NULL)
- secure = STRDUP("");
- n = strlen(GET_COMMAND)
- + strlen(cmd)
- + strlen(reg)
- + strlen(trusted)
- + strlen(sport)
- + strlen(secure) + 1;
- command = MALLOC(n);
- SNPRINTF(command,
- n,
- GET_COMMAND,
- reg,
- cmd,
- trusted,
- sport,
- secure);
- FREE(trusted);
- FREE(secure);
- FREE(reg);
- curpos = strlen(command)+1;
- curpos = SEND_BLOCKING_ALL(sock,
- command,
- curpos);
- if (SYSERR == (int)curpos) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Failed so send HTTP request `%s' to host `%s': %s\n"),
- command,
- hostname,
- STRERROR(errno));
- FREE(command);
- FREE(hostname);
- closefile(sock);
- return;
- }
- FREE(command);
- FREE(hostname);
- cronTime(&start);
+ secure = STRDUP ("");
+ n = strlen (GET_COMMAND)
+ + strlen (cmd)
+ + strlen (reg) + strlen (trusted) + strlen (sport) + strlen (secure) + 1;
+ command = MALLOC (n);
+ SNPRINTF (command, n, GET_COMMAND, reg, cmd, trusted, sport, secure);
+ FREE (trusted);
+ FREE (secure);
+ FREE (reg);
+ curpos = strlen (command) + 1;
+ curpos = SEND_BLOCKING_ALL (sock, command, curpos);
+ if (SYSERR == (int) curpos)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Failed so send HTTP request `%s' to host `%s': %s\n"),
+ command, hostname, STRERROR (errno));
+ FREE (command);
+ FREE (hostname);
+ closefile (sock);
+ return;
+ }
+ FREE (command);
+ FREE (hostname);
+ cronTime (&start);
- /* we first have to read out the http_response*/
+ /* we first have to read out the http_response */
/* it ends with four line delimiters: "\r\n\r\n" */
curpos = 0;
- while (curpos < 4) {
- int success;
+ while (curpos < 4)
+ {
+ int success;
- if (start + 5 * cronMINUTES < get_time())
- break; /* exit after 5m */
- success = RECV_NONBLOCKING(sock,
- &c,
- sizeof(c),
- &ret);
- if ( success == NO ) {
- PTHREAD_SLEEP(100 * cronMILLIS);
- continue;
+ if (start + 5 * cronMINUTES < get_time ())
+ break; /* exit after 5m */
+ success = RECV_NONBLOCKING (sock, &c, sizeof (c), &ret);
+ if (success == NO)
+ {
+ PTHREAD_SLEEP (100 * cronMILLIS);
+ continue;
+ }
+ if ((ret == 0) || (ret == (size_t) - 1))
+ break; /* end of transmission or error */
+ if ((c == '\r') || (c == '\n'))
+ curpos += ret;
+ else
+ curpos = 0;
}
- if ( (ret == 0) || (ret == (size_t) -1) )
- break; /* end of transmission or error */
- if ((c=='\r') || (c=='\n'))
- curpos += ret;
- else
- curpos=0;
- }
- closefile(sock);
- if (curpos < 4) { /* invalid response */
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Exit register (error: no http response read).\n"));
- }
+ closefile (sock);
+ if (curpos < 4)
+ { /* invalid response */
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Exit register (error: no http response read).\n"));
+ }
#if DEBUG_TESTBED
- GE_LOG(ectx, GE_INFO | GE_REQUEST | GE_USER,
- "Exit register (%d seconds before timeout)\n",
- (int)(start + 300 * cronSECONDS - get_time())/cronSECONDS);
+ GE_LOG (ectx, GE_INFO | GE_REQUEST | GE_USER,
+ "Exit register (%d seconds before timeout)\n",
+ (int) (start + 300 * cronSECONDS - get_time ()) / cronSECONDS);
#endif
}
/**
* When a client exits, kill all associated processes.
*/
-static void testbedClientExitHandler(ClientHandle client) {
+static void
+testbedClientExitHandler (ClientHandle client)
+{
int i;
int pding;
- void * unused;
+ void *unused;
pding = 0;
/* kill all processes */
- MUTEX_LOCK(&lock);
- for (i=ptSize-1;i>=0;i--) {
- if (pt[i]->client == client) {
- pding++;
- if (pt[i]->hasExited == NO)
- kill(pt[i]->pid, SIGKILL); /* die NOW */
+ MUTEX_LOCK (&lock);
+ for (i = ptSize - 1; i >= 0; i--)
+ {
+ if (pt[i]->client == client)
+ {
+ pding++;
+ if (pt[i]->hasExited == NO)
+ kill (pt[i]->pid, SIGKILL); /* die NOW */
+ }
}
- }
- MUTEX_UNLOCK(&lock);
+ MUTEX_UNLOCK (&lock);
/* join on all pthreads, but since they may be
blocking on the same lock, unlock from time
to time for a while to let them leave...
FIXME: not really elegant, better use
semaphores... */
- while (pding > 0) {
- pding = 0;
- PTHREAD_SLEEP(50);
- MUTEX_LOCK(&lock);
- for (i=ptSize-1;i>=0;i--) {
- if (pt[i]->client == client) {
- if (pt[i]->hasExited == YES) {
- PTHREAD_JOIN(&pt[i]->reader,
- &unused);
- GROW(pt[i]->output,
- pt[i]->outputSize,
- 0);
- FREE(pt[i]);
- pt[i] = pt[ptSize-1];
- GROW(pt,
- ptSize,
- ptSize-1);
- } else {
- pding++;
- }
- }
+ while (pding > 0)
+ {
+ pding = 0;
+ PTHREAD_SLEEP (50);
+ MUTEX_LOCK (&lock);
+ for (i = ptSize - 1; i >= 0; i--)
+ {
+ if (pt[i]->client == client)
+ {
+ if (pt[i]->hasExited == YES)
+ {
+ PTHREAD_JOIN (&pt[i]->reader, &unused);
+ GROW (pt[i]->output, pt[i]->outputSize, 0);
+ FREE (pt[i]);
+ pt[i] = pt[ptSize - 1];
+ GROW (pt, ptSize, ptSize - 1);
+ }
+ else
+ {
+ pding++;
+ }
+ }
+ }
+ MUTEX_UNLOCK (&lock);
}
- MUTEX_UNLOCK(&lock);
- }
}
/**
@@ -1330,71 +1330,75 @@
* the library name (libgnunet_XXX => initialize_XXX).
* @return SYSERR on errors
*/
-int initialize_module_testbed(CoreAPIForApplication * capi) {
+int
+initialize_module_testbed (CoreAPIForApplication * capi)
+{
unsigned int i;
/* some checks */
- for (i=0;i<TESTBED_MAX_MSG;i++)
- if ( (handlers[i].msgId != i) &&
- (handlers[i].handler != &tb_undefined) )
- GE_ASSERT(ectx, 0);
- GE_ASSERT(ectx, handlers[TESTBED_MAX_MSG].handler == NULL);
- identity = capi->requestService("identity");
+ for (i = 0; i < TESTBED_MAX_MSG; i++)
+ if ((handlers[i].msgId != i) && (handlers[i].handler != &tb_undefined))
+ GE_ASSERT (ectx, 0);
+ GE_ASSERT (ectx, handlers[TESTBED_MAX_MSG].handler == NULL);
+ identity = capi->requestService ("identity");
if (identity == NULL)
return SYSERR;
- MUTEX_CREATE(&lock);
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "TESTBED registering handler %d!\n",
- CS_PROTO_testbed_REQUEST);
+ MUTEX_CREATE (&lock);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "TESTBED registering handler %d!\n", CS_PROTO_testbed_REQUEST);
coreAPI = capi;
- GE_ASSERT(ectx, SYSERR !=
capi->registerClientExitHandler(&testbedClientExitHandler));
- GE_ASSERT(ectx, SYSERR !=
capi->registerClientHandler(CS_PROTO_testbed_REQUEST,
-
(CSHandler)&csHandleTestbedRequest));
- httpRegister("startup");
+ GE_ASSERT (ectx,
+ SYSERR !=
+ capi->registerClientExitHandler (&testbedClientExitHandler));
+ GE_ASSERT (ectx,
+ SYSERR != capi->registerClientHandler (CS_PROTO_testbed_REQUEST,
+ (CSHandler) &
+ csHandleTestbedRequest));
+ httpRegister ("startup");
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "testbed",
- gettext_noop("allows construction of
a P2P-testbed"
- " (incomplete)")));
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "testbed",
+ gettext_noop
+ ("allows construction of
a P2P-testbed"
+ " (incomplete)")));
return OK;
}
/**
* Shutdown the testbed module.
*/
-void done_module_testbed() {
+void
+done_module_testbed ()
+{
int i;
/* kill all child-processes */
- for (i=0;i<ptSize;i++) {
- ProcessInfo * pi;
- void * unused;
+ for (i = 0; i < ptSize; i++)
+ {
+ ProcessInfo *pi;
+ void *unused;
- pi = pt[i];
- if (pi->hasExited != NO)
- kill(pi->pid, SIGKILL);
- PTHREAD_JOIN(&pi->reader,
- &unused);
- FREENONNULL(pi->output);
- FREE(pi);
- }
- GROW(pt,
- ptSize,
- 0);
+ pi = pt[i];
+ if (pi->hasExited != NO)
+ kill (pi->pid, SIGKILL);
+ PTHREAD_JOIN (&pi->reader, &unused);
+ FREENONNULL (pi->output);
+ FREE (pi);
+ }
+ GROW (pt, ptSize, 0);
- httpRegister("shutdown");
- MUTEX_DESTROY(&lock);
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "TESTBED unregistering handler %d\n",
- CS_PROTO_testbed_REQUEST);
- coreAPI->unregisterClientHandler(CS_PROTO_testbed_REQUEST,
- (CSHandler)&csHandleTestbedRequest);
- coreAPI->unregisterClientExitHandler(&testbedClientExitHandler);
- coreAPI->releaseService(identity);
+ httpRegister ("shutdown");
+ MUTEX_DESTROY (&lock);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "TESTBED unregistering handler %d\n", CS_PROTO_testbed_REQUEST);
+ coreAPI->unregisterClientHandler (CS_PROTO_testbed_REQUEST,
+ (CSHandler) & csHandleTestbedRequest);
+ coreAPI->unregisterClientExitHandler (&testbedClientExitHandler);
+ coreAPI->releaseService (identity);
identity = NULL;
coreAPI = NULL;
}
Modified: GNUnet/src/applications/testbed/testbed.h
===================================================================
--- GNUnet/src/applications/testbed/testbed.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/testbed/testbed.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -32,23 +32,23 @@
#include "gnunet_core.h"
/* */
-#define TESTBED_hello_RESPONSE 0 /* peer responds with a hello */
-#define TESTBED_ADD_PEER 1 /* Add a peer to a peer connection pool
*/
-#define TESTBED_DEL_PEER 2 /* Delete a peer from a peer connection
pool */
-#define TESTBED_DEL_ALL_PEERS 3 /* Delete all peers from a peer
connection pool */
-#define TESTBED_GET_hello 4 /* Get the complete host information
(ID, IP, ...) */
-#define TESTBED_SET_TVALUE 5 /* Set trust value for a peer
*/
-#define TESTBED_GET_TVALUE 6 /* Get trust value of a peer
*/
-#define TESTBED_OUTPUT_RESPONSE 7 /* Reply to GET_OUTPUT
*/
-#define TESTBED_SET_BW 8 /* Set in/outbound bandwidth
*/
-#define TESTBED_SET_LOSS_RATE 9 /* Set the drop probability of a
connection */
+#define TESTBED_hello_RESPONSE 0 /* peer responds with a hello */
+#define TESTBED_ADD_PEER 1 /* Add a peer to a peer connection pool
*/
+#define TESTBED_DEL_PEER 2 /* Delete a peer from a peer connection
pool */
+#define TESTBED_DEL_ALL_PEERS 3 /* Delete all peers from a peer
connection pool */
+#define TESTBED_GET_hello 4 /* Get the complete host information
(ID, IP, ...) */
+#define TESTBED_SET_TVALUE 5 /* Set trust value for a peer
*/
+#define TESTBED_GET_TVALUE 6 /* Get trust value of a peer
*/
+#define TESTBED_OUTPUT_RESPONSE 7 /* Reply to GET_OUTPUT
*/
+#define TESTBED_SET_BW 8 /* Set in/outbound bandwidth
*/
+#define TESTBED_SET_LOSS_RATE 9 /* Set the drop probability of a
connection */
#define TESTBED_LOAD_MODULE 10 /* load a module
*/
#define TESTBED_UNLOAD_MODULE 11 /* unload a module
*/
-#define TESTBED_UPLOAD_FILE 12 /* Upload a file to a peer
*/
-#define TESTBED_DISABLE_hello 13 /* stop sending hellos */
-#define TESTBED_ENABLE_hello 14 /* start sending hellos */
-#define TESTBED_DISABLE_AUTOCONNECT 15 /* stop automatically
connecting to other peers */
-#define TESTBED_ENABLE_AUTOCONNECT 16 /* start trying to
automatically connect to other peers */
+#define TESTBED_UPLOAD_FILE 12 /* Upload a file to a peer
*/
+#define TESTBED_DISABLE_hello 13 /* stop sending hellos */
+#define TESTBED_ENABLE_hello 14 /* start sending hellos */
+#define TESTBED_DISABLE_AUTOCONNECT 15 /* stop automatically
connecting to other peers */
+#define TESTBED_ENABLE_AUTOCONNECT 16 /* start trying to
automatically connect to other peers */
#define TESTBED_ALLOW_CONNECT 17 /* only allow connections from a
certain group of peers */
#define TESTBED_DENY_CONNECT 18 /* deny connections from a certain
group of peers */
#define TESTBED_EXEC 19 /* execute process */
@@ -71,87 +71,104 @@
AFS insert a file on a specific machine.
*/
-typedef struct {
+typedef struct
+{
CS_MESSAGE_HEADER header;
- unsigned int msgType; /* The message types listed above */
+ unsigned int msgType; /* The message types listed above */
} TESTBED_CS_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE testbed_cs_message;
- char data[1]; /* Value is dependent on the type field */
+ char data[1]; /* Value is dependent on the type field */
} TESTBED_CS_MESSAGE_GENERIC;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
} TESTBED_undefined_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
unsigned short proto;
- unsigned short reserved; /* for alignment */
+ unsigned short reserved; /* for alignment */
} TESTBED_GET_hello_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
- unsigned int in_bw; /* Inbound bandwidth */
- unsigned int out_bw; /* Outbound bandwidth */
+ unsigned int in_bw; /* Inbound bandwidth */
+ unsigned int out_bw; /* Outbound bandwidth */
} TESTBED_SET_BW_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
P2P_hello_MESSAGE helo;
} TESTBED_hello_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
P2P_hello_MESSAGE helo;
} TESTBED_ADD_PEER_MESSAGE;
-typedef struct {
- TESTBED_CS_MESSAGE header;
- PeerIdentity host;
+typedef struct
+{
+ TESTBED_CS_MESSAGE header;
+ PeerIdentity host;
} TESTBED_DEL_PEER_MESSAGE;
-typedef struct {
- TESTBED_CS_MESSAGE header;
+typedef struct
+{
+ TESTBED_CS_MESSAGE header;
} TESTBED_DEL_ALL_PEERS_MESSAGE;
-typedef struct {
- TESTBED_CS_MESSAGE header;
- PeerIdentity otherPeer;
+typedef struct
+{
+ TESTBED_CS_MESSAGE header;
+ PeerIdentity otherPeer;
} TESTBED_GET_TVALUE_MESSAGE;
-typedef struct {
- TESTBED_CS_MESSAGE header;
- PeerIdentity otherPeer;
- unsigned int trust;
+typedef struct
+{
+ TESTBED_CS_MESSAGE header;
+ PeerIdentity otherPeer;
+ unsigned int trust;
} TESTBED_SET_TVALUE_MESSAGE;
-typedef struct {
- TESTBED_CS_MESSAGE header;
- PeerIdentity otherPeer;
+typedef struct
+{
+ TESTBED_CS_MESSAGE header;
+ PeerIdentity otherPeer;
} TESTBED_BLACKLIST_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
unsigned int percentageLossInbound;
unsigned int percentageLossOutbound;
} TESTBED_SET_LOSS_RATE_MESSAGE;
-typedef struct {
- TESTBED_CS_MESSAGE header;
+typedef struct
+{
+ TESTBED_CS_MESSAGE header;
} TESTBED_LOAD_MODULE_MESSAGE;
-typedef struct {
- TESTBED_LOAD_MODULE_MESSAGE load_module_message;
- char modulename[1];
+typedef struct
+{
+ TESTBED_LOAD_MODULE_MESSAGE load_module_message;
+ char modulename[1];
} TESTBED_LOAD_MODULE_MESSAGE_GENERIC;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
} TESTBED_UNLOAD_MODULE_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_UNLOAD_MODULE_MESSAGE unload_module_message;
char modulename[1];
} TESTBED_UNLOAD_MODULE_MESSAGE_GENERIC;
@@ -161,75 +178,91 @@
#define TESTBED_FILE_BLK_SIZE 1400
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
unsigned int type;
} TESTBED_UPLOAD_FILE_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_UPLOAD_FILE_MESSAGE upload_file_message;
char buf[1];
} TESTBED_UPLOAD_FILE_MESSAGE_GENERIC;
-typedef struct {
- TESTBED_CS_MESSAGE header;
+typedef struct
+{
+ TESTBED_CS_MESSAGE header;
} TESTBED_DISABLE_hello_MESSAGE;
-typedef struct {
- TESTBED_CS_MESSAGE header;
+typedef struct
+{
+ TESTBED_CS_MESSAGE header;
} TESTBED_ENABLE_hello_MESSAGE;
-typedef struct {
- TESTBED_CS_MESSAGE header;
+typedef struct
+{
+ TESTBED_CS_MESSAGE header;
} TESTBED_ENABLE_AUTOCONNECT_MESSAGE;
-typedef struct {
- TESTBED_CS_MESSAGE header;
+typedef struct
+{
+ TESTBED_CS_MESSAGE header;
} TESTBED_DISABLE_AUTOCONNECT_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
} TESTBED_ALLOW_CONNECT_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_ALLOW_CONNECT_MESSAGE allow_connect_message;
PeerIdentity peers[1];
} TESTBED_ALLOW_CONNECT_MESSAGE_GENERIC;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
} TESTBED_DENY_CONNECT_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_DENY_CONNECT_MESSAGE deny_connect_message;
PeerIdentity peers[1];
} TESTBED_DENY_CONNECT_MESSAGE_GENERIC;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
} TESTBED_EXEC_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_EXEC_MESSAGE exec_message;
char commandLine[1];
} TESTBED_EXEC_MESSAGE_GENERIC;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
unsigned int pid;
int signal;
} TESTBED_SIGNAL_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
int pid;
} TESTBED_GET_OUTPUT_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_CS_MESSAGE header;
} TESTBED_OUTPUT_REPLY_MESSAGE;
-typedef struct {
+typedef struct
+{
TESTBED_OUTPUT_REPLY_MESSAGE output_reply_message;
char data[1];
} TESTBED_OUTPUT_REPLY_MESSAGE_GENERIC;
Modified: GNUnet/src/applications/testing/testing.c
===================================================================
--- GNUnet/src/applications/testing/testing.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/testing/testing.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,29 +30,27 @@
#include "gnunet_util_config_impl.h"
#include "gnunet_testing_lib.h"
-static void updatePort(struct GC_Configuration *cfg,
- const char * section,
- unsigned short offset) {
+static void
+updatePort (struct GC_Configuration *cfg,
+ const char *section, unsigned short offset)
+{
unsigned long long old;
- if ( (YES == GC_have_configuration_value(cfg,
- section,
- "PORT")) &&
- (0 == GC_get_configuration_value_number(cfg,
- section,
- "PORT",
- 0,
- 65535,
- 65535,
- &old)) ) {
- old += offset;
- GE_ASSERT(NULL,
- 0 == GC_set_configuration_value_number(cfg,
- NULL,
- section,
- "PORT",
- old));
- }
+ if ((YES == GC_have_configuration_value (cfg,
+ section,
+ "PORT")) &&
+ (0 == GC_get_configuration_value_number (cfg,
+ section,
+ "PORT",
+ 0, 65535, 65535, &old)))
+ {
+ old += offset;
+ GE_ASSERT (NULL,
+ 0 == GC_set_configuration_value_number (cfg,
+ NULL,
+ section,
+ "PORT", old));
+ }
}
/**
@@ -67,162 +65,136 @@
* @param peer identity of the peer (set)
* @return OK on success, SYSERR on error
*/
-int gnunet_testing_start_daemon(unsigned short app_port,
- unsigned short tra_offset,
- const char * gnunetd_home,
- const char * transports,
- const char * applications,
- pid_t * pid,
- PeerIdentity * peer,
- char ** configFile) {
+int
+gnunet_testing_start_daemon (unsigned short app_port,
+ unsigned short tra_offset,
+ const char *gnunetd_home,
+ const char *transports,
+ const char *applications,
+ pid_t * pid,
+ PeerIdentity * peer, char **configFile)
+{
int ret;
- char * ipath;
- char * dpath;
- struct GC_Configuration * cfg;
+ char *ipath;
+ char *dpath;
+ struct GC_Configuration *cfg;
char host[128];
- struct ClientServerConnection * sock;
- P2P_hello_MESSAGE * hello;
+ struct ClientServerConnection *sock;
+ P2P_hello_MESSAGE *hello;
int round;
- fprintf(stderr,
- "Starting peer on port %u\n",
- app_port);
+ fprintf (stderr, "Starting peer on port %u\n", app_port);
#if 0
/* do not usually do this -- may easily
exhaust entropy pool for hostkey generation... */
- disk_directory_remove(NULL, gnunetd_home);
+ disk_directory_remove (NULL, gnunetd_home);
#endif
- ipath = os_get_installation_path(IPK_DATADIR);
+ ipath = os_get_installation_path (IPK_DATADIR);
if (ipath == NULL)
return SYSERR;
- dpath = MALLOC(strlen(ipath) + 128);
- strcpy(dpath, ipath);
- FREE(ipath);
- strcat(dpath, DIR_SEPARATOR_STR "gnunet-testing.conf");
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- dpath)) {
- fprintf(stderr,
- "Failed to read default configuration file `%s'\n",
- dpath);
- GC_free(cfg);
- FREE(dpath);
- return SYSERR;
- }
- FREE(dpath);
- updatePort(cfg, "TCP", tra_offset);
- updatePort(cfg, "TCP6", tra_offset);
- updatePort(cfg, "UDP", tra_offset);
- updatePort(cfg, "UDP6", tra_offset);
- updatePort(cfg, "HTTP", tra_offset);
- updatePort(cfg, "SMTP", tra_offset);
- GC_set_configuration_value_string(cfg,
- NULL,
- "PATHS",
- "GNUNETD_HOME",
- gnunetd_home);
+ dpath = MALLOC (strlen (ipath) + 128);
+ strcpy (dpath, ipath);
+ FREE (ipath);
+ strcat (dpath, DIR_SEPARATOR_STR "gnunet-testing.conf");
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, dpath))
+ {
+ fprintf (stderr,
+ "Failed to read default configuration file `%s'\n", dpath);
+ GC_free (cfg);
+ FREE (dpath);
+ return SYSERR;
+ }
+ FREE (dpath);
+ updatePort (cfg, "TCP", tra_offset);
+ updatePort (cfg, "TCP6", tra_offset);
+ updatePort (cfg, "UDP", tra_offset);
+ updatePort (cfg, "UDP6", tra_offset);
+ updatePort (cfg, "HTTP", tra_offset);
+ updatePort (cfg, "SMTP", tra_offset);
+ GC_set_configuration_value_string (cfg,
+ NULL,
+ "PATHS", "GNUNETD_HOME", gnunetd_home);
if (transports != NULL)
- GC_set_configuration_value_string(cfg,
- NULL,
- "GNUNETD",
- "TRANSPORTS",
- transports);
+ GC_set_configuration_value_string (cfg,
+ NULL,
+ "GNUNETD", "TRANSPORTS", transports);
if (applications != NULL)
- GC_set_configuration_value_string(cfg,
- NULL,
- "GNUNETD",
- "APPLICATIONS",
- applications);
- GC_set_configuration_value_number(cfg,
- NULL,
- "NETWORK",
- "PORT",
- app_port);
- dpath = STRDUP("/tmp/gnunet-config.XXXXXX");
- ret = mkstemp(dpath);
- if (ret == -1) {
- GE_LOG_STRERROR_FILE(NULL,
- GE_ERROR | GE_USER | GE_BULK,
- "mkstemp",
- dpath);
- FREE(dpath);
- GC_free(cfg);
- return SYSERR;
- }
- CLOSE(ret);
- if (0 != GC_write_configuration(cfg,
- dpath)) {
- fprintf(stderr,
- "Failed to write peer configuration file `%s'\n",
- dpath);
- FREE(dpath);
- GC_free(cfg);
- return SYSERR;
- }
- GC_free(cfg);
+ GC_set_configuration_value_string (cfg,
+ NULL,
+ "GNUNETD",
+ "APPLICATIONS", applications);
+ GC_set_configuration_value_number (cfg, NULL, "NETWORK", "PORT", app_port);
+ dpath = STRDUP ("/tmp/gnunet-config.XXXXXX");
+ ret = mkstemp (dpath);
+ if (ret == -1)
+ {
+ GE_LOG_STRERROR_FILE (NULL,
+ GE_ERROR | GE_USER | GE_BULK, "mkstemp", dpath);
+ FREE (dpath);
+ GC_free (cfg);
+ return SYSERR;
+ }
+ CLOSE (ret);
+ if (0 != GC_write_configuration (cfg, dpath))
+ {
+ fprintf (stderr,
+ "Failed to write peer configuration file `%s'\n", dpath);
+ FREE (dpath);
+ GC_free (cfg);
+ return SYSERR;
+ }
+ GC_free (cfg);
- cfg = GC_create_C_impl();
+ cfg = GC_create_C_impl ();
/* cfg is now client CFG for os_daemon_start */
- SNPRINTF(host,
- 128,
- "localhost:%u",
- app_port);
- GC_set_configuration_value_string(cfg,
- NULL,
- "NETWORK",
- "HOST",
- host);
+ SNPRINTF (host, 128, "localhost:%u", app_port);
+ GC_set_configuration_value_string (cfg, NULL, "NETWORK", "HOST", host);
- ret = os_daemon_start(NULL,
- cfg,
- dpath,
- NO);
- if (ret == -1) {
- fprintf(stderr,
- "Failed to start daemon!\n");
- GC_free(cfg);
- return SYSERR;
- }
+ ret = os_daemon_start (NULL, cfg, dpath, NO);
+ if (ret == -1)
+ {
+ fprintf (stderr, "Failed to start daemon!\n");
+ GC_free (cfg);
+ return SYSERR;
+ }
*pid = ret;
/* now get peer ID */
/* we need to wait quite a while since the peers
maybe creating public keys and waiting for
entropy! */
- if (OK != connection_wait_for_running(NULL,
- cfg,
- 15 * cronMINUTES)) {
- fprintf(stderr,
- "Failed to confirm daemon running!\n");
- GC_free(cfg);
- UNLINK(dpath);
- FREE(dpath);
- return SYSERR;
- }
+ if (OK != connection_wait_for_running (NULL, cfg, 15 * cronMINUTES))
+ {
+ fprintf (stderr, "Failed to confirm daemon running!\n");
+ GC_free (cfg);
+ UNLINK (dpath);
+ FREE (dpath);
+ return SYSERR;
+ }
*configFile = dpath;
dpath = NULL;
round = 0;
ret = SYSERR;
- while ( (round++ < 10) &&
- (ret == SYSERR) ) {
- sock = client_connection_create(NULL,
- cfg);
- ret = gnunet_identity_get_self(sock,
- &hello);
- if (ret == OK) {
- hash(&hello->publicKey,
- sizeof(PublicKey),
- &peer->hashPubKey);
- FREE(hello);
- } else {
- PTHREAD_SLEEP(2 * cronSECONDS);
+ while ((round++ < 10) && (ret == SYSERR))
+ {
+ sock = client_connection_create (NULL, cfg);
+ ret = gnunet_identity_get_self (sock, &hello);
+ if (ret == OK)
+ {
+ hash (&hello->publicKey, sizeof (PublicKey), &peer->hashPubKey);
+ FREE (hello);
+ }
+ else
+ {
+ PTHREAD_SLEEP (2 * cronSECONDS);
+ }
+ connection_destroy (sock);
}
- connection_destroy(sock);
- }
- GC_free(cfg);
+ GC_free (cfg);
if (ret == SYSERR)
- fprintf(stderr,
- "Failed to obtain daemon's identity (is a transport loaded?)!\n");
+ fprintf (stderr,
+ "Failed to obtain daemon's identity (is a transport loaded?)!\n");
return ret;
@@ -236,86 +208,74 @@
* @param port2 client port of the second daemon
* @return OK on success, SYSERR on failure
*/
-int gnunet_testing_connect_daemons(unsigned short port1,
- unsigned short port2) {
+int
+gnunet_testing_connect_daemons (unsigned short port1, unsigned short port2)
+{
char host[128];
- GC_Configuration * cfg1 = GC_create_C_impl();
- GC_Configuration * cfg2 = GC_create_C_impl();
- struct ClientServerConnection * sock1;
- struct ClientServerConnection * sock2;
+ GC_Configuration *cfg1 = GC_create_C_impl ();
+ GC_Configuration *cfg2 = GC_create_C_impl ();
+ struct ClientServerConnection *sock1;
+ struct ClientServerConnection *sock2;
int ret;
- P2P_hello_MESSAGE * h1;
- P2P_hello_MESSAGE * h2;
+ P2P_hello_MESSAGE *h1;
+ P2P_hello_MESSAGE *h2;
ret = SYSERR;
- SNPRINTF(host,
- 128,
- "localhost:%u",
- port1);
- GC_set_configuration_value_string(cfg1,
- NULL,
- "NETWORK",
- "HOST",
- host);
- SNPRINTF(host,
- 128,
- "localhost:%u",
- port2);
- GC_set_configuration_value_string(cfg2,
- NULL,
- "NETWORK",
- "HOST",
- host);
- if ( (OK == connection_wait_for_running(NULL,
- cfg1,
- 300 * cronSECONDS) ) &&
- (OK == connection_wait_for_running(NULL,
- cfg2,
- 300 * cronSECONDS) ) ) {
- sock1 = client_connection_create(NULL,
- cfg1);
- sock2 = client_connection_create(NULL,
- cfg2);
- ret = - 10;
- fprintf(stderr,
- _("Waiting for peers to connect"));
- while ( (ret++ < -1) &&
- (GNUNET_SHUTDOWN_TEST() == NO) ) {
- h1 = NULL;
- h2 = NULL;
- if ( (OK == gnunet_identity_get_self(sock1,
- &h1)) &&
- (OK == gnunet_identity_get_self(sock2,
- &h2)) &&
- (OK == gnunet_identity_peer_add(sock1,
- h2)) &&
- (OK == gnunet_identity_peer_add(sock2,
- h1)) ) {
- fprintf(stderr, ".");
- if (YES == gnunet_identity_request_connect(sock1,
- &h2->senderIdentity)) {
- ret = OK;
- break;
- }
- if (YES == gnunet_identity_request_connect(sock2,
- &h1->senderIdentity)) {
- ret = OK;
- break;
- }
- PTHREAD_SLEEP(100 * cronMILLIS);
- }
- FREENONNULL(h1);
- FREENONNULL(h2);
+ SNPRINTF (host, 128, "localhost:%u", port1);
+ GC_set_configuration_value_string (cfg1, NULL, "NETWORK", "HOST", host);
+ SNPRINTF (host, 128, "localhost:%u", port2);
+ GC_set_configuration_value_string (cfg2, NULL, "NETWORK", "HOST", host);
+ if ((OK == connection_wait_for_running (NULL,
+ cfg1,
+ 300 * cronSECONDS)) &&
+ (OK == connection_wait_for_running (NULL, cfg2, 300 * cronSECONDS)))
+ {
+ sock1 = client_connection_create (NULL, cfg1);
+ sock2 = client_connection_create (NULL, cfg2);
+ ret = -10;
+ fprintf (stderr, _("Waiting for peers to connect"));
+ while ((ret++ < -1) && (GNUNET_SHUTDOWN_TEST () == NO))
+ {
+ h1 = NULL;
+ h2 = NULL;
+ if ((OK == gnunet_identity_get_self (sock1,
+ &h1)) &&
+ (OK == gnunet_identity_get_self (sock2,
+ &h2)) &&
+ (OK == gnunet_identity_peer_add (sock1,
+ h2)) &&
+ (OK == gnunet_identity_peer_add (sock2, h1)))
+ {
+ fprintf (stderr, ".");
+ if (YES == gnunet_identity_request_connect (sock1,
+ &h2->
+ senderIdentity))
+ {
+ ret = OK;
+ break;
+ }
+ if (YES == gnunet_identity_request_connect (sock2,
+ &h1->
+ senderIdentity))
+ {
+ ret = OK;
+ break;
+ }
+ PTHREAD_SLEEP (100 * cronMILLIS);
+ }
+ FREENONNULL (h1);
+ FREENONNULL (h2);
+ }
+ fprintf (stderr, "%s\n", ret == OK ? "!" : "?");
+ connection_destroy (sock1);
+ connection_destroy (sock2);
}
- fprintf(stderr, "%s\n", ret == OK ? "!" : "?");
- connection_destroy(sock1);
- connection_destroy(sock2);
- } else {
- fprintf(stderr,
- "Failed to establish connection with peers.\n");
- }
- GC_free(cfg1);
- GC_free(cfg2);
+ else
+ {
+ fprintf (stderr, "Failed to establish connection with peers.\n");
+ }
+ GC_free (cfg1);
+ GC_free (cfg2);
return ret;
}
@@ -326,9 +286,10 @@
*
* @return OK on success, SYSERR on failure
*/
-int gnunet_testing_stop_daemon(unsigned short port,
- pid_t pid) {
- if (os_daemon_stop(NULL, pid) != YES)
+int
+gnunet_testing_stop_daemon (unsigned short port, pid_t pid)
+{
+ if (os_daemon_stop (NULL, pid) != YES)
return SYSERR;
return OK;
}
@@ -342,73 +303,70 @@
* @return handle used to stop the daemons, NULL on error
*/
struct DaemonContext *
-gnunet_testing_start_daemons(const char * transports,
- const char * applications,
- const char * gnunetd_home_prefix,
- unsigned short app_baseport,
- unsigned short delta,
- unsigned int count) {
- struct DaemonContext * ret;
- struct DaemonContext * nxt;
+gnunet_testing_start_daemons (const char *transports,
+ const char *applications,
+ const char *gnunetd_home_prefix,
+ unsigned short app_baseport,
+ unsigned short delta, unsigned int count)
+{
+ struct DaemonContext *ret;
+ struct DaemonContext *nxt;
unsigned int pos;
- char * home;
+ char *home;
size_t max;
pid_t pid;
PeerIdentity peer;
- char * cf;
+ char *cf;
ret = NULL;
- max = strlen(gnunetd_home_prefix) + 14;
- home = MALLOC(max);
- for (pos=0;pos<count;pos++) {
- SNPRINTF(home,
- max,
- "%s.%u",
- gnunetd_home_prefix,
- pos);
- if (OK != gnunet_testing_start_daemon(app_baseport + pos * delta,
- delta * pos,
- home,
- transports,
- applications,
- &pid,
- &peer,
- &cf)) {
- gnunet_testing_stop_daemons(ret);
- ret = NULL;
- break;
+ max = strlen (gnunetd_home_prefix) + 14;
+ home = MALLOC (max);
+ for (pos = 0; pos < count; pos++)
+ {
+ SNPRINTF (home, max, "%s.%u", gnunetd_home_prefix, pos);
+ if (OK != gnunet_testing_start_daemon (app_baseport + pos * delta,
+ delta * pos,
+ home,
+ transports,
+ applications, &pid, &peer, &cf))
+ {
+ gnunet_testing_stop_daemons (ret);
+ ret = NULL;
+ break;
+ }
+ nxt = MALLOC (sizeof (struct DaemonContext));
+ nxt->next = ret;
+ nxt->pid = pid;
+ nxt->peer = peer;
+ nxt->configFile = cf;
+ nxt->port = app_baseport + pos * delta;
+ ret = nxt;
}
- nxt = MALLOC(sizeof(struct DaemonContext));
- nxt->next = ret;
- nxt->pid = pid;
- nxt->peer = peer;
- nxt->configFile = cf;
- nxt->port = app_baseport + pos * delta;
- ret = nxt;
- }
- FREE(home);
+ FREE (home);
return ret;
}
-int gnunet_testing_stop_daemons(struct DaemonContext * peers) {
- struct DaemonContext * next;
+int
+gnunet_testing_stop_daemons (struct DaemonContext *peers)
+{
+ struct DaemonContext *next;
int ret;
ret = OK;
- while (peers != NULL) {
- next = peers->next;
- if (OK != gnunet_testing_stop_daemon(peers->port,
- peers->pid))
- ret = SYSERR;
- UNLINK(peers->configFile);
- FREE(peers->configFile);
- FREE(peers);
- peers = next;
- }
+ while (peers != NULL)
+ {
+ next = peers->next;
+ if (OK != gnunet_testing_stop_daemon (peers->port, peers->pid))
+ ret = SYSERR;
+ UNLINK (peers->configFile);
+ FREE (peers->configFile);
+ FREE (peers);
+ peers = next;
+ }
return ret;
}
-
+
/* end of testing.c */
Modified: GNUnet/src/applications/testing/testingtest.c
===================================================================
--- GNUnet/src/applications/testing/testingtest.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/testing/testingtest.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -32,51 +32,47 @@
* Testcase
* @return 0: ok, -1: error
*/
-int main(int argc,
- const char ** argv) {
+int
+main (int argc, const char **argv)
+{
pid_t daemon1;
pid_t daemon2;
PeerIdentity p1;
PeerIdentity p2;
- char * c1 = NULL;
- char * c2 = NULL;
+ char *c1 = NULL;
+ char *c2 = NULL;
int ret = 0;
- if (OK != gnunet_testing_start_daemon(12087,
- 10000,
- "/tmp/gnunet-testing-1",
- "tcp",
- "advertising stats",
- &daemon1,
- &p1,
- &c1))
+ if (OK != gnunet_testing_start_daemon (12087,
+ 10000,
+ "/tmp/gnunet-testing-1",
+ "tcp",
+ "advertising stats",
+ &daemon1, &p1, &c1))
ret |= 1;
- if (OK != gnunet_testing_start_daemon(22087,
- 20000,
- "/tmp/gnunet-testing-2",
- "tcp",
- "advertising stats",
- &daemon2,
- &p2,
- &c2))
+ if (OK != gnunet_testing_start_daemon (22087,
+ 20000,
+ "/tmp/gnunet-testing-2",
+ "tcp",
+ "advertising stats",
+ &daemon2, &p2, &c2))
ret |= 2;
- if (OK != gnunet_testing_connect_daemons(12087,
- 22087))
+ if (OK != gnunet_testing_connect_daemons (12087, 22087))
ret |= 4;
- if (OK != gnunet_testing_stop_daemon(12087,
- daemon1))
+ if (OK != gnunet_testing_stop_daemon (12087, daemon1))
ret |= 8;
- if (OK != gnunet_testing_stop_daemon(22087,
- daemon2))
+ if (OK != gnunet_testing_stop_daemon (22087, daemon2))
ret |= 16;
- if (c1 != NULL) {
- UNLINK(c1);
- FREE(c1);
- }
- if (c2 != NULL) {
- UNLINK(c2);
- FREE(c2);
- }
+ if (c1 != NULL)
+ {
+ UNLINK (c1);
+ FREE (c1);
+ }
+ if (c2 != NULL)
+ {
+ UNLINK (c2);
+ FREE (c2);
+ }
return ret;
}
Modified: GNUnet/src/applications/topology_default/topology.c
===================================================================
--- GNUnet/src/applications/topology_default/topology.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/topology_default/topology.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -68,13 +68,13 @@
*/
#define LIVE_PING_EFFECTIVENESS 20
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
-static Transport_ServiceAPI * transport;
+static Transport_ServiceAPI *transport;
-static Pingpong_ServiceAPI * pingpong;
+static Pingpong_ServiceAPI *pingpong;
/**
* How many peers are we connected to in relation
@@ -87,7 +87,8 @@
* Record for state maintanance between scanHelperCount,
* scanHelperSelect and scanForHosts.
*/
-typedef struct {
+typedef struct
+{
unsigned int index;
unsigned int matchCount;
long long costSelector;
@@ -103,24 +104,23 @@
* @param proto what transport protocol are we looking at
* @param im updated structure used to select the peer
*/
-static int scanHelperCount(const PeerIdentity * id,
- unsigned short proto,
- int confirmed,
- void * data) {
- IndexMatch * im = data;
+static int
+scanHelperCount (const PeerIdentity * id,
+ unsigned short proto, int confirmed, void *data)
+{
+ IndexMatch *im = data;
- if (0 == memcmp(coreAPI->myIdentity,
- id,
- sizeof(PeerIdentity)))
+ if (0 == memcmp (coreAPI->myIdentity, id, sizeof (PeerIdentity)))
return OK;
- if (coreAPI->computeIndex(id) != im->index)
+ if (coreAPI->computeIndex (id) != im->index)
return OK;
- if (OK == coreAPI->queryPeerStatus(id, NULL, NULL))
+ if (OK == coreAPI->queryPeerStatus (id, NULL, NULL))
return OK;
- if (YES == transport->isAvailable(proto)) {
- im->matchCount++;
- im->costSelector += transport->getCost(proto);
- }
+ if (YES == transport->isAvailable (proto))
+ {
+ im->matchCount++;
+ im->costSelector += transport->getCost (proto);
+ }
return OK;
}
@@ -132,29 +132,28 @@
* @param proto the protocol of the current peer
* @param im structure responsible for the selection process
*/
-static int scanHelperSelect(const PeerIdentity * id,
- unsigned short proto,
- int confirmed,
- void * data) {
- IndexMatch * im = data;
+static int
+scanHelperSelect (const PeerIdentity * id,
+ unsigned short proto, int confirmed, void *data)
+{
+ IndexMatch *im = data;
- if (0 == memcmp(coreAPI->myIdentity,
- id,
- sizeof(PeerIdentity)))
+ if (0 == memcmp (coreAPI->myIdentity, id, sizeof (PeerIdentity)))
return OK;
- if (coreAPI->computeIndex(id) != im->index)
+ if (coreAPI->computeIndex (id) != im->index)
return OK;
- if (OK == coreAPI->queryPeerStatus(id, NULL, NULL))
+ if (OK == coreAPI->queryPeerStatus (id, NULL, NULL))
return OK;
- if (YES == transport->isAvailable(proto)) {
- im->costSelector -= transport->getCost(proto);
- if ( (im->matchCount == 0) ||
- (im->costSelector < 0) ) {
- im->match = *id;
- return SYSERR;
+ if (YES == transport->isAvailable (proto))
+ {
+ im->costSelector -= transport->getCost (proto);
+ if ((im->matchCount == 0) || (im->costSelector < 0))
+ {
+ im->match = *id;
+ return SYSERR;
+ }
+ im->matchCount--;
}
- im->matchCount--;
- }
return OK;
}
@@ -166,72 +165,64 @@
* @param index for which entry in the connection table
* are we looking for peers?
*/
-static void scanForHosts(unsigned int index) {
+static void
+scanForHosts (unsigned int index)
+{
IndexMatch indexMatch;
cron_t now;
#if DEBUG_TOPOLOGY
EncName enc;
#endif
- if (os_network_monitor_get_load(coreAPI->load_monitor,
- Upload) > 100)
- return; /* bandwidth saturated, do not
- push it higher! */
- now = get_time();
+ if (os_network_monitor_get_load (coreAPI->load_monitor, Upload) > 100)
+ return; /* bandwidth saturated, do not
+ push it higher! */
+ now = get_time ();
indexMatch.index = index;
indexMatch.matchCount = 0;
indexMatch.costSelector = 0;
- identity->forEachHost(now,
- &scanHelperCount,
- &indexMatch);
- if (indexMatch.matchCount == 0) {
+ identity->forEachHost (now, &scanHelperCount, &indexMatch);
+ if (indexMatch.matchCount == 0)
+ {
#if DEBUG_TOPOLOGY
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "No peers found for slot %u\n",
- index);
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "No peers found for slot %u\n", index);
#endif
- return; /* no matching peers found! */
- }
+ return; /* no matching peers found! */
+ }
if (indexMatch.costSelector > 0)
- indexMatch.costSelector
- = weak_randomi64(indexMatch.costSelector);
+ indexMatch.costSelector = weak_randomi64 (indexMatch.costSelector);
indexMatch.match = *(coreAPI->myIdentity);
- identity->forEachHost(now,
- &scanHelperSelect,
- &indexMatch);
- if (0 == memcmp(coreAPI->myIdentity,
- &indexMatch.match,
- sizeof(PeerIdentity)))
- return; /* should happen really rarely */
- if (coreAPI->computeIndex(&indexMatch.match) != index) {
- GE_BREAK(NULL, 0); /* should REALLY not happen */
- return;
- }
- if (OK == coreAPI->queryPeerStatus(&indexMatch.match, NULL, NULL)) {
- GE_BREAK(NULL, 0); /* should REALLY not happen */
- return;
- }
+ identity->forEachHost (now, &scanHelperSelect, &indexMatch);
+ if (0 == memcmp (coreAPI->myIdentity,
+ &indexMatch.match, sizeof (PeerIdentity)))
+ return; /* should happen really rarely */
+ if (coreAPI->computeIndex (&indexMatch.match) != index)
+ {
+ GE_BREAK (NULL, 0); /* should REALLY not happen */
+ return;
+ }
+ if (OK == coreAPI->queryPeerStatus (&indexMatch.match, NULL, NULL))
+ {
+ GE_BREAK (NULL, 0); /* should REALLY not happen */
+ return;
+ }
#if DEBUG_TOPOLOGY
- IF_GELOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER | GE_DEVELOPER,
- hash2enc(&indexMatch.match.hashPubKey,
- &enc));
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER | GE_DEVELOPER,
- "Trying to connect to peer `%s'\n",
- &enc);
+ IF_GELOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER | GE_DEVELOPER,
+ hash2enc (&indexMatch.match.hashPubKey, &enc));
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER | GE_DEVELOPER,
+ "Trying to connect to peer `%s'\n", &enc);
#endif
- if (NO == identity->isBlacklistedStrict(&indexMatch.match)) {
- coreAPI->unicast(&indexMatch.match,
- NULL,
- 0,
- 0);
- identity->blacklistHost(&indexMatch.match,
- (unsigned int) (saturation * 5 * 60 * 60), /* 5 hours at
full saturation */
- NO);
- }
+ if (NO == identity->isBlacklistedStrict (&indexMatch.match))
+ {
+ coreAPI->unicast (&indexMatch.match, NULL, 0, 0);
+ identity->blacklistHost (&indexMatch.match, (unsigned int) (saturation *
5 * 60 * 60), /* 5 hours at full saturation */
+ NO);
+ }
}
/**
@@ -239,72 +230,69 @@
*
* @param hostId the peer that gave a sign of live
*/
-static void notifyPONG(void * cls) {
- PeerIdentity * hostId = cls;
+static void
+notifyPONG (void *cls)
+{
+ PeerIdentity *hostId = cls;
#if DEBUG_TOPOLOGY || DEBUG_LIVENESS
EncName enc;
- IF_GELOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- hash2enc(&hostId->hashPubKey,
- &enc));
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Received liveness confirmation from `%s'.\n",
- &enc);
+ IF_GELOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ hash2enc (&hostId->hashPubKey, &enc));
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Received liveness confirmation from `%s'.\n", &enc);
#endif
- coreAPI->confirmSessionUp(hostId);
- FREE(hostId);
+ coreAPI->confirmSessionUp (hostId);
+ FREE (hostId);
}
/**
* Check the liveness of the peer and possibly ping it.
*/
-static void checkNeedForPing(const PeerIdentity * peer,
- void * unused) {
+static void
+checkNeedForPing (const PeerIdentity * peer, void *unused)
+{
cron_t now;
cron_t act;
- PeerIdentity * hi;
+ PeerIdentity *hi;
int ran;
- ran = weak_randomi(LIVE_PING_EFFECTIVENESS);
+ ran = weak_randomi (LIVE_PING_EFFECTIVENESS);
if (ran != 0)
return;
- now = get_time();
- if (SYSERR == coreAPI->getLastActivityOf(peer, &act)) {
- GE_BREAK(coreAPI->ectx, 0);
- return; /* this should not happen... */
- }
+ now = get_time ();
+ if (SYSERR == coreAPI->getLastActivityOf (peer, &act))
+ {
+ GE_BREAK (coreAPI->ectx, 0);
+ return; /* this should not happen... */
+ }
- if (now - act > SECONDS_PINGATTEMPT * cronSECONDS) {
- /* if we have less than 75% of the number of connections
- that we would like to have, try ping-ing the other side
- to keep the connection open instead of hanging up */
+ if (now - act > SECONDS_PINGATTEMPT * cronSECONDS)
+ {
+ /* if we have less than 75% of the number of connections
+ that we would like to have, try ping-ing the other side
+ to keep the connection open instead of hanging up */
#if DEBUG_TOPOLOGY || DEBUG_LIVENESS
- EncName enc;
+ EncName enc;
- IF_GELOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- hash2enc(&peer->hashPubKey,
- &enc));
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Peer `%s' was inactive for %llus. Sending PING.\n",
- &enc,
- (now-act)/cronSECONDS);
+ IF_GELOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ hash2enc (&peer->hashPubKey, &enc));
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Peer `%s' was inactive for %llus. Sending PING.\n",
+ &enc, (now - act) / cronSECONDS);
#endif
- hi = MALLOC(sizeof(PeerIdentity));
- *hi = *peer;
- if (OK != pingpong->ping(peer,
- ¬ifyPONG,
- hi,
- NO,
- rand()))
- FREE(hi);
- }
+ hi = MALLOC (sizeof (PeerIdentity));
+ *hi = *peer;
+ if (OK != pingpong->ping (peer, ¬ifyPONG, hi, NO, rand ()))
+ FREE (hi);
+ }
}
#define MAX_PEERS_PER_SLOT 10
@@ -314,48 +302,49 @@
*
* @param unused not used, just to make signature type nicely
*/
-static void cronCheckLiveness(void * unused) {
+static void
+cronCheckLiveness (void *unused)
+{
int i;
int slotCount;
int active;
unsigned int minint;
int autoconnect;
- autoconnect = GC_get_configuration_value_yesno(coreAPI->cfg,
- "GNUNETD",
- "DISABLE-AUTOCONNECT",
- NO);
- slotCount = coreAPI->getSlotCount();
- if ( (NO == autoconnect) &&
- (saturation < 1) ) {
- if (saturation * MAX_PEERS_PER_SLOT >= 1)
- minint = (unsigned int) (1 / saturation);
- else
- minint = MAX_PEERS_PER_SLOT; /* never put more than 10 peers into a slot
*/
- for (i=slotCount-1;i>=0;i--) {
- if (weak_randomi(LIVE_SCAN_EFFECTIVENESS) != 0)
- continue;
- if (minint > coreAPI->isSlotUsed(i))
- scanForHosts(i);
+ autoconnect = GC_get_configuration_value_yesno (coreAPI->cfg,
+ "GNUNETD",
+ "DISABLE-AUTOCONNECT", NO);
+ slotCount = coreAPI->getSlotCount ();
+ if ((NO == autoconnect) && (saturation < 1))
+ {
+ if (saturation * MAX_PEERS_PER_SLOT >= 1)
+ minint = (unsigned int) (1 / saturation);
+ else
+ minint = MAX_PEERS_PER_SLOT; /* never put more than 10 peers into a
slot */
+ for (i = slotCount - 1; i >= 0; i--)
+ {
+ if (weak_randomi (LIVE_SCAN_EFFECTIVENESS) != 0)
+ continue;
+ if (minint > coreAPI->isSlotUsed (i))
+ scanForHosts (i);
+ }
}
- }
- active = coreAPI->forAllConnectedNodes(&checkNeedForPing,
- NULL);
+ active = coreAPI->forAllConnectedNodes (&checkNeedForPing, NULL);
saturation = 1.0 * active / slotCount;
}
-static int estimateNetworkSize() {
+static int
+estimateNetworkSize ()
+{
unsigned int active;
unsigned int known;
- active = coreAPI->forAllConnectedNodes(NULL, NULL);
+ active = coreAPI->forAllConnectedNodes (NULL, NULL);
if (active == 0)
return 0;
- known = identity->forEachHost(0,
- NULL,
- NULL);
+ known = identity->forEachHost (0, NULL, NULL);
if (active > known)
- return active; /* should not be possible */
+ return active; /* should not be possible */
/* Assumption:
if we only connect to X% of all machines
that we know, we probably also only know X%
@@ -370,75 +359,78 @@
Example:
- we connect to all machines we have ever heard
- of => network size == # active
+ of => network size == # active
- we connect to only 1% of the machines we have
- heard of => network size = 100 * # active
- */
+ heard of => network size = 100 * # active
+ */
if (known * known / active < known)
- return 0x7FFFFFFF; /* integer overflow, return max int */
+ return 0x7FFFFFFF; /* integer overflow, return max int */
return known * known / active;
}
-static double estimateSaturation() {
+static double
+estimateSaturation ()
+{
return saturation;
}
-static int allowConnection(const PeerIdentity * peer) {
- if ( (coreAPI->myIdentity != NULL) &&
- (0 == memcmp(coreAPI->myIdentity,
- peer,
- sizeof(PeerIdentity))) )
- return SYSERR; /* disallow connections to self */
- return OK; /* allow everything else */
+static int
+allowConnection (const PeerIdentity * peer)
+{
+ if ((coreAPI->myIdentity != NULL) &&
+ (0 == memcmp (coreAPI->myIdentity, peer, sizeof (PeerIdentity))))
+ return SYSERR; /* disallow connections to self */
+ return OK; /* allow everything else */
}
Topology_ServiceAPI *
-provide_module_topology_default(CoreAPIForApplication * capi) {
+provide_module_topology_default (CoreAPIForApplication * capi)
+{
static Topology_ServiceAPI api;
coreAPI = capi;
- identity = capi->requestService("identity");
- if (identity == NULL) {
- GE_BREAK(capi->ectx, 0);
- return NULL;
- }
- transport = capi->requestService("transport");
- if (transport == NULL) {
- GE_BREAK(capi->ectx, 0);
- capi->releaseService(identity);
- identity = NULL;
- return NULL;
- }
- pingpong = capi->requestService("pingpong");
- if (pingpong == NULL) {
- GE_BREAK(capi->ectx, 0);
- capi->releaseService(identity);
- identity = NULL;
- capi->releaseService(transport);
- transport = NULL;
- return NULL;
- }
- cron_add_job(capi->cron,
- &cronCheckLiveness,
- LIVE_SCAN_FREQUENCY,
- LIVE_SCAN_FREQUENCY,
- NULL);
+ identity = capi->requestService ("identity");
+ if (identity == NULL)
+ {
+ GE_BREAK (capi->ectx, 0);
+ return NULL;
+ }
+ transport = capi->requestService ("transport");
+ if (transport == NULL)
+ {
+ GE_BREAK (capi->ectx, 0);
+ capi->releaseService (identity);
+ identity = NULL;
+ return NULL;
+ }
+ pingpong = capi->requestService ("pingpong");
+ if (pingpong == NULL)
+ {
+ GE_BREAK (capi->ectx, 0);
+ capi->releaseService (identity);
+ identity = NULL;
+ capi->releaseService (transport);
+ transport = NULL;
+ return NULL;
+ }
+ cron_add_job (capi->cron,
+ &cronCheckLiveness,
+ LIVE_SCAN_FREQUENCY, LIVE_SCAN_FREQUENCY, NULL);
api.estimateNetworkSize = &estimateNetworkSize;
api.getSaturation = &estimateSaturation;
api.allowConnectionFrom = &allowConnection;
return &api;
}
-int release_module_topology_default() {
- cron_del_job(coreAPI->cron,
- &cronCheckLiveness,
- LIVE_SCAN_FREQUENCY,
- NULL);
- coreAPI->releaseService(identity);
+int
+release_module_topology_default ()
+{
+ cron_del_job (coreAPI->cron, &cronCheckLiveness, LIVE_SCAN_FREQUENCY, NULL);
+ coreAPI->releaseService (identity);
identity = NULL;
- coreAPI->releaseService(transport);
+ coreAPI->releaseService (transport);
transport = NULL;
- coreAPI->releaseService(pingpong);
+ coreAPI->releaseService (pingpong);
pingpong = NULL;
coreAPI = NULL;
return OK;
@@ -447,33 +439,39 @@
/**
* Update topology module.
*/
-void update_module_topology_default(UpdateAPI * uapi) {
- uapi->updateModule("state");
- uapi->updateModule("identity");
- uapi->updateModule("transport");
- uapi->updateModule("pingpong");
+void
+update_module_topology_default (UpdateAPI * uapi)
+{
+ uapi->updateModule ("state");
+ uapi->updateModule ("identity");
+ uapi->updateModule ("transport");
+ uapi->updateModule ("pingpong");
}
-static CoreAPIForApplication * myCapi;
+static CoreAPIForApplication *myCapi;
-static Topology_ServiceAPI * myTopology;
+static Topology_ServiceAPI *myTopology;
-int initialize_module_topology_default(CoreAPIForApplication * capi) {
+int
+initialize_module_topology_default (CoreAPIForApplication * capi)
+{
myCapi = capi;
- myTopology = capi->requestService("topology");
- GE_ASSERT(capi->ectx,
- myTopology != NULL);
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "topology",
- gettext_noop("maintains GNUnet
default mesh topology")));
+ myTopology = capi->requestService ("topology");
+ GE_ASSERT (capi->ectx, myTopology != NULL);
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "topology",
+ gettext_noop
+ ("maintains GNUnet
default mesh topology")));
return OK;
}
-void done_module_topology_default() {
- myCapi->releaseService(myTopology);
+void
+done_module_topology_default ()
+{
+ myCapi->releaseService (myTopology);
myCapi = NULL;
myTopology = NULL;
}
Modified: GNUnet/src/applications/topology_f2f/topology.c
===================================================================
--- GNUnet/src/applications/topology_f2f/topology.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/topology_f2f/topology.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -67,15 +67,15 @@
*/
#define LIVE_PING_EFFECTIVENESS 20
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
-static Transport_ServiceAPI * transport;
+static Transport_ServiceAPI *transport;
-static Pingpong_ServiceAPI * pingpong;
+static Pingpong_ServiceAPI *pingpong;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
/**
* How many peers are we connected to in relation
@@ -88,28 +88,27 @@
* Record for state maintanance between scanHelperCount,
* scanHelperSelect and scanForHosts.
*/
-typedef struct {
+typedef struct
+{
unsigned int index;
unsigned int matchCount;
long long costSelector;
PeerIdentity match;
} IndexMatch;
-static PeerIdentity * friends;
+static PeerIdentity *friends;
static unsigned int friendCount;
-static int allowConnection(const PeerIdentity * peer) {
+static int
+allowConnection (const PeerIdentity * peer)
+{
int i;
- if ( (coreAPI->myIdentity != NULL) &&
- (0 == memcmp(coreAPI->myIdentity,
- peer,
- sizeof(PeerIdentity))) )
- return SYSERR; /* disallow connections to self */
- for (i=friendCount-1;i>=0;i--)
- if (0 == memcmp(&friends[i],
- peer,
- sizeof(PeerIdentity)))
+ if ((coreAPI->myIdentity != NULL) &&
+ (0 == memcmp (coreAPI->myIdentity, peer, sizeof (PeerIdentity))))
+ return SYSERR; /* disallow connections to self */
+ for (i = friendCount - 1; i >= 0; i--)
+ if (0 == memcmp (&friends[i], peer, sizeof (PeerIdentity)))
return OK;
return SYSERR;
}
@@ -123,25 +122,23 @@
* @param proto what transport protocol are we looking at
* @param im updated structure used to select the peer
*/
-static int scanHelperCount(const PeerIdentity * id,
- unsigned short proto,
- int confirmed,
- void * cls) {
- IndexMatch * im = cls;
+static int
+scanHelperCount (const PeerIdentity * id,
+ unsigned short proto, int confirmed, void *cls)
+{
+ IndexMatch *im = cls;
- if (0 == memcmp(coreAPI->myIdentity,
- id,
- sizeof(PeerIdentity)))
+ if (0 == memcmp (coreAPI->myIdentity, id, sizeof (PeerIdentity)))
return OK;
- if (coreAPI->computeIndex(id) != im->index)
+ if (coreAPI->computeIndex (id) != im->index)
return OK;
- if (OK == coreAPI->queryPeerStatus(id, NULL, NULL))
+ if (OK == coreAPI->queryPeerStatus (id, NULL, NULL))
return OK;
- if ( (YES == transport->isAvailable(proto)) &&
- (OK == allowConnection(id)) ) {
- im->matchCount++;
- im->costSelector += transport->getCost(proto);
- }
+ if ((YES == transport->isAvailable (proto)) && (OK == allowConnection (id)))
+ {
+ im->matchCount++;
+ im->costSelector += transport->getCost (proto);
+ }
return OK;
}
@@ -153,29 +150,27 @@
* @param proto the protocol of the current peer
* @param im structure responsible for the selection process
*/
-static int scanHelperSelect(const PeerIdentity * id,
- const unsigned short proto,
- int confirmed,
- void * cls) {
- IndexMatch * im = cls;
- if (0 == memcmp(coreAPI->myIdentity,
- id,
- sizeof(PeerIdentity)))
+static int
+scanHelperSelect (const PeerIdentity * id,
+ const unsigned short proto, int confirmed, void *cls)
+{
+ IndexMatch *im = cls;
+ if (0 == memcmp (coreAPI->myIdentity, id, sizeof (PeerIdentity)))
return OK;
- if (coreAPI->computeIndex(id) != im->index)
+ if (coreAPI->computeIndex (id) != im->index)
return OK;
- if (OK == coreAPI->queryPeerStatus(id, NULL, NULL))
+ if (OK == coreAPI->queryPeerStatus (id, NULL, NULL))
return OK;
- if ( (OK == allowConnection(id)) &&
- (YES == transport->isAvailable(proto)) ) {
- im->costSelector -= transport->getCost(proto);
- if ( (im->matchCount == 0) ||
- (im->costSelector < 0) ) {
- im->match = *id;
- return SYSERR; /* abort iteration */
+ if ((OK == allowConnection (id)) && (YES == transport->isAvailable (proto)))
+ {
+ im->costSelector -= transport->getCost (proto);
+ if ((im->matchCount == 0) || (im->costSelector < 0))
+ {
+ im->match = *id;
+ return SYSERR; /* abort iteration */
+ }
+ im->matchCount--;
}
- im->matchCount--;
- }
return OK;
}
@@ -186,58 +181,51 @@
*
* @param index for which entry in the connection table are we looking for
peers?
*/
-static void scanForHosts(unsigned int index) {
+static void
+scanForHosts (unsigned int index)
+{
IndexMatch indexMatch;
cron_t now;
#if DEBUG_TOPOLOGY
EncName enc;
#endif
- now = get_time();
+ now = get_time ();
indexMatch.index = index;
indexMatch.matchCount = 0;
indexMatch.costSelector = 0;
- identity->forEachHost(now,
- &scanHelperCount,
- &indexMatch);
+ identity->forEachHost (now, &scanHelperCount, &indexMatch);
if (indexMatch.matchCount == 0)
- return; /* no matching peers found! */
+ return; /* no matching peers found! */
if (indexMatch.costSelector > 0)
- indexMatch.costSelector
- = weak_randomi(indexMatch.costSelector/4)*4;
+ indexMatch.costSelector = weak_randomi (indexMatch.costSelector / 4) * 4;
indexMatch.match = *(coreAPI->myIdentity);
- identity->forEachHost(now,
- &scanHelperSelect,
- &indexMatch);
- if (0 == memcmp(coreAPI->myIdentity,
- &indexMatch.match,
- sizeof(PeerIdentity))) {
- GE_BREAK(ectx, 0); /* should not happen, at least not often... */
- return;
- }
- if (coreAPI->computeIndex(&indexMatch.match) != index) {
- GE_BREAK(ectx, 0); /* should REALLY not happen */
- return;
- }
+ identity->forEachHost (now, &scanHelperSelect, &indexMatch);
+ if (0 == memcmp (coreAPI->myIdentity,
+ &indexMatch.match, sizeof (PeerIdentity)))
+ {
+ GE_BREAK (ectx, 0); /* should not happen, at least not often... */
+ return;
+ }
+ if (coreAPI->computeIndex (&indexMatch.match) != index)
+ {
+ GE_BREAK (ectx, 0); /* should REALLY not happen */
+ return;
+ }
#if DEBUG_TOPOLOGY
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&indexMatch.match.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Topology: trying to connect to `%s'.\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&indexMatch.match.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Topology: trying to connect to `%s'.\n", &enc);
#endif
- if (NO == identity->isBlacklistedStrict(&indexMatch.match)) {
- coreAPI->unicast(&indexMatch.match,
- NULL,
- 0,
- 0);
- identity->blacklistHost(&indexMatch.match,
- (unsigned int) 5 * 60 * 60 * saturation, /* 5h at
full saturation */
- NO);
- }
+ if (NO == identity->isBlacklistedStrict (&indexMatch.match))
+ {
+ coreAPI->unicast (&indexMatch.match, NULL, 0, 0);
+ identity->blacklistHost (&indexMatch.match, (unsigned int) 5 * 60 * 60 *
saturation, /* 5h at full saturation */
+ NO);
+ }
}
/**
@@ -245,61 +233,60 @@
*
* @param hostId the peer that gave a sign of live
*/
-static void notifyPONG(void * cls) {
- PeerIdentity * hostId = cls;
+static void
+notifyPONG (void *cls)
+{
+ PeerIdentity *hostId = cls;
#if DEBUG_TOPOLOGY
EncName enc;
- hash2enc(&hostId->hashPubKey,
- &enc);
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Received pong from `%s', telling core that peer is still alive.\n",
- (char*)&enc);
+ hash2enc (&hostId->hashPubKey, &enc);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Received pong from `%s', telling core that peer is still alive.\n",
+ (char *) &enc);
#endif
- coreAPI->confirmSessionUp(hostId);
- FREE(hostId);
+ coreAPI->confirmSessionUp (hostId);
+ FREE (hostId);
}
/**
* Check the liveness of the ping and possibly ping it.
*/
-static void checkNeedForPing(const PeerIdentity * peer,
- void * unused) {
+static void
+checkNeedForPing (const PeerIdentity * peer, void *unused)
+{
cron_t now;
cron_t act;
#if DEBUG_TOPOLOGY
EncName enc;
#endif
- if (weak_randomi(LIVE_PING_EFFECTIVENESS) != 0)
+ if (weak_randomi (LIVE_PING_EFFECTIVENESS) != 0)
return;
- now = get_time();
- if (SYSERR == coreAPI->getLastActivityOf(peer, &act)) {
- GE_BREAK(ectx, 0);
- return; /* this should not happen... */
- }
+ now = get_time ();
+ if (SYSERR == coreAPI->getLastActivityOf (peer, &act))
+ {
+ GE_BREAK (ectx, 0);
+ return; /* this should not happen... */
+ }
- if (now - act > SECONDS_PINGATTEMPT * cronSECONDS) {
- /* if we have less than 75% of the number of connections
- that we would like to have, try ping-ing the other side
- to keep the connection open instead of hanging up */
- PeerIdentity * hi = MALLOC(sizeof(PeerIdentity));
- *hi = *peer;
+ if (now - act > SECONDS_PINGATTEMPT * cronSECONDS)
+ {
+ /* if we have less than 75% of the number of connections
+ that we would like to have, try ping-ing the other side
+ to keep the connection open instead of hanging up */
+ PeerIdentity *hi = MALLOC (sizeof (PeerIdentity));
+ *hi = *peer;
#if DEBUG_TOPOLOGY
- hash2enc(&hi->hashPubKey,
- &enc);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Sending ping to `%s' to prevent connection timeout.\n",
- (char*)&enc);
+ hash2enc (&hi->hashPubKey, &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Sending ping to `%s' to prevent connection timeout.\n",
+ (char *) &enc);
#endif
- if (OK != pingpong->ping(peer,
- ¬ifyPONG,
- hi,
- NO,
- rand()))
- FREE(hi);
- }
+ if (OK != pingpong->ping (peer, ¬ifyPONG, hi, NO, rand ()))
+ FREE (hi);
+ }
}
/**
@@ -307,221 +294,228 @@
*
* @param unused not used, just to make signature type nicely
*/
-static void cronCheckLiveness(void * unused) {
+static void
+cronCheckLiveness (void *unused)
+{
int i;
int slotCount;
int active;
int autoconnect;
- autoconnect = GC_get_configuration_value_yesno(coreAPI->cfg,
- "GNUNETD",
- "DISABLE-AUTOCONNECT",
- NO);
- slotCount = coreAPI->getSlotCount();
- if ( (NO == autoconnect) &&
- (saturation < 1) ) {
- for (i=slotCount-1;i>=0;i--) {
- if (weak_randomi(LIVE_SCAN_EFFECTIVENESS) != 0)
- continue;
- if (0 == coreAPI->isSlotUsed(i))
- scanForHosts(i);
+ autoconnect = GC_get_configuration_value_yesno (coreAPI->cfg,
+ "GNUNETD",
+ "DISABLE-AUTOCONNECT", NO);
+ slotCount = coreAPI->getSlotCount ();
+ if ((NO == autoconnect) && (saturation < 1))
+ {
+ for (i = slotCount - 1; i >= 0; i--)
+ {
+ if (weak_randomi (LIVE_SCAN_EFFECTIVENESS) != 0)
+ continue;
+ if (0 == coreAPI->isSlotUsed (i))
+ scanForHosts (i);
+ }
}
- }
- active = coreAPI->forAllConnectedNodes(&checkNeedForPing,
- NULL);
+ active = coreAPI->forAllConnectedNodes (&checkNeedForPing, NULL);
saturation = 1.0 * active / slotCount;
}
-static int estimateNetworkSize() {
+static int
+estimateNetworkSize ()
+{
return friendCount;
}
-static double estimateSaturation() {
+static double
+estimateSaturation ()
+{
return saturation;
}
/**
* @return 0 on success.
*/
-static int rereadConfiguration(void * ctx,
- struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option) {
- char * fn;
- char * data;
+static int
+rereadConfiguration (void *ctx,
+ struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section, const char *option)
+{
+ char *fn;
+ char *data;
unsigned long long size;
size_t pos;
EncName enc;
HashCode512 hc;
- if (0 != strcmp(section, "F2F"))
+ if (0 != strcmp (section, "F2F"))
return 0;
- GROW(friends,
- friendCount,
- 0);
+ GROW (friends, friendCount, 0);
fn = NULL;
- GC_get_configuration_value_filename(cfg,
- "F2F",
- "FRIENDS",
- VAR_DAEMON_DIRECTORY "/friends",
- &fn);
- if ( (0 == disk_file_test(ectx, fn)) ||
- (OK != disk_file_size(ectx, fn, &size, YES)) ) {
- GE_LOG(ectx,
- GE_USER | GE_ADMIN | GE_ERROR | GE_IMMEDIATE,
- "Could not read friends list `%s'\n",
- fn);
- FREE(fn);
- return SYSERR;
- }
- data = MALLOC(size);
- if (size != disk_file_read(ectx, fn, size, data)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Failed to read friends list from `%s'\n"),
- fn);
- FREE(fn);
- FREE(data);
- return SYSERR;
- }
- FREE(fn);
+ GC_get_configuration_value_filename (cfg,
+ "F2F",
+ "FRIENDS",
+ VAR_DAEMON_DIRECTORY "/friends", &fn);
+ if ((0 == disk_file_test (ectx, fn)) ||
+ (OK != disk_file_size (ectx, fn, &size, YES)))
+ {
+ GE_LOG (ectx,
+ GE_USER | GE_ADMIN | GE_ERROR | GE_IMMEDIATE,
+ "Could not read friends list `%s'\n", fn);
+ FREE (fn);
+ return SYSERR;
+ }
+ data = MALLOC (size);
+ if (size != disk_file_read (ectx, fn, size, data))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Failed to read friends list from `%s'\n"), fn);
+ FREE (fn);
+ FREE (data);
+ return SYSERR;
+ }
+ FREE (fn);
pos = 0;
- while ( (pos < size) &&
- isspace(data[pos]))
+ while ((pos < size) && isspace (data[pos]))
pos++;
- while (pos <= size - sizeof(EncName)) {
- memcpy(&enc,
- &data[pos],
- sizeof(EncName));
- if (! isspace(enc.encoding[sizeof(EncName)-1])) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Syntax error in topology specification, skipping bytes.\n"));
- continue;
+ while (pos <= size - sizeof (EncName))
+ {
+ memcpy (&enc, &data[pos], sizeof (EncName));
+ if (!isspace (enc.encoding[sizeof (EncName) - 1]))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("Syntax error in topology specification, skipping
bytes.\n"));
+ continue;
+ }
+ enc.encoding[sizeof (EncName) - 1] = '\0';
+ if (OK == enc2hash ((char *) &enc, &hc))
+ {
+ GROW (friends, friendCount, friendCount + 1);
+ friends[friendCount - 1].hashPubKey = hc;
+ }
+ else
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("Syntax error in topology specification, skipping bytes
`%s'.\n"),
+ &enc);
+ }
+ pos = pos + sizeof (EncName);
+ while ((pos < size) && isspace (data[pos]))
+ pos++;
}
- enc.encoding[sizeof(EncName)-1] = '\0';
- if (OK == enc2hash((char*)&enc,
- &hc)) {
- GROW(friends,
- friendCount,
- friendCount+1);
- friends[friendCount-1].hashPubKey = hc;
- } else {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Syntax error in topology specification, skipping bytes
`%s'.\n"),
- &enc);
- }
- pos = pos + sizeof(EncName);
- while ( (pos < size) &&
- isspace(data[pos]))
- pos++;
- }
return 0;
}
Topology_ServiceAPI *
-provide_module_topology_f2f(CoreAPIForApplication * capi) {
+provide_module_topology_f2f (CoreAPIForApplication * capi)
+{
static Topology_ServiceAPI api;
coreAPI = capi;
ectx = capi->ectx;
- identity = capi->requestService("identity");
- if (identity == NULL) {
- GE_BREAK(ectx, 0);
- return NULL;
- }
- transport = capi->requestService("transport");
- if (transport == NULL) {
- GE_BREAK(ectx, 0);
- capi->releaseService(identity);
- identity = NULL;
- return NULL;
- }
- pingpong = capi->requestService("pingpong");
- if (pingpong == NULL) {
- GE_BREAK(ectx, 0);
- capi->releaseService(identity);
- identity = NULL;
- capi->releaseService(transport);
- transport = NULL;
- return NULL;
- }
- if (0 != GC_attach_change_listener(coreAPI->cfg,
- &rereadConfiguration,
- NULL)) {
- GE_BREAK(ectx, 0);
- capi->releaseService(identity);
- identity = NULL;
- capi->releaseService(transport);
- transport = NULL;
- capi->releaseService(pingpong);
- pingpong = NULL;
- return NULL;
- }
+ identity = capi->requestService ("identity");
+ if (identity == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
+ transport = capi->requestService ("transport");
+ if (transport == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ capi->releaseService (identity);
+ identity = NULL;
+ return NULL;
+ }
+ pingpong = capi->requestService ("pingpong");
+ if (pingpong == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ capi->releaseService (identity);
+ identity = NULL;
+ capi->releaseService (transport);
+ transport = NULL;
+ return NULL;
+ }
+ if (0 != GC_attach_change_listener (coreAPI->cfg,
+ &rereadConfiguration, NULL))
+ {
+ GE_BREAK (ectx, 0);
+ capi->releaseService (identity);
+ identity = NULL;
+ capi->releaseService (transport);
+ transport = NULL;
+ capi->releaseService (pingpong);
+ pingpong = NULL;
+ return NULL;
+ }
- cron_add_job(coreAPI->cron,
- &cronCheckLiveness,
- LIVE_SCAN_FREQUENCY,
- LIVE_SCAN_FREQUENCY,
- NULL);
+ cron_add_job (coreAPI->cron,
+ &cronCheckLiveness,
+ LIVE_SCAN_FREQUENCY, LIVE_SCAN_FREQUENCY, NULL);
api.estimateNetworkSize = &estimateNetworkSize;
api.getSaturation = &estimateSaturation;
api.allowConnectionFrom = &allowConnection;
return &api;
}
-int release_module_topology_f2f() {
- cron_del_job(coreAPI->cron,
- &cronCheckLiveness,
- LIVE_SCAN_FREQUENCY,
- NULL);
- GC_detach_change_listener(coreAPI->cfg,
- &rereadConfiguration,
- NULL);
- coreAPI->releaseService(identity);
+int
+release_module_topology_f2f ()
+{
+ cron_del_job (coreAPI->cron, &cronCheckLiveness, LIVE_SCAN_FREQUENCY, NULL);
+ GC_detach_change_listener (coreAPI->cfg, &rereadConfiguration, NULL);
+ coreAPI->releaseService (identity);
identity = NULL;
- coreAPI->releaseService(transport);
+ coreAPI->releaseService (transport);
transport = NULL;
- coreAPI->releaseService(pingpong);
+ coreAPI->releaseService (pingpong);
pingpong = NULL;
coreAPI = NULL;
- GROW(friends,
- friendCount,
- 0);
+ GROW (friends, friendCount, 0);
return OK;
}
/**
* Update topology module.
*/
-void update_module_topology_default(UpdateAPI * uapi) {
- uapi->updateModule("state");
- uapi->updateModule("identity");
- uapi->updateModule("transport");
- uapi->updateModule("pingpong");
+void
+update_module_topology_default (UpdateAPI * uapi)
+{
+ uapi->updateModule ("state");
+ uapi->updateModule ("identity");
+ uapi->updateModule ("transport");
+ uapi->updateModule ("pingpong");
}
-static CoreAPIForApplication * myCapi;
+static CoreAPIForApplication *myCapi;
-static Topology_ServiceAPI * myTopology;
+static Topology_ServiceAPI *myTopology;
-int initialize_module_topology_f2f(CoreAPIForApplication * capi) {
+int
+initialize_module_topology_f2f (CoreAPIForApplication * capi)
+{
myCapi = capi;
- myTopology = capi->requestService("topology");
- GE_ASSERT(ectx, myTopology != NULL);
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "topology",
- gettext_noop("maintains a
friend-to-friend restricted topology")));
+ myTopology = capi->requestService ("topology");
+ GE_ASSERT (ectx, myTopology != NULL);
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "topology",
+ gettext_noop
+ ("maintains a
friend-to-friend restricted topology")));
return OK;
}
-void done_module_topology_f2f() {
- myCapi->releaseService(myTopology);
+void
+done_module_topology_f2f ()
+{
+ myCapi->releaseService (myTopology);
myCapi = NULL;
myTopology = NULL;
}
Modified: GNUnet/src/applications/tracekit/gnunet-tracekit.c
===================================================================
--- GNUnet/src/applications/tracekit/gnunet-tracekit.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/tracekit/gnunet-tracekit.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -31,66 +31,65 @@
#include "gnunet_util_crypto.h"
#include "tracekit.h"
-static struct SEMAPHORE * doneSem;
+static struct SEMAPHORE *doneSem;
-static char * cfgFilename;
+static char *cfgFilename;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
/**
* All gnunet-tracekit command line options
*/
static struct CommandLineOption gnunettracekitOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- { 'D', "depth", "DEPTH",
- gettext_noop("probe network to the given DEPTH"), 1,
- &gnunet_getopt_configure_set_option, "GNUNET-TRACEKIT:HOPS" },
- { 'F', "format", "FORMAT",
- gettext_noop("specify output format; 0 for human readable output, 1 for
dot, 2 for vcg"), 1,
- &gnunet_getopt_configure_set_option, "GNUNET-TRACEKIT:FORMAT" },
- COMMAND_LINE_OPTION_HELP(gettext_noop("Start GNUnet transport benchmarking
tool.")), /* -h */
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ {'D', "depth", "DEPTH",
+ gettext_noop ("probe network to the given DEPTH"), 1,
+ &gnunet_getopt_configure_set_option, "GNUNET-TRACEKIT:HOPS"},
+ {'F', "format", "FORMAT",
+ gettext_noop
+ ("specify output format; 0 for human readable output, 1 for dot, 2 for
vcg"),
+ 1,
+ &gnunet_getopt_configure_set_option, "GNUNET-TRACEKIT:FORMAT"},
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Start GNUnet transport benchmarking
tool.")), /* -h */
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'P', "priority", "PRIO",
- gettext_noop("use PRIO for the priority of the trace request"), 1,
- &gnunet_getopt_configure_set_option, "GNUNET-TRACEKIT:PRIORITY" },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
- { 'W', "wait", "DELAY",
- gettext_noop("wait DELAY seconds for replies"), 1,
- &gnunet_getopt_configure_set_option, "GNUNET-TRACEKIT:WAIT" },
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'P', "priority", "PRIO",
+ gettext_noop ("use PRIO for the priority of the trace request"), 1,
+ &gnunet_getopt_configure_set_option, "GNUNET-TRACEKIT:PRIORITY"},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
+ {'W', "wait", "DELAY",
+ gettext_noop ("wait DELAY seconds for replies"), 1,
+ &gnunet_getopt_configure_set_option, "GNUNET-TRACEKIT:WAIT"},
COMMAND_LINE_OPTION_END,
};
static unsigned int
-getConfigurationInt(const char * sec,
- const char * opt,
- unsigned int max) {
+getConfigurationInt (const char *sec, const char *opt, unsigned int max)
+{
unsigned long long val;
- GC_get_configuration_value_number(cfg,
- sec,
- opt,
- 0,
- max,
- 0,
- &val);
+ GC_get_configuration_value_number (cfg, sec, opt, 0, max, 0, &val);
return (unsigned int) val;
}
-static void run_shutdown(void * unused) {
- GNUNET_SHUTDOWN_INITIATE();
+static void
+run_shutdown (void *unused)
+{
+ GNUNET_SHUTDOWN_INITIATE ();
}
-static void * receiveThread(void * cls) {
- struct ClientServerConnection * sock = cls;
- CS_tracekit_reply_MESSAGE * buffer;
+static void *
+receiveThread (void *cls)
+{
+ struct ClientServerConnection *sock = cls;
+ CS_tracekit_reply_MESSAGE *buffer;
unsigned long long format;
- PeerIdentity * peersSeen;
+ PeerIdentity *peersSeen;
unsigned int psCount;
unsigned int psSize;
- PeerIdentity * peersResponding;
+ PeerIdentity *peersResponding;
unsigned int prCount;
unsigned int prSize;
int i;
@@ -99,184 +98,188 @@
psCount = 0;
psSize = 1;
- peersSeen = MALLOC(psSize * sizeof(PeerIdentity));
+ peersSeen = MALLOC (psSize * sizeof (PeerIdentity));
prCount = 0;
prSize = 1;
- peersResponding = MALLOC(prSize * sizeof(PeerIdentity));
- buffer = MALLOC(MAX_BUFFER_SIZE);
+ peersResponding = MALLOC (prSize * sizeof (PeerIdentity));
+ buffer = MALLOC (MAX_BUFFER_SIZE);
if (-1 ==
- GC_get_configuration_value_number(cfg,
- "GNUNET-TRACEKIT",
- "FORMAT",
- 0,
- 2,
- 0,
- &format)) {
- printf(_("Format specification invalid. "
- "Use 0 for user-readable, 1 for dot, 2 for vcg.\n"));
- SEMAPHORE_UP(doneSem);
- FREE(peersResponding);
- FREE(peersSeen);
- FREE(buffer);
- return NULL;
- }
+ GC_get_configuration_value_number (cfg,
+ "GNUNET-TRACEKIT",
+ "FORMAT", 0, 2, 0, &format))
+ {
+ printf (_("Format specification invalid. "
+ "Use 0 for user-readable, 1 for dot, 2 for vcg.\n"));
+ SEMAPHORE_UP (doneSem);
+ FREE (peersResponding);
+ FREE (peersSeen);
+ FREE (buffer);
+ return NULL;
+ }
if (format == 1)
- printf("digraph G {\n");
+ printf ("digraph G {\n");
if (format == 2)
- printf("graph: {\n");
- while (OK == connection_read(sock,
- (MESSAGE_HEADER**)&buffer)) {
- int count;
- EncName enc;
+ printf ("graph: {\n");
+ while (OK == connection_read (sock, (MESSAGE_HEADER **) & buffer))
+ {
+ int count;
+ EncName enc;
- count = ntohs(buffer->header.size) - sizeof(CS_tracekit_reply_MESSAGE);
- if (count < 0) {
- GE_BREAK(ectx, 0);
- break; /* faulty reply */
- }
- hash2enc(&buffer->responderId.hashPubKey,
- &enc);
- match = NO;
- for (j=0;j<prCount;j++)
- if (equalsHashCode512(&buffer->responderId.hashPubKey,
- &peersResponding[j].hashPubKey))
- match = YES;
- if (match == NO) {
- if (prCount == prSize)
- GROW(peersResponding,
- prSize,
- prSize*2);
- memcpy(&peersResponding[prCount++],
- &buffer->responderId.hashPubKey,
- sizeof(PeerIdentity));
- }
- count = count / sizeof(PeerIdentity);
- if (ntohs(buffer->header.size) !=
- sizeof(CS_tracekit_reply_MESSAGE) +
- count * sizeof(PeerIdentity)) {
- GE_BREAK(ectx, 0);
- break;
- }
- if (count == 0) {
- switch (format) {
- case 0:
- printf(_("`%s' is not connected to any peer.\n"),
- (char*)&enc);
- break;
- case 1:
- printf(" %.*s;\n",
- 4, (char*)&enc);
- break;
- case 2:
- /* deferred -- vcg needs all node data in one line */
- break;
- }
- } else {
- EncName other;
+ count =
+ ntohs (buffer->header.size) - sizeof (CS_tracekit_reply_MESSAGE);
+ if (count < 0)
+ {
+ GE_BREAK (ectx, 0);
+ break; /* faulty reply */
+ }
+ hash2enc (&buffer->responderId.hashPubKey, &enc);
+ match = NO;
+ for (j = 0; j < prCount; j++)
+ if (equalsHashCode512 (&buffer->responderId.hashPubKey,
+ &peersResponding[j].hashPubKey))
+ match = YES;
+ if (match == NO)
+ {
+ if (prCount == prSize)
+ GROW (peersResponding, prSize, prSize * 2);
+ memcpy (&peersResponding[prCount++],
+ &buffer->responderId.hashPubKey, sizeof (PeerIdentity));
+ }
+ count = count / sizeof (PeerIdentity);
+ if (ntohs (buffer->header.size) !=
+ sizeof (CS_tracekit_reply_MESSAGE) + count * sizeof (PeerIdentity))
+ {
+ GE_BREAK (ectx, 0);
+ break;
+ }
+ if (count == 0)
+ {
+ switch (format)
+ {
+ case 0:
+ printf (_("`%s' is not connected to any peer.\n"),
+ (char *) &enc);
+ break;
+ case 1:
+ printf (" %.*s;\n", 4, (char *) &enc);
+ break;
+ case 2:
+ /* deferred -- vcg needs all node data in one line */
+ break;
+ }
+ }
+ else
+ {
+ EncName other;
- for (i=0;i<count;i++) {
- match = NO;
- for (j=0;j<psCount;j++)
- if
(equalsHashCode512(&((CS_tracekit_reply_MESSAGE_GENERIC*)buffer)->peerList[i].hashPubKey,
- &peersSeen[j].hashPubKey))
- match = YES;
- if (match == NO) {
- if (psCount == psSize)
- GROW(peersSeen,
- psSize,
- psSize * 2);
- memcpy(&peersSeen[psCount++],
- &((CS_tracekit_reply_MESSAGE_GENERIC*)buffer)->peerList[i].hashPubKey,
- sizeof(PeerIdentity));
- }
+ for (i = 0; i < count; i++)
+ {
+ match = NO;
+ for (j = 0; j < psCount; j++)
+ if (equalsHashCode512
+ (&((CS_tracekit_reply_MESSAGE_GENERIC *) buffer)->
+ peerList[i].hashPubKey, &peersSeen[j].hashPubKey))
+ match = YES;
+ if (match == NO)
+ {
+ if (psCount == psSize)
+ GROW (peersSeen, psSize, psSize * 2);
+ memcpy (&peersSeen[psCount++],
+ &((CS_tracekit_reply_MESSAGE_GENERIC *) buffer)->
+ peerList[i].hashPubKey, sizeof (PeerIdentity));
+ }
-
hash2enc(&((CS_tracekit_reply_MESSAGE_GENERIC*)buffer)->peerList[i].hashPubKey,
- &other);
- switch (format) {
- case 0:
- printf(_("`%s' connected to `%s'.\n"),
- (char*)&enc,
- (char*)&other);
- break;
- case 1: /* dot */
- printf(" \"%.*s\" -> \"%.*s\";\n",
- 4, (char*)&enc,
- 4, (char*)&other);
- break;
- case 2: /* vcg */
- printf("\tedge: { sourcename: \"%s\" targetname: \"%s\" }\n",
- (char*)&enc,
- (char*)&other);
- break;
- default: /* undef */
- printf(_("Format specification invalid. "
- "Use 0 for user-readable, 1 for dot\n"));
- break;
- }
- }
+ hash2enc (&((CS_tracekit_reply_MESSAGE_GENERIC *) buffer)->
+ peerList[i].hashPubKey, &other);
+ switch (format)
+ {
+ case 0:
+ printf (_("`%s' connected to `%s'.\n"),
+ (char *) &enc, (char *) &other);
+ break;
+ case 1: /* dot */
+ printf (" \"%.*s\" -> \"%.*s\";\n",
+ 4, (char *) &enc, 4, (char *) &other);
+ break;
+ case 2: /* vcg */
+ printf
+ ("\tedge: { sourcename: \"%s\" targetname: \"%s\" }\n",
+ (char *) &enc, (char *) &other);
+ break;
+ default: /* undef */
+ printf (_("Format specification invalid. "
+ "Use 0 for user-readable, 1 for dot\n"));
+ break;
+ }
+ }
+ }
}
- }
- FREE(buffer);
- for (i=0;i<psCount;i++) {
- EncName enc;
+ FREE (buffer);
+ for (i = 0; i < psCount; i++)
+ {
+ EncName enc;
- match = NO;
- for (j=0;j<prCount;j++)
- if (equalsHashCode512(&peersResponding[j].hashPubKey,
- &peersSeen[i].hashPubKey)) {
- match = YES;
- break;
- }
- if (match == NO) {
- hash2enc(&peersSeen[i].hashPubKey,
- &enc);
- switch (format) {
- case 0:
- printf(_("Peer `%s' did not report back.\n"),
- (char*)&enc);
- break;
- case 1:
- printf(" \"%.*s\" [style=filled,color=\".7 .3 1.0\"];\n",
- 4,
- (char*)&enc);
- break;
- case 2:
- printf("\tnode: { title: \"%s\" label: \"%.*s\" shape: \"ellipse\" }\n",
- (char*)&enc,
- 4, (char*) &enc);
- break;
- default:
- break;
- }
- } else {
- switch (format) {
- case 2:
- hash2enc(&peersSeen[i].hashPubKey,
- &enc);
- printf("\tnode: { title: \"%s\" label: \"%.*s\" }\n",
- (char*)&enc, 4, (char*)&enc);
- break;
- default:
- break;
- }
+ match = NO;
+ for (j = 0; j < prCount; j++)
+ if (equalsHashCode512 (&peersResponding[j].hashPubKey,
+ &peersSeen[i].hashPubKey))
+ {
+ match = YES;
+ break;
+ }
+ if (match == NO)
+ {
+ hash2enc (&peersSeen[i].hashPubKey, &enc);
+ switch (format)
+ {
+ case 0:
+ printf (_("Peer `%s' did not report back.\n"), (char *) &enc);
+ break;
+ case 1:
+ printf (" \"%.*s\" [style=filled,color=\".7 .3 1.0\"];\n",
+ 4, (char *) &enc);
+ break;
+ case 2:
+ printf
+ ("\tnode: { title: \"%s\" label: \"%.*s\" shape: \"ellipse\"
}\n",
+ (char *) &enc, 4, (char *) &enc);
+ break;
+ default:
+ break;
+ }
+ }
+ else
+ {
+ switch (format)
+ {
+ case 2:
+ hash2enc (&peersSeen[i].hashPubKey, &enc);
+ printf ("\tnode: { title: \"%s\" label: \"%.*s\" }\n",
+ (char *) &enc, 4, (char *) &enc);
+ break;
+ default:
+ break;
+ }
+ }
}
- }
- if (psCount == 0) {
- switch (format) {
- case 2:
- printf("\tnode: { title: \"NO CONNECTIONS\" }\n");
- break;
- default:
- break;
+ if (psCount == 0)
+ {
+ switch (format)
+ {
+ case 2:
+ printf ("\tnode: { title: \"NO CONNECTIONS\" }\n");
+ break;
+ default:
+ break;
+ }
}
- }
if (format == 1)
- printf("}\n");
+ printf ("}\n");
if (format == 2)
- printf("}\n");
- SEMAPHORE_UP(doneSem);
- FREE(peersResponding);
- FREE(peersSeen);
+ printf ("}\n");
+ SEMAPHORE_UP (doneSem);
+ FREE (peersResponding);
+ FREE (peersSeen);
return NULL;
}
@@ -285,85 +288,69 @@
* @param argv command line arguments
* @return return value from gnunet-tracekit: 0: ok, -1: error
*/
-int main(int argc,
- char * const * argv) {
- struct ClientServerConnection * sock;
- struct PTHREAD * messageReceiveThread;
- void * unused;
+int
+main (int argc, char *const *argv)
+{
+ struct ClientServerConnection *sock;
+ struct PTHREAD *messageReceiveThread;
+ void *unused;
CS_tracekit_probe_MESSAGE probe;
int sleepTime;
- struct GE_Context * ectx;
- struct CronManager * cron;
+ struct GE_Context *ectx;
+ struct CronManager *cron;
int res;
- res = GNUNET_init(argc,
- argv,
- "gnunet-tracekit",
- &cfgFilename,
- gnunettracekitOptions,
- &ectx,
- &cfg);
- if (res == -1) {
- GNUNET_fini(ectx, cfg);
- return -1;
- }
- sock = client_connection_create(ectx, cfg);
- if (sock == NULL) {
- fprintf(stderr,
- _("Error establishing connection with gnunetd.\n"));
- GNUNET_fini(ectx, cfg);
- return 1;
- }
+ res = GNUNET_init (argc,
+ argv,
+ "gnunet-tracekit",
+ &cfgFilename, gnunettracekitOptions, &ectx, &cfg);
+ if (res == -1)
+ {
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
+ sock = client_connection_create (ectx, cfg);
+ if (sock == NULL)
+ {
+ fprintf (stderr, _("Error establishing connection with gnunetd.\n"));
+ GNUNET_fini (ectx, cfg);
+ return 1;
+ }
- doneSem = SEMAPHORE_CREATE(0);
- messageReceiveThread = PTHREAD_CREATE(&receiveThread,
- sock,
- 128 * 1024);
+ doneSem = SEMAPHORE_CREATE (0);
+ messageReceiveThread = PTHREAD_CREATE (&receiveThread, sock, 128 * 1024);
if (messageReceiveThread == NULL)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_IMMEDIATE | GE_ADMIN,
- "pthread_create");
+ GE_DIE_STRERROR (ectx,
+ GE_FATAL | GE_IMMEDIATE | GE_ADMIN, "pthread_create");
- probe.header.size
- = htons(sizeof(CS_tracekit_probe_MESSAGE));
- probe.header.type
- = htons(CS_PROTO_tracekit_PROBE);
+ probe.header.size = htons (sizeof (CS_tracekit_probe_MESSAGE));
+ probe.header.type = htons (CS_PROTO_tracekit_PROBE);
probe.hops
- = htonl(getConfigurationInt("GNUNET-TRACEKIT",
- "HOPS",
- 0xFFFFFFFF));
+ = htonl (getConfigurationInt ("GNUNET-TRACEKIT", "HOPS", 0xFFFFFFFF));
probe.priority
- = htonl(getConfigurationInt("GNUNET-TRACEKIT",
- "PRIORITY",
- 0xFFFFFFFF));
- if (SYSERR == connection_write(sock,
- &probe.header)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Could not send request to gnunetd.\n"));
- return -1;
- }
- cron = cron_create(ectx);
- cron_start(cron);
- sleepTime = getConfigurationInt("GNUNET-TRACEKIT",
- "WAIT",
- 0xFFFFFFFF);
+ = htonl (getConfigurationInt ("GNUNET-TRACEKIT", "PRIORITY", 0xFFFFFFFF));
+ if (SYSERR == connection_write (sock, &probe.header))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Could not send request to gnunetd.\n"));
+ return -1;
+ }
+ cron = cron_create (ectx);
+ cron_start (cron);
+ sleepTime = getConfigurationInt ("GNUNET-TRACEKIT", "WAIT", 0xFFFFFFFF);
if (sleepTime == 0)
sleepTime = 5;
- cron_add_job(cron,
- &run_shutdown,
- cronSECONDS * sleepTime,
- 0,
- NULL);
- GNUNET_SHUTDOWN_WAITFOR();
- connection_close_forever(sock);
- SEMAPHORE_DOWN(doneSem, YES);
- SEMAPHORE_DESTROY(doneSem);
- PTHREAD_JOIN(messageReceiveThread, &unused);
- connection_destroy(sock);
- cron_stop(cron);
- cron_destroy(cron);
- GNUNET_fini(ectx, cfg);
+ cron_add_job (cron, &run_shutdown, cronSECONDS * sleepTime, 0, NULL);
+ GNUNET_SHUTDOWN_WAITFOR ();
+ connection_close_forever (sock);
+ SEMAPHORE_DOWN (doneSem, YES);
+ SEMAPHORE_DESTROY (doneSem);
+ PTHREAD_JOIN (messageReceiveThread, &unused);
+ connection_destroy (sock);
+ cron_stop (cron);
+ cron_destroy (cron);
+ GNUNET_fini (ectx, cfg);
return 0;
}
Modified: GNUnet/src/applications/tracekit/tracekit.c
===================================================================
--- GNUnet/src/applications/tracekit/tracekit.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/tracekit/tracekit.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -29,17 +29,18 @@
#include "gnunet_protocols.h"
#include "tracekit.h"
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
static unsigned int clientCount;
-static struct ClientHandle ** clients;
+static struct ClientHandle **clients;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-typedef struct {
+typedef struct
+{
PeerIdentity initiator;
PeerIdentity replyTo;
TIME_T timestamp;
@@ -48,139 +49,144 @@
#define MAXROUTE 64
-static RTE * routeTable[MAXROUTE];
+static RTE *routeTable[MAXROUTE];
-static int handlep2pReply(const PeerIdentity * sender,
- const MESSAGE_HEADER * message) {
+static int
+handlep2pReply (const PeerIdentity * sender, const MESSAGE_HEADER * message)
+{
unsigned int i;
unsigned int hostCount;
- P2P_tracekit_reply_MESSAGE * reply;
+ P2P_tracekit_reply_MESSAGE *reply;
EncName initiator;
EncName sen;
- hash2enc(&sender->hashPubKey,
- &sen);
- hostCount =
(ntohs(message->size)-sizeof(P2P_tracekit_reply_MESSAGE))/sizeof(PeerIdentity);
- if (ntohs(message->size) !=
- sizeof(P2P_tracekit_reply_MESSAGE)+hostCount*sizeof(PeerIdentity)) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Received invalid `%s' message from `%s'.\n"),
- "P2P_tracekit_probe_MESSAGE",
- &sen);
- return SYSERR;
- }
- reply = (P2P_tracekit_reply_MESSAGE*)message;
- hash2enc(&reply->initiatorId.hashPubKey,
- &initiator);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT: Sending reply back to initiator `%s'.\n",
- &initiator);
- MUTEX_LOCK(lock);
- for (i=0;i<MAXROUTE;i++) {
- if (routeTable[i] == NULL)
- continue;
- if ( (routeTable[i]->timestamp ==
(TIME_T)ntohl(reply->initiatorTimestamp)) &&
- (0 == memcmp(&routeTable[i]->initiator.hashPubKey,
- &reply->initiatorId.hashPubKey,
- sizeof(HashCode512)) ) ) {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT: found matching entry in routing table\n");
- if (0 == memcmp(&coreAPI->myIdentity->hashPubKey,
- &routeTable[i]->replyTo.hashPubKey,
- sizeof(HashCode512)) ) {
- unsigned int idx;
- CS_tracekit_reply_MESSAGE * csReply;
+ hash2enc (&sender->hashPubKey, &sen);
+ hostCount =
+ (ntohs (message->size) -
+ sizeof (P2P_tracekit_reply_MESSAGE)) / sizeof (PeerIdentity);
+ if (ntohs (message->size) !=
+ sizeof (P2P_tracekit_reply_MESSAGE) + hostCount * sizeof (PeerIdentity))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Received invalid `%s' message from `%s'.\n"),
+ "P2P_tracekit_probe_MESSAGE", &sen);
+ return SYSERR;
+ }
+ reply = (P2P_tracekit_reply_MESSAGE *) message;
+ hash2enc (&reply->initiatorId.hashPubKey, &initiator);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "TRACEKIT: Sending reply back to initiator `%s'.\n", &initiator);
+ MUTEX_LOCK (lock);
+ for (i = 0; i < MAXROUTE; i++)
+ {
+ if (routeTable[i] == NULL)
+ continue;
+ if ((routeTable[i]->timestamp ==
+ (TIME_T) ntohl (reply->initiatorTimestamp))
+ && (0 ==
+ memcmp (&routeTable[i]->initiator.hashPubKey,
+ &reply->initiatorId.hashPubKey, sizeof (HashCode512))))
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "TRACEKIT: found matching entry in routing table\n");
+ if (0 == memcmp (&coreAPI->myIdentity->hashPubKey,
+ &routeTable[i]->replyTo.hashPubKey,
+ sizeof (HashCode512)))
+ {
+ unsigned int idx;
+ CS_tracekit_reply_MESSAGE *csReply;
- idx = ntohl(reply->clientId);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT: I am initiator, sending to client.\n");
- if (idx >= clientCount) {
- GE_BREAK(ectx, 0);
- continue; /* discard */
- }
- if (clients[idx] == NULL) {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT: received response on slot %u, but client already exited.\n",
- idx);
- continue; /* discard */
- }
+ idx = ntohl (reply->clientId);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "TRACEKIT: I am initiator, sending to client.\n");
+ if (idx >= clientCount)
+ {
+ GE_BREAK (ectx, 0);
+ continue; /* discard */
+ }
+ if (clients[idx] == NULL)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "TRACEKIT: received response on slot %u, but client
already exited.\n",
+ idx);
+ continue; /* discard */
+ }
- csReply =
MALLOC(sizeof(CS_tracekit_reply_MESSAGE)+hostCount*sizeof(PeerIdentity));
- /* build msg */
- csReply->header.size
- = htons(sizeof(CS_tracekit_reply_MESSAGE)+hostCount*sizeof(PeerIdentity));
- csReply->header.type
- = htons(CS_PROTO_tracekit_REPLY);
- csReply->responderId
- = reply->responderId;
- memcpy(&((CS_tracekit_reply_MESSAGE_GENERIC*)csReply)->peerList[0],
- &((P2P_tracekit_reply_MESSAGE_GENERIC*)reply)->peerList[0],
- hostCount * sizeof(PeerIdentity));
- coreAPI->sendToClient(clients[idx],
- &csReply->header);
- FREE(csReply);
- } else {
- EncName hop;
+ csReply =
+ MALLOC (sizeof (CS_tracekit_reply_MESSAGE) +
+ hostCount * sizeof (PeerIdentity));
+ /* build msg */
+ csReply->header.size
+ =
+ htons (sizeof (CS_tracekit_reply_MESSAGE) +
+ hostCount * sizeof (PeerIdentity));
+ csReply->header.type = htons (CS_PROTO_tracekit_REPLY);
+ csReply->responderId = reply->responderId;
+ memcpy (&((CS_tracekit_reply_MESSAGE_GENERIC *) csReply)->
+ peerList[0],
+ &((P2P_tracekit_reply_MESSAGE_GENERIC *) reply)->
+ peerList[0], hostCount * sizeof (PeerIdentity));
+ coreAPI->sendToClient (clients[idx], &csReply->header);
+ FREE (csReply);
+ }
+ else
+ {
+ EncName hop;
- hash2enc(&routeTable[i]->replyTo.hashPubKey,
- &hop);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT: forwarding to next hop `%s'\n",
- &hop);
- coreAPI->unicast(&routeTable[i]->replyTo,
- message,
- routeTable[i]->priority,
- 0);
- }
+ hash2enc (&routeTable[i]->replyTo.hashPubKey, &hop);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "TRACEKIT: forwarding to next hop `%s'\n", &hop);
+ coreAPI->unicast (&routeTable[i]->replyTo,
+ message, routeTable[i]->priority, 0);
+ }
+ }
}
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return OK;
}
-typedef struct {
- PeerIdentity * peers;
+typedef struct
+{
+ PeerIdentity *peers;
unsigned int max;
int pos;
} Tracekit_Collect_Trace_Closure;
-static void getPeerCallback(const PeerIdentity * id,
- void * cls) {
- Tracekit_Collect_Trace_Closure * closure = cls;
- if (closure->pos == closure->max) {
- GROW(closure->peers,
- closure->max,
- closure->max + 32);
- }
- if (closure->pos < closure->max) {
- /* check needed since #connections may change anytime! */
- closure->peers[closure->pos++] = *id;
- }
+static void
+getPeerCallback (const PeerIdentity * id, void *cls)
+{
+ Tracekit_Collect_Trace_Closure *closure = cls;
+ if (closure->pos == closure->max)
+ {
+ GROW (closure->peers, closure->max, closure->max + 32);
+ }
+ if (closure->pos < closure->max)
+ {
+ /* check needed since #connections may change anytime! */
+ closure->peers[closure->pos++] = *id;
+ }
}
-static void transmit(const PeerIdentity * id,
- void * cls) {
- P2P_tracekit_probe_MESSAGE * pro = cls;
- if (0 != memcmp(id,
- &pro->initiatorId,
- sizeof(PeerIdentity)))
- coreAPI->unicast(id,
- &pro->header,
- ntohl(pro->priority),
- 0);
+static void
+transmit (const PeerIdentity * id, void *cls)
+{
+ P2P_tracekit_probe_MESSAGE *pro = cls;
+ if (0 != memcmp (id, &pro->initiatorId, sizeof (PeerIdentity)))
+ coreAPI->unicast (id, &pro->header, ntohl (pro->priority), 0);
}
-static int handlep2pProbe(const PeerIdentity * sender,
- const MESSAGE_HEADER * message) {
- P2P_tracekit_reply_MESSAGE * reply;
- P2P_tracekit_probe_MESSAGE * msg;
+static int
+handlep2pProbe (const PeerIdentity * sender, const MESSAGE_HEADER * message)
+{
+ P2P_tracekit_reply_MESSAGE *reply;
+ P2P_tracekit_probe_MESSAGE *msg;
Tracekit_Collect_Trace_Closure closure;
int i;
int sel;
@@ -192,294 +198,268 @@
EncName sen;
TIME_T now;
- hash2enc(&sender->hashPubKey,
- &sen);
- if (ntohs(message->size) !=
- sizeof(P2P_tracekit_probe_MESSAGE)) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Received invalid `%s' message from `%s'.\n"),
- "P2P_tracekit_probe_MESSAGE",
- &sen);
- return SYSERR;
- }
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT: received probe\n");
- TIME(&now);
- msg = (P2P_tracekit_probe_MESSAGE*) message;
- if ((TIME_T)ntohl(msg->timestamp) > 3600 + now) {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT: probe has timestamp in the far future (%d > %d), dropping\n",
- ntohl(msg->timestamp),
- 3600 + now);
- return SYSERR; /* Timestamp is more than 1h in the future. Invalid! */
- }
- hash2enc(&msg->initiatorId.hashPubKey,
- &init);
- MUTEX_LOCK(lock);
+ hash2enc (&sender->hashPubKey, &sen);
+ if (ntohs (message->size) != sizeof (P2P_tracekit_probe_MESSAGE))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Received invalid `%s' message from `%s'.\n"),
+ "P2P_tracekit_probe_MESSAGE", &sen);
+ return SYSERR;
+ }
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "TRACEKIT: received probe\n");
+ TIME (&now);
+ msg = (P2P_tracekit_probe_MESSAGE *) message;
+ if ((TIME_T) ntohl (msg->timestamp) > 3600 + now)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "TRACEKIT: probe has timestamp in the far future (%d > %d),
dropping\n",
+ ntohl (msg->timestamp), 3600 + now);
+ return SYSERR; /* Timestamp is more than 1h in the future.
Invalid! */
+ }
+ hash2enc (&msg->initiatorId.hashPubKey, &init);
+ MUTEX_LOCK (lock);
/* test if already processed */
- for (i=0;i<MAXROUTE;i++) {
- if (routeTable[i] == NULL)
- continue;
- if ( (routeTable[i]->timestamp == (TIME_T)ntohl(msg->timestamp)) &&
- 0 == memcmp(&routeTable[i]->initiator.hashPubKey,
- &msg->initiatorId.hashPubKey,
- sizeof(HashCode512)) ) {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT-PROBE %d from `%s' received twice (slot %d), ignored\n",
- ntohl(msg->timestamp),
- &init,
- i);
- MUTEX_UNLOCK(lock);
- return OK;
+ for (i = 0; i < MAXROUTE; i++)
+ {
+ if (routeTable[i] == NULL)
+ continue;
+ if ((routeTable[i]->timestamp == (TIME_T) ntohl (msg->timestamp)) &&
+ 0 == memcmp (&routeTable[i]->initiator.hashPubKey,
+ &msg->initiatorId.hashPubKey, sizeof (HashCode512)))
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "TRACEKIT-PROBE %d from `%s' received twice (slot %d),
ignored\n",
+ ntohl (msg->timestamp), &init, i);
+ MUTEX_UNLOCK (lock);
+ return OK;
+ }
}
- }
/* no, find and kill oldest entry */
- oldest = ntohl(msg->timestamp);
+ oldest = ntohl (msg->timestamp);
sel = -1;
- for (i=0;i<MAXROUTE;i++) {
- if (routeTable[i] == NULL) {
- sel = i;
- oldest = 0;
- continue;
+ for (i = 0; i < MAXROUTE; i++)
+ {
+ if (routeTable[i] == NULL)
+ {
+ sel = i;
+ oldest = 0;
+ continue;
+ }
+ if (oldest > routeTable[i]->timestamp)
+ {
+ oldest = routeTable[i]->timestamp;
+ sel = i;
+ }
+ if (routeTable[i]->timestamp < now - 3600)
+ {
+ /* side-effect: drop very old entries */
+ FREE (routeTable[i]);
+ routeTable[i] = NULL;
+ }
}
- if (oldest > routeTable[i]->timestamp) {
- oldest = routeTable[i]->timestamp;
- sel = i;
+ if (sel == -1)
+ {
+ MUTEX_UNLOCK (lock);
+ GE_LOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ _("TRACEKIT: routing table full, trace request dropped\n"));
+ return OK;
}
- if (routeTable[i]->timestamp < now - 3600) {
- /* side-effect: drop very old entries */
- FREE(routeTable[i]);
- routeTable[i] = NULL;
- }
- }
- if (sel == -1) {
- MUTEX_UNLOCK(lock);
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- _("TRACEKIT: routing table full, trace request dropped\n"));
- return OK;
- }
if (routeTable[sel] == NULL)
- routeTable[sel] = MALLOC(sizeof(RTE));
- routeTable[sel]->timestamp
- = ntohl(msg->timestamp);
- routeTable[sel]->priority
- = ntohl(msg->priority);
- routeTable[sel]->initiator
- = msg->initiatorId;
- routeTable[sel]->replyTo
- = *sender;
- MUTEX_UNLOCK(lock);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT-PROBE started at %d by peer `%s' received, processing in slot %d
with %u hops\n",
- ntohl(msg->timestamp),
- &init,
- sel,
- ntohl(msg->hopsToGo));
- hops = ntohl(msg->hopsToGo);
+ routeTable[sel] = MALLOC (sizeof (RTE));
+ routeTable[sel]->timestamp = ntohl (msg->timestamp);
+ routeTable[sel]->priority = ntohl (msg->priority);
+ routeTable[sel]->initiator = msg->initiatorId;
+ routeTable[sel]->replyTo = *sender;
+ MUTEX_UNLOCK (lock);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "TRACEKIT-PROBE started at %d by peer `%s' received, processing in
slot %d with %u hops\n",
+ ntohl (msg->timestamp), &init, sel, ntohl (msg->hopsToGo));
+ hops = ntohl (msg->hopsToGo);
/* forward? */
- if (hops > 0) {
- msg->hopsToGo = htonl(hops-1);
- coreAPI->forAllConnectedNodes(&transmit,
- msg);
- }
+ if (hops > 0)
+ {
+ msg->hopsToGo = htonl (hops - 1);
+ coreAPI->forAllConnectedNodes (&transmit, msg);
+ }
closure.peers = NULL;
closure.max = 0;
closure.pos = 0;
- coreAPI->forAllConnectedNodes(&getPeerCallback,
- &closure);
+ coreAPI->forAllConnectedNodes (&getPeerCallback, &closure);
/* build local reply */
- while (closure.pos > 0) {
- count = closure.pos;
- if (count > 60000 / sizeof(PeerIdentity))
- count = 60000 / sizeof(PeerIdentity);
- size = sizeof(P2P_tracekit_reply_MESSAGE) + count*sizeof(PeerIdentity);
- reply = MALLOC(size);
- reply->header.size
- = htons(size);
- reply->header.type
- = htons(P2P_PROTO_tracekit_REPLY);
- reply->initiatorId
- = msg->initiatorId;
- reply->responderId
- = *(coreAPI->myIdentity);
- reply->initiatorTimestamp
- = msg->timestamp;
- reply->clientId
- = msg->clientId;
- memcpy(&reply[1],
- &closure.peers[closure.pos - count],
- count * sizeof(PeerIdentity));
- if (equalsHashCode512(&coreAPI->myIdentity->hashPubKey,
- &sender->hashPubKey)) {
- handlep2pReply(coreAPI->myIdentity,
- &reply->header);
- } else {
- coreAPI->unicast(sender,
- &reply->header,
- ntohl(msg->priority),
- 0);
+ while (closure.pos > 0)
+ {
+ count = closure.pos;
+ if (count > 60000 / sizeof (PeerIdentity))
+ count = 60000 / sizeof (PeerIdentity);
+ size =
+ sizeof (P2P_tracekit_reply_MESSAGE) + count * sizeof (PeerIdentity);
+ reply = MALLOC (size);
+ reply->header.size = htons (size);
+ reply->header.type = htons (P2P_PROTO_tracekit_REPLY);
+ reply->initiatorId = msg->initiatorId;
+ reply->responderId = *(coreAPI->myIdentity);
+ reply->initiatorTimestamp = msg->timestamp;
+ reply->clientId = msg->clientId;
+ memcpy (&reply[1],
+ &closure.peers[closure.pos - count],
+ count * sizeof (PeerIdentity));
+ if (equalsHashCode512 (&coreAPI->myIdentity->hashPubKey,
+ &sender->hashPubKey))
+ {
+ handlep2pReply (coreAPI->myIdentity, &reply->header);
+ }
+ else
+ {
+ coreAPI->unicast (sender, &reply->header, ntohl (msg->priority), 0);
+ }
+ closure.pos -= count;
+ FREE (reply);
}
- closure.pos -= count;
- FREE(reply);
- }
- GROW(closure.peers,
- closure.max,
- 0);
+ GROW (closure.peers, closure.max, 0);
return OK;
}
-static int csHandle(struct ClientHandle * client,
- const MESSAGE_HEADER * message) {
+static int
+csHandle (struct ClientHandle *client, const MESSAGE_HEADER * message)
+{
int i;
int idx;
- CS_tracekit_probe_MESSAGE * csProbe;
+ CS_tracekit_probe_MESSAGE *csProbe;
P2P_tracekit_probe_MESSAGE p2pProbe;
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT: client sends probe request\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "TRACEKIT: client sends probe request\n");
/* build probe, broadcast */
- csProbe = (CS_tracekit_probe_MESSAGE*) message;
- if (ntohs(csProbe->header.size) !=
- sizeof(CS_tracekit_probe_MESSAGE) ) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("TRACEKIT: received invalid `%s' message\n"),
- "CS_tracekit_probe_MESSAGE");
- return SYSERR;
- }
+ csProbe = (CS_tracekit_probe_MESSAGE *) message;
+ if (ntohs (csProbe->header.size) != sizeof (CS_tracekit_probe_MESSAGE))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("TRACEKIT: received invalid `%s' message\n"),
+ "CS_tracekit_probe_MESSAGE");
+ return SYSERR;
+ }
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
idx = -1;
- for (i=0;i<clientCount;i++) {
- if (clients[i] == client) {
- idx = i;
- break;
+ for (i = 0; i < clientCount; i++)
+ {
+ if (clients[i] == client)
+ {
+ idx = i;
+ break;
+ }
+ if ((clients[i] == NULL) && (idx == -1))
+ {
+ idx = i;
+ break;
+ }
}
- if ( (clients[i] == NULL) &&
- (idx == -1) ) {
- idx = i;
- break;
+ if (idx == -1)
+ {
+ GROW (clients, clientCount, clientCount + 1);
+ idx = clientCount - 1;
}
- }
- if (idx == -1) {
- GROW(clients,
- clientCount,
- clientCount+1);
- idx = clientCount-1;
- }
clients[idx] = client;
- MUTEX_UNLOCK(lock);
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT: client joins in slot %u.\n",
- idx);
+ MUTEX_UNLOCK (lock);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "TRACEKIT: client joins in slot %u.\n", idx);
- p2pProbe.header.size
- = htons(sizeof(P2P_tracekit_probe_MESSAGE));
- p2pProbe.header.type
- = htons(P2P_PROTO_tracekit_PROBE);
- p2pProbe.clientId
- = htonl(idx);
- p2pProbe.hopsToGo
- = csProbe->hops;
- p2pProbe.timestamp
- = htonl(TIME(NULL));
- p2pProbe.priority
- = csProbe->priority;
- memcpy(&p2pProbe.initiatorId,
- coreAPI->myIdentity,
- sizeof(PeerIdentity));
- handlep2pProbe(coreAPI->myIdentity,
- &p2pProbe.header); /* FIRST send to myself! */
+ p2pProbe.header.size = htons (sizeof (P2P_tracekit_probe_MESSAGE));
+ p2pProbe.header.type = htons (P2P_PROTO_tracekit_PROBE);
+ p2pProbe.clientId = htonl (idx);
+ p2pProbe.hopsToGo = csProbe->hops;
+ p2pProbe.timestamp = htonl (TIME (NULL));
+ p2pProbe.priority = csProbe->priority;
+ memcpy (&p2pProbe.initiatorId, coreAPI->myIdentity, sizeof (PeerIdentity));
+ handlep2pProbe (coreAPI->myIdentity, &p2pProbe.header); /* FIRST send
to myself! */
return OK;
}
-static void clientExitHandler(struct ClientHandle * c) {
+static void
+clientExitHandler (struct ClientHandle *c)
+{
int i;
- MUTEX_LOCK(lock);
- for (i=0;i<clientCount;i++)
- if (clients[i] == c) {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT: client in slot %u exits.\n",
- i);
- clients[i] = NULL;
- break;
- }
- i=clientCount-1;
- while ( (i >= 0) &&
- (clients[i] == NULL) )
+ MUTEX_LOCK (lock);
+ for (i = 0; i < clientCount; i++)
+ if (clients[i] == c)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "TRACEKIT: client in slot %u exits.\n", i);
+ clients[i] = NULL;
+ break;
+ }
+ i = clientCount - 1;
+ while ((i >= 0) && (clients[i] == NULL))
i--;
i++;
if (i != clientCount)
- GROW(clients,
- clientCount,
- i);
- MUTEX_UNLOCK(lock);
+ GROW (clients, clientCount, i);
+ MUTEX_UNLOCK (lock);
}
-int initialize_module_tracekit(CoreAPIForApplication * capi) {
+int
+initialize_module_tracekit (CoreAPIForApplication * capi)
+{
int ok = OK;
ectx = capi->ectx;
- lock = MUTEX_CREATE(NO);
+ lock = MUTEX_CREATE (NO);
coreAPI = capi;
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "TRACEKIT registering handlers %d %d and %d\n",
- P2P_PROTO_tracekit_PROBE,
- P2P_PROTO_tracekit_REPLY,
- CS_PROTO_tracekit_PROBE);
- memset(routeTable,
- 0,
- MAXROUTE*sizeof(RTE*));
- if (SYSERR == capi->registerHandler(P2P_PROTO_tracekit_PROBE,
- &handlep2pProbe))
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "TRACEKIT registering handlers %d %d and %d\n",
+ P2P_PROTO_tracekit_PROBE,
+ P2P_PROTO_tracekit_REPLY, CS_PROTO_tracekit_PROBE);
+ memset (routeTable, 0, MAXROUTE * sizeof (RTE *));
+ if (SYSERR == capi->registerHandler (P2P_PROTO_tracekit_PROBE,
+ &handlep2pProbe))
ok = SYSERR;
- if (SYSERR == capi->registerHandler(P2P_PROTO_tracekit_REPLY,
- &handlep2pReply))
+ if (SYSERR == capi->registerHandler (P2P_PROTO_tracekit_REPLY,
+ &handlep2pReply))
ok = SYSERR;
- if (SYSERR == capi->registerClientExitHandler(&clientExitHandler))
+ if (SYSERR == capi->registerClientExitHandler (&clientExitHandler))
ok = SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_tracekit_PROBE,
- (CSHandler)&csHandle))
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_tracekit_PROBE,
+ (CSHandler) & csHandle))
ok = SYSERR;
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "tracekit",
- gettext_noop("allows mapping of the
network topology")));
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "tracekit",
+ gettext_noop
+ ("allows mapping of the
network topology")));
return ok;
}
-void done_module_tracekit() {
+void
+done_module_tracekit ()
+{
int i;
- coreAPI->unregisterHandler(P2P_PROTO_tracekit_PROBE,
- &handlep2pProbe);
- coreAPI->unregisterHandler(P2P_PROTO_tracekit_REPLY,
- &handlep2pReply);
- coreAPI->unregisterClientExitHandler(&clientExitHandler);
- coreAPI->unregisterClientHandler(CS_PROTO_tracekit_PROBE,
- &csHandle);
- for (i=0;i<MAXROUTE;i++) {
- FREENONNULL(routeTable[i]);
- routeTable[i] = NULL;
- }
- GROW(clients,
- clientCount,
- 0);
- MUTEX_DESTROY(lock);
+ coreAPI->unregisterHandler (P2P_PROTO_tracekit_PROBE, &handlep2pProbe);
+ coreAPI->unregisterHandler (P2P_PROTO_tracekit_REPLY, &handlep2pReply);
+ coreAPI->unregisterClientExitHandler (&clientExitHandler);
+ coreAPI->unregisterClientHandler (CS_PROTO_tracekit_PROBE, &csHandle);
+ for (i = 0; i < MAXROUTE; i++)
+ {
+ FREENONNULL (routeTable[i]);
+ routeTable[i] = NULL;
+ }
+ GROW (clients, clientCount, 0);
+ MUTEX_DESTROY (lock);
lock = NULL;
coreAPI = NULL;
}
Modified: GNUnet/src/applications/tracekit/tracekit.h
===================================================================
--- GNUnet/src/applications/tracekit/tracekit.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/tracekit/tracekit.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -28,7 +28,8 @@
#include "gnunet_core.h"
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -59,7 +60,8 @@
} P2P_tracekit_probe_MESSAGE;
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -87,7 +89,8 @@
} P2P_tracekit_reply_MESSAGE;
-typedef struct {
+typedef struct
+{
P2P_tracekit_reply_MESSAGE p2p_reply;
/**
@@ -98,7 +101,8 @@
} P2P_tracekit_reply_MESSAGE_GENERIC;
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -112,7 +116,8 @@
unsigned int priority;
} CS_tracekit_probe_MESSAGE;
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -123,7 +128,8 @@
} CS_tracekit_reply_MESSAGE;
-typedef struct {
+typedef struct
+{
CS_tracekit_reply_MESSAGE cs_reply;
/**
Modified: GNUnet/src/applications/traffic/clientapi.c
===================================================================
--- GNUnet/src/applications/traffic/clientapi.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/traffic/clientapi.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -43,49 +43,50 @@
* @param peers set to number of peers involved
* @return OK on success, SYSERR on error
*/
-int gnunet_traffic_poll(struct ClientServerConnection * sock,
- unsigned int timeframe,
- unsigned short type,
- unsigned short direction,
- unsigned int * count,
- unsigned int * avg_size,
- unsigned int * peers,
- unsigned int * time) {
- CS_traffic_info_MESSAGE * info;
+int
+gnunet_traffic_poll (struct ClientServerConnection *sock,
+ unsigned int timeframe,
+ unsigned short type,
+ unsigned short direction,
+ unsigned int *count,
+ unsigned int *avg_size,
+ unsigned int *peers, unsigned int *time)
+{
+ CS_traffic_info_MESSAGE *info;
CS_traffic_request_MESSAGE req;
int i;
- req.header.size
- = htons(sizeof(CS_traffic_request_MESSAGE));
- req.header.type
- = htons(CS_PROTO_traffic_QUERY);
- req.timePeriod
- = htonl(timeframe);
- if (SYSERR == connection_write(sock,
- &req.header))
+ req.header.size = htons (sizeof (CS_traffic_request_MESSAGE));
+ req.header.type = htons (CS_PROTO_traffic_QUERY);
+ req.timePeriod = htonl (timeframe);
+ if (SYSERR == connection_write (sock, &req.header))
return SYSERR;
info = NULL;
- if (SYSERR == connection_read(sock,
- (MESSAGE_HEADER**)&info))
+ if (SYSERR == connection_read (sock, (MESSAGE_HEADER **) & info))
return SYSERR;
- if ( (ntohs(info->header.type) !=
- CS_PROTO_traffic_INFO) ||
- (ntohs(info->header.size) !=
- sizeof(CS_traffic_info_MESSAGE) +
ntohl(info->count)*sizeof(TRAFFIC_COUNTER)) ) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
+ if ((ntohs (info->header.type) !=
+ CS_PROTO_traffic_INFO) ||
+ (ntohs (info->header.size) !=
+ sizeof (CS_traffic_info_MESSAGE) +
+ ntohl (info->count) * sizeof (TRAFFIC_COUNTER)))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
- for (i=ntohl(info->count)-1;i>=0;i--) {
- const TRAFFIC_COUNTER * tc =
&((CS_traffic_info_MESSAGE_GENERIC*)info)->counters[i];
- if ((tc->flags & TC_TYPE_MASK) == direction) {
- *count = ntohl(tc->count);
- *avg_size = ntohl(tc->avrg_size);
- *peers = ntohs(tc->flags) & TC_DIVERSITY_MASK;
- *time = ntohl(tc->time_slots);
- } /* end if received */
- } /* end for all counters */
- FREE(info);
+ for (i = ntohl (info->count) - 1; i >= 0; i--)
+ {
+ const TRAFFIC_COUNTER *tc =
+ &((CS_traffic_info_MESSAGE_GENERIC *) info)->counters[i];
+ if ((tc->flags & TC_TYPE_MASK) == direction)
+ {
+ *count = ntohl (tc->count);
+ *avg_size = ntohl (tc->avrg_size);
+ *peers = ntohs (tc->flags) & TC_DIVERSITY_MASK;
+ *time = ntohl (tc->time_slots);
+ } /* end if received */
+ } /* end for all counters */
+ FREE (info);
return OK;
}
Modified: GNUnet/src/applications/traffic/traffic.c
===================================================================
--- GNUnet/src/applications/traffic/traffic.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/traffic/traffic.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -50,7 +50,7 @@
*/
#define HISTORY_SIZE 32
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static int stat_traffic_received_by_type[P2P_PROTO_MAX_USED];
@@ -77,7 +77,8 @@
* Information about when a peer was last involved
* in a message of the given type.
*/
-typedef struct {
+typedef struct
+{
/**
* The ".a" member of the Host identity of the peer.
@@ -94,7 +95,8 @@
/**
* Numbers for one receive/send/self-send type.
*/
-typedef struct {
+typedef struct
+{
/**
* When was this record last updated?
@@ -127,7 +129,8 @@
/**
* Type of the internal traffic counters.
*/
-typedef struct {
+typedef struct
+{
/**
* Statistics for sending
@@ -144,7 +147,7 @@
/**
* Lock to synchronize access.
*/
-static struct MUTEX * lock;
+static struct MUTEX *lock;
/**
* Highest message type seen so far.
@@ -154,23 +157,23 @@
/**
* The actual counters.
*/
-static TrafficCounter ** counters = NULL;
+static TrafficCounter **counters = NULL;
#if DEBUG
static unsigned long long server_port;
#endif
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
/**
* Update the use table dtc. A message of the given
* size was processed interacting with a peer with
* the given peerId.
*/
-static void updateUse(DirectedTrafficCounter * dtc,
- unsigned short size,
- int peerId,
- int expireOnly) {
+static void
+updateUse (DirectedTrafficCounter * dtc,
+ unsigned short size, int peerId, int expireOnly)
+{
cron_t now;
cron_t delta;
unsigned int unitNow;
@@ -180,53 +183,58 @@
unsigned int i;
unsigned int slot;
- now = get_time();
+ now = get_time ();
unitNow = now / TRAFFIC_TIME_UNIT;
delta = now - dtc->lastUpdate;
dtc->lastUpdate = now;
deltaUnits = delta / TRAFFIC_TIME_UNIT;
- if (NO == expireOnly) {
- /* update peer identities */
- minPeerTime = 0;
- minPeerId = 0;
- for (i=0;i<MAX_PEER_IDs;i++) {
- if (dtc->peers[i].time < minPeerTime)
- minPeerId = i;
- if (dtc->peers[i].peerIdentity_a == peerId) {
- minPeerId = i;
- break; /* if the peer is already listed, re-use
- that slot & update the time! */
- }
+ if (NO == expireOnly)
+ {
+ /* update peer identities */
+ minPeerTime = 0;
+ minPeerId = 0;
+ for (i = 0; i < MAX_PEER_IDs; i++)
+ {
+ if (dtc->peers[i].time < minPeerTime)
+ minPeerId = i;
+ if (dtc->peers[i].peerIdentity_a == peerId)
+ {
+ minPeerId = i;
+ break; /* if the peer is already listed, re-use
+ that slot & update the time! */
+ }
+ }
+ dtc->peers[minPeerId].time = unitNow;
+ dtc->peers[minPeerId].peerIdentity_a = peerId;
}
- dtc->peers[minPeerId].time = unitNow;
- dtc->peers[minPeerId].peerIdentity_a = peerId;
- }
/* update expired slots: set appropriate slots to 0 */
if (deltaUnits > HISTORY_SIZE)
deltaUnits = HISTORY_SIZE;
- for (i=0;i<deltaUnits;i++) {
- dtc->count[HS_SLOT(unitNow - HISTORY_SIZE - i)] = 0;
- dtc->avgSize[HS_SLOT(unitNow - HISTORY_SIZE - i)] = 0.0;
- }
+ for (i = 0; i < deltaUnits; i++)
+ {
+ dtc->count[HS_SLOT (unitNow - HISTORY_SIZE - i)] = 0;
+ dtc->avgSize[HS_SLOT (unitNow - HISTORY_SIZE - i)] = 0.0;
+ }
- if (NO == expireOnly) {
- int devideBy;
+ if (NO == expireOnly)
+ {
+ int devideBy;
- /* update slots */
- dtc->slots = 0x80000000 | (dtc->slots >> deltaUnits);
+ /* update slots */
+ dtc->slots = 0x80000000 | (dtc->slots >> deltaUnits);
- /* recompute average, increment count */
- slot = HS_SLOT(unitNow);
- dtc->count[slot]++;
- devideBy = dtc->count[slot];
- if (devideBy <= 0)
- dtc->avgSize[slot] = 0; /* how can this happen? */
- else
- dtc->avgSize[slot]
- = ((dtc->avgSize[slot] * (dtc->count[slot]-1)) + size) / devideBy;
- }
+ /* recompute average, increment count */
+ slot = HS_SLOT (unitNow);
+ dtc->count[slot]++;
+ devideBy = dtc->count[slot];
+ if (devideBy <= 0)
+ dtc->avgSize[slot] = 0; /* how can this happen? */
+ else
+ dtc->avgSize[slot]
+ = ((dtc->avgSize[slot] * (dtc->count[slot] - 1)) + size) / devideBy;
+ }
}
/**
@@ -239,11 +247,12 @@
* the history into consideration (max is HISTORY_SIZE).
* @param msgType what is the type of the message that the dtc is for?
*/
-static void buildSummary(TRAFFIC_COUNTER * res,
- DirectedTrafficCounter * dtc,
- unsigned int tcType,
- unsigned int countTimeUnits,
- unsigned short msgType) {
+static void
+buildSummary (TRAFFIC_COUNTER * res,
+ DirectedTrafficCounter * dtc,
+ unsigned int tcType,
+ unsigned int countTimeUnits, unsigned short msgType)
+{
unsigned int i;
unsigned short peerCount;
cron_t now;
@@ -251,92 +260,95 @@
unsigned int msgCount;
unsigned long long totalMsgSize;
- updateUse(dtc, 0, 0, YES); /* expire old entries */
- now = get_time();
+ updateUse (dtc, 0, 0, YES); /* expire old entries */
+ now = get_time ();
unitNow = now / TRAFFIC_TIME_UNIT;
/* count number of peers that we interacted with in
the last countTimeUnits */
peerCount = 0;
- for (i=0;i<MAX_PEER_IDs;i++)
+ for (i = 0; i < MAX_PEER_IDs; i++)
if (dtc->peers[i].time > now - countTimeUnits)
peerCount++;
- res->flags = htons(tcType|peerCount);
+ res->flags = htons (tcType | peerCount);
/* determine number of messages and average size */
msgCount = 0;
totalMsgSize = 0;
- for (i=0;i<countTimeUnits;i++) {
- unsigned int slot = HS_SLOT(unitNow - i);
- totalMsgSize += dtc->count[slot] * dtc->avgSize[slot];
- msgCount += dtc->count[slot];
- }
+ for (i = 0; i < countTimeUnits; i++)
+ {
+ unsigned int slot = HS_SLOT (unitNow - i);
+ totalMsgSize += dtc->count[slot] * dtc->avgSize[slot];
+ msgCount += dtc->count[slot];
+ }
- res->count = htonl(msgCount);
- res->type = htons(msgType);
+ res->count = htonl (msgCount);
+ res->type = htons (msgType);
if (msgCount > 0)
- res->avrg_size = htonl(totalMsgSize / msgCount);
+ res->avrg_size = htonl (totalMsgSize / msgCount);
else
res->avrg_size = 0;
- res->time_slots = htonl(dtc->slots);
+ res->time_slots = htonl (dtc->slots);
}
/**
* Build a reply message for the client.
*/
-static CS_traffic_info_MESSAGE * buildReply(unsigned int countTimeUnits) {
- CS_traffic_info_MESSAGE * reply;
+static CS_traffic_info_MESSAGE *
+buildReply (unsigned int countTimeUnits)
+{
+ CS_traffic_info_MESSAGE *reply;
unsigned int count;
unsigned int i;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
count = 0;
- for (i=0;i<max_message_type;i++)
- if (counters[i] != NULL) {
- if (counters[i]->send.slots != 0)
- count++;
- if (counters[i]->receive.slots != 0)
- count++;
- }
- reply = MALLOC(sizeof(CS_traffic_info_MESSAGE)+
- count * sizeof(TRAFFIC_COUNTER));
- reply->header.type = htons(CS_PROTO_traffic_INFO);
- reply->header.size = htons(sizeof(CS_traffic_info_MESSAGE)+
- count * sizeof(TRAFFIC_COUNTER));
- reply->count = htonl(count);
+ for (i = 0; i < max_message_type; i++)
+ if (counters[i] != NULL)
+ {
+ if (counters[i]->send.slots != 0)
+ count++;
+ if (counters[i]->receive.slots != 0)
+ count++;
+ }
+ reply = MALLOC (sizeof (CS_traffic_info_MESSAGE) +
+ count * sizeof (TRAFFIC_COUNTER));
+ reply->header.type = htons (CS_PROTO_traffic_INFO);
+ reply->header.size = htons (sizeof (CS_traffic_info_MESSAGE) +
+ count * sizeof (TRAFFIC_COUNTER));
+ reply->count = htonl (count);
count = 0;
- for (i=0;i<max_message_type;i++)
- if (counters[i] != NULL) {
- if (counters[i]->send.slots != 0)
- buildSummary(&((CS_traffic_info_MESSAGE_GENERIC*)reply)->counters[count++],
- &counters[i]->send,
- TC_SENT,
- countTimeUnits,
- i);
- if (counters[i]->receive.slots != 0)
- buildSummary(&((CS_traffic_info_MESSAGE_GENERIC*)reply)->counters[count++],
- &counters[i]->receive,
- TC_RECEIVED,
- countTimeUnits,
- i);
- }
+ for (i = 0; i < max_message_type; i++)
+ if (counters[i] != NULL)
+ {
+ if (counters[i]->send.slots != 0)
+ buildSummary (&((CS_traffic_info_MESSAGE_GENERIC *) reply)->
+ counters[count++], &counters[i]->send, TC_SENT,
+ countTimeUnits, i);
+ if (counters[i]->receive.slots != 0)
+ buildSummary (&((CS_traffic_info_MESSAGE_GENERIC *) reply)->
+ counters[count++], &counters[i]->receive, TC_RECEIVED,
+ countTimeUnits, i);
+ }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return reply;
}
-static int trafficQueryHandler(struct ClientHandle * sock,
- const MESSAGE_HEADER * message) {
- const CS_traffic_request_MESSAGE * msg;
- CS_traffic_info_MESSAGE * reply;
+static int
+trafficQueryHandler (struct ClientHandle *sock,
+ const MESSAGE_HEADER * message)
+{
+ const CS_traffic_request_MESSAGE *msg;
+ CS_traffic_info_MESSAGE *reply;
int ret;
- if (sizeof(CS_traffic_request_MESSAGE) != ntohs(message->size))
+ if (sizeof (CS_traffic_request_MESSAGE) != ntohs (message->size))
return SYSERR;
- msg = (const CS_traffic_request_MESSAGE*) message;
- reply = buildReply(ntohl(msg->timePeriod));
- ret = coreAPI->sendToClient(sock, &reply->header);
- FREE(reply);
+ msg = (const CS_traffic_request_MESSAGE *) message;
+ reply = buildReply (ntohl (msg->timePeriod));
+ ret = coreAPI->sendToClient (sock, &reply->header);
+ FREE (reply);
return ret;
}
@@ -356,57 +368,59 @@
* highest bit is current time-unit, bit 1 is 32 time-units ago (set)
* @return OK on success, SYSERR on error
*/
-static int getTrafficStats(unsigned int timePeriod,
- unsigned short messageType,
- unsigned short sendReceive,
- unsigned int * messageCount,
- unsigned int * peerCount,
- unsigned int * avgMessageSize,
- unsigned int * timeDistribution) {
- DirectedTrafficCounter * dtc;
+static int
+getTrafficStats (unsigned int timePeriod,
+ unsigned short messageType,
+ unsigned short sendReceive,
+ unsigned int *messageCount,
+ unsigned int *peerCount,
+ unsigned int *avgMessageSize, unsigned int *timeDistribution)
+{
+ DirectedTrafficCounter *dtc;
unsigned int i;
unsigned int nowUnit;
double totSize;
if (timePeriod > HISTORY_SIZE)
timePeriod = HISTORY_SIZE;
- MUTEX_LOCK(lock);
- if ( (messageType >= max_message_type) ||
- (counters[messageType] == NULL) ) {
- *avgMessageSize = 0;
- *messageCount = 0;
- *peerCount = 0;
- *timeDistribution = 0;
- MUTEX_UNLOCK(lock);
- return OK;
- }
+ MUTEX_LOCK (lock);
+ if ((messageType >= max_message_type) || (counters[messageType] == NULL))
+ {
+ *avgMessageSize = 0;
+ *messageCount = 0;
+ *peerCount = 0;
+ *timeDistribution = 0;
+ MUTEX_UNLOCK (lock);
+ return OK;
+ }
if (sendReceive == TC_SENT)
dtc = &counters[messageType]->send;
else
dtc = &counters[messageType]->receive;
- updateUse(dtc, 0, 0, YES);
+ updateUse (dtc, 0, 0, YES);
- nowUnit = get_time() / TRAFFIC_TIME_UNIT;
+ nowUnit = get_time () / TRAFFIC_TIME_UNIT;
*peerCount = 0;
*messageCount = 0;
totSize = 0;
- for (i=0;i<MAX_PEER_IDs;i++)
+ for (i = 0; i < MAX_PEER_IDs; i++)
if (dtc->peers[i].time > nowUnit - timePeriod)
(*peerCount)++;
- for (i=0;i<timePeriod;i++) {
- unsigned int slot;
+ for (i = 0; i < timePeriod; i++)
+ {
+ unsigned int slot;
- slot = HS_SLOT(nowUnit-i);
- (*messageCount) += dtc->count[slot];
- totSize += dtc->count[slot] * dtc->avgSize[slot];
- }
- if (*messageCount>0)
+ slot = HS_SLOT (nowUnit - i);
+ (*messageCount) += dtc->count[slot];
+ totSize += dtc->count[slot] * dtc->avgSize[slot];
+ }
+ if (*messageCount > 0)
*avgMessageSize = (unsigned short) (totSize / (*messageCount));
else
*avgMessageSize = 0;
*timeDistribution = dtc->slots;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return OK;
}
@@ -416,74 +430,68 @@
* size and a valid traffic counter allocated for the
* given port.
*/
-static void checkPort(unsigned short port) {
+static void
+checkPort (unsigned short port)
+{
if (port >= max_message_type)
- GROW(counters,
- max_message_type,
- port + 1);
- if (counters[port] == NULL) {
- counters[port] = MALLOC(sizeof(TrafficCounter));
- memset(counters[port],
- 0,
- sizeof(TrafficCounter));
- }
+ GROW (counters, max_message_type, port + 1);
+ if (counters[port] == NULL)
+ {
+ counters[port] = MALLOC (sizeof (TrafficCounter));
+ memset (counters[port], 0, sizeof (TrafficCounter));
+ }
}
-static void updateTrafficSendCounter(unsigned short ptyp,
- unsigned short plen) {
+static void
+updateTrafficSendCounter (unsigned short ptyp, unsigned short plen)
+{
if (ptyp >= P2P_PROTO_MAX_USED)
- return; /* not tracked */
- if (0 == stat_traffic_transmitted_by_type[ptyp]) {
- char * s;
- s = MALLOC(256);
- SNPRINTF(s,
- 256,
- _("# bytes transmitted of type %d"),
- ptyp);
- stat_traffic_transmitted_by_type[ptyp]
- = stats->create(s);
- FREE(s);
- }
- stats->change(stat_traffic_transmitted_by_type[ptyp],
- plen);
+ return; /* not tracked */
+ if (0 == stat_traffic_transmitted_by_type[ptyp])
+ {
+ char *s;
+ s = MALLOC (256);
+ SNPRINTF (s, 256, _("# bytes transmitted of type %d"), ptyp);
+ stat_traffic_transmitted_by_type[ptyp] = stats->create (s);
+ FREE (s);
+ }
+ stats->change (stat_traffic_transmitted_by_type[ptyp], plen);
}
-static void updateTrafficReceiveCounter(unsigned short ptyp,
- unsigned short plen) {
- if (ptyp < P2P_PROTO_MAX_USED) {
- if (0 == stat_traffic_received_by_type[ptyp]) {
- char * s;
- s = MALLOC(256);
- SNPRINTF(s,
- 256,
- _("# bytes received of type %d"),
- ptyp);
- stat_traffic_received_by_type[ptyp]
- = stats->create(s);
- FREE(s);
+static void
+updateTrafficReceiveCounter (unsigned short ptyp, unsigned short plen)
+{
+ if (ptyp < P2P_PROTO_MAX_USED)
+ {
+ if (0 == stat_traffic_received_by_type[ptyp])
+ {
+ char *s;
+ s = MALLOC (256);
+ SNPRINTF (s, 256, _("# bytes received of type %d"), ptyp);
+ stat_traffic_received_by_type[ptyp] = stats->create (s);
+ FREE (s);
+ }
+ stats->change (stat_traffic_received_by_type[ptyp], plen);
}
- stats->change(stat_traffic_received_by_type[ptyp],
- plen);
- }
}
-static void updatePlaintextTrafficReceiveCounter(unsigned short ptyp,
- unsigned short plen) {
- if (ptyp < P2P_PROTO_MAX_USED) {
- if (0 == stat_pt_traffic_received_by_type[ptyp]) {
- char * s;
- s = MALLOC(256);
- SNPRINTF(s,
- 256,
- _("# bytes received in plaintext of type %d"),
- ptyp);
- stat_pt_traffic_received_by_type[ptyp]
- = stats->create(s);
- FREE(s);
+static void
+updatePlaintextTrafficReceiveCounter (unsigned short ptyp,
+ unsigned short plen)
+{
+ if (ptyp < P2P_PROTO_MAX_USED)
+ {
+ if (0 == stat_pt_traffic_received_by_type[ptyp])
+ {
+ char *s;
+ s = MALLOC (256);
+ SNPRINTF (s,
+ 256, _("# bytes received in plaintext of type %d"), ptyp);
+ stat_pt_traffic_received_by_type[ptyp] = stats->create (s);
+ FREE (s);
+ }
+ stats->change (stat_pt_traffic_received_by_type[ptyp], plen);
}
- stats->change(stat_pt_traffic_received_by_type[ptyp],
- plen);
- }
}
/**
@@ -492,20 +500,18 @@
* @param header the header of the message
* @param sender the identity of the sender
*/
-static int trafficReceive(const PeerIdentity * sender,
- const MESSAGE_HEADER * header) {
+static int
+trafficReceive (const PeerIdentity * sender, const MESSAGE_HEADER * header)
+{
unsigned short port;
- port = ntohs(header->type);
- updateTrafficReceiveCounter(port,
- ntohs(header->size));
- MUTEX_LOCK(lock);
- checkPort(port);
- updateUse(&counters[port]->receive,
- ntohs(header->size),
- sender->hashPubKey.bits[0],
- NO);
- MUTEX_UNLOCK(lock);
+ port = ntohs (header->type);
+ updateTrafficReceiveCounter (port, ntohs (header->size));
+ MUTEX_LOCK (lock);
+ checkPort (port);
+ updateUse (&counters[port]->receive,
+ ntohs (header->size), sender->hashPubKey.bits[0], NO);
+ MUTEX_UNLOCK (lock);
return OK;
}
@@ -516,20 +522,19 @@
* @param header the header of the message
* @param receiver the identity of the receiver
*/
-static int trafficSend(const PeerIdentity * receiver,
- const MESSAGE_HEADER * header) {
+static int
+trafficSend (const PeerIdentity * receiver, const MESSAGE_HEADER * header)
+{
unsigned short port;
- port = ntohs(MAKE_UNALIGNED(header->type));
- updateTrafficSendCounter(port,
- ntohs(MAKE_UNALIGNED(header->size)));
- MUTEX_LOCK(lock);
- checkPort(port);
- updateUse(&counters[port]->send,
- ntohs(MAKE_UNALIGNED(header->size)),
- receiver->hashPubKey.bits[0],
- NO);
- MUTEX_UNLOCK(lock);
+ port = ntohs (MAKE_UNALIGNED (header->type));
+ updateTrafficSendCounter (port, ntohs (MAKE_UNALIGNED (header->size)));
+ MUTEX_LOCK (lock);
+ checkPort (port);
+ updateUse (&counters[port]->send,
+ ntohs (MAKE_UNALIGNED (header->size)),
+ receiver->hashPubKey.bits[0], NO);
+ MUTEX_UNLOCK (lock);
return OK;
}
@@ -539,14 +544,16 @@
* @param header the header of the message
* @param receiver the identity of the receiver
*/
-static int plaintextReceive(const PeerIdentity * receiver,
- const MESSAGE_HEADER * header,
- TSession * session) {
+static int
+plaintextReceive (const PeerIdentity * receiver,
+ const MESSAGE_HEADER * header, TSession * session)
+{
unsigned short port;
- port = ntohs(MAKE_UNALIGNED(header->type));
- updatePlaintextTrafficReceiveCounter(port,
- ntohs(MAKE_UNALIGNED(header->size)));
+ port = ntohs (MAKE_UNALIGNED (header->type));
+ updatePlaintextTrafficReceiveCounter (port,
+ ntohs (MAKE_UNALIGNED
+ (header->size)));
return OK;
}
@@ -555,100 +562,101 @@
* Initialize the traffic module.
*/
Traffic_ServiceAPI *
-provide_module_traffic(CoreAPIForApplication * capi) {
+provide_module_traffic (CoreAPIForApplication * capi)
+{
static Traffic_ServiceAPI api;
int i;
coreAPI = capi;
#if DEBUG
- GC_get_configuration_value_number(capi->cfg,
- "NETWORK",
- "PORT",
- 0,
- 65536,
- 2087,
- &server_port);
+ GC_get_configuration_value_number (capi->cfg,
+ "NETWORK",
+ "PORT", 0, 65536, 2087, &server_port);
#endif
api.get = &getTrafficStats;
- for (i=0;i<P2P_PROTO_MAX_USED;i++)
+ for (i = 0; i < P2P_PROTO_MAX_USED; i++)
stat_traffic_transmitted_by_type[i] = 0;
- coreAPI->registerSendNotify(&trafficSend);
- for (i=0;i<P2P_PROTO_MAX_USED;i++) {
- stat_traffic_received_by_type[i] = 0;
- coreAPI->registerHandler(i,
- &trafficReceive);
- coreAPI->registerPlaintextHandler(i,
- &plaintextReceive);
- }
+ coreAPI->registerSendNotify (&trafficSend);
+ for (i = 0; i < P2P_PROTO_MAX_USED; i++)
+ {
+ stat_traffic_received_by_type[i] = 0;
+ coreAPI->registerHandler (i, &trafficReceive);
+ coreAPI->registerPlaintextHandler (i, &plaintextReceive);
+ }
- GE_ASSERT(coreAPI->ectx, counters == NULL);
- lock = MUTEX_CREATE(NO);
- stats = capi->requestService("stats");
+ GE_ASSERT (coreAPI->ectx, counters == NULL);
+ lock = MUTEX_CREATE (NO);
+ stats = capi->requestService ("stats");
return &api;
}
/**
* Shutdown the traffic module.
*/
-void release_module_traffic() {
+void
+release_module_traffic ()
+{
unsigned int i;
- for (i=0;i<P2P_PROTO_MAX_USED;i++) {
- coreAPI->unregisterHandler(i,
- &trafficReceive);
- coreAPI->unregisterPlaintextHandler(i,
- &plaintextReceive);
- }
- coreAPI->unregisterSendNotify(&trafficSend);
- coreAPI->releaseService(stats);
+ for (i = 0; i < P2P_PROTO_MAX_USED; i++)
+ {
+ coreAPI->unregisterHandler (i, &trafficReceive);
+ coreAPI->unregisterPlaintextHandler (i, &plaintextReceive);
+ }
+ coreAPI->unregisterSendNotify (&trafficSend);
+ coreAPI->releaseService (stats);
stats = NULL;
- for (i=0;i<max_message_type;i++)
- FREENONNULL(counters[i]);
- GROW(counters,
- max_message_type,
- 0);
- MUTEX_DESTROY(lock);
+ for (i = 0; i < max_message_type; i++)
+ FREENONNULL (counters[i]);
+ GROW (counters, max_message_type, 0);
+ MUTEX_DESTROY (lock);
lock = NULL;
coreAPI = NULL;
}
-static Traffic_ServiceAPI * myApi;
-static CoreAPIForApplication * myCoreAPI;
+static Traffic_ServiceAPI *myApi;
+static CoreAPIForApplication *myCoreAPI;
/**
* Initialize the traffic module.
*/
-int initialize_module_traffic(CoreAPIForApplication * capi) {
- GE_ASSERT(capi->ectx, myCoreAPI == NULL);
+int
+initialize_module_traffic (CoreAPIForApplication * capi)
+{
+ GE_ASSERT (capi->ectx, myCoreAPI == NULL);
myCoreAPI = capi;
- myApi = capi->requestService("traffic");
- if (myApi == NULL) {
- GE_BREAK(capi->ectx, 0);
- myCoreAPI = NULL;
- return SYSERR;
- }
- capi->registerClientHandler(CS_PROTO_traffic_QUERY,
- &trafficQueryHandler);
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "traffic",
- gettext_noop("tracks bandwidth
utilization by gnunetd")));
- return OK;
+ myApi = capi->requestService ("traffic");
+ if (myApi == NULL)
+ {
+ GE_BREAK (capi->ectx, 0);
+ myCoreAPI = NULL;
+ return SYSERR;
+ }
+ capi->registerClientHandler (CS_PROTO_traffic_QUERY, &trafficQueryHandler);
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "traffic",
+ gettext_noop
+ ("tracks bandwidth
utilization by gnunetd")));
+ return OK;
}
/**
* Shutdown the traffic module.
*/
-void done_module_traffic() {
- GE_ASSERT(NULL, myCoreAPI != NULL);
- GE_ASSERT(myCoreAPI->ectx,
- SYSERR != myCoreAPI->unregisterClientHandler(CS_PROTO_traffic_QUERY,
- &trafficQueryHandler));
- myCoreAPI->releaseService(myApi);
+void
+done_module_traffic ()
+{
+ GE_ASSERT (NULL, myCoreAPI != NULL);
+ GE_ASSERT (myCoreAPI->ectx,
+ SYSERR !=
+ myCoreAPI->unregisterClientHandler (CS_PROTO_traffic_QUERY,
+ &trafficQueryHandler));
+ myCoreAPI->releaseService (myApi);
myApi = NULL;
myCoreAPI = NULL;
}
Modified: GNUnet/src/applications/traffic/traffic.h
===================================================================
--- GNUnet/src/applications/traffic/traffic.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/traffic/traffic.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,7 +30,8 @@
/**
* Counter for traffic.
*/
-typedef struct {
+typedef struct
+{
/**
* Flags. See TC_XXXX definitions.
@@ -69,7 +70,8 @@
* A message of this format is send back to the client
* if it sends a CS_TRAFFIC_QUERY to gnunetd.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -84,7 +86,8 @@
* Generic version of CS_traffic_info_MESSAGE with field for accessing end of
struct
* (use the other version for allocation).
*/
-typedef struct {
+typedef struct
+{
CS_traffic_info_MESSAGE cs_traffic_info;
/**
@@ -97,7 +100,8 @@
/**
* Request for CS_traffic_info_MESSAGE.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
Modified: GNUnet/src/applications/transport/transport.c
===================================================================
--- GNUnet/src/applications/transport/transport.c 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/applications/transport/transport.c 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -36,24 +36,24 @@
static CoreAPIForTransport ctapi;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
/**
* Note that this array MUST not be modified
* (in size/NULLs) after gnunetd has started
* to go multi-threaded!
*/
-static TransportAPI ** tapis = NULL;
+static TransportAPI **tapis = NULL;
static unsigned int tapis_count = 0;
static unsigned long long hello_live;
-static struct MUTEX * tapis_lock;
+static struct MUTEX *tapis_lock;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
#define HELLO_RECREATE_FREQ (5 * cronMINUTES)
@@ -63,45 +63,46 @@
* Create signed hello for this transport and put it into
* the cache tapi->hello.
*/
-static void createSignedhello(void * cls) {
- TransportAPI * tapi = cls;
- MUTEX_LOCK(tapis_lock);
- FREENONNULL(tapi->hello);
- tapi->hello = tapi->createhello();
- if (NULL == tapi->hello) {
- MUTEX_UNLOCK(tapis_lock);
- return;
- }
- memcpy(&tapi->hello->publicKey,
- identity->getPublicPrivateKey(),
- sizeof(PublicKey));
- memcpy(&tapi->hello->senderIdentity,
- coreAPI->myIdentity,
- sizeof(PeerIdentity));
- tapi->hello->expirationTime
- = htonl(TIME(NULL) + hello_live);
- tapi->hello->header.type
- = htons(p2p_PROTO_hello);
- tapi->hello->header.size
- = htons(P2P_hello_MESSAGE_size(tapi->hello));
- if (SYSERR == identity->signData(&(tapi->hello)->senderIdentity,
- P2P_hello_MESSAGE_size(tapi->hello)
- - sizeof(Signature)
- - sizeof(PublicKey)
- - sizeof(MESSAGE_HEADER),
- &tapi->hello->signature)) {
- FREE(tapi->hello);
- tapi->hello = NULL;
- GE_BREAK(ectx, 0);
- }
- MUTEX_UNLOCK(tapis_lock);
+static void
+createSignedhello (void *cls)
+{
+ TransportAPI *tapi = cls;
+ MUTEX_LOCK (tapis_lock);
+ FREENONNULL (tapi->hello);
+ tapi->hello = tapi->createhello ();
+ if (NULL == tapi->hello)
+ {
+ MUTEX_UNLOCK (tapis_lock);
+ return;
+ }
+ memcpy (&tapi->hello->publicKey,
+ identity->getPublicPrivateKey (), sizeof (PublicKey));
+ memcpy (&tapi->hello->senderIdentity,
+ coreAPI->myIdentity, sizeof (PeerIdentity));
+ tapi->hello->expirationTime = htonl (TIME (NULL) + hello_live);
+ tapi->hello->header.type = htons (p2p_PROTO_hello);
+ tapi->hello->header.size = htons (P2P_hello_MESSAGE_size (tapi->hello));
+ if (SYSERR == identity->signData (&(tapi->hello)->senderIdentity,
+ P2P_hello_MESSAGE_size (tapi->hello)
+ - sizeof (Signature)
+ - sizeof (PublicKey)
+ - sizeof (MESSAGE_HEADER),
+ &tapi->hello->signature))
+ {
+ FREE (tapi->hello);
+ tapi->hello = NULL;
+ GE_BREAK (ectx, 0);
+ }
+ MUTEX_UNLOCK (tapis_lock);
}
/**
* Is this transport mechanism available (for sending)?
* @return YES or NO
*/
-static int isTransportAvailable(unsigned short ttype) {
+static int
+isTransportAvailable (unsigned short ttype)
+{
if (ttype >= tapis_count)
return NO;
if (NULL == tapis[ttype])
@@ -112,22 +113,21 @@
/**
* Add an implementation of a transport protocol.
*/
-static int addTransport(TransportAPI * tapi) {
+static int
+addTransport (TransportAPI * tapi)
+{
if (tapi->protocolNumber >= tapis_count)
- GROW(tapis,
- tapis_count,
- tapi->protocolNumber+1);
- if (tapis[tapi->protocolNumber] != NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ GROW (tapis, tapis_count, tapi->protocolNumber + 1);
+ if (tapis[tapi->protocolNumber] != NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
tapis[tapi->protocolNumber] = tapi;
tapi->hello = NULL;
- cron_add_job(coreAPI->cron,
- &createSignedhello,
- HELLO_RECREATE_FREQ,
- HELLO_RECREATE_FREQ,
- tapi);
+ cron_add_job (coreAPI->cron,
+ &createSignedhello,
+ HELLO_RECREATE_FREQ, HELLO_RECREATE_FREQ, tapi);
return OK;
}
@@ -135,23 +135,22 @@
* Convert hello to string.
*/
static int
-helloToAddress(const P2P_hello_MESSAGE * hello,
- void ** sa,
- unsigned int * sa_len) {
+helloToAddress (const P2P_hello_MESSAGE * hello,
+ void **sa, unsigned int *sa_len)
+{
unsigned short prot;
- prot = ntohs(hello->protocol);
- if ( (prot >= tapis_count) ||
- (tapis[prot] == NULL) ) {
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- _("Converting peer address to string failed, transport type %d not
supported\n"),
- ntohs(hello->protocol));
- return SYSERR;
- }
- return tapis[prot]->helloToAddress(hello,
- sa,
- sa_len);
+ prot = ntohs (hello->protocol);
+ if ((prot >= tapis_count) || (tapis[prot] == NULL))
+ {
+ GE_LOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ _
+ ("Converting peer address to string failed, transport type %d
not supported\n"),
+ ntohs (hello->protocol));
+ return SYSERR;
+ }
+ return tapis[prot]->helloToAddress (hello, sa, sa_len);
}
/**
@@ -159,19 +158,22 @@
* @param callback the method to call on each transport API implementation
* @param data second argument to callback
*/
-static int forEachTransport(TransportCallback callback,
- void * data) {
+static int
+forEachTransport (TransportCallback callback, void *data)
+{
int i;
int ret;
ret = 0;
- for (i=0;i<tapis_count;i++) {
- if (tapis[i] != NULL) {
- ret++;
- if (callback != NULL)
- callback(tapis[i], data);
+ for (i = 0; i < tapis_count; i++)
+ {
+ if (tapis[i] != NULL)
+ {
+ ret++;
+ if (callback != NULL)
+ callback (tapis[i], data);
+ }
}
- }
return ret;
}
@@ -184,34 +186,35 @@
* @return session on success, NULL on error
*/
static TSession *
-transportConnect(const P2P_hello_MESSAGE * hello) {
+transportConnect (const P2P_hello_MESSAGE * hello)
+{
unsigned short prot;
- TSession * tsession;
+ TSession *tsession;
- prot = ntohs(hello->protocol);
- if ( (prot >= tapis_count) ||
- (tapis[prot] == NULL) ) {
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER | GE_ADMIN,
- _("Transport connection attempt failed, transport type %d not
supported\n"),
- prot);
- return NULL;
- }
+ prot = ntohs (hello->protocol);
+ if ((prot >= tapis_count) || (tapis[prot] == NULL))
+ {
+ GE_LOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER | GE_ADMIN,
+ _
+ ("Transport connection attempt failed, transport type %d not
supported\n"),
+ prot);
+ return NULL;
+ }
tsession = NULL;
- if (OK != tapis[prot]->connect(hello,
- &tsession))
+ if (OK != tapis[prot]->connect (hello, &tsession))
return NULL;
tsession->ttype = prot;
return tsession;
}
static TSession *
-transportConnectFreely(const PeerIdentity * peer,
- int useTempList) {
+transportConnectFreely (const PeerIdentity * peer, int useTempList)
+{
int i;
- P2P_hello_MESSAGE * hello;
- int * perm;
- TSession * ret;
+ P2P_hello_MESSAGE *hello;
+ int *perm;
+ TSession *ret;
unsigned int hc;
#if DEBUG_TRANSPORT
EncName enc;
@@ -219,35 +222,35 @@
hc = 0;
ret = NULL;
- perm = permute(WEAK, tapis_count);
- for (i=0;i<tapis_count;i++) {
- if (tapis[perm[i]] == NULL)
- continue;
- hello = identity->identity2Hello(peer,
- perm[i],
- useTempList);
- if (hello == NULL)
- continue;
- hc++;
- ret = transportConnect(hello);
- FREE(hello);
- if (ret != NULL) {
- ret->ttype = perm[i];
- break;
+ perm = permute (WEAK, tapis_count);
+ for (i = 0; i < tapis_count; i++)
+ {
+ if (tapis[perm[i]] == NULL)
+ continue;
+ hello = identity->identity2Hello (peer, perm[i], useTempList);
+ if (hello == NULL)
+ continue;
+ hc++;
+ ret = transportConnect (hello);
+ FREE (hello);
+ if (ret != NULL)
+ {
+ ret->ttype = perm[i];
+ break;
+ }
}
- }
- FREE(perm);
- if (ret == NULL) {
+ FREE (perm);
+ if (ret == NULL)
+ {
#if DEBUG_TRANSPORT
- hash2enc(&peer->hashPubKey,
- &enc);
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_ADMIN,
- _("Transport failed to connect to peer `%s' (%u HELLOs known, none
worked)\n"),
- &enc,
- hc);
+ hash2enc (&peer->hashPubKey, &enc);
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_ADMIN,
+ _
+ ("Transport failed to connect to peer `%s' (%u HELLOs known,
none worked)\n"),
+ &enc, hc);
#endif
- }
+ }
return ret;
}
@@ -262,21 +265,23 @@
* @return OK if the session could be associated,
* SYSERR if not.
*/
-static int transportAssociate(TSession * tsession) {
- if ( (tsession == NULL) ||
- (tsession->ttype >= tapis_count) ||
- (tapis[tsession->ttype] == NULL) )
+static int
+transportAssociate (TSession * tsession)
+{
+ if ((tsession == NULL) ||
+ (tsession->ttype >= tapis_count) || (tapis[tsession->ttype] == NULL))
return SYSERR;
- return tapis[tsession->ttype]->associate(tsession);
+ return tapis[tsession->ttype]->associate (tsession);
}
/**
* Get the cost of a message in for the given transport mechanism.
*/
-static unsigned int transportGetCost(int ttype) {
- if ( (ttype >= tapis_count) ||
- (tapis[ttype] == NULL) )
- return SYSERR; /* -1 = INFTY */
+static unsigned int
+transportGetCost (int ttype)
+{
+ if ((ttype >= tapis_count) || (tapis[ttype] == NULL))
+ return SYSERR; /* -1 = INFTY */
return tapis[ttype]->cost;
}
@@ -289,46 +294,47 @@
* @return OK on success, SYSERR on persistent error, NO on
* temporary error
*/
-static int transportSend(TSession * tsession,
- const void * msg,
- unsigned int size,
- int important) {
- if (tsession == NULL) {
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Transmission attempted on uni-directional pipe, failing.\n");
- return SYSERR; /* can't do that, can happen for unidirectional pipes
- that call core with TSession being NULL. */
- }
- if ( (tsession->ttype >= tapis_count) ||
- (tapis[tsession->ttype] == NULL) ) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("Transmission attempt failed, transport type %d unknown.\n"),
- tsession->ttype);
- return SYSERR;
- }
- return tapis[tsession->ttype]->send(tsession,
- msg,
- size,
- important);
+static int
+transportSend (TSession * tsession,
+ const void *msg, unsigned int size, int important)
+{
+ if (tsession == NULL)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Transmission attempted on uni-directional pipe, failing.\n");
+ return SYSERR; /* can't do that, can happen for
unidirectional pipes
+ that call core with TSession being NULL. */
+ }
+ if ((tsession->ttype >= tapis_count) || (tapis[tsession->ttype] == NULL))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("Transmission attempt failed, transport type %d unknown.\n"),
+ tsession->ttype);
+ return SYSERR;
+ }
+ return tapis[tsession->ttype]->send (tsession, msg, size, important);
}
/**
* Close the session with the remote node.
* @return OK on success, SYSERR on error
*/
-static int transportDisconnect(TSession * tsession) {
- if (tsession == NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- if ( (tsession->ttype >= tapis_count) ||
- (tapis[tsession->ttype] == NULL) ) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- return tapis[tsession->ttype]->disconnect(tsession);
+static int
+transportDisconnect (TSession * tsession)
+{
+ if (tsession == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ if ((tsession->ttype >= tapis_count) || (tapis[tsession->ttype] == NULL))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ return tapis[tsession->ttype]->disconnect (tsession);
}
/**
@@ -337,25 +343,27 @@
* @return OK if the attempt to verify is on the way,
* SYSERR if the transport mechanism is not supported
*/
-static int transportVerifyHello(const P2P_hello_MESSAGE * hello) {
+static int
+transportVerifyHello (const P2P_hello_MESSAGE * hello)
+{
unsigned short prot;
- if ( (ntohs(hello->header.size) != P2P_hello_MESSAGE_size(hello)) ||
- (ntohs(hello->header.type) != p2p_PROTO_hello) )
- return SYSERR; /* invalid */
- prot = ntohs(hello->protocol);
- if ( (prot >= tapis_count) ||
- (tapis[prot] == NULL) )
- return SYSERR; /* not supported */
- return tapis[prot]->verifyHello(hello);
+ if ((ntohs (hello->header.size) != P2P_hello_MESSAGE_size (hello)) ||
+ (ntohs (hello->header.type) != p2p_PROTO_hello))
+ return SYSERR; /* invalid */
+ prot = ntohs (hello->protocol);
+ if ((prot >= tapis_count) || (tapis[prot] == NULL))
+ return SYSERR; /* not supported */
+ return tapis[prot]->verifyHello (hello);
}
/**
* Get the MTU for a given transport type.
*/
-static int transportGetMTU(unsigned short ttype) {
- if ( (ttype >= tapis_count) ||
- (tapis[ttype] == NULL) )
+static int
+transportGetMTU (unsigned short ttype)
+{
+ if ((ttype >= tapis_count) || (tapis[ttype] == NULL))
return SYSERR;
return tapis[ttype]->mtu;
}
@@ -365,48 +373,49 @@
* transport type for this node.
*/
static P2P_hello_MESSAGE *
-transportCreatehello(unsigned short ttype) {
- TransportAPI * tapi;
- P2P_hello_MESSAGE * hello;
+transportCreatehello (unsigned short ttype)
+{
+ TransportAPI *tapi;
+ P2P_hello_MESSAGE *hello;
- MUTEX_LOCK(tapis_lock);
- if (ttype == ANY_PROTOCOL_NUMBER) {
- int * perm;
+ MUTEX_LOCK (tapis_lock);
+ if (ttype == ANY_PROTOCOL_NUMBER)
+ {
+ int *perm;
- perm = permute(WEAK, tapis_count);
- ttype = tapis_count-1;
- while ( (ttype < tapis_count) &&
- ( (tapis[perm[ttype]] == NULL) ||
- (tapis[perm[ttype]] != NULL &&
- tapis[perm[ttype]]->hello == NULL) ) )
- ttype--; /* unsigned, will wrap around! */
- if (ttype >= tapis_count) {
- FREE(perm);
- MUTEX_UNLOCK(tapis_lock);
+ perm = permute (WEAK, tapis_count);
+ ttype = tapis_count - 1;
+ while ((ttype < tapis_count) &&
+ ((tapis[perm[ttype]] == NULL) ||
+ (tapis[perm[ttype]] != NULL &&
+ tapis[perm[ttype]]->hello == NULL)))
+ ttype--; /* unsigned, will wrap around! */
+ if (ttype >= tapis_count)
+ {
+ FREE (perm);
+ MUTEX_UNLOCK (tapis_lock);
+ return NULL;
+ }
+ ttype = perm[ttype];
+ FREE (perm);
+ }
+ if ((ttype >= tapis_count) || (tapis[ttype] == NULL))
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_BULK | GE_USER,
+ _("No transport of type %d known.\n"), ttype);
+ MUTEX_UNLOCK (tapis_lock);
return NULL;
}
- ttype = perm[ttype];
- FREE(perm);
- }
- if ( (ttype >= tapis_count) ||
- (tapis[ttype] == NULL) ) {
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- _("No transport of type %d known.\n"),
- ttype);
- MUTEX_UNLOCK(tapis_lock);
- return NULL;
- }
tapi = tapis[ttype];
- if (tapi->hello == NULL) {
- MUTEX_UNLOCK(tapis_lock);
- return NULL; /* send-only transport */
- }
- hello = MALLOC(P2P_hello_MESSAGE_size(tapi->hello));
- memcpy(hello,
- tapi->hello,
- P2P_hello_MESSAGE_size(tapi->hello));
- MUTEX_UNLOCK(tapis_lock);
+ if (tapi->hello == NULL)
+ {
+ MUTEX_UNLOCK (tapis_lock);
+ return NULL; /* send-only transport */
+ }
+ hello = MALLOC (P2P_hello_MESSAGE_size (tapi->hello));
+ memcpy (hello, tapi->hello, P2P_hello_MESSAGE_size (tapi->hello));
+ MUTEX_UNLOCK (tapis_lock);
return hello;
}
@@ -423,100 +432,103 @@
* @param buff where to write the hello messages
* @return the number of bytes written to buff, -1 on error
*/
-static int getAdvertisedhellos(unsigned int maxLen,
- char * buff) {
+static int
+getAdvertisedhellos (unsigned int maxLen, char *buff)
+{
int i;
int tcount;
- P2P_hello_MESSAGE ** hellos;
+ P2P_hello_MESSAGE **hellos;
int used;
- MUTEX_LOCK(tapis_lock);
+ MUTEX_LOCK (tapis_lock);
tcount = 0;
- for (i=0;i<tapis_count;i++)
+ for (i = 0; i < tapis_count; i++)
if (tapis[i] != NULL)
tcount++;
- hellos = MALLOC(tcount * sizeof(P2P_hello_MESSAGE*));
+ hellos = MALLOC (tcount * sizeof (P2P_hello_MESSAGE *));
tcount = 0;
- for (i=0;i<tapis_count;i++) {
- if (tapis[i] != NULL) {
- hellos[tcount] = transportCreatehello(i);
- if (NULL != hellos[tcount])
- tcount++;
+ for (i = 0; i < tapis_count; i++)
+ {
+ if (tapis[i] != NULL)
+ {
+ hellos[tcount] = transportCreatehello (i);
+ if (NULL != hellos[tcount])
+ tcount++;
+ }
}
- }
- MUTEX_UNLOCK(tapis_lock);
- if (tcount == 0) {
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- _("No transport succeeded in creating a hello!\n"));
- FREE(hellos);
- return SYSERR;
- }
+ MUTEX_UNLOCK (tapis_lock);
+ if (tcount == 0)
+ {
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ _("No transport succeeded in creating a hello!\n"));
+ FREE (hellos);
+ return SYSERR;
+ }
used = 0;
- while (tcount > 0) {
- i = weak_randomi(tcount); /* select a hello at random */
- if ((unsigned int)P2P_hello_MESSAGE_size(hellos[i]) <= maxLen - used) {
- memcpy(&buff[used],
- hellos[i],
- P2P_hello_MESSAGE_size(hellos[i]));
- used += P2P_hello_MESSAGE_size(hellos[i]);
+ while (tcount > 0)
+ {
+ i = weak_randomi (tcount); /* select a hello at random */
+ if ((unsigned int) P2P_hello_MESSAGE_size (hellos[i]) <= maxLen - used)
+ {
+ memcpy (&buff[used], hellos[i], P2P_hello_MESSAGE_size (hellos[i]));
+ used += P2P_hello_MESSAGE_size (hellos[i]);
+ }
+ FREE (hellos[i]);
+ hellos[i] = hellos[--tcount];
}
- FREE(hellos[i]);
- hellos[i] = hellos[--tcount];
- }
- for (i=0;i<tcount;i++)
- FREE(hellos[i]);
- FREE(hellos);
+ for (i = 0; i < tcount; i++)
+ FREE (hellos[i]);
+ FREE (hellos);
if (used == 0)
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
- "No HELLOs fit in %u bytes.\n",
- maxLen);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ "No HELLOs fit in %u bytes.\n", maxLen);
return used;
}
-static void initHello(void * cls) {
- TransportAPI * tapi = cls;
- P2P_hello_MESSAGE * hello;
+static void
+initHello (void *cls)
+{
+ TransportAPI *tapi = cls;
+ P2P_hello_MESSAGE *hello;
- createSignedhello(tapi);
- hello = transportCreatehello(tapi->protocolNumber);
- if (NULL != hello) {
- identity->addHost(hello);
- FREE(hello);
- }
+ createSignedhello (tapi);
+ hello = transportCreatehello (tapi->protocolNumber);
+ if (NULL != hello)
+ {
+ identity->addHost (hello);
+ FREE (hello);
+ }
}
-static void doneHelper(TransportAPI * tapi,
- void * unused) {
+static void
+doneHelper (TransportAPI * tapi, void *unused)
+{
/* In the (rare) case that we shutdown transports
before the cron-jobs had a chance to run, stop
the cron-jobs */
- cron_del_job(coreAPI->cron,
- &initHello,
- 0,
- tapi);
+ cron_del_job (coreAPI->cron, &initHello, 0, tapi);
}
-static void unloadTransport(int i) {
- void (*ptr)();
+static void
+unloadTransport (int i)
+{
+ void (*ptr) ();
- doneHelper(tapis[i], NULL);
- cron_del_job(coreAPI->cron,
- &createSignedhello,
- HELLO_RECREATE_FREQ,
- tapis[i]);
- ptr = os_plugin_resolve_function(tapis[i]->libHandle,
- "donetransport_",
- NO);
+ doneHelper (tapis[i], NULL);
+ cron_del_job (coreAPI->cron,
+ &createSignedhello, HELLO_RECREATE_FREQ, tapis[i]);
+ ptr = os_plugin_resolve_function (tapis[i]->libHandle,
+ "donetransport_", NO);
if (ptr != NULL)
- ptr();
- FREE(tapis[i]->transName);
- FREENONNULL(tapis[i]->hello);
+ ptr ();
+ FREE (tapis[i]->transName);
+ FREENONNULL (tapis[i]->hello);
tapis[i]->hello = NULL;
- os_plugin_unload(tapis[i]->libHandle);
+ os_plugin_unload (tapis[i]->libHandle);
tapis[i] = NULL;
}
@@ -525,31 +537,37 @@
* Actually start the transport services and begin
* receiving messages.
*/
-static void startTransports(P2P_PACKETProcessor mpp) {
+static void
+startTransports (P2P_PACKETProcessor mpp)
+{
int i;
ctapi.receive = mpp;
- for (i=0;i<tapis_count;i++)
- if (tapis[i] != NULL) {
- if (OK != tapis[i]->startTransportServer())
- unloadTransport(i);
- }
+ for (i = 0; i < tapis_count; i++)
+ if (tapis[i] != NULL)
+ {
+ if (OK != tapis[i]->startTransportServer ())
+ unloadTransport (i);
+ }
}
/**
* Stop the transport services, stop receiving messages.
*/
-static void stopTransports() {
+static void
+stopTransports ()
+{
int i;
- for (i=0;i<tapis_count;i++)
+ for (i = 0; i < tapis_count; i++)
if (tapis[i] != NULL)
- tapis[i]->stopTransportServer();
+ tapis[i]->stopTransportServer ();
ctapi.receive = NULL;
}
-static void initHelper(TransportAPI * tapi,
- void * unused) {
+static void
+initHelper (TransportAPI * tapi, void *unused)
+{
/* Creation of HELLOs takes longer if a locally
unresolvable hostname ((Dyn)DNS) was specified
as this host's address and we have no network
@@ -557,11 +575,7 @@
blocks the startup process in this case.
This is why we create the HELLOs in another
thread. */
- cron_add_job(coreAPI->cron,
- &initHello,
- 0,
- 0,
- tapi);
+ cron_add_job (coreAPI->cron, &initHello, 0, 0, tapi);
}
/**
@@ -577,51 +591,48 @@
* NO if the transport would just drop the message,
* SYSERR if the size/session is invalid
*/
-static int testWouldTry(TSession * tsession,
- unsigned int size,
- int important) {
+static int
+testWouldTry (TSession * tsession, unsigned int size, int important)
+{
if (tsession == NULL)
return SYSERR;
- if ( (tsession->ttype >= tapis_count) ||
- (tapis[tsession->ttype] == NULL) )
+ if ((tsession->ttype >= tapis_count) || (tapis[tsession->ttype] == NULL))
return SYSERR;
- return tapis[tsession->ttype]->testWouldTry(tsession,
- size,
- important);
+ return tapis[tsession->ttype]->testWouldTry (tsession, size, important);
}
/**
* Initialize the transport layer.
*/
Transport_ServiceAPI *
-provide_module_transport(CoreAPIForApplication * capi) {
+provide_module_transport (CoreAPIForApplication * capi)
+{
static Transport_ServiceAPI ret;
- TransportAPI * tapi;
+ TransportAPI *tapi;
TransportMainMethod tptr;
- char * dso;
- char * next;
- char * pos;
- struct PluginHandle * lib;
+ char *dso;
+ char *next;
+ char *pos;
+ struct PluginHandle *lib;
EncName myself;
ectx = capi->ectx;
- if (-1 == GC_get_configuration_value_number(capi->cfg,
- "GNUNETD",
- "HELLOEXPIRES",
- 1,
- MAX_HELLO_EXPIRES / 60,
- 60,
- &hello_live))
+ if (-1 == GC_get_configuration_value_number (capi->cfg,
+ "GNUNETD",
+ "HELLOEXPIRES",
+ 1,
+ MAX_HELLO_EXPIRES / 60,
+ 60, &hello_live))
return NULL;
hello_live *= 60;
- GE_ASSERT(ectx,
- sizeof(P2P_hello_MESSAGE) == 600);
- identity = capi->requestService("identity");
- if (identity == NULL) {
- GE_BREAK(ectx, 0);
- return NULL;
- }
+ GE_ASSERT (ectx, sizeof (P2P_hello_MESSAGE) == 600);
+ identity = capi->requestService ("identity");
+ if (identity == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return NULL;
+ }
coreAPI = capi;
ctapi.version = 1;
ctapi.myIdentity = coreAPI->myIdentity;
@@ -629,100 +640,94 @@
ctapi.cfg = coreAPI->cfg;
ctapi.load_monitor = coreAPI->load_monitor;
ctapi.cron = coreAPI->cron;
- ctapi.receive = NULL; /* initialized LATER! */
+ ctapi.receive = NULL; /* initialized LATER! */
ctapi.requestService = coreAPI->requestService;
ctapi.releaseService = coreAPI->releaseService;
- GROW(tapis,
- tapis_count,
- UDP_PROTOCOL_NUMBER+1);
+ GROW (tapis, tapis_count, UDP_PROTOCOL_NUMBER + 1);
- tapis_lock = MUTEX_CREATE(YES);
+ tapis_lock = MUTEX_CREATE (YES);
/* now load transports */
dso = NULL;
- GE_ASSERT(ectx,
- -1 != GC_get_configuration_value_string(capi->cfg,
- "GNUNETD",
- "TRANSPORTS",
- "udp tcp nat",
- &dso));
- if (strlen(dso) != 0) {
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- _("Loading transports `%s'\n"),
- dso);
- next = dso;
- do {
- pos = next;
- while ( (*next != '\0') &&
- (*next != ' ') )
- next++;
- if (*next == '\0')
- next = NULL; /* terminate! */
- else {
- *next = '\0'; /* add 0-termination for pos */
- next++;
- }
- lib = os_plugin_load(ectx,
- "libgnunettransport_",
- pos);
- if (lib == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- _("Could not load transport plugin `%s'\n"),
- pos);
- continue;
- }
- tptr = os_plugin_resolve_function(lib,
- "inittransport_",
- YES);
- if (tptr == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
- _("Transport library `%s' did not provide required function
'%s%s'.\n"),
- pos,
- "inittransport_",
- pos);
- os_plugin_unload(lib);
- continue;
- }
- tapi = tptr(&ctapi);
- if (tapi == NULL) {
- os_plugin_unload(lib);
- continue;
- }
- tapi->libHandle = lib;
- tapi->transName = STRDUP(pos);
- if (OK != addTransport(tapi)) {
- void (*ptr)();
+ GE_ASSERT (ectx,
+ -1 != GC_get_configuration_value_string (capi->cfg,
+ "GNUNETD",
+ "TRANSPORTS",
+ "udp tcp nat", &dso));
+ if (strlen (dso) != 0)
+ {
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ _("Loading transports `%s'\n"), dso);
+ next = dso;
+ do
+ {
+ pos = next;
+ while ((*next != '\0') && (*next != ' '))
+ next++;
+ if (*next == '\0')
+ next = NULL; /* terminate! */
+ else
+ {
+ *next = '\0'; /* add 0-termination for pos */
+ next++;
+ }
+ lib = os_plugin_load (ectx, "libgnunettransport_", pos);
+ if (lib == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ _("Could not load transport plugin `%s'\n"), pos);
+ continue;
+ }
+ tptr = os_plugin_resolve_function (lib, "inittransport_", YES);
+ if (tptr == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_DEVELOPER |
+ GE_IMMEDIATE,
+ _
+ ("Transport library `%s' did not provide required
function '%s%s'.\n"),
+ pos, "inittransport_", pos);
+ os_plugin_unload (lib);
+ continue;
+ }
+ tapi = tptr (&ctapi);
+ if (tapi == NULL)
+ {
+ os_plugin_unload (lib);
+ continue;
+ }
+ tapi->libHandle = lib;
+ tapi->transName = STRDUP (pos);
+ if (OK != addTransport (tapi))
+ {
+ void (*ptr) ();
- FREE(tapi->transName);
- ptr = os_plugin_resolve_function(lib,
- "donetransport_",
- NO);
- if (ptr != NULL)
- ptr();
- os_plugin_unload(lib);
- } else {
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- _("Loaded transport `%s'\n"),
- pos);
- }
- } while (next != NULL);
- }
- FREE(dso);
+ FREE (tapi->transName);
+ ptr = os_plugin_resolve_function (lib, "donetransport_", NO);
+ if (ptr != NULL)
+ ptr ();
+ os_plugin_unload (lib);
+ }
+ else
+ {
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ _("Loaded transport `%s'\n"), pos);
+ }
+ }
+ while (next != NULL);
+ }
+ FREE (dso);
- IF_GELOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- hash2enc(&coreAPI->myIdentity->hashPubKey,
- &myself));
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- _("I am peer `%s'.\n"),
- &myself);
- forEachTransport(&initHelper, NULL);
+ IF_GELOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ hash2enc (&coreAPI->myIdentity->hashPubKey, &myself));
+ GE_LOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER, _("I am peer `%s'.\n"), &myself);
+ forEachTransport (&initHelper, NULL);
ret.start = &startTransports;
ret.stop = &stopTransports;
@@ -749,24 +754,24 @@
/**
* Shutdown the transport layer.
*/
-int release_module_transport() {
+int
+release_module_transport ()
+{
int i;
- forEachTransport(&doneHelper, NULL);
- for (i=0;i<tapis_count;i++)
+ forEachTransport (&doneHelper, NULL);
+ for (i = 0; i < tapis_count; i++)
if (tapis[i] != NULL)
- unloadTransport(i);
- MUTEX_DESTROY(tapis_lock);
+ unloadTransport (i);
+ MUTEX_DESTROY (tapis_lock);
tapis_lock = NULL;
- GROW(tapis,
- tapis_count,
- 0);
+ GROW (tapis, tapis_count, 0);
- coreAPI->releaseService(identity);
+ coreAPI->releaseService (identity);
identity = NULL;
coreAPI = NULL;
return OK;
}
-/* end of transport.c */
+/* end of transport.c */
Modified: GNUnet/src/applications/vpn/gnunet-vpn.c
===================================================================
--- GNUnet/src/applications/vpn/gnunet-vpn.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/applications/vpn/gnunet-vpn.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,79 +35,85 @@
#define buf ((MESSAGE_HEADER*)&buffer)
-static struct SEMAPHORE * doneSem;
-static struct SEMAPHORE * cmdAck;
-static struct SEMAPHORE * exitCheck;
-static struct MUTEX * lock;
+static struct SEMAPHORE *doneSem;
+static struct SEMAPHORE *cmdAck;
+static struct SEMAPHORE *exitCheck;
+static struct MUTEX *lock;
static int wantExit;
static int silent;
-static char * cfgFilename;
+static char *cfgFilename;
/**
* All gnunet-transport-check command line options
*/
static struct CommandLineOption gnunetvpnOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- COMMAND_LINE_OPTION_HELP(gettext_noop("Print statistics about GNUnet
operations.")), /* -h */
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Print statistics about GNUnet
operations.")), /* -h */
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 's', "silent", NULL,
- gettext_noop("Suppress display of asynchronous log messages"),
- 0, &gnunet_getopt_configure_set_one, &silent },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'s', "silent", NULL,
+ gettext_noop ("Suppress display of asynchronous log messages"),
+ 0, &gnunet_getopt_configure_set_one, &silent},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_END,
};
-static void * receiveThread(void * arg) {
- struct ClientServerConnection * sock = arg;
+static void *
+receiveThread (void *arg)
+{
+ struct ClientServerConnection *sock = arg;
char buffer[MAX_BUFFER_SIZE];
- MESSAGE_HEADER * bufp = buf;
+ MESSAGE_HEADER *bufp = buf;
/* buffer = MALLOC(MAX_BUFFER_SIZE); */
- while (OK == connection_read(sock, &bufp)) {
- switch (ntohs(buf->type)) {
- case CS_PROTO_VPN_DEBUGOFF:
- case CS_PROTO_VPN_DEBUGON:
- case CS_PROTO_VPN_TUNNELS:
- case CS_PROTO_VPN_ROUTES:
- case CS_PROTO_VPN_REALISED:
- case CS_PROTO_VPN_RESET:
- case CS_PROTO_VPN_REALISE:
- case CS_PROTO_VPN_ADD:
- case CS_PROTO_VPN_TRUST:
- if (ntohs(buf->size) > sizeof(MESSAGE_HEADER)) {
- fwrite( buffer+sizeof(MESSAGE_HEADER),
- sizeof(char),
- ntohs(buf->size)-sizeof(MESSAGE_HEADER),
- stdout);
- }
+ while (OK == connection_read (sock, &bufp))
+ {
+ switch (ntohs (buf->type))
+ {
+ case CS_PROTO_VPN_DEBUGOFF:
+ case CS_PROTO_VPN_DEBUGON:
+ case CS_PROTO_VPN_TUNNELS:
+ case CS_PROTO_VPN_ROUTES:
+ case CS_PROTO_VPN_REALISED:
+ case CS_PROTO_VPN_RESET:
+ case CS_PROTO_VPN_REALISE:
+ case CS_PROTO_VPN_ADD:
+ case CS_PROTO_VPN_TRUST:
+ if (ntohs (buf->size) > sizeof (MESSAGE_HEADER))
+ {
+ fwrite (buffer + sizeof (MESSAGE_HEADER),
+ sizeof (char),
+ ntohs (buf->size) - sizeof (MESSAGE_HEADER), stdout);
+ }
- SEMAPHORE_UP(cmdAck);
- SEMAPHORE_DOWN(exitCheck, YES);
- MUTEX_LOCK(lock);
- if (wantExit == YES) {
- MUTEX_UNLOCK(lock);
- SEMAPHORE_UP(doneSem);
- return NULL;
- }
- MUTEX_UNLOCK(lock);
- break;;
- case CS_PROTO_VPN_MSG:
- if (silent == YES) break;;
- case CS_PROTO_VPN_REPLY:
-
- if (ntohs(buf->size) > sizeof(MESSAGE_HEADER)) {
- fwrite( buffer+sizeof(MESSAGE_HEADER),
- sizeof(char),
- ntohs(buf->size)-sizeof(MESSAGE_HEADER),
- stdout);
- }
- break;;
- }
- }
+ SEMAPHORE_UP (cmdAck);
+ SEMAPHORE_DOWN (exitCheck, YES);
+ MUTEX_LOCK (lock);
+ if (wantExit == YES)
+ {
+ MUTEX_UNLOCK (lock);
+ SEMAPHORE_UP (doneSem);
+ return NULL;
+ }
+ MUTEX_UNLOCK (lock);
+ break;;
+ case CS_PROTO_VPN_MSG:
+ if (silent == YES)
+ break;;
+ case CS_PROTO_VPN_REPLY:
+
+ if (ntohs (buf->size) > sizeof (MESSAGE_HEADER))
+ {
+ fwrite (buffer + sizeof (MESSAGE_HEADER),
+ sizeof (char),
+ ntohs (buf->size) - sizeof (MESSAGE_HEADER), stdout);
+ }
+ break;;
+ }
+ }
/* FREE(buffer); */
- SEMAPHORE_UP(doneSem);
+ SEMAPHORE_UP (doneSem);
return NULL;
}
@@ -116,142 +122,182 @@
* @param argv command line arguments
* @return return value from gnunet-template: 0: ok, -1: error
*/
-int main(int argc,
- char * const * argv) {
- struct ClientServerConnection * sock;
- struct PTHREAD * messageReceiveThread;
- void * unused;
- char buffer[sizeof(MESSAGE_HEADER) + 1024];
+int
+main (int argc, char *const *argv)
+{
+ struct ClientServerConnection *sock;
+ struct PTHREAD *messageReceiveThread;
+ void *unused;
+ char buffer[sizeof (MESSAGE_HEADER) + 1024];
int rancommand = 0;
- struct GC_Configuration * cfg;
- struct GE_Context * ectx;
+ struct GC_Configuration *cfg;
+ struct GE_Context *ectx;
int i;
- i = GNUNET_init(argc,
- argv,
- "gnunet-vpn",
- &cfgFilename,
- gnunetvpnOptions,
- &ectx,
- &cfg);
- if (i == -1) {
- GNUNET_fini(ectx, cfg);
- return -1;
- }
- sock = client_connection_create(ectx,
- cfg);
- if (sock == NULL) {
- fprintf(stderr,
- _("Error establishing connection with gnunetd.\n"));
- GNUNET_fini(ectx, cfg);
- return 1;
- }
+ i = GNUNET_init (argc,
+ argv,
+ "gnunet-vpn", &cfgFilename, gnunetvpnOptions, &ectx, &cfg);
+ if (i == -1)
+ {
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
+ sock = client_connection_create (ectx, cfg);
+ if (sock == NULL)
+ {
+ fprintf (stderr, _("Error establishing connection with gnunetd.\n"));
+ GNUNET_fini (ectx, cfg);
+ return 1;
+ }
- doneSem = SEMAPHORE_CREATE(0);
- cmdAck = SEMAPHORE_CREATE(0);
- exitCheck = SEMAPHORE_CREATE(0);
- lock = MUTEX_CREATE(NO);
+ doneSem = SEMAPHORE_CREATE (0);
+ cmdAck = SEMAPHORE_CREATE (0);
+ exitCheck = SEMAPHORE_CREATE (0);
+ lock = MUTEX_CREATE (NO);
wantExit = NO;
- messageReceiveThread = PTHREAD_CREATE(&receiveThread,
- sock,
- 128 * 1024);
+ messageReceiveThread = PTHREAD_CREATE (&receiveThread, sock, 128 * 1024);
if (messageReceiveThread == NULL)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_USER | GE_IMMEDIATE,
- "pthread_create");
+ GE_DIE_STRERROR (ectx,
+ GE_FATAL | GE_ADMIN | GE_USER | GE_IMMEDIATE,
+ "pthread_create");
/* accept keystrokes from user and send to gnunetd */
- while (NULL != fgets(buffer, 1024, stdin)) {
- if (rancommand) {
- rancommand = 0;
- SEMAPHORE_UP(exitCheck);
- }
- if (strncmp(buffer, "debug0", 6) == 0) {
- ((MESSAGE_HEADER*)&buffer)->type = htons(CS_PROTO_VPN_DEBUGOFF);
- ((MESSAGE_HEADER*)&buffer)->size = htons(sizeof(MESSAGE_HEADER));
- if (SYSERR == connection_write(sock, (MESSAGE_HEADER*)&buffer)) return
-1;
- rancommand = 1;
- SEMAPHORE_DOWN(cmdAck, YES);
- } else if (strncmp(buffer, "debug1", 6) == 0) {
- ((MESSAGE_HEADER*)&buffer)->type = htons(CS_PROTO_VPN_DEBUGON);
- ((MESSAGE_HEADER*)&buffer)->size = htons(sizeof(MESSAGE_HEADER));
- if (SYSERR == connection_write(sock, (MESSAGE_HEADER*)&buffer)) return
-1;
- rancommand = 1;
- SEMAPHORE_DOWN(cmdAck, YES);
- } else if (strncmp(buffer, "tunnels", 7) == 0) {
- ((MESSAGE_HEADER*)&buffer)->type = htons(CS_PROTO_VPN_TUNNELS);
- ((MESSAGE_HEADER*)&buffer)->size = htons(sizeof(MESSAGE_HEADER));
- if (SYSERR == connection_write(sock, (MESSAGE_HEADER*)&buffer)) return
-1;
- rancommand = 1;
- SEMAPHORE_DOWN(cmdAck, YES);
- } else if (strncmp(buffer, "route", 5) == 0) {
- ((MESSAGE_HEADER*)&buffer)->type = htons(CS_PROTO_VPN_ROUTES);
- ((MESSAGE_HEADER*)&buffer)->size = htons(sizeof(MESSAGE_HEADER));
- if (SYSERR == connection_write(sock, (MESSAGE_HEADER*)&buffer)) return
-1;
- rancommand = 1;
- SEMAPHORE_DOWN(cmdAck, YES);
- } else if (strncmp(buffer, "realised", 8) == 0) {
- ((MESSAGE_HEADER*)&buffer)->type = htons(CS_PROTO_VPN_REALISED);
- ((MESSAGE_HEADER*)&buffer)->size = htons(sizeof(MESSAGE_HEADER));
- if (SYSERR == connection_write(sock, (MESSAGE_HEADER*)&buffer)) return
-1;
- rancommand = 1;
- SEMAPHORE_DOWN(cmdAck, YES);
- } else if (strncmp(buffer, "reset", 5) == 0) {
- ((MESSAGE_HEADER*)&buffer)->type = htons(CS_PROTO_VPN_RESET);
- ((MESSAGE_HEADER*)&buffer)->size = htons(sizeof(MESSAGE_HEADER));
- if (SYSERR == connection_write(sock, (MESSAGE_HEADER*)&buffer)) return
-1;
- rancommand = 1;
- SEMAPHORE_DOWN(cmdAck, YES);
- } else if (strncmp(buffer, "realise", 7) == 0) {
- ((MESSAGE_HEADER*)&buffer)->type = htons(CS_PROTO_VPN_REALISE);
- ((MESSAGE_HEADER*)&buffer)->size = htons(sizeof(MESSAGE_HEADER));
- if (SYSERR == connection_write(sock, (MESSAGE_HEADER*)&buffer)) return
-1;
- rancommand = 1;
- SEMAPHORE_DOWN(cmdAck, YES);
- } else if (strncmp(buffer, "trust", 5) == 0) {
- ((MESSAGE_HEADER*)&buffer)->type = htons(CS_PROTO_VPN_TRUST);
- ((MESSAGE_HEADER*)&buffer)->size = htons(sizeof(MESSAGE_HEADER));
- if (SYSERR == connection_write(sock, (MESSAGE_HEADER*)&buffer)) return
-1;
- rancommand = 1;
- SEMAPHORE_DOWN(cmdAck, YES);
- } else if (strncmp(buffer, "add ", 4) == 0) {
- /* message header is 4 bytes long, we overwrite "add " with it
- * also don't include \r or \n in the message
- */
- if (strlen(&buffer[4]) > 1) {
- ((MESSAGE_HEADER*)&buffer)->type = htons(CS_PROTO_VPN_ADD);
- ((MESSAGE_HEADER*)&buffer)->size = htons(sizeof(MESSAGE_HEADER)
+ strlen(&buffer[5]));
- if (SYSERR == connection_write(sock, (MESSAGE_HEADER*)&buffer))
return -1;
- rancommand = 1;
- SEMAPHORE_DOWN(cmdAck, YES);
- } else {
- printf("add requires hash as a parameter!\n");
- }
- } else {
- printf("debug0, debug1, tunnels, route, realise, realised, reset,
trust, add <hash>\n");
- }
- }
+ while (NULL != fgets (buffer, 1024, stdin))
+ {
+ if (rancommand)
+ {
+ rancommand = 0;
+ SEMAPHORE_UP (exitCheck);
+ }
+ if (strncmp (buffer, "debug0", 6) == 0)
+ {
+ ((MESSAGE_HEADER *) & buffer)->type = htons (CS_PROTO_VPN_DEBUGOFF);
+ ((MESSAGE_HEADER *) & buffer)->size =
+ htons (sizeof (MESSAGE_HEADER));
+ if (SYSERR == connection_write (sock, (MESSAGE_HEADER *) & buffer))
+ return -1;
+ rancommand = 1;
+ SEMAPHORE_DOWN (cmdAck, YES);
+ }
+ else if (strncmp (buffer, "debug1", 6) == 0)
+ {
+ ((MESSAGE_HEADER *) & buffer)->type = htons (CS_PROTO_VPN_DEBUGON);
+ ((MESSAGE_HEADER *) & buffer)->size =
+ htons (sizeof (MESSAGE_HEADER));
+ if (SYSERR == connection_write (sock, (MESSAGE_HEADER *) & buffer))
+ return -1;
+ rancommand = 1;
+ SEMAPHORE_DOWN (cmdAck, YES);
+ }
+ else if (strncmp (buffer, "tunnels", 7) == 0)
+ {
+ ((MESSAGE_HEADER *) & buffer)->type = htons (CS_PROTO_VPN_TUNNELS);
+ ((MESSAGE_HEADER *) & buffer)->size =
+ htons (sizeof (MESSAGE_HEADER));
+ if (SYSERR == connection_write (sock, (MESSAGE_HEADER *) & buffer))
+ return -1;
+ rancommand = 1;
+ SEMAPHORE_DOWN (cmdAck, YES);
+ }
+ else if (strncmp (buffer, "route", 5) == 0)
+ {
+ ((MESSAGE_HEADER *) & buffer)->type = htons (CS_PROTO_VPN_ROUTES);
+ ((MESSAGE_HEADER *) & buffer)->size =
+ htons (sizeof (MESSAGE_HEADER));
+ if (SYSERR == connection_write (sock, (MESSAGE_HEADER *) & buffer))
+ return -1;
+ rancommand = 1;
+ SEMAPHORE_DOWN (cmdAck, YES);
+ }
+ else if (strncmp (buffer, "realised", 8) == 0)
+ {
+ ((MESSAGE_HEADER *) & buffer)->type = htons (CS_PROTO_VPN_REALISED);
+ ((MESSAGE_HEADER *) & buffer)->size =
+ htons (sizeof (MESSAGE_HEADER));
+ if (SYSERR == connection_write (sock, (MESSAGE_HEADER *) & buffer))
+ return -1;
+ rancommand = 1;
+ SEMAPHORE_DOWN (cmdAck, YES);
+ }
+ else if (strncmp (buffer, "reset", 5) == 0)
+ {
+ ((MESSAGE_HEADER *) & buffer)->type = htons (CS_PROTO_VPN_RESET);
+ ((MESSAGE_HEADER *) & buffer)->size =
+ htons (sizeof (MESSAGE_HEADER));
+ if (SYSERR == connection_write (sock, (MESSAGE_HEADER *) & buffer))
+ return -1;
+ rancommand = 1;
+ SEMAPHORE_DOWN (cmdAck, YES);
+ }
+ else if (strncmp (buffer, "realise", 7) == 0)
+ {
+ ((MESSAGE_HEADER *) & buffer)->type = htons (CS_PROTO_VPN_REALISE);
+ ((MESSAGE_HEADER *) & buffer)->size =
+ htons (sizeof (MESSAGE_HEADER));
+ if (SYSERR == connection_write (sock, (MESSAGE_HEADER *) & buffer))
+ return -1;
+ rancommand = 1;
+ SEMAPHORE_DOWN (cmdAck, YES);
+ }
+ else if (strncmp (buffer, "trust", 5) == 0)
+ {
+ ((MESSAGE_HEADER *) & buffer)->type = htons (CS_PROTO_VPN_TRUST);
+ ((MESSAGE_HEADER *) & buffer)->size =
+ htons (sizeof (MESSAGE_HEADER));
+ if (SYSERR == connection_write (sock, (MESSAGE_HEADER *) & buffer))
+ return -1;
+ rancommand = 1;
+ SEMAPHORE_DOWN (cmdAck, YES);
+ }
+ else if (strncmp (buffer, "add ", 4) == 0)
+ {
+ /* message header is 4 bytes long, we overwrite "add " with it
+ * also don't include \r or \n in the message
+ */
+ if (strlen (&buffer[4]) > 1)
+ {
+ ((MESSAGE_HEADER *) & buffer)->type = htons (CS_PROTO_VPN_ADD);
+ ((MESSAGE_HEADER *) & buffer)->size =
+ htons (sizeof (MESSAGE_HEADER) + strlen (&buffer[5]));
+ if (SYSERR ==
+ connection_write (sock, (MESSAGE_HEADER *) & buffer))
+ return -1;
+ rancommand = 1;
+ SEMAPHORE_DOWN (cmdAck, YES);
+ }
+ else
+ {
+ printf ("add requires hash as a parameter!\n");
+ }
+ }
+ else
+ {
+ printf
+ ("debug0, debug1, tunnels, route, realise, realised, reset, trust,
add <hash>\n");
+ }
+ }
/* wait for shutdown... */
- if (rancommand) {
- MUTEX_LOCK(lock);
- wantExit = YES;
- MUTEX_UNLOCK(lock);
- SEMAPHORE_UP(exitCheck);
- }
+ if (rancommand)
+ {
+ MUTEX_LOCK (lock);
+ wantExit = YES;
+ MUTEX_UNLOCK (lock);
+ SEMAPHORE_UP (exitCheck);
+ }
/* we can't guarantee that this can be called while the other thread is
waiting for read */
- connection_close_forever(sock);
- SEMAPHORE_DOWN(doneSem, YES);
+ connection_close_forever (sock);
+ SEMAPHORE_DOWN (doneSem, YES);
- SEMAPHORE_DESTROY(doneSem);
- SEMAPHORE_DESTROY(cmdAck);
- SEMAPHORE_DESTROY(exitCheck);
- MUTEX_DESTROY(lock);
- PTHREAD_JOIN(messageReceiveThread, &unused);
- connection_destroy(sock);
- GNUNET_fini(ectx, cfg);
+ SEMAPHORE_DESTROY (doneSem);
+ SEMAPHORE_DESTROY (cmdAck);
+ SEMAPHORE_DESTROY (exitCheck);
+ MUTEX_DESTROY (lock);
+ PTHREAD_JOIN (messageReceiveThread, &unused);
+ connection_destroy (sock);
+ GNUNET_fini (ectx, cfg);
return 0;
}
Modified: GNUnet/src/applications/vpn/vpn.c
===================================================================
--- GNUnet/src/applications/vpn/vpn.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/applications/vpn/vpn.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -69,7 +69,8 @@
/* This is derived from ifconfig source code... in6_ifreq needed from
<linux/ipv6.h> */
#include <asm/types.h>
#ifndef _LINUX_IN6_H
-struct in6_ifreq {
+struct in6_ifreq
+{
struct in6_addr ifr6_addr;
__u32 ifr6_prefixlen;
unsigned int ifr6_ifindex;
@@ -100,22 +101,22 @@
/**
* Identity service, to reset the core.
*/
-static Identity_ServiceAPI * identity;
-static Session_ServiceAPI * session;
+static Identity_ServiceAPI *identity;
+static Session_ServiceAPI *session;
-static CoreAPIForApplication * coreAPI;
+static CoreAPIForApplication *coreAPI;
-static struct ClientHandle ** clients_store;
+static struct ClientHandle **clients_store;
static int clients_entries;
static int clients_capacity;
static int cdebug;
static int interval = 60;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-static struct PTHREAD * tunThreadInfo;
+static struct PTHREAD *tunThreadInfo;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
/* id = number portion of interface name. I.e. 0 = gnu0, 1= gnu1 ...
* hd = filedescriptor of this tunnel
@@ -123,7 +124,8 @@
* route_entry = index in the remote node's routing table we have requested
* ifindex = linux internal number to identify an interface
*/
-typedef struct {
+typedef struct
+{
/* char name[IFNAMSIZ]; */
int id;
int fd;
@@ -160,7 +162,8 @@
*/
/* This is an entry in the routing table */
-typedef struct {
+typedef struct
+{
/** owner's public key */
PublicKey owner;
/** hops to owner 1 = have a tunnel to owner, 0 = I am the owner.*/
@@ -182,7 +185,8 @@
*
* also the fields here are network byte order.
*/
-typedef struct {
+typedef struct
+{
PublicKey owner;
int hops;
} transit_route;
@@ -196,78 +200,101 @@
static int realised_capacity = 0;
/** send given string to client */
-static void cprintf(struct ClientHandle * c, int t, const char* format, ...) {
+static void
+cprintf (struct ClientHandle *c, int t, const char *format, ...)
+{
va_list args;
int r = -1;
int size = 100;
MESSAGE_HEADER *b = NULL, *nb = NULL;
- if ((b = MALLOC(sizeof(MESSAGE_HEADER)+size)) == NULL) {
- return;
- }
- while (1) {
- va_start(args, format);
- r = VSNPRINTF((char*)(b+1), size, format, args);
- va_end(args);
- if (r > -1 && r < size)
- break;
- if (r > -1) {
- size = r + 1;
- } else {
- size *= 2;
- }
- if ((nb = REALLOC(b, sizeof(MESSAGE_HEADER) + size)) == NULL) {
- FREE(b);
- return;
- } else {
- b = nb;
- }
- }
- b->type=htons(t);
- b->size=htons(sizeof(MESSAGE_HEADER) + strlen((char*)(b+1)));
- if (c != NULL) {
- coreAPI->sendToClient(c, b);
- } else {
- for(r = 0; r < clients_entries; r++) {
- coreAPI->sendToClient(*(clients_store+r), b);
- }
- }
- FREE(b);
+ if ((b = MALLOC (sizeof (MESSAGE_HEADER) + size)) == NULL)
+ {
+ return;
+ }
+ while (1)
+ {
+ va_start (args, format);
+ r = VSNPRINTF ((char *) (b + 1), size, format, args);
+ va_end (args);
+ if (r > -1 && r < size)
+ break;
+ if (r > -1)
+ {
+ size = r + 1;
+ }
+ else
+ {
+ size *= 2;
+ }
+ if ((nb = REALLOC (b, sizeof (MESSAGE_HEADER) + size)) == NULL)
+ {
+ FREE (b);
+ return;
+ }
+ else
+ {
+ b = nb;
+ }
+ }
+ b->type = htons (t);
+ b->size = htons (sizeof (MESSAGE_HEADER) + strlen ((char *) (b + 1)));
+ if (c != NULL)
+ {
+ coreAPI->sendToClient (c, b);
+ }
+ else
+ {
+ for (r = 0; r < clients_entries; r++)
+ {
+ coreAPI->sendToClient (*(clients_store + r), b);
+ }
+ }
+ FREE (b);
}
+
#define VLOG if ((cdebug & (GE_DEBUG | GE_DEVELOPER | GE_REQUEST)) > 0)
cprintf(NULL,CS_PROTO_VPN_MSG,
/** Test if two PublicKey are equal or not */
-static int isEqualP(const PublicKey *first, const PublicKey *second) {
+static int
+isEqualP (const PublicKey * first, const PublicKey * second)
+{
int i;
- int ln = maxi(first->sizen, second->sizen);
- int sn = mini(first->sizen, second->sizen);
+ int ln = maxi (first->sizen, second->sizen);
+ int sn = mini (first->sizen, second->sizen);
/* compare common mode modulus */
- if (memcmp( (first->key)+((first->sizen)-sn),
(second->key)+((second->sizen)-sn), sn) != 0)
- return NO;
+ if (memcmp
+ ((first->key) + ((first->sizen) - sn),
+ (second->key) + ((second->sizen) - sn), sn) != 0)
+ return NO;
/* difference before n should be 0 */
- for(i = 0; i < (first->sizen)-sn; i++) {
- if (*(first->key+i) != 0)
- return NO;
- }
- for(i = 0; i < (second->sizen)-sn; i++) {
- if (*(second->key+i) != 0)
- return NO;
- }
+ for (i = 0; i < (first->sizen) - sn; i++)
+ {
+ if (*(first->key + i) != 0)
+ return NO;
+ }
+ for (i = 0; i < (second->sizen) - sn; i++)
+ {
+ if (*(second->key + i) != 0)
+ return NO;
+ }
/* compare common mode exponent */
- if (memcmp( (first->key)+ln, (second->key)+ln, RSA_KEY_LEN-ln) != 0)
- return NO;
+ if (memcmp ((first->key) + ln, (second->key) + ln, RSA_KEY_LEN - ln) != 0)
+ return NO;
- for(i = first->sizen; i < ln; i++) {
- if (*(first->key+i) != 0)
- return NO;
- }
- for(i = second->sizen; i < ln; i++) {
- if (*(second->key+i) != 0)
- return NO;
- }
+ for (i = first->sizen; i < ln; i++)
+ {
+ if (*(first->key + i) != 0)
+ return NO;
+ }
+ for (i = second->sizen; i < ln; i++)
+ {
+ if (*(second->key + i) != 0)
+ return NO;
+ }
return YES;
}
@@ -276,165 +303,204 @@
* clear out the prototype routes table
* called at start or when we know a peer changes its route table.
*/
-static void init_router() {
+static void
+init_router ()
+{
int reqcapacity;
route_info *reqstore;
- reqcapacity = sizeof(route_info);
- if (reqcapacity > route_capacity) {
- reqstore = REALLOC(route_store, reqcapacity);
- if (reqstore == NULL) return; /* not enough ram, cannot init! */
- route_store = reqstore;
- route_capacity = reqcapacity;
- }
+ reqcapacity = sizeof (route_info);
+ if (reqcapacity > route_capacity)
+ {
+ reqstore = REALLOC (route_store, reqcapacity);
+ if (reqstore == NULL)
+ return; /* not enough ram, cannot init! */
+ route_store = reqstore;
+ route_capacity = reqcapacity;
+ }
route_entries = 1;
- route_store->hops = 0; /* us! */
- route_store->tunnel = -1; /* n/a! */
- route_store->owner = *(identity->getPublicPrivateKey()); /* us! */
+ route_store->hops = 0; /* us! */
+ route_store->tunnel = -1; /* n/a! */
+ route_store->owner = *(identity->getPublicPrivateKey ()); /* us! */
}
/**
* clear out the actual route at startup only
*/
-static void init_realised() {
+static void
+init_realised ()
+{
int reqcapacity;
- route_info *reqstore;
- reqcapacity = sizeof(route_info);
- if (reqcapacity > realised_capacity) {
- reqstore = REALLOC(realised_store, reqcapacity);
- if (reqstore == NULL) return; /* not enough ram, cannot init! */
- realised_store = reqstore;
- realised_capacity = reqcapacity;
- }
+ route_info *reqstore;
+ reqcapacity = sizeof (route_info);
+ if (reqcapacity > realised_capacity)
+ {
+ reqstore = REALLOC (realised_store, reqcapacity);
+ if (reqstore == NULL)
+ return; /* not enough ram, cannot init! */
+ realised_store = reqstore;
+ realised_capacity = reqcapacity;
+ }
realised_entries = 1;
- realised_store->hops = 0; /* us! */
- realised_store->tunnel = -1; /* n/a! */
- realised_store->owner = *(identity->getPublicPrivateKey()); /* us! */
+ realised_store->hops = 0; /* us! */
+ realised_store->tunnel = -1; /* n/a! */
+ realised_store->owner = *(identity->getPublicPrivateKey ()); /* us! */
}
/* adds a route to prototype route table, unless it has same PublicKey and
tunnel as another entry */
-static void add_route(PublicKey* them, int hops, int tunnel) {
+static void
+add_route (PublicKey * them, int hops, int tunnel)
+{
int i;
route_info *rstore;
int rcapacity;
- for (i = 0; i < route_entries; i++) {
- if (isEqualP(them, &(route_store+i)->owner)) {
- if ((route_store+i)->hops == 0) {
- /* we don't store alternative routes to ourselves,
- * as we already know how to route to ourself
- */
- VLOG _("Not storing route to myself from peer %d\n"), tunnel);
- return;
- }
- if ((route_store+i)->tunnel == tunnel) {
- /* also, we only keep one route to a node per peer,
- * but store the lowest hop count that the peer is
advertising for that node.
- */
- (route_store+i)->hops = mini((route_store+i)->hops,
hops);
- VLOG _("Duplicate route to node from peer %d, choosing
minimum hops"), tunnel);
- return;
- }
- }
- }
+ for (i = 0; i < route_entries; i++)
+ {
+ if (isEqualP (them, &(route_store + i)->owner))
+ {
+ if ((route_store + i)->hops == 0)
+ {
+ /* we don't store alternative routes to ourselves,
+ * as we already know how to route to ourself
+ */
+ VLOG _("Not storing route to myself from peer %d\n"), tunnel);
+ return;
+ }
+ if ((route_store + i)->tunnel == tunnel)
+ {
+ /* also, we only keep one route to a node per peer,
+ * but store the lowest hop count that the peer is advertising
for that node.
+ */
+ (route_store + i)->hops = mini ((route_store + i)->hops, hops);
+ VLOG
+ _
+ ("Duplicate route to node from peer %d, choosing minimum
hops"),
+ tunnel);
+ return;
+ }
+ }
+ }
route_entries++;
- rcapacity = route_entries * sizeof(route_info);
- if (rcapacity > route_capacity) {
- rstore = REALLOC(route_store, rcapacity);
- if (rstore == NULL) {
- route_entries--;
- return; /* not enough ram, we will have to drop this route. */
- }
- route_capacity = rcapacity;
- route_store = rstore;
- }
+ rcapacity = route_entries * sizeof (route_info);
+ if (rcapacity > route_capacity)
+ {
+ rstore = REALLOC (route_store, rcapacity);
+ if (rstore == NULL)
+ {
+ route_entries--;
+ return; /* not enough ram, we will have to drop this
route. */
+ }
+ route_capacity = rcapacity;
+ route_store = rstore;
+ }
/*
* we really should keep the route table in ascending hop count order...
*/
- if (route_entries > 0) {
- i = route_entries - 1; /* i = insert location */
- while ((i > 0) && ((route_store+(i-1))->hops > hops)) {
- (route_store+i)->hops = (route_store+(i-1))->hops;
- (route_store+i)->tunnel = (route_store+(i-1))->hops;
- (route_store+i)->owner = (route_store+(i-1))->owner;
- i--;
- }
- VLOG _("Inserting route from peer %d in route table at location %d\n"),
tunnel, i);
- (route_store+i)->hops = hops;
- (route_store+i)->tunnel = tunnel;
- (route_store+i)->owner = *them;
- }
+ if (route_entries > 0)
+ {
+ i = route_entries - 1; /* i = insert location */
+ while ((i > 0) && ((route_store + (i - 1))->hops > hops))
+ {
+ (route_store + i)->hops = (route_store + (i - 1))->hops;
+ (route_store + i)->tunnel = (route_store + (i - 1))->hops;
+ (route_store + i)->owner = (route_store + (i - 1))->owner;
+ i--;
+ }
+ VLOG _("Inserting route from peer %d in route table at location %d\n"),
+ tunnel, i);
+ (route_store + i)->hops = hops;
+ (route_store + i)->tunnel = tunnel;
+ (route_store + i)->owner = *them;
+ }
}
/**
* Render IPv4 or IPv6 packet info for logging.
*/
-static void ipinfo(char *info, const struct ip6_hdr* fp) {
- struct in_addr fr4;
- struct in_addr to4;
+static void ipinfo (char *info, const struct ip6_hdr *fp)
+{
+ struct in_addr fr4;
+ struct in_addr to4;
- if ((((const struct iphdr*)fp)->version == 4)) {
- fr4.s_addr = ((const struct iphdr*)fp)->saddr;
- to4.s_addr = ((const struct iphdr*)fp)->daddr;
- sprintf(info, "IPv4 %s -> ", inet_ntoa(fr4));
- strcat(info, inet_ntoa(to4));
- return;
- }
- if ((((const struct iphdr*)fp)->version == 6)) {
- sprintf(info, "IPv6 %x:%x:%x:%x:%x:%x:%x:%x -> %x:%x:%x:%x:%x:%x:%x:%x",
- ntohs(fp->ip6_src.s6_addr16[0]),
- ntohs(fp->ip6_src.s6_addr16[1]),
- ntohs(fp->ip6_src.s6_addr16[2]),
- ntohs(fp->ip6_src.s6_addr16[3]),
- ntohs(fp->ip6_src.s6_addr16[4]),
- ntohs(fp->ip6_src.s6_addr16[5]),
- ntohs(fp->ip6_src.s6_addr16[6]),
- ntohs(fp->ip6_src.s6_addr16[7]),
- ntohs(fp->ip6_dst.s6_addr16[0]),
- ntohs(fp->ip6_dst.s6_addr16[1]),
- ntohs(fp->ip6_dst.s6_addr16[2]),
- ntohs(fp->ip6_dst.s6_addr16[3]),
- ntohs(fp->ip6_dst.s6_addr16[4]),
- ntohs(fp->ip6_dst.s6_addr16[5]),
- ntohs(fp->ip6_dst.s6_addr16[6]),
- ntohs(fp->ip6_dst.s6_addr16[7])
- );
- return;
- }
- sprintf(info, "IPv%d ?", ((const struct iphdr*)fp)->version);
+ if ((((const struct iphdr *) fp)->version == 4))
+ {
+ fr4.s_addr = ((const struct iphdr *) fp)->saddr;
+ to4.s_addr = ((const struct iphdr *) fp)->daddr;
+ sprintf (info, "IPv4 %s -> ", inet_ntoa (fr4));
+ strcat (info, inet_ntoa (to4));
+ return;
+ }
+ if ((((const struct iphdr *) fp)->version == 6))
+ {
+ sprintf (info,
+ "IPv6 %x:%x:%x:%x:%x:%x:%x:%x -> %x:%x:%x:%x:%x:%x:%x:%x",
+ ntohs (fp->ip6_src.s6_addr16[0]),
+ ntohs (fp->ip6_src.s6_addr16[1]),
+ ntohs (fp->ip6_src.s6_addr16[2]),
+ ntohs (fp->ip6_src.s6_addr16[3]),
+ ntohs (fp->ip6_src.s6_addr16[4]),
+ ntohs (fp->ip6_src.s6_addr16[5]),
+ ntohs (fp->ip6_src.s6_addr16[6]),
+ ntohs (fp->ip6_src.s6_addr16[7]),
+ ntohs (fp->ip6_dst.s6_addr16[0]),
+ ntohs (fp->ip6_dst.s6_addr16[1]),
+ ntohs (fp->ip6_dst.s6_addr16[2]),
+ ntohs (fp->ip6_dst.s6_addr16[3]),
+ ntohs (fp->ip6_dst.s6_addr16[4]),
+ ntohs (fp->ip6_dst.s6_addr16[5]),
+ ntohs (fp->ip6_dst.s6_addr16[6]),
+ ntohs (fp->ip6_dst.s6_addr16[7]));
+ return;
+ }
+ sprintf (info, "IPv%d ?", ((const struct iphdr *) fp)->version);
}
/** check that ethertype matches ip version for incoming packets from linux
specific code */
-static int valid_incoming(int len, struct tun_pi* tp, struct ip6_hdr* fp) {
+static int valid_incoming (int len, struct tun_pi *tp, struct ip6_hdr *fp)
+{
char info[100];
- if (len > (65535 - sizeof(struct tun_pi))) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("RFC4193 Frame length %d
is too big for GNUnet!\n"), len);
- return NO;
- }
- if (len < sizeof(struct tun_pi)) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("RFC4193 Frame length %d
too small\n"), len);
- return NO;
- }
- if ((ntohs(tp->proto) == ETH_P_IP) && (((struct iphdr*)fp)->version == 4)) {
- return YES;
- } else if ((ntohs(tp->proto) == ETH_P_IPV6) && (((struct iphdr*)fp)->version
== 6)) {
- ipinfo(info, fp);
- VLOG "-> GNUnet(%d) : %s\n", len - sizeof(struct tun_pi), info);
- return YES;
- }
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("RFC4193 Ethertype %x and IP
version %x do not match!\n"),
- ntohs(tp->proto), ((struct iphdr*)fp)->version);
+ if (len > (65535 - sizeof (struct tun_pi)))
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("RFC4193 Frame length %d is too big for GNUnet!\n"), len);
+ return NO;
+ }
+ if (len < sizeof (struct tun_pi))
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("RFC4193 Frame length %d too small\n"), len);
+ return NO;
+ }
+ if ((ntohs (tp->proto) == ETH_P_IP)
+ && (((struct iphdr *) fp)->version == 4))
+ {
+ return YES;
+ }
+ else if ((ntohs (tp->proto) == ETH_P_IPV6)
+ && (((struct iphdr *) fp)->version == 6))
+ {
+ ipinfo (info, fp);
+ VLOG "-> GNUnet(%d) : %s\n", len - sizeof (struct tun_pi), info);
+ return YES;
+ }
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("RFC4193 Ethertype %x and IP version %x do not match!\n"),
+ ntohs (tp->proto), ((struct iphdr *) fp)->version);
return NO;
}
/** Test if two PeerIdentity are equal or not */
-static int isEqual(const PeerIdentity *first, const PeerIdentity *second) {
+static int isEqual (const PeerIdentity * first, const PeerIdentity * second)
+{
int i;
- for (i = 0; i < 512/8/sizeof(unsigned int); i++) {
- if (first->hashPubKey.bits[i] != second->hashPubKey.bits[i]) {
- return 0;
- }
- }
+ for (i = 0; i < 512 / 8 / sizeof (unsigned int); i++)
+ {
+ if (first->hashPubKey.bits[i] != second->hashPubKey.bits[i])
+ {
+ return 0;
+ }
+ }
return -1;
}
@@ -442,18 +508,21 @@
* Convert a PeerIdentify into a "random" RFC4193 prefix
* actually we make the first 40 bits of the hash into the prefix!
*/
-static void id2ip(struct ClientHandle * cx, const PeerIdentity* them) {
- unsigned char a,b,c,d,e;
+static void id2ip (struct ClientHandle *cx, const PeerIdentity * them)
+{
+ unsigned char a, b, c, d, e;
a = (them->hashPubKey.bits[0] >> 8) & 0xff;
b = (them->hashPubKey.bits[0] >> 0) & 0xff;
c = (them->hashPubKey.bits[1] >> 8) & 0xff;
d = (them->hashPubKey.bits[1] >> 0) & 0xff;
e = (them->hashPubKey.bits[2] >> 8) & 0xff;
- cprintf(cx, CS_PROTO_VPN_REPLY, "fd%02x:%02x%02x:%02x%02x",a,b,c,d,e);
+ cprintf (cx, CS_PROTO_VPN_REPLY, "fd%02x:%02x%02x:%02x%02x", a, b, c, d, e);
}
+
/* convert PeerIdentity into network octet order IPv6 address */
-static void id2net(struct in6_addr* buf, const PeerIdentity* them) {
- unsigned char a,b,c,d,e;
+static void id2net (struct in6_addr *buf, const PeerIdentity * them)
+{
+ unsigned char a, b, c, d, e;
a = (them->hashPubKey.bits[0] >> 8) & 0xff;
b = (them->hashPubKey.bits[0] >> 0) & 0xff;
c = (them->hashPubKey.bits[1] >> 8) & 0xff;
@@ -461,9 +530,9 @@
e = (them->hashPubKey.bits[2] >> 8) & 0xff;
/* we are unique random */
- buf->s6_addr16[0] = htons(0xfd00 + a);
- buf->s6_addr16[1] = htons(b * 256 + c);
- buf->s6_addr16[2] = htons(d * 256 + e);
+ buf->s6_addr16[0] = htons (0xfd00 + a);
+ buf->s6_addr16[1] = htons (b * 256 + c);
+ buf->s6_addr16[2] = htons (d * 256 + e);
/* IPv6 /48 subnet number is zero */
buf->s6_addr16[3] = 0;
@@ -475,23 +544,25 @@
buf->s6_addr16[7] = 0;
}
-static void setup_tunnel(int n, const PeerIdentity *them) {
+static void setup_tunnel (int n, const PeerIdentity * them)
+{
struct ifreq ifr;
struct in6_ifreq ifr6;
struct in6_rtmsg rt;
int i, used, fd, id = 0;
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("RFC4193 Going to try
and make a tunnel in slot %d\n"), n);
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("RFC4193 Going to try and make a tunnel in slot %d\n"), n);
- fd = open("/dev/net/tun", O_RDWR);
- if (fd < 0) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("Cannot open tunnel device
because of %s"), strerror(fd));
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_BULK,
- "open");
- }
- memset(&ifr, 0, sizeof(ifr));
+ fd = open ("/dev/net/tun", O_RDWR);
+ if (fd < 0)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Cannot open tunnel device because of %s"), strerror (fd));
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_ADMIN | GE_BULK, "open");
+ }
+ memset (&ifr, 0, sizeof (ifr));
/* IFF_TUN = IP Packets
* IFF_TAP = Ethernet packets
@@ -511,34 +582,48 @@
ifr.ifr_flags = IFF_TUN;
/* try various names until we find a free one */
- do {
- used = 0;
- for (i = 0; i < entries1; i++) {
- if ((store1+i)->id == id) {
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
_("RFC4193 Create skips gnu%d as we are already using it\n"), id);
- id++;
- used = 1;
- }
- }
- if (used == 0) {
- sprintf(ifr.ifr_name, "gnu%d", id);
- if ( ioctl(fd, TUNSETIFF, (void *) &ifr) < 0) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("Cannot
set tunnel name to %s because of %s\n"), ifr.ifr_name, strerror(errno));
- id++;
- used = 1;
- } else {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
_("Configured tunnel name to %s\n"), ifr.ifr_name);
- }
- }
- } while (used);
+ do
+ {
+ used = 0;
+ for (i = 0; i < entries1; i++)
+ {
+ if ((store1 + i)->id == id)
+ {
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _
+ ("RFC4193 Create skips gnu%d as we are already using
it\n"),
+ id);
+ id++;
+ used = 1;
+ }
+ }
+ if (used == 0)
+ {
+ sprintf (ifr.ifr_name, "gnu%d", id);
+ if (ioctl (fd, TUNSETIFF, (void *) &ifr) < 0)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Cannot set tunnel name to %s because of %s\n"),
+ ifr.ifr_name, strerror (errno));
+ id++;
+ used = 1;
+ }
+ else
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Configured tunnel name to %s\n"), ifr.ifr_name);
+ }
+ }
+ }
+ while (used);
- ioctl(fd, TUNSETNOCSUM, 1);
- memcpy(&((store1+n)->peer), them, sizeof(PeerIdentity));
- (store1+n)->id = id;
- (store1+n)->fd = fd;
- (store1+n)->active = YES;
- (store1+n)->route_entry = 0;
+ ioctl (fd, TUNSETNOCSUM, 1);
+ memcpy (&((store1 + n)->peer), them, sizeof (PeerIdentity));
+ (store1 + n)->id = id;
+ (store1 + n)->fd = fd;
+ (store1 + n)->active = YES;
+ (store1 + n)->route_entry = 0;
/* tun_alloc can change the tunnel name */
/* strncpy((store1+n)->name, ifr.ifr_name,IFNAMSIZ); */
@@ -546,13 +631,13 @@
/* here we should give the tunnel an IPv6 address and fake up a route to the
other end
* the format looks like this, and the net/host split is fixed at /48 as in
rfc4193
* local /64
- * net: my PeerIdentity
- * subnet: interface number+2
- * interface: NULL
+ * net: my PeerIdentity
+ * subnet: interface number+2
+ * interface: NULL
*
* remote /48
- * net: their PeerIdentity
- * host: NULL (it's not needed for routes)
+ * net: their PeerIdentity
+ * host: NULL (it's not needed for routes)
*/
/* Run some system commands to set it up... */
@@ -564,109 +649,138 @@
/* Bring interface up, like system("sudo ifconfig %s up"); */
/* not needed, we already have the iface name ... strncpy(ifr.ifr_name,
name, IFNAMSIZ); */
- if (ioctl(admin_fd, SIOCGIFFLAGS, &ifr) < 0) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("Cannot get socket flags
for gnu%d because %s\n"), id, strerror(errno));
- } else {
- ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
- if (ioctl(admin_fd, SIOCSIFFLAGS, &ifr) < 0) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("Cannot set socket
flags for gnu%d because %s\n"), id, strerror(errno));
- }
- }
+ if (ioctl (admin_fd, SIOCGIFFLAGS, &ifr) < 0)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Cannot get socket flags for gnu%d because %s\n"), id,
+ strerror (errno));
+ }
+ else
+ {
+ ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
+ if (ioctl (admin_fd, SIOCSIFFLAGS, &ifr) < 0)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Cannot set socket flags for gnu%d because %s\n"), id,
+ strerror (errno));
+ }
+ }
/* Seems to go better with lower mtu, aka system("sudo ifconfig %s mtu
1280") */
ifr.ifr_mtu = 1280;
- if (ioctl(admin_fd, SIOCSIFMTU, &ifr) < 0) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("Cannot set MTU for gnu%d
because %s\n"), id, strerror(errno));
- }
+ if (ioctl (admin_fd, SIOCSIFMTU, &ifr) < 0)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Cannot set MTU for gnu%d because %s\n"), id,
+ strerror (errno));
+ }
/* lets add an IP address... aka "sudo ifconfig %s add %s:%04x::1/64" */
- if (ioctl(admin_fd, SIOCGIFINDEX, &ifr) < 0) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("Cannot get interface
index for gnu%d because %s\n"), id, strerror(errno));
- } else {
- /* note to self... htons(64) = kernel oops. */
- (store1+n)->ifindex = ifr.ifr_ifindex;
- ifr6.ifr6_prefixlen = 64;
- ifr6.ifr6_ifindex = ifr.ifr_ifindex;
- id2net(&ifr6.ifr6_addr, coreAPI->myIdentity);
- ifr6.ifr6_addr.s6_addr16[3] = htons(n+VC_START);
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("IPv6 ifaddr gnu%d
- %x:%x:%x:%x:%x:%x:%x:%x/%d\n"),
- id,
- ntohs(ifr6.ifr6_addr.s6_addr16[0]),
- ntohs(ifr6.ifr6_addr.s6_addr16[1]),
- ntohs(ifr6.ifr6_addr.s6_addr16[2]),
- ntohs(ifr6.ifr6_addr.s6_addr16[3]),
- ntohs(ifr6.ifr6_addr.s6_addr16[4]),
- ntohs(ifr6.ifr6_addr.s6_addr16[5]),
- ntohs(ifr6.ifr6_addr.s6_addr16[6]),
- ntohs(ifr6.ifr6_addr.s6_addr16[7]),
- ifr6.ifr6_prefixlen);
- if (ioctl(admin_fd, SIOCSIFADDR, &ifr6) < 0) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("Cannot set
interface IPv6 address for gnu%d because %s\n"), id, strerror(errno));
- }
-
- /* lets add a route to the peer, aka "#sudo route -A inet6 add %s::/48
dev %s" */
- memset((char*)&rt, 0, sizeof(struct in6_rtmsg));
- /* rtmsg_ifindex would be zero for routes not specifying a device, such
as by gateway */
- rt.rtmsg_ifindex = ifr.ifr_ifindex;
- id2net(&rt.rtmsg_dst, them);
- rt.rtmsg_flags = RTF_UP;
- rt.rtmsg_metric = 1; /* how many hops to owner of public key */
- rt.rtmsg_dst_len = 48; /* network prefix len is 48 by standard */
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("IPv6 route gnu%d
- destination %x:%x:%x:%x:%x:%x:%x:%x/%d\n"),
- id,
- ntohs(rt.rtmsg_dst.s6_addr16[0]),
- ntohs(rt.rtmsg_dst.s6_addr16[1]),
- ntohs(rt.rtmsg_dst.s6_addr16[2]),
- ntohs(rt.rtmsg_dst.s6_addr16[3]),
- ntohs(rt.rtmsg_dst.s6_addr16[4]),
- ntohs(rt.rtmsg_dst.s6_addr16[5]),
- ntohs(rt.rtmsg_dst.s6_addr16[6]),
- ntohs(rt.rtmsg_dst.s6_addr16[7]),
- rt.rtmsg_dst_len);
- if (ioctl(admin_fd, SIOCADDRT, &rt) < 0) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("Cannot add route
IPv6 address for gnu%s because %s\n"), id, strerror(errno));
- }
- }
+ if (ioctl (admin_fd, SIOCGIFINDEX, &ifr) < 0)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Cannot get interface index for gnu%d because %s\n"), id,
+ strerror (errno));
+ }
+ else
+ {
+ /* note to self... htons(64) = kernel oops. */
+ (store1 + n)->ifindex = ifr.ifr_ifindex;
+ ifr6.ifr6_prefixlen = 64;
+ ifr6.ifr6_ifindex = ifr.ifr_ifindex;
+ id2net (&ifr6.ifr6_addr, coreAPI->myIdentity);
+ ifr6.ifr6_addr.s6_addr16[3] = htons (n + VC_START);
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("IPv6 ifaddr gnu%d - %x:%x:%x:%x:%x:%x:%x:%x/%d\n"), id,
+ ntohs (ifr6.ifr6_addr.s6_addr16[0]),
+ ntohs (ifr6.ifr6_addr.s6_addr16[1]),
+ ntohs (ifr6.ifr6_addr.s6_addr16[2]),
+ ntohs (ifr6.ifr6_addr.s6_addr16[3]),
+ ntohs (ifr6.ifr6_addr.s6_addr16[4]),
+ ntohs (ifr6.ifr6_addr.s6_addr16[5]),
+ ntohs (ifr6.ifr6_addr.s6_addr16[6]),
+ ntohs (ifr6.ifr6_addr.s6_addr16[7]), ifr6.ifr6_prefixlen);
+ if (ioctl (admin_fd, SIOCSIFADDR, &ifr6) < 0)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("Cannot set interface IPv6 address for gnu%d because %s\n"),
+ id, strerror (errno));
+ }
+
+ /* lets add a route to the peer, aka "#sudo route -A inet6 add %s::/48
dev %s" */
+ memset ((char *) &rt, 0, sizeof (struct in6_rtmsg));
+ /* rtmsg_ifindex would be zero for routes not specifying a device, such
as by gateway */
+ rt.rtmsg_ifindex = ifr.ifr_ifindex;
+ id2net (&rt.rtmsg_dst, them);
+ rt.rtmsg_flags = RTF_UP;
+ rt.rtmsg_metric = 1; /* how many hops to owner of public key */
+ rt.rtmsg_dst_len = 48; /* network prefix len is 48 by standard */
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _
+ ("IPv6 route gnu%d - destination %x:%x:%x:%x:%x:%x:%x:%x/%d\n"),
+ id, ntohs (rt.rtmsg_dst.s6_addr16[0]),
+ ntohs (rt.rtmsg_dst.s6_addr16[1]),
+ ntohs (rt.rtmsg_dst.s6_addr16[2]),
+ ntohs (rt.rtmsg_dst.s6_addr16[3]),
+ ntohs (rt.rtmsg_dst.s6_addr16[4]),
+ ntohs (rt.rtmsg_dst.s6_addr16[5]),
+ ntohs (rt.rtmsg_dst.s6_addr16[6]),
+ ntohs (rt.rtmsg_dst.s6_addr16[7]), rt.rtmsg_dst_len);
+ if (ioctl (admin_fd, SIOCADDRT, &rt) < 0)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Cannot add route IPv6 address for gnu%s because %s\n"),
+ id, strerror (errno));
+ }
+ }
}
/**
* See if we already got a TUN/TAP open for the given GNUnet peer. if not,
make one, stick
* PeerIdentity and the filehandle and name of the TUN/TAP in an array so we
remember we did it.
*/
-static void checkensure_peer(const PeerIdentity *them, void *callerinfo) {
+static void checkensure_peer (const PeerIdentity * them, void *callerinfo)
+{
int i;
- tunnel_info* rstore1;
+ tunnel_info *rstore1;
int rcapacity1;
/* GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("RFC4193 Going to
checkensure peer %x then\n"), them->hashPubKey.bits[0]); */
/* first entry in array will be known as gnu0 */
/* if a tunnel is already setup, we don't setup another */
- for (i = 0; i < entries1; i++) {
- if (isEqual(them, &((store1+i)->peer))) {
- (store1+i)->active = YES;
- return;
- }
- }
+ for (i = 0; i < entries1; i++)
+ {
+ if (isEqual (them, &((store1 + i)->peer)))
+ {
+ (store1 + i)->active = YES;
+ return;
+ }
+ }
/*
* append it at the end.
*/
entries1++;
- rcapacity1 = entries1 * sizeof(tunnel_info);
- if (rcapacity1 > capacity1) {
- rstore1 = REALLOC(store1, rcapacity1);
- if (rstore1 == NULL) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("RFC4193 We have
run out of memory and so I can't store a tunnel for this peer.\n"));
- entries1--;
- return;
- }
- store1 = rstore1;
- capacity1 = rcapacity1;
- }
+ rcapacity1 = entries1 * sizeof (tunnel_info);
+ if (rcapacity1 > capacity1)
+ {
+ rstore1 = REALLOC (store1, rcapacity1);
+ if (rstore1 == NULL)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("RFC4193 We have run out of memory and so I can't store a
tunnel for this peer.\n"));
+ entries1--;
+ return;
+ }
+ store1 = rstore1;
+ capacity1 = rcapacity1;
+ }
/* GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("RFC4193 Extending
array for new tunnel\n")); */
- setup_tunnel((entries1 - 1), them);
+ setup_tunnel ((entries1 - 1), them);
}
/* make new thread...
@@ -678,7 +792,8 @@
* own IPv6 addr is fdXX:XXXX:XXXX::P/48 where X= 40 bits own key, P = gnu0 + 2
* route add -net fdXX(remote key) dev gnu0 is then used.
*/
-static void * tunThread(void* arg) {
+static void *tunThread (void *arg)
+{
fd_set readSet;
fd_set errorSet;
fd_set writeSet;
@@ -691,89 +806,103 @@
* other systems like HURD, etc may use different headers
*/
char frame[IP_FRAME + HEADER_FRAME];
- struct ip6_hdr* fp;
- struct tun_pi* tp;
- MESSAGE_HEADER* gp;
+ struct ip6_hdr *fp;
+ struct tun_pi *tp;
+ MESSAGE_HEADER *gp;
struct timeval timeout;
/* need the cast otherwise it increments by HEADER_FRAME * sizeof(frame)
rather than HEADER_FRAME */
- fp = (struct ip6_hdr*)(((char*)&frame) + HEADER_FRAME);
+ fp = (struct ip6_hdr *) (((char *) &frame) + HEADER_FRAME);
/* this trick decrements the pointer by the sizes of the respective structs
*/
- tp = ((struct tun_pi*)fp)-1;
- gp = ((MESSAGE_HEADER*)fp)-1;
+ tp = ((struct tun_pi *) fp) - 1;
+ gp = ((MESSAGE_HEADER *) fp) - 1;
running = 1;
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("RFC4193 Thread running
(frame %d tunnel %d f2f %d) ...\n"), fp, tp, gp);
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("RFC4193 Thread running (frame %d tunnel %d f2f %d) ...\n"), fp,
+ tp, gp);
- MUTEX_LOCK(lock);
- while (running) {
+ MUTEX_LOCK (lock);
+ while (running)
+ {
- FD_ZERO(&readSet);
- FD_ZERO(&errorSet);
- FD_ZERO(&writeSet);
+ FD_ZERO (&readSet);
+ FD_ZERO (&errorSet);
+ FD_ZERO (&writeSet);
- max = signalingPipe[0];
+ max = signalingPipe[0];
- if (-1 != FSTAT(signalingPipe[0], &statinfo)) {
- FD_SET(signalingPipe[0], &readSet);
- } else {
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_BULK,
- "fstat");
- }
- for (i = 0; i < entries1; i++) {
- FD_SET(((store1+i)->fd), &readSet);
- max = maxi(max,(store1+i)->fd);
- }
- MUTEX_UNLOCK(lock);
- timeout.tv_sec = interval;
- timeout.tv_usec = 0;
+ if (-1 != FSTAT (signalingPipe[0], &statinfo))
+ {
+ FD_SET (signalingPipe[0], &readSet);
+ }
+ else
+ {
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_ADMIN | GE_BULK, "fstat");
+ }
+ for (i = 0; i < entries1; i++)
+ {
+ FD_SET (((store1 + i)->fd), &readSet);
+ max = maxi (max, (store1 + i)->fd);
+ }
+ MUTEX_UNLOCK (lock);
+ timeout.tv_sec = interval;
+ timeout.tv_usec = 0;
- ret = SELECT(max+1,
- &readSet,
- &writeSet,
- &errorSet,
- &timeout);
- if (ret < 0) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, "From the vpn
select: %s\n", strerror(errno));
- running = 0;
- break;
- }
- if (FD_ISSET(signalingPipe[0], &readSet)) {
- if (0 >= READ(signalingPipe[0],
- &tmp[0],
- MAXSIG_BUF))
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- "vpn could not read from exit control
pipe\n");
- }
- MUTEX_LOCK(lock);
- for (i = 0; i < entries1; i++) {
- if (FD_ISSET(((store1+i)->fd), &readSet)) {
- ret = read(((store1+i)->fd), tp, IP_FRAME);
+ ret = SELECT (max + 1, &readSet, &writeSet, &errorSet, &timeout);
+ if (ret < 0)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ "From the vpn select: %s\n", strerror (errno));
+ running = 0;
+ break;
+ }
+ if (FD_ISSET (signalingPipe[0], &readSet))
+ {
+ if (0 >= READ (signalingPipe[0], &tmp[0], MAXSIG_BUF))
+ GE_LOG_STRERROR (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ "vpn could not read from exit control pipe\n");
+ }
+ MUTEX_LOCK (lock);
+ for (i = 0; i < entries1; i++)
+ {
+ if (FD_ISSET (((store1 + i)->fd), &readSet))
+ {
+ ret = read (((store1 + i)->fd), tp, IP_FRAME);
- /* goodbye IPv6 packet, enjoy the GNUnet... :-)
- * IP is of course very important so it will enjoy
- * the very highest priority
- */
- if (valid_incoming(ret, tp, fp)) {
- gp->type = htons(P2P_PROTO_aip_IP);
- gp->size = htons(sizeof(MESSAGE_HEADER) + ret -
sizeof(struct tun_pi));
-
coreAPI->unicast(&((store1+i)->peer),gp,EXTREME_PRIORITY,1);
-
coreAPI->preferTrafficFrom(&((store1+i)->peer),1000);
- }
- }
- /* we do this here as we get a race if the p2p handler tries it
*/
- if (((store1+i)->active) == 0) {
- if ( close( (store1+i)->fd ) == 0) {
- GE_LOG(ectx, GE_INFO | GE_REQUEST | GE_USER,
_("VPN dropping connection %x\n"), i);
- *(store1+i) = *(store1+(entries1-1));
- entries1--;
- } else {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
_("VPN cannot drop connection %x\n"), i);
- }
- }
- }
+ /* goodbye IPv6 packet, enjoy the GNUnet... :-)
+ * IP is of course very important so it will enjoy
+ * the very highest priority
+ */
+ if (valid_incoming (ret, tp, fp))
+ {
+ gp->type = htons (P2P_PROTO_aip_IP);
+ gp->size =
+ htons (sizeof (MESSAGE_HEADER) + ret -
+ sizeof (struct tun_pi));
+ coreAPI->unicast (&((store1 + i)->peer), gp,
+ EXTREME_PRIORITY, 1);
+ coreAPI->preferTrafficFrom (&((store1 + i)->peer), 1000);
+ }
+ }
+ /* we do this here as we get a race if the p2p handler tries it */
+ if (((store1 + i)->active) == 0)
+ {
+ if (close ((store1 + i)->fd) == 0)
+ {
+ GE_LOG (ectx, GE_INFO | GE_REQUEST | GE_USER,
+ _("VPN dropping connection %x\n"), i);
+ *(store1 + i) = *(store1 + (entries1 - 1));
+ entries1--;
+ }
+ else
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("VPN cannot drop connection %x\n"), i);
+ }
+ }
+ }
/*
if (timeout.tv_sec < (interval / 2)) {
for (i = 0; i < entries1; i++) {
@@ -787,9 +916,10 @@
}
}
*/
- }
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("RFC4193 Thread
exiting\n"));
- MUTEX_UNLOCK(lock);
+ }
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("RFC4193 Thread exiting\n"));
+ MUTEX_UNLOCK (lock);
return NULL;
}
@@ -801,172 +931,211 @@
* Mainly this routine exchanges the MESSAGE_HEADER on incoming ipv6 packets
* for a TUN/TAP header for writing it to TUNTAP.
*/
-static int handlep2pMSG(const PeerIdentity * sender, const MESSAGE_HEADER *
gp) {
+static int handlep2pMSG (const PeerIdentity * sender,
+ const MESSAGE_HEADER * gp)
+{
int i = 0, fd;
char loginfo[100];
- MESSAGE_HEADER * rgp = NULL;
- char frame[IP_FRAME + sizeof(struct tun_pi)];
- const struct ip6_hdr* fp = (struct ip6_hdr*)(gp+1);
- struct ip6_hdr* new_fp = (struct ip6_hdr*)(((char*)&frame) +
sizeof(struct tun_pi));
- struct tun_pi* tp = (struct tun_pi*)(&frame);
+ MESSAGE_HEADER *rgp = NULL;
+ char frame[IP_FRAME + sizeof (struct tun_pi)];
+ const struct ip6_hdr *fp = (struct ip6_hdr *) (gp + 1);
+ struct ip6_hdr *new_fp =
+ (struct ip6_hdr *) (((char *) &frame) + sizeof (struct tun_pi));
+ struct tun_pi *tp = (struct tun_pi *) (&frame);
- switch (ntohs(gp->type)) {
- case P2P_PROTO_aip_IP:
- tp->flags = 0;
+ switch (ntohs (gp->type))
+ {
+ case P2P_PROTO_aip_IP:
+ tp->flags = 0;
- /* better check src/dst IP for anonymity preservation requirements
here...
- * I.e. in fd::/8 and check next header as well.
- *
- * Also permit multicast [ RFC 3306 ] ff3x:0030:fdnn:nnnn:nnnn::/96
- * where x = diameter. n are the random bits from the allocater's IP
- * (and must match the sender's )
- * 30 = usual bit length of a sender's node/network-prefix,
- * we allow longer, and that must match sender if specified.
- */
- switch (((struct iphdr*)fp)->version) {
- case 6:
- tp->proto = htons(ETH_P_IPV6);
- if ( ntohs(fp->ip6_src.s6_addr16[0]) < 0xFD00 ) {
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER |
GE_REQUEST, _("VPN IP src not anonymous. drop..\n"));
- return OK;
- }
- if ( ntohs(fp->ip6_dst.s6_addr16[0]) < 0xFD00 ) {
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER |
GE_REQUEST, _("VPN IP not anonymous, drop.\n"));
- return OK;
- }
- break;
- case 4:
- tp->proto = htons(ETH_P_IP);
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
_("VPN Received, not anonymous, drop.\n"));
- return OK;
- default:
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("VPN
Received unknown IP version %d...\n"), ((struct iphdr*)fp)->version);
- return OK;
- }
+ /* better check src/dst IP for anonymity preservation requirements
here...
+ * I.e. in fd::/8 and check next header as well.
+ *
+ * Also permit multicast [ RFC 3306 ] ff3x:0030:fdnn:nnnn:nnnn::/96
+ * where x = diameter. n are the random bits from the allocater's IP
+ * (and must match the sender's )
+ * 30 = usual bit length of a sender's node/network-prefix,
+ * we allow longer, and that must match sender if specified.
+ */
+ switch (((struct iphdr *) fp)->version)
+ {
+ case 6:
+ tp->proto = htons (ETH_P_IPV6);
+ if (ntohs (fp->ip6_src.s6_addr16[0]) < 0xFD00)
+ {
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("VPN IP src not anonymous. drop..\n"));
+ return OK;
+ }
+ if (ntohs (fp->ip6_dst.s6_addr16[0]) < 0xFD00)
+ {
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("VPN IP not anonymous, drop.\n"));
+ return OK;
+ }
+ break;
+ case 4:
+ tp->proto = htons (ETH_P_IP);
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("VPN Received, not anonymous, drop.\n"));
+ return OK;
+ default:
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("VPN Received unknown IP version %d...\n"),
+ ((struct iphdr *) fp)->version);
+ return OK;
+ }
- ipinfo(loginfo, fp);
+ ipinfo (loginfo, fp);
- /* do packet memcpy outside of mutex for speed */
- memcpy(new_fp, fp, ntohs(gp->size)-sizeof(MESSAGE_HEADER));
+ /* do packet memcpy outside of mutex for speed */
+ memcpy (new_fp, fp, ntohs (gp->size) - sizeof (MESSAGE_HEADER));
- MUTEX_LOCK(lock);
- VLOG _("<- GNUnet(%d) : %s\n"), ntohs(gp->size) -
sizeof(MESSAGE_HEADER), loginfo);
- for (i = 0; i < entries1; i++) {
- if (isEqual(sender, &((store1+i)->peer))) {
- fd = ((store1+i)->fd);
+ MUTEX_LOCK (lock);
+ VLOG _("<- GNUnet(%d) : %s\n"),
+ ntohs (gp->size) - sizeof (MESSAGE_HEADER), loginfo);
+ for (i = 0; i < entries1; i++)
+ {
+ if (isEqual (sender, &((store1 + i)->peer)))
+ {
+ fd = ((store1 + i)->fd);
- (store1+i)->active = YES;
+ (store1 + i)->active = YES;
- /* We are only allowed one call to write() per packet.
- * We need to write packet and packetinfo together in
one go.
- */
- write(fd, tp, ntohs(gp->size) + sizeof(struct tun_pi) -
sizeof(MESSAGE_HEADER));
- coreAPI->preferTrafficFrom(&((store1+i)->peer),1000);
- MUTEX_UNLOCK(lock);
+ /* We are only allowed one call to write() per packet.
+ * We need to write packet and packetinfo together in one go.
+ */
+ write (fd, tp,
+ ntohs (gp->size) + sizeof (struct tun_pi) -
+ sizeof (MESSAGE_HEADER));
+ coreAPI->preferTrafficFrom (&((store1 + i)->peer), 1000);
+ MUTEX_UNLOCK (lock);
+ return OK;
+ }
+ }
+ /* do not normally get here... but checkensure so any future packets
could be routed... */
+ checkensure_peer (sender, NULL);
+ MUTEX_UNLOCK (lock);
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _
+ ("Could not write the tunnelled IP to the OS... Did to setup a
tunnel?\n"));
+ return OK;
+ case p2p_PROTO_PONG:
+ MUTEX_LOCK (lock);
+ checkensure_peer (sender, NULL);
+ MUTEX_UNLOCK (lock);
+ return OK;
+ case P2P_PROTO_hangup:
+ MUTEX_LOCK (lock);
+ for (i = 0; i < entries1; i++)
+ {
+ if ((((store1 + i)->fd) > 0) &&
+ isEqual (sender, &((store1 + i)->peer)))
+ {
+ (store1 + i)->active = NO;
+ }
+ }
+ MUTEX_UNLOCK (lock);
+ return OK;
+ case P2P_PROTO_aip_GETROUTE:
+ /** peer wants an entry from our routing table */
+ VLOG _("Receive route request\n"));
+ if (ntohs (gp->size) == (sizeof (MESSAGE_HEADER) + sizeof (int)))
+ {
+ i = ntohl (*((int *) fp));
+ MUTEX_LOCK (lock);
+ if (i < realised_entries)
+ {
+ VLOG _("Prepare route announcement level %d\n"), i);
+ rgp = MALLOC (sizeof (MESSAGE_HEADER) + sizeof (transit_route));
+ if (rgp == NULL)
+ {
+ MUTEX_UNLOCK (lock);
+ return OK;
+ }
+ rgp->size =
+ htons (sizeof (MESSAGE_HEADER) + sizeof (transit_route));
+ rgp->type = htons (P2P_PROTO_aip_ROUTE);
+ ((transit_route *) (rgp + 1))->owner =
+ (realised_store + i)->owner;
+ ((transit_route *) (rgp + 1))->hops =
+ htonl ((realised_store + i)->hops);
+ MUTEX_UNLOCK (lock);
+ VLOG _("Send route announcement %d with route announce\n"), i);
+ /* it must be delivered if possible, but it can wait longer than
IP */
+ coreAPI->unicast (sender, rgp, EXTREME_PRIORITY, 15);
+ FREE (rgp);
+ return OK;
+ }
+ VLOG _("Send outside table info %d\n"), i);
+ rgp = MALLOC (sizeof (MESSAGE_HEADER) + sizeof (int));
+ if (rgp == NULL)
+ {
+ MUTEX_UNLOCK (lock);
+ return OK;
+ }
+ rgp->size = htons (sizeof (MESSAGE_HEADER) + sizeof (int));
+ rgp->type = htons (P2P_PROTO_aip_ROUTES);
+ *((int *) (rgp + 1)) = htonl (realised_entries);
+ MUTEX_UNLOCK (lock);
+ coreAPI->unicast (sender, rgp, EXTREME_PRIORITY, 15);
+ FREE (rgp);
+ return OK;
+ }
+ return OK;
+ case P2P_PROTO_aip_ROUTE:
+ VLOG _("Receive route announce.\n"));
+ /** peer sent us a route, insert it into routing table, then req next
entry */
+ if (ntohs (gp->size) ==
+ (sizeof (MESSAGE_HEADER) + sizeof (transit_route)))
+ {
+ MUTEX_LOCK (lock);
+ VLOG _("Going to try insert route into local table.\n"));
+ for (i = 0; i < entries1; i++)
+ {
+ if (isEqual (sender, &((store1 + i)->peer)))
+ {
+ (store1 + i)->active = YES;
+ VLOG _("Inserting with hops %d\n"),
+ ntohl (((transit_route *) (gp + 1))->hops));
+ add_route (&(((transit_route *) (gp + 1))->owner),
+ 1 + ntohl (((transit_route *) (gp + 1))->hops),
+ i);
+ if ((store1 + i)->route_entry < GNUNET_VIEW_LIMIT)
+ {
+ (store1 + i)->route_entry++;
+ rgp = MALLOC (sizeof (MESSAGE_HEADER) + sizeof (int));
+ if (rgp == NULL)
+ {
+ MUTEX_UNLOCK (lock);
return OK;
- }
- }
- /* do not normally get here... but checkensure so any future packets
could be routed... */
- checkensure_peer(sender, NULL);
- MUTEX_UNLOCK(lock);
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("Could not write
the tunnelled IP to the OS... Did to setup a tunnel?\n"));
- return OK;
- case p2p_PROTO_PONG:
- MUTEX_LOCK(lock);
- checkensure_peer(sender, NULL);
- MUTEX_UNLOCK(lock);
- return OK;
- case P2P_PROTO_hangup:
- MUTEX_LOCK(lock);
- for (i = 0; i < entries1; i++) {
- if (
- (((store1+i)->fd) > 0) &&
- isEqual(sender, &((store1+i)->peer))
- ) {
- (store1+i)->active = NO;
- }
- }
- MUTEX_UNLOCK(lock);
- return OK;
- case P2P_PROTO_aip_GETROUTE:
- /** peer wants an entry from our routing table */
- VLOG _("Receive route request\n"));
- if (ntohs(gp->size) == (sizeof(MESSAGE_HEADER) + sizeof(int))) {
- i = ntohl(*((int*)fp));
- MUTEX_LOCK(lock);
- if (i < realised_entries) {
- VLOG _("Prepare route announcement level %d\n"), i);
- rgp = MALLOC(sizeof(MESSAGE_HEADER) +
sizeof(transit_route));
- if (rgp == NULL) {
- MUTEX_UNLOCK(lock);
- return OK;
- }
- rgp->size = htons(sizeof(MESSAGE_HEADER) +
sizeof(transit_route));
- rgp->type = htons(P2P_PROTO_aip_ROUTE);
- ((transit_route*)(rgp+1))->owner =
(realised_store+i)->owner;
- ((transit_route*)(rgp+1))->hops =
htonl((realised_store+i)->hops);
- MUTEX_UNLOCK(lock);
- VLOG _("Send route announcement %d with route
announce\n"), i);
- /* it must be delivered if possible, but it can wait
longer than IP */
- coreAPI->unicast(sender, rgp, EXTREME_PRIORITY, 15);
- FREE(rgp);
- return OK;
- }
- VLOG _("Send outside table info %d\n"), i);
- rgp = MALLOC(sizeof(MESSAGE_HEADER) + sizeof(int));
- if (rgp == NULL) {
- MUTEX_UNLOCK(lock);
- return OK;
- }
- rgp->size = htons(sizeof(MESSAGE_HEADER) + sizeof(int));
- rgp->type = htons(P2P_PROTO_aip_ROUTES);
- *((int*)(rgp+1)) = htonl(realised_entries);
- MUTEX_UNLOCK(lock);
- coreAPI->unicast(sender, rgp, EXTREME_PRIORITY, 15);
- FREE(rgp);
- return OK;
- }
- return OK;
- case P2P_PROTO_aip_ROUTE:
- VLOG _("Receive route announce.\n"));
- /** peer sent us a route, insert it into routing table, then req next
entry */
- if (ntohs(gp->size) == (sizeof(MESSAGE_HEADER) +
sizeof(transit_route))) {
- MUTEX_LOCK(lock);
- VLOG _("Going to try insert route into local table.\n"));
- for (i = 0; i < entries1; i++) {
- if (isEqual(sender, &((store1+i)->peer))) {
- (store1+i)->active = YES;
- VLOG _("Inserting with hops %d\n"), ntohl(
((transit_route*)(gp+1))->hops));
- add_route( &(
((transit_route*)(gp+1))->owner ),
- 1 + ntohl(
((transit_route*)(gp+1))->hops),
- i);
- if ((store1+i)->route_entry <
GNUNET_VIEW_LIMIT) {
- (store1+i)->route_entry++;
- rgp = MALLOC(sizeof(MESSAGE_HEADER) +
sizeof(int));
- if (rgp == NULL) {
- MUTEX_UNLOCK(lock);
- return OK;
- }
- rgp->type =
htons(P2P_PROTO_aip_GETROUTE);
- rgp->size =
htons(sizeof(MESSAGE_HEADER) + sizeof(int));
- *((int*)(rgp+1)) =
htonl((store1+i)->route_entry);
- VLOG _("Request level %d from peer
%d\n"), (store1+i)->route_entry, i);
-
coreAPI->unicast(&((store1+i)->peer),rgp,EXTREME_PRIORITY,60);
- FREE(rgp);
- }
- break;
- }
- }
- MUTEX_UNLOCK(lock);
- }
- return OK;
- case P2P_PROTO_aip_ROUTES:
- if (ntohs(gp->size) == (sizeof(MESSAGE_HEADER) + sizeof(int))) {
- /* if this is the last route message, we do route realisation
- * that is, insert the routes into the operating system.
- */
- VLOG _("Receive table limit on peer reached %d\n"), ntohl(
*((int*)fp)) );
+ }
+ rgp->type = htons (P2P_PROTO_aip_GETROUTE);
+ rgp->size =
+ htons (sizeof (MESSAGE_HEADER) + sizeof (int));
+ *((int *) (rgp + 1)) =
+ htonl ((store1 + i)->route_entry);
+ VLOG _("Request level %d from peer %d\n"),
+ (store1 + i)->route_entry, i);
+ coreAPI->unicast (&((store1 + i)->peer), rgp,
+ EXTREME_PRIORITY, 60);
+ FREE (rgp);
+ }
+ break;
+ }
+ }
+ MUTEX_UNLOCK (lock);
+ }
+ return OK;
+ case P2P_PROTO_aip_ROUTES:
+ if (ntohs (gp->size) == (sizeof (MESSAGE_HEADER) + sizeof (int)))
+ {
+ /* if this is the last route message, we do route realisation
+ * that is, insert the routes into the operating system.
+ */
+ VLOG _("Receive table limit on peer reached %d\n"),
+ ntohl (*((int *) fp)));
/* MUTEX_LOCK(lock);
for (i = 0; i < entries1; i++) {
if (isEqual(sender, &((store1+i)->peer))) {
@@ -976,387 +1145,463 @@
}
}
MUTEX_UNLOCK(lock);
-*/ }
- return OK;
- }
+*/ }
+ return OK;
+ }
return OK;
}
/* here we copy the prototype route table we are collecting from peers to the
actual
* "realised" route table we distribute to peers, and to the kernel's table.
*/
-static void realise(struct ClientHandle * c) {
+static void realise (struct ClientHandle *c)
+{
int i, j, found;
PeerIdentity id;
int reqcapacity;
route_info *reqstore;
struct in6_rtmsg rt;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
/* make sure realised table can take the new routes - if it wont, abort now!
*/
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("realise alloc ram\n"));
- if (route_entries > realised_entries) {
- reqcapacity = sizeof(route_info) * route_entries;
- if (reqcapacity > realised_capacity) {
- reqstore = REALLOC(realised_store, reqcapacity);
- if (reqstore == NULL) {
- cprintf(c, CS_PROTO_VPN_REPLY, "I cannot up the ram for
realised routes.\n");
- MUTEX_UNLOCK(lock);
- return;
- }
- realised_store = reqstore;
- realised_capacity = reqcapacity;
- }
- }
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("realise alloc ram\n"));
+ if (route_entries > realised_entries)
+ {
+ reqcapacity = sizeof (route_info) * route_entries;
+ if (reqcapacity > realised_capacity)
+ {
+ reqstore = REALLOC (realised_store, reqcapacity);
+ if (reqstore == NULL)
+ {
+ cprintf (c, CS_PROTO_VPN_REPLY,
+ "I cannot up the ram for realised routes.\n");
+ MUTEX_UNLOCK (lock);
+ return;
+ }
+ realised_store = reqstore;
+ realised_capacity = reqcapacity;
+ }
+ }
/* add routes that are in the new table but not the old */
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("realise add
routes\n"));
- for (i = 0; i < route_entries; i++) {
- found = 0;
- for (j = 0; j < realised_entries; j++) {
- /* compare public key */
- if
(isEqualP(&(route_store+i)->owner,&(realised_store+j)->owner) &&
- ((route_store+i)->hops == (realised_store+j)->hops) &&
- ((route_store+i)->tunnel == (realised_store+j)->tunnel)
- ) {
- found = 1;
- }
- }
- /* we are hops == 0
- * hops == 1 auto added by tunneler
- * hops >= 2 added here!
- */
- if (!(found) && ((route_store+i)->hops > 1)) {
- /* lets add a route to this long remote node */
- memset((char*)&rt, 0, sizeof(struct in6_rtmsg));
- /* rtmsg_ifindex would be zero for routes not specifying a
device, such as by gateway */
- rt.rtmsg_ifindex = (store1+((route_store+i)->tunnel))->ifindex;
- identity->getPeerIdentity(&(route_store+i)->owner, &id);
- id2net(&rt.rtmsg_dst, &id);
- rt.rtmsg_flags = RTF_UP;
- rt.rtmsg_metric = (route_store+i)->hops;
- /* how many hops to owner of public key */
- rt.rtmsg_dst_len = 48; /* always 48 as per RFC4193 */
- cprintf(c, CS_PROTO_VPN_REPLY, "Add route gnu%d hops %d dst
%x:%x:%x:%x:%x:%x:%x:%x/%d\n",
- id,
- rt.rtmsg_metric,
- ntohs(rt.rtmsg_dst.s6_addr16[0]),
- ntohs(rt.rtmsg_dst.s6_addr16[1]),
- ntohs(rt.rtmsg_dst.s6_addr16[2]),
- ntohs(rt.rtmsg_dst.s6_addr16[3]),
- ntohs(rt.rtmsg_dst.s6_addr16[4]),
- ntohs(rt.rtmsg_dst.s6_addr16[5]),
- ntohs(rt.rtmsg_dst.s6_addr16[6]),
- ntohs(rt.rtmsg_dst.s6_addr16[7]),
- rt.rtmsg_dst_len);
- if (ioctl(admin_fd, SIOCADDRT, &rt) < 0) {
- cprintf(c, CS_PROTO_VPN_REPLY, "Cannot add route IPv6
address for gnu%s because %s\n", id, strerror(errno));
- }
- }
- }
- cprintf(c, CS_PROTO_VPN_REPLY, "Removing routes\n");
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("realise pull
routes\n"));
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("realise add routes\n"));
+ for (i = 0; i < route_entries; i++)
+ {
+ found = 0;
+ for (j = 0; j < realised_entries; j++)
+ {
+ /* compare public key */
+ if (isEqualP
+ (&(route_store + i)->owner, &(realised_store + j)->owner)
+ && ((route_store + i)->hops == (realised_store + j)->hops)
+ && ((route_store + i)->tunnel == (realised_store + j)->tunnel))
+ {
+ found = 1;
+ }
+ }
+ /* we are hops == 0
+ * hops == 1 auto added by tunneler
+ * hops >= 2 added here!
+ */
+ if (!(found) && ((route_store + i)->hops > 1))
+ {
+ /* lets add a route to this long remote node */
+ memset ((char *) &rt, 0, sizeof (struct in6_rtmsg));
+ /* rtmsg_ifindex would be zero for routes not specifying a device,
such as by gateway */
+ rt.rtmsg_ifindex = (store1 + ((route_store + i)->tunnel))->ifindex;
+ identity->getPeerIdentity (&(route_store + i)->owner, &id);
+ id2net (&rt.rtmsg_dst, &id);
+ rt.rtmsg_flags = RTF_UP;
+ rt.rtmsg_metric = (route_store + i)->hops;
+ /* how many hops to owner of public key */
+ rt.rtmsg_dst_len = 48; /* always 48 as per RFC4193 */
+ cprintf (c, CS_PROTO_VPN_REPLY,
+ "Add route gnu%d hops %d dst %x:%x:%x:%x:%x:%x:%x:%x/%d\n",
+ id, rt.rtmsg_metric, ntohs (rt.rtmsg_dst.s6_addr16[0]),
+ ntohs (rt.rtmsg_dst.s6_addr16[1]),
+ ntohs (rt.rtmsg_dst.s6_addr16[2]),
+ ntohs (rt.rtmsg_dst.s6_addr16[3]),
+ ntohs (rt.rtmsg_dst.s6_addr16[4]),
+ ntohs (rt.rtmsg_dst.s6_addr16[5]),
+ ntohs (rt.rtmsg_dst.s6_addr16[6]),
+ ntohs (rt.rtmsg_dst.s6_addr16[7]), rt.rtmsg_dst_len);
+ if (ioctl (admin_fd, SIOCADDRT, &rt) < 0)
+ {
+ cprintf (c, CS_PROTO_VPN_REPLY,
+ "Cannot add route IPv6 address for gnu%s because %s\n",
+ id, strerror (errno));
+ }
+ }
+ }
+ cprintf (c, CS_PROTO_VPN_REPLY, "Removing routes\n");
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("realise pull routes\n"));
/* pull routes that are in the old table but not the new */
- for (i = 0; i < realised_entries; i++) {
- found = 0;
- for (j = 0; j < route_entries; j++) {
- /* compare public key */
- if
(isEqualP(&(realised_store+i)->owner,&(route_store+j)->owner) &&
- ((realised_store+i)->hops == (route_store+j)->hops) &&
- ((realised_store+i)->tunnel == (route_store+j)->tunnel)
- ) {
- found = 1;
- }
- }
- /* we are hops == 0
- * hops == 1 auto added by tunneler
- * hops >= 2 added here!
- */
- if (!(found) && ((realised_store+i)->hops > 1)) {
- /* remove the route to this long remote node */
- memset((char*)&rt, 0, sizeof(struct in6_rtmsg));
- /* rtmsg_ifindex would be zero for routes not specifying a
device, such as by gateway */
- rt.rtmsg_ifindex =
(store1+((realised_store+i)->tunnel))->ifindex;
- identity->getPeerIdentity(&(realised_store+i)->owner, &id);
- id2net(&rt.rtmsg_dst, &id);
- rt.rtmsg_flags = RTF_UP;
- rt.rtmsg_metric = (realised_store+i)->hops;
- /* how many hops to owner of public key */
- rt.rtmsg_dst_len = 48; /* always 48 as per RFC4193 */
- cprintf(c, CS_PROTO_VPN_REPLY, "Delete route gnu%d hops %d dst
%x:%x:%x:%x:%x:%x:%x:%x/%d\n",
- id,
- rt.rtmsg_metric,
- ntohs(rt.rtmsg_dst.s6_addr16[0]),
- ntohs(rt.rtmsg_dst.s6_addr16[1]),
- ntohs(rt.rtmsg_dst.s6_addr16[2]),
- ntohs(rt.rtmsg_dst.s6_addr16[3]),
- ntohs(rt.rtmsg_dst.s6_addr16[4]),
- ntohs(rt.rtmsg_dst.s6_addr16[5]),
- ntohs(rt.rtmsg_dst.s6_addr16[6]),
- ntohs(rt.rtmsg_dst.s6_addr16[7]),
- rt.rtmsg_dst_len);
- if (ioctl(admin_fd, SIOCDELRT, &rt) < 0) {
- cprintf(c, CS_PROTO_VPN_REPLY, "Cannot del route IPv6
address for gnu%s because %s\n", id, strerror(errno));
- }
- }
- }
- cprintf(c, CS_PROTO_VPN_REPLY, "Copying table\n");
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("realise copy
table\n"));
+ for (i = 0; i < realised_entries; i++)
+ {
+ found = 0;
+ for (j = 0; j < route_entries; j++)
+ {
+ /* compare public key */
+ if (isEqualP
+ (&(realised_store + i)->owner, &(route_store + j)->owner)
+ && ((realised_store + i)->hops == (route_store + j)->hops)
+ && ((realised_store + i)->tunnel == (route_store + j)->tunnel))
+ {
+ found = 1;
+ }
+ }
+ /* we are hops == 0
+ * hops == 1 auto added by tunneler
+ * hops >= 2 added here!
+ */
+ if (!(found) && ((realised_store + i)->hops > 1))
+ {
+ /* remove the route to this long remote node */
+ memset ((char *) &rt, 0, sizeof (struct in6_rtmsg));
+ /* rtmsg_ifindex would be zero for routes not specifying a device,
such as by gateway */
+ rt.rtmsg_ifindex =
+ (store1 + ((realised_store + i)->tunnel))->ifindex;
+ identity->getPeerIdentity (&(realised_store + i)->owner, &id);
+ id2net (&rt.rtmsg_dst, &id);
+ rt.rtmsg_flags = RTF_UP;
+ rt.rtmsg_metric = (realised_store + i)->hops;
+ /* how many hops to owner of public key */
+ rt.rtmsg_dst_len = 48; /* always 48 as per RFC4193 */
+ cprintf (c, CS_PROTO_VPN_REPLY,
+ "Delete route gnu%d hops %d dst
%x:%x:%x:%x:%x:%x:%x:%x/%d\n",
+ id, rt.rtmsg_metric, ntohs (rt.rtmsg_dst.s6_addr16[0]),
+ ntohs (rt.rtmsg_dst.s6_addr16[1]),
+ ntohs (rt.rtmsg_dst.s6_addr16[2]),
+ ntohs (rt.rtmsg_dst.s6_addr16[3]),
+ ntohs (rt.rtmsg_dst.s6_addr16[4]),
+ ntohs (rt.rtmsg_dst.s6_addr16[5]),
+ ntohs (rt.rtmsg_dst.s6_addr16[6]),
+ ntohs (rt.rtmsg_dst.s6_addr16[7]), rt.rtmsg_dst_len);
+ if (ioctl (admin_fd, SIOCDELRT, &rt) < 0)
+ {
+ cprintf (c, CS_PROTO_VPN_REPLY,
+ "Cannot del route IPv6 address for gnu%s because %s\n",
+ id, strerror (errno));
+ }
+ }
+ }
+ cprintf (c, CS_PROTO_VPN_REPLY, "Copying table\n");
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("realise copy table\n"));
realised_entries = route_entries;
- memcpy(realised_store,route_store, sizeof(route_info) * route_entries);
+ memcpy (realised_store, route_store, sizeof (route_info) * route_entries);
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
-static void add_client(struct ClientHandle * c) {
- struct ClientHandle ** rstore;
+static void add_client (struct ClientHandle *c)
+{
+ struct ClientHandle **rstore;
int i, rcapacity;
/* we already have them, equality is assumed if the filehandles match */
- for (i = 0; i < clients_entries; i++) {
- if (*(clients_store+i) == c) return;
- }
+ for (i = 0; i < clients_entries; i++)
+ {
+ if (*(clients_store + i) == c)
+ return;
+ }
clients_entries++;
/* do we need more ram to hold the client handle? */
- rcapacity = clients_entries * sizeof(struct ClientHandle *);
- if (rcapacity > clients_capacity) {
- rstore = REALLOC(clients_store, rcapacity);
- if (rstore == NULL) {
- clients_entries--;
- /* not enough ram, warn in the logs that they
- * will forego receiving logging
- */
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER, _("Cannot store
client info\n"));
- return;
- }
- clients_capacity = rcapacity;
- clients_store = rstore;
- }
- *(clients_store+(clients_entries-1)) = c;
+ rcapacity = clients_entries * sizeof (struct ClientHandle *);
+ if (rcapacity > clients_capacity)
+ {
+ rstore = REALLOC (clients_store, rcapacity);
+ if (rstore == NULL)
+ {
+ clients_entries--;
+ /* not enough ram, warn in the logs that they
+ * will forego receiving logging
+ */
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Cannot store client info\n"));
+ return;
+ }
+ clients_capacity = rcapacity;
+ clients_store = rstore;
+ }
+ *(clients_store + (clients_entries - 1)) = c;
}
-static void remove_client(struct ClientHandle * c) {
+static void remove_client (struct ClientHandle *c)
+{
int i;
- for (i = 0; i < clients_entries; i++) {
- if (*(clients_store+i) == c) {
- *(clients_store+i) = *(clients_store+(clients_entries-1));
- clients_entries--;
- return;
- }
- }
+ for (i = 0; i < clients_entries; i++)
+ {
+ if (*(clients_store + i) == c)
+ {
+ *(clients_store + i) = *(clients_store + (clients_entries - 1));
+ clients_entries--;
+ return;
+ }
+ }
}
/** The console client is used to admin/debug vpn */
-static int csHandle(struct ClientHandle * c,
- const MESSAGE_HEADER * message) {
- MESSAGE_HEADER * rgp = NULL;
+static int csHandle (struct ClientHandle *c, const MESSAGE_HEADER * message)
+{
+ MESSAGE_HEADER *rgp = NULL;
int i;
PeerIdentity id;
- int parameter = ntohs(message->size) - sizeof(MESSAGE_HEADER);
- char* ccmd = (char*)(message+1);
- char* parm;
+ int parameter = ntohs (message->size) - sizeof (MESSAGE_HEADER);
+ char *ccmd = (char *) (message + 1);
+ char *parm;
- MUTEX_LOCK(lock);
- add_client(c);
- MUTEX_UNLOCK(lock);
+ MUTEX_LOCK (lock);
+ add_client (c);
+ MUTEX_UNLOCK (lock);
/* issued command from client */
- if (ntohs(message->type) == CS_PROTO_VPN_MSG) {
- if (ntohs(message->size) == 0) return OK;
- }
- /* while ((l < ll) && (*(ccmd+cl) > 32)) cl++; */
+ if (ntohs (message->type) == CS_PROTO_VPN_MSG)
+ {
+ if (ntohs (message->size) == 0)
+ return OK;
+ }
+ /* while ((l < ll) && (*(ccmd+cl) > 32)) cl++; */
- if (ntohs(message->type) == CS_PROTO_VPN_DEBUGOFF) {
- MUTEX_LOCK(lock);
- cdebug = 0;
- MUTEX_UNLOCK(lock);
- cprintf(c, CS_PROTO_VPN_DEBUGOFF, "LOG NOTHING\n");
- return OK;
- }
- if (ntohs(message->type) == CS_PROTO_VPN_DEBUGON) {
- MUTEX_LOCK(lock);
- cdebug = GE_DEBUG | GE_DEVELOPER | GE_REQUEST;
- MUTEX_UNLOCK(lock);
- cprintf(c, CS_PROTO_VPN_DEBUGON, "LOG DEBUG\n");
- return OK;
- }
- if (ntohs(message->type) == CS_PROTO_VPN_TUNNELS) {
- MUTEX_LOCK(lock);
- id2ip(c, coreAPI->myIdentity);
- cprintf(c, CS_PROTO_VPN_REPLY, "::/48 This Node\n");
- for (i = 0; i < entries1; i++) {
- id2ip(c, &(store1+i)->peer);
- cprintf(c, CS_PROTO_VPN_REPLY, "::/48 gnu%d active=%s
routeentry=%d\n",
- (store1+i)->id,
- (store1+i)->active ? _("Yes") : _("No"),
- (store1+i)->route_entry);
- }
- cprintf(c, CS_PROTO_VPN_TUNNELS, "%d Tunnels\n", entries1);
- MUTEX_UNLOCK(lock);
- }
- if (ntohs(message->type) == CS_PROTO_VPN_ROUTES) {
- MUTEX_LOCK(lock);
- for (i = 0; i < route_entries; i++) {
- identity->getPeerIdentity(&(route_store+i)->owner, &id);
- id2ip(c, &id);
- if ((route_store+i)->hops == 0) {
- cprintf(c, CS_PROTO_VPN_REPLY, "::/48 hops 0 (This
Node)\n");
- } else {
- cprintf(c, CS_PROTO_VPN_REPLY, "::/48 hops %d tunnel
gnu%d\n", (route_store+i)->hops,
- (store1+((route_store+i)->tunnel))->id);
- }
- }
- cprintf(c, CS_PROTO_VPN_ROUTES, "%d Routes\n", route_entries);
- MUTEX_UNLOCK(lock);
- }
- if (ntohs(message->type) == CS_PROTO_VPN_REALISED) {
- MUTEX_LOCK(lock);
- for (i = 0; i < realised_entries; i++) {
- identity->getPeerIdentity(&(realised_store+i)->owner, &id);
- id2ip(c, &id);
- if ((realised_store+i)->hops == 0) {
- cprintf(c, CS_PROTO_VPN_REPLY, "::/48 hops 0 (This
Node)\n");
- } else {
- cprintf(c, CS_PROTO_VPN_REPLY, "::/48 hops %d tunnel
gnu%d\n", (realised_store+i)->hops,
- (store1+((realised_store+i)->tunnel))->id);
- }
- }
- cprintf(c, CS_PROTO_VPN_REALISED, "%d Realised\n", realised_entries);
- MUTEX_UNLOCK(lock);
- }
+ if (ntohs (message->type) == CS_PROTO_VPN_DEBUGOFF)
+ {
+ MUTEX_LOCK (lock);
+ cdebug = 0;
+ MUTEX_UNLOCK (lock);
+ cprintf (c, CS_PROTO_VPN_DEBUGOFF, "LOG NOTHING\n");
+ return OK;
+ }
+ if (ntohs (message->type) == CS_PROTO_VPN_DEBUGON)
+ {
+ MUTEX_LOCK (lock);
+ cdebug = GE_DEBUG | GE_DEVELOPER | GE_REQUEST;
+ MUTEX_UNLOCK (lock);
+ cprintf (c, CS_PROTO_VPN_DEBUGON, "LOG DEBUG\n");
+ return OK;
+ }
+ if (ntohs (message->type) == CS_PROTO_VPN_TUNNELS)
+ {
+ MUTEX_LOCK (lock);
+ id2ip (c, coreAPI->myIdentity);
+ cprintf (c, CS_PROTO_VPN_REPLY, "::/48 This Node\n");
+ for (i = 0; i < entries1; i++)
+ {
+ id2ip (c, &(store1 + i)->peer);
+ cprintf (c, CS_PROTO_VPN_REPLY,
+ "::/48 gnu%d active=%s routeentry=%d\n", (store1 + i)->id,
+ (store1 + i)->active ? _("Yes") : _("No"),
+ (store1 + i)->route_entry);
+ }
+ cprintf (c, CS_PROTO_VPN_TUNNELS, "%d Tunnels\n", entries1);
+ MUTEX_UNLOCK (lock);
+ }
+ if (ntohs (message->type) == CS_PROTO_VPN_ROUTES)
+ {
+ MUTEX_LOCK (lock);
+ for (i = 0; i < route_entries; i++)
+ {
+ identity->getPeerIdentity (&(route_store + i)->owner, &id);
+ id2ip (c, &id);
+ if ((route_store + i)->hops == 0)
+ {
+ cprintf (c, CS_PROTO_VPN_REPLY, "::/48 hops 0 (This Node)\n");
+ }
+ else
+ {
+ cprintf (c, CS_PROTO_VPN_REPLY, "::/48 hops %d tunnel gnu%d\n",
+ (route_store + i)->hops,
+ (store1 + ((route_store + i)->tunnel))->id);
+ }
+ }
+ cprintf (c, CS_PROTO_VPN_ROUTES, "%d Routes\n", route_entries);
+ MUTEX_UNLOCK (lock);
+ }
+ if (ntohs (message->type) == CS_PROTO_VPN_REALISED)
+ {
+ MUTEX_LOCK (lock);
+ for (i = 0; i < realised_entries; i++)
+ {
+ identity->getPeerIdentity (&(realised_store + i)->owner, &id);
+ id2ip (c, &id);
+ if ((realised_store + i)->hops == 0)
+ {
+ cprintf (c, CS_PROTO_VPN_REPLY, "::/48 hops 0 (This Node)\n");
+ }
+ else
+ {
+ cprintf (c, CS_PROTO_VPN_REPLY, "::/48 hops %d tunnel gnu%d\n",
+ (realised_store + i)->hops,
+ (store1 + ((realised_store + i)->tunnel))->id);
+ }
+ }
+ cprintf (c, CS_PROTO_VPN_REALISED, "%d Realised\n", realised_entries);
+ MUTEX_UNLOCK (lock);
+ }
/* add routes in route but not realised to OS
* delete routes in realised but not route from OS
* memcpy routes to realised metric
*/
- if (ntohs(message->type) == CS_PROTO_VPN_REALISE) {
- realise(c);
- cprintf(c, CS_PROTO_VPN_REALISE, "Realise done\n");
- }
- if (ntohs(message->type) == CS_PROTO_VPN_RESET) {
- MUTEX_LOCK(lock);
- init_router();
- for (i = 0; i < entries1; i++) {
- (store1+i)->route_entry = 0;
- /* lets send it to everyone - expect response only from VPN
enabled nodes tho :-) */
+ if (ntohs (message->type) == CS_PROTO_VPN_REALISE)
+ {
+ realise (c);
+ cprintf (c, CS_PROTO_VPN_REALISE, "Realise done\n");
+ }
+ if (ntohs (message->type) == CS_PROTO_VPN_RESET)
+ {
+ MUTEX_LOCK (lock);
+ init_router ();
+ for (i = 0; i < entries1; i++)
+ {
+ (store1 + i)->route_entry = 0;
+ /* lets send it to everyone - expect response only from VPN enabled
nodes tho :-) */
/* if ((store1+i)->active == YES) { */
- rgp = MALLOC(sizeof(MESSAGE_HEADER) + sizeof(int));
- if (rgp == NULL) { break; }
- rgp->type = htons(P2P_PROTO_aip_GETROUTE);
- rgp->size = htons(sizeof(MESSAGE_HEADER) + sizeof(int));
- *((int*)(rgp+1)) = htonl((store1+i)->route_entry);
- cprintf(c, CS_PROTO_VPN_REPLY, "Request level %d from
peer %d ", (store1+i)->route_entry, i);
- id2ip(c, &((store1+i)->peer));
- cprintf(c, CS_PROTO_VPN_REPLY, "\n");
-
coreAPI->unicast(&((store1+i)->peer),rgp,EXTREME_PRIORITY,60);
- FREE(rgp);
+ rgp = MALLOC (sizeof (MESSAGE_HEADER) + sizeof (int));
+ if (rgp == NULL)
+ {
+ break;
+ }
+ rgp->type = htons (P2P_PROTO_aip_GETROUTE);
+ rgp->size = htons (sizeof (MESSAGE_HEADER) + sizeof (int));
+ *((int *) (rgp + 1)) = htonl ((store1 + i)->route_entry);
+ cprintf (c, CS_PROTO_VPN_REPLY, "Request level %d from peer %d ",
+ (store1 + i)->route_entry, i);
+ id2ip (c, &((store1 + i)->peer));
+ cprintf (c, CS_PROTO_VPN_REPLY, "\n");
+ coreAPI->unicast (&((store1 + i)->peer), rgp, EXTREME_PRIORITY, 60);
+ FREE (rgp);
/* } */
- }
- MUTEX_UNLOCK(lock);
- cprintf(c, CS_PROTO_VPN_RESET, "Rebuilding routing tables done\n");
- }
- if (ntohs(message->type) == CS_PROTO_VPN_TRUST) {
- MUTEX_LOCK(lock);
- for (i = 0; i < entries1; i++) {
- if ((store1+i)->active == YES) {
- cprintf(c, CS_PROTO_VPN_REPLY, "Uprating peer ");
- id2ip(c, &(store1+i)->peer);
- cprintf(c, CS_PROTO_VPN_REPLY, " with credit %d\n",
identity->changeHostTrust(&(store1+i)->peer, 1000));
- }
- }
- cprintf(c, CS_PROTO_VPN_TRUST, "Gave credit to active nodes of %d
nodes...\n", entries1);
- MUTEX_UNLOCK(lock);
- }
- if (ntohs(message->type) == CS_PROTO_VPN_ADD) {
- if (parameter > 0) {
- if ((parm = MALLOC(parameter+1)) != NULL) {
- strncpy(parm, ccmd, parameter);
- *(parm+parameter) = 0;
- cprintf(c, CS_PROTO_VPN_REPLY, "Connect ");
- if (OK == enc2hash(parm, &(id.hashPubKey))) {
- id2ip(c, &id);
+ }
+ MUTEX_UNLOCK (lock);
+ cprintf (c, CS_PROTO_VPN_RESET, "Rebuilding routing tables done\n");
+ }
+ if (ntohs (message->type) == CS_PROTO_VPN_TRUST)
+ {
+ MUTEX_LOCK (lock);
+ for (i = 0; i < entries1; i++)
+ {
+ if ((store1 + i)->active == YES)
+ {
+ cprintf (c, CS_PROTO_VPN_REPLY, "Uprating peer ");
+ id2ip (c, &(store1 + i)->peer);
+ cprintf (c, CS_PROTO_VPN_REPLY, " with credit %d\n",
+ identity->changeHostTrust (&(store1 + i)->peer, 1000));
+ }
+ }
+ cprintf (c, CS_PROTO_VPN_TRUST,
+ "Gave credit to active nodes of %d nodes...\n", entries1);
+ MUTEX_UNLOCK (lock);
+ }
+ if (ntohs (message->type) == CS_PROTO_VPN_ADD)
+ {
+ if (parameter > 0)
+ {
+ if ((parm = MALLOC (parameter + 1)) != NULL)
+ {
+ strncpy (parm, ccmd, parameter);
+ *(parm + parameter) = 0;
+ cprintf (c, CS_PROTO_VPN_REPLY, "Connect ");
+ if (OK == enc2hash (parm, &(id.hashPubKey)))
+ {
+ id2ip (c, &id);
- /* this does not seem to work, strangeness with
threads and capabilities?
- * MUTEX_LOCK(lock);
- * checkensure_peer(&id, NULL);
- * MUTEX_UNLOCK(lock);
- */
+ /* this does not seem to work, strangeness with threads and
capabilities?
+ * MUTEX_LOCK(lock);
+ * checkensure_peer(&id, NULL);
+ * MUTEX_UNLOCK(lock);
+ */
- /* get it off the local blacklist */
- identity->whitelistHost(&id);
-
- switch (session->tryConnect(&id)) {
- case YES:
- cprintf(c, CS_PROTO_VPN_REPLY, "
already connected.\n");
- break;
- case NO:
- cprintf(c, CS_PROTO_VPN_REPLY, "
schedule connection.\n");
- break;
- case SYSERR:
- cprintf(c, CS_PROTO_VPN_REPLY, " core
refused.\n");
- break;
- default:
- cprintf(c, CS_PROTO_VPN_REPLY, " misc
error.\n");
- break;
- }
+ /* get it off the local blacklist */
+ identity->whitelistHost (&id);
- /* req route level 0
- rgp = MALLOC(sizeof(MESSAGE_HEADER) +
sizeof(int));
- if (rgp != NULL) {
- rgp->type =
htons(P2P_PROTO_aip_GETROUTE);
- rgp->size =
htons(sizeof(MESSAGE_HEADER) + sizeof(int));
- *((int*)(rgp+1)) = 0;
-
coreAPI->unicast(&id,rgp,EXTREME_PRIORITY,4);
- cprintf(c, " Sent");
- FREE(rgp);
- } */
+ switch (session->tryConnect (&id))
+ {
+ case YES:
+ cprintf (c, CS_PROTO_VPN_REPLY,
+ " already connected.\n");
+ break;
+ case NO:
+ cprintf (c, CS_PROTO_VPN_REPLY,
+ " schedule connection.\n");
+ break;
+ case SYSERR:
+ cprintf (c, CS_PROTO_VPN_REPLY, " core refused.\n");
+ break;
+ default:
+ cprintf (c, CS_PROTO_VPN_REPLY, " misc error.\n");
+ break;
+ }
- cprintf(c, CS_PROTO_VPN_ADD, "\n");
- } else {
- cprintf(c, CS_PROTO_VPN_ADD, "Could not decode
PeerId %s from parameter.\n", parm);
-
- }
- FREE(parm);
- } else {
- cprintf(c, CS_PROTO_VPN_ADD, "Could not allocate for
key.\n");
- }
- } else {
- cprintf(c, CS_PROTO_VPN_ADD, "Require key for parameter\n");
- }
- }
+ /* req route level 0
+ rgp = MALLOC(sizeof(MESSAGE_HEADER) + sizeof(int));
+ if (rgp != NULL) {
+ rgp->type = htons(P2P_PROTO_aip_GETROUTE);
+ rgp->size = htons(sizeof(MESSAGE_HEADER) + sizeof(int));
+ *((int*)(rgp+1)) = 0;
+ coreAPI->unicast(&id,rgp,EXTREME_PRIORITY,4);
+ cprintf(c, " Sent");
+ FREE(rgp);
+ } */
+
+ cprintf (c, CS_PROTO_VPN_ADD, "\n");
+ }
+ else
+ {
+ cprintf (c, CS_PROTO_VPN_ADD,
+ "Could not decode PeerId %s from parameter.\n",
+ parm);
+
+ }
+ FREE (parm);
+ }
+ else
+ {
+ cprintf (c, CS_PROTO_VPN_ADD, "Could not allocate for key.\n");
+ }
+ }
+ else
+ {
+ cprintf (c, CS_PROTO_VPN_ADD, "Require key for parameter\n");
+ }
+ }
return OK;
}
-static void clientExitHandler(struct ClientHandle * c) {
- MUTEX_LOCK(lock);
- remove_client(c);
- MUTEX_UNLOCK(lock);
+static void clientExitHandler (struct ClientHandle *c)
+{
+ MUTEX_LOCK (lock);
+ remove_client (c);
+ MUTEX_UNLOCK (lock);
}
-static int makeNonblocking(int handle) {
+static int makeNonblocking (int handle)
+{
#if MINGW
u_long mode;
mode = 1;
- if (ioctlsocket(handle,
- FIONBIO,
- &mode == SOCKET_ERROR) {
- SetErrnoFromWinsockError(WSAGetLastError());
- return SYSERR;
- } else {
- /* store the blocking mode */
- __win_SetHandleBlockingMode(handle, 0);
- }
+ if (ioctlsocket (handle, FIONBIO, &mode == SOCKET_ERROR))
+ {
+ SetErrnoFromWinsockError (WSAGetLastError ());
+ return SYSERR;
+ }
+ else
+ {
+ /* store the blocking mode */
+ __win_SetHandleBlockingMode (handle, 0);
+ }
#else
- int flags = fcntl(handle, F_GETFL);
+ int flags = fcntl (handle, F_GETFL);
flags |= O_NONBLOCK;
- if (-1 == fcntl(handle,
- F_SETFL,
- flags)) {
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "fcntl");
- return SYSERR;
- }
+ if (-1 == fcntl (handle, F_SETFL, flags))
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ "fcntl");
+ return SYSERR;
+ }
#endif
return OK;
}
@@ -1368,85 +1613,114 @@
* Also enumerate all current peers and create taps for them.
*
*/
-int initialize_module_vpn(CoreAPIForApplication * capi) {
+int initialize_module_vpn (CoreAPIForApplication * capi)
+{
int pfd;
- char* str = "OK\r\n";
+ char *str = "OK\r\n";
ectx = capi->ectx;
- lock = MUTEX_CREATE(NO);
+ lock = MUTEX_CREATE (NO);
coreAPI = capi;
/* Signal to the root init script we want cap_net_admin
*/
- pfd = open("/var/lib/GNUnet/gnunet.vpn", O_WRONLY);
- if (pfd > -1) {
- write(pfd, str, strlen(str));
- close(pfd);
- }
- pfd = open("/var/lib/GNUnet/gnunet.vpn", O_RDONLY);
- if (pfd > -1) {
- read(pfd, str, strlen(str));
- close(pfd);
- }
- unlink("/var/lib/GNUnet/gnunet.vpn");
+ pfd = open ("/var/lib/GNUnet/gnunet.vpn", O_WRONLY);
+ if (pfd > -1)
+ {
+ write (pfd, str, strlen (str));
+ close (pfd);
+ }
+ pfd = open ("/var/lib/GNUnet/gnunet.vpn", O_RDONLY);
+ if (pfd > -1)
+ {
+ read (pfd, str, strlen (str));
+ close (pfd);
+ }
+ unlink ("/var/lib/GNUnet/gnunet.vpn");
/* system("sudo setpcaps cap_net_admin+eip `pidof gnunetd`"); */
- admin_fd = socket(AF_INET6, SOCK_DGRAM, 0);
+ admin_fd = socket (AF_INET6, SOCK_DGRAM, 0);
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("`%s' initialising
RFC4913 module %d and %d\n"), "template", CS_PROTO_MAX_USED,
P2P_PROTO_MAX_USED);
- GE_LOG(ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST, _("RFC4193 my First 4 hex
digits of host id are %x\n"), capi->myIdentity->hashPubKey.bits[0]);
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("`%s' initialising RFC4913 module %d and %d\n"), "template",
+ CS_PROTO_MAX_USED, P2P_PROTO_MAX_USED);
+ GE_LOG (ectx, GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("RFC4193 my First 4 hex digits of host id are %x\n"),
+ capi->myIdentity->hashPubKey.bits[0]);
/* core calls us to receive messages */
/* get a PONG = peer is online */
/* get a HANGUP = peer is offline */
- if (SYSERR == capi->registerHandler(P2P_PROTO_aip_IP, &handlep2pMSG)) return
SYSERR;
- if (SYSERR == capi->registerHandler(P2P_PROTO_aip_GETROUTE, &handlep2pMSG))
return SYSERR;
- if (SYSERR == capi->registerHandler(P2P_PROTO_aip_ROUTE, &handlep2pMSG))
return SYSERR;
- if (SYSERR == capi->registerHandler(P2P_PROTO_aip_ROUTES, &handlep2pMSG))
return SYSERR;
- if (SYSERR == capi->registerHandler(p2p_PROTO_PONG, &handlep2pMSG)) return
SYSERR;
- if (SYSERR == capi->registerHandler(P2P_PROTO_hangup, &handlep2pMSG)) return
SYSERR;
- if (SYSERR == capi->registerClientExitHandler(&clientExitHandler)) return
SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_VPN_MSG, &csHandle))
return SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_VPN_DEBUGOFF, &csHandle))
return SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_VPN_DEBUGON, &csHandle))
return SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_VPN_TUNNELS, &csHandle))
return SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_VPN_ROUTES, &csHandle))
return SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_VPN_REALISED, &csHandle))
return SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_VPN_RESET, &csHandle))
return SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_VPN_REALISE, &csHandle))
return SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_VPN_ADD, &csHandle))
return SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_VPN_TRUST, &csHandle))
return SYSERR;
- if (SYSERR == capi->registerClientHandler(CS_PROTO_VPN_REPLY, &csHandle))
return SYSERR;
+ if (SYSERR == capi->registerHandler (P2P_PROTO_aip_IP, &handlep2pMSG))
+ return SYSERR;
+ if (SYSERR == capi->registerHandler (P2P_PROTO_aip_GETROUTE, &handlep2pMSG))
+ return SYSERR;
+ if (SYSERR == capi->registerHandler (P2P_PROTO_aip_ROUTE, &handlep2pMSG))
+ return SYSERR;
+ if (SYSERR == capi->registerHandler (P2P_PROTO_aip_ROUTES, &handlep2pMSG))
+ return SYSERR;
+ if (SYSERR == capi->registerHandler (p2p_PROTO_PONG, &handlep2pMSG))
+ return SYSERR;
+ if (SYSERR == capi->registerHandler (P2P_PROTO_hangup, &handlep2pMSG))
+ return SYSERR;
+ if (SYSERR == capi->registerClientExitHandler (&clientExitHandler))
+ return SYSERR;
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_VPN_MSG, &csHandle))
+ return SYSERR;
+ if (SYSERR ==
+ capi->registerClientHandler (CS_PROTO_VPN_DEBUGOFF, &csHandle))
+ return SYSERR;
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_VPN_DEBUGON, &csHandle))
+ return SYSERR;
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_VPN_TUNNELS, &csHandle))
+ return SYSERR;
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_VPN_ROUTES, &csHandle))
+ return SYSERR;
+ if (SYSERR ==
+ capi->registerClientHandler (CS_PROTO_VPN_REALISED, &csHandle))
+ return SYSERR;
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_VPN_RESET, &csHandle))
+ return SYSERR;
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_VPN_REALISE, &csHandle))
+ return SYSERR;
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_VPN_ADD, &csHandle))
+ return SYSERR;
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_VPN_TRUST, &csHandle))
+ return SYSERR;
+ if (SYSERR == capi->registerClientHandler (CS_PROTO_VPN_REPLY, &csHandle))
+ return SYSERR;
- identity = coreAPI->requestService("identity");
- session = coreAPI->requestService("session");
+ identity = coreAPI->requestService ("identity");
+ session = coreAPI->requestService ("session");
- GE_ASSERT(ectx, identity != NULL);
- GE_ASSERT(ectx, session != NULL);
+ GE_ASSERT (ectx, identity != NULL);
+ GE_ASSERT (ectx, session != NULL);
- init_router(); /* reqire identity */
- init_realised(); /* reqire identity */
+ init_router (); /* reqire identity */
+ init_realised (); /* reqire identity */
- PIPE(signalingPipe);
+ PIPE (signalingPipe);
/* important: make signalingPipe non-blocking
- to avoid stalling on signaling! */
- makeNonblocking(signalingPipe[1]);
+ to avoid stalling on signaling! */
+ makeNonblocking (signalingPipe[1]);
/* Yes we have to make our own thread, cause the GUNnet API is
* missing some callbacks (Namely CanReadThisFd - SELECT()) that I would
like ;-(
* They may go in the thread that usually monitors the GUI port.
*/
- tunThreadInfo = PTHREAD_CREATE((PThreadMain) &tunThread, NULL, 128 * 1024);
+ tunThreadInfo =
+ PTHREAD_CREATE ((PThreadMain) & tunThread, NULL, 128 * 1024);
/* use capi->unicast to send messages to connected peers */
- GE_ASSERT(capi->ectx,
- 0 == GC_set_configuration_value_string(capi->cfg,
- capi->ectx,
- "ABOUT",
- "vpn",
- _("enables IPv6 over GNUnet
(incomplete)")));
+ GE_ASSERT (capi->ectx,
+ 0 == GC_set_configuration_value_string (capi->cfg,
+ capi->ectx,
+ "ABOUT",
+ "vpn",
+ _
+ ("enables IPv6 over
GNUnet (incomplete)")));
return OK;
}
@@ -1454,71 +1728,78 @@
/**
* Module uninserted.
*/
-void done_module_vpn() {
+void done_module_vpn ()
+{
int i;
int ret;
void *returnval;
- coreAPI->unregisterHandler(P2P_PROTO_aip_IP, &handlep2pMSG);
- coreAPI->unregisterHandler(P2P_PROTO_aip_GETROUTE, &handlep2pMSG);
- coreAPI->unregisterHandler(P2P_PROTO_aip_ROUTE, &handlep2pMSG);
- coreAPI->unregisterHandler(P2P_PROTO_aip_ROUTES, &handlep2pMSG);
- coreAPI->unregisterHandler(p2p_PROTO_PONG, &handlep2pMSG);
- coreAPI->unregisterHandler(P2P_PROTO_hangup, &handlep2pMSG);
- coreAPI->unregisterClientHandler(CS_PROTO_VPN_MSG, &csHandle);
- coreAPI->unregisterClientHandler(CS_PROTO_VPN_DEBUGOFF, &csHandle);
- coreAPI->unregisterClientHandler(CS_PROTO_VPN_DEBUGON, &csHandle);
- coreAPI->unregisterClientHandler(CS_PROTO_VPN_TUNNELS, &csHandle);
- coreAPI->unregisterClientHandler(CS_PROTO_VPN_ROUTES, &csHandle);
- coreAPI->unregisterClientHandler(CS_PROTO_VPN_REALISED, &csHandle);
- coreAPI->unregisterClientHandler(CS_PROTO_VPN_RESET, &csHandle);
- coreAPI->unregisterClientHandler(CS_PROTO_VPN_REALISE, &csHandle);
- coreAPI->unregisterClientHandler(CS_PROTO_VPN_ADD, &csHandle);
- coreAPI->unregisterClientHandler(CS_PROTO_VPN_TRUST, &csHandle);
- coreAPI->unregisterClientHandler(CS_PROTO_VPN_REPLY, &csHandle);
- coreAPI->unregisterClientExitHandler(&clientExitHandler);
+ coreAPI->unregisterHandler (P2P_PROTO_aip_IP, &handlep2pMSG);
+ coreAPI->unregisterHandler (P2P_PROTO_aip_GETROUTE, &handlep2pMSG);
+ coreAPI->unregisterHandler (P2P_PROTO_aip_ROUTE, &handlep2pMSG);
+ coreAPI->unregisterHandler (P2P_PROTO_aip_ROUTES, &handlep2pMSG);
+ coreAPI->unregisterHandler (p2p_PROTO_PONG, &handlep2pMSG);
+ coreAPI->unregisterHandler (P2P_PROTO_hangup, &handlep2pMSG);
+ coreAPI->unregisterClientHandler (CS_PROTO_VPN_MSG, &csHandle);
+ coreAPI->unregisterClientHandler (CS_PROTO_VPN_DEBUGOFF, &csHandle);
+ coreAPI->unregisterClientHandler (CS_PROTO_VPN_DEBUGON, &csHandle);
+ coreAPI->unregisterClientHandler (CS_PROTO_VPN_TUNNELS, &csHandle);
+ coreAPI->unregisterClientHandler (CS_PROTO_VPN_ROUTES, &csHandle);
+ coreAPI->unregisterClientHandler (CS_PROTO_VPN_REALISED, &csHandle);
+ coreAPI->unregisterClientHandler (CS_PROTO_VPN_RESET, &csHandle);
+ coreAPI->unregisterClientHandler (CS_PROTO_VPN_REALISE, &csHandle);
+ coreAPI->unregisterClientHandler (CS_PROTO_VPN_ADD, &csHandle);
+ coreAPI->unregisterClientHandler (CS_PROTO_VPN_TRUST, &csHandle);
+ coreAPI->unregisterClientHandler (CS_PROTO_VPN_REPLY, &csHandle);
+ coreAPI->unregisterClientExitHandler (&clientExitHandler);
- GE_LOG(ectx, GE_INFO | GE_REQUEST | GE_USER, _("RFC4193 Waiting for tun
thread to end\n"));
+ GE_LOG (ectx, GE_INFO | GE_REQUEST | GE_USER,
+ _("RFC4193 Waiting for tun thread to end\n"));
running = 0;
/* thread should wake up and exit */
- ret = write(signalingPipe[1], &running, sizeof(char));
- if (ret != sizeof(char))
- if (errno != EAGAIN)
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- "RFC4193 can not tell thread to exit");
+ ret = write (signalingPipe[1], &running, sizeof (char));
+ if (ret != sizeof (char))
+ if (errno != EAGAIN)
+ GE_LOG_STRERROR (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ "RFC4193 can not tell thread to exit");
/* wait for it to exit */
- PTHREAD_JOIN(tunThreadInfo, &returnval);
- GE_LOG(ectx, GE_INFO | GE_REQUEST | GE_USER, _("RFC4193 The tun thread has
ended\n"));
+ PTHREAD_JOIN (tunThreadInfo, &returnval);
+ GE_LOG (ectx, GE_INFO | GE_REQUEST | GE_USER,
+ _("RFC4193 The tun thread has ended\n"));
- coreAPI->releaseService(identity);
- coreAPI->releaseService(session);
+ coreAPI->releaseService (identity);
+ coreAPI->releaseService (session);
identity = NULL;
- CLOSE(signalingPipe[0]);
- CLOSE(signalingPipe[1]);
+ CLOSE (signalingPipe[0]);
+ CLOSE (signalingPipe[1]);
/* bye bye TUNTAP ... */
- for (i = 0; i < entries1; i++) {
- if (((store1+i)->fd) != 0) {
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
- _("RFC4193 Closing tunnel %d fd %d\n"), i,
(store1+i)->fd);
- close((store1+i)->fd);
- (store1+i)->fd = 0;
- }
- }
- if (store1 != NULL) {
- entries1 = 0;
- capacity1 = 0;
- FREE(store1);
- }
- close(admin_fd);
+ for (i = 0; i < entries1; i++)
+ {
+ if (((store1 + i)->fd) != 0)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ _("RFC4193 Closing tunnel %d fd %d\n"), i,
+ (store1 + i)->fd);
+ close ((store1 + i)->fd);
+ (store1 + i)->fd = 0;
+ }
+ }
+ if (store1 != NULL)
+ {
+ entries1 = 0;
+ capacity1 = 0;
+ FREE (store1);
+ }
+ close (admin_fd);
- MUTEX_DESTROY(lock);
+ MUTEX_DESTROY (lock);
coreAPI = NULL;
}
Modified: GNUnet/src/include/core.h
===================================================================
--- GNUnet/src/include/core.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/include/core.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,30 +33,29 @@
/**
* Initialize the CORE's globals.
*/
-int initCore(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct CronManager * cron,
- struct LoadMonitor * monitor);
+int initCore (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct CronManager *cron, struct LoadMonitor *monitor);
/**
* Shutdown the CORE modules (also shuts down all
* application modules).
*/
-void doneCore(void);
+void doneCore (void);
-void * requestService(const char * pos);
+void *requestService (const char *pos);
-int releaseService(void * service);
+int releaseService (void *service);
/**
* @return OK on success, SYSERR if some modules failed to unload
*/
-int unloadApplicationModules(void);
+int unloadApplicationModules (void);
/**
* @return OK on success, SYSERR if some modules failed to load
*/
-int loadApplicationModules(void);
+int loadApplicationModules (void);
Modified: GNUnet/src/include/dht.h
===================================================================
--- GNUnet/src/include/dht.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/include/dht.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,8 +33,9 @@
#include "gnunet_util.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -48,15 +49,16 @@
*
* The given struct is followed by the value.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
- unsigned int type; /* nbo */
+ unsigned int type; /* nbo */
HashCode512 key;
- unsigned long long expire; /* nbo */
+ unsigned long long expire; /* nbo */
} CS_dht_request_put_MESSAGE;
@@ -65,19 +67,20 @@
* a CS_dht_request_put_MESSAGE messages. Clients can abort
* the GET operation early by closing the connection.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
- unsigned int type; /* nbo */
+ unsigned int type; /* nbo */
HashCode512 key;
- unsigned long long timeout; /* nbo */
+ unsigned long long timeout; /* nbo */
} CS_dht_request_get_MESSAGE;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/ecrs_core.h
===================================================================
--- GNUnet/src/include/ecrs_core.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/include/ecrs_core.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -36,7 +36,8 @@
/**
* @brief content hash key
*/
-typedef struct {
+typedef struct
+{
HashCode512 key;
HashCode512 query;
} CHK;
@@ -44,7 +45,8 @@
/**
* @brief data block
*/
-typedef struct {
+typedef struct
+{
/**
* Type of the block, in network byte order.
@@ -55,7 +57,8 @@
} DBlock;
-typedef struct {
+typedef struct
+{
/**
* Type of the block (IBLOCK), in network byte order.
@@ -72,7 +75,8 @@
* A FileIdentifier groups the information
* required to download (and check) a file.
*/
-typedef struct {
+typedef struct
+{
/**
* Total size of the file in bytes. (network byte order (!))
@@ -89,7 +93,8 @@
/**
* @brief keyword block (advertising data under a keyword)
*/
-typedef struct {
+typedef struct
+{
/**
* Type of the block (KBLOCK), in network byte order.
@@ -112,7 +117,8 @@
} KBlock;
-typedef struct {
+typedef struct
+{
/**
* Type of the block (SBLOCK), in network byte order.
@@ -169,16 +175,17 @@
/* variable-size Meta-Data follows here! */
} SBlock;
-typedef struct {
+typedef struct
+{
/**
* Type of the block (NBLOCK), in network byte order.
*/
unsigned int type;
- Signature signature; /* 256 b */
+ Signature signature; /* 256 b */
- PublicKey subspace; /* S = H(subspace); 264 b */
+ PublicKey subspace; /* S = H(subspace); 264 b */
/**
* Must be all zeros
@@ -204,7 +211,8 @@
/**
* @brief keyword-NBlock (advertising namespace under a keyword)
*/
-typedef struct {
+typedef struct
+{
/**
* Type of the block (KNBLOCK), in network byte order.
@@ -231,33 +239,29 @@
* @return OK on success, SYSERR if data does not
* match the query
*/
-int fileBlockEncode(const DBlock * data,
- unsigned int len,
- const HashCode512 * query,
- Datastore_Value ** value);
+int fileBlockEncode (const DBlock * data,
+ unsigned int len,
+ const HashCode512 * query, Datastore_Value ** value);
/**
* Get the query that will be used to query for
* a certain block of data.
*/
-void fileBlockGetQuery(const DBlock * data,
- unsigned int len,
- HashCode512 * query);
+void fileBlockGetQuery (const DBlock * data,
+ unsigned int len, HashCode512 * query);
/**
* Get the key that will be used to decrypt
* a certain block of data.
*/
-void fileBlockGetKey(const DBlock * data,
- unsigned int len,
- HashCode512 * key);
+void fileBlockGetKey (const DBlock * data,
+ unsigned int len, HashCode512 * key);
/**
* What is the type of the given block of data?
*/
-unsigned int getTypeOfBlock(unsigned int size,
- const DBlock * data);
+unsigned int getTypeOfBlock (unsigned int size, const DBlock * data);
/**
* What is the main query (the one that is used in
@@ -272,10 +276,8 @@
* @return SYSERR if the content is invalid or
* the content type is not known
*/
-int getQueryFor(unsigned int size,
- const DBlock * data,
- int verify,
- HashCode512 * query);
+int getQueryFor (unsigned int size,
+ const DBlock * data, int verify, HashCode512 * query);
/**
* Verify that the given Datum is a valid response
@@ -291,11 +293,10 @@
* NO; SYSERR if the keyCount does not match the
* query type
*/
-int isDatumApplicable(unsigned int type,
- unsigned int size,
- const DBlock * data,
- const HashCode512 * knownDatumQuery,
- unsigned int keyCount,
- const HashCode512 * keys);
+int isDatumApplicable (unsigned int type,
+ unsigned int size,
+ const DBlock * data,
+ const HashCode512 * knownDatumQuery,
+ unsigned int keyCount, const HashCode512 * keys);
#endif
Modified: GNUnet/src/include/fs.h
===================================================================
--- GNUnet/src/include/fs.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/include/fs.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -34,7 +34,8 @@
* there maybe more than one (the semantics depend
* on the type).
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -79,7 +80,8 @@
* header is followed by variable size data (the data portion
* of the Datastore_Value).
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
unsigned int anonymityLevel;
@@ -94,7 +96,8 @@
* This struct is followed by a variable
* number of bytes of content.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -121,7 +124,8 @@
* (for on-demand encoding). This struct is followed
* by the filename to index.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
unsigned int reserved;
@@ -139,7 +143,8 @@
* encoding). This struct is followed by a variable
* number of bytes of content.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -178,7 +183,8 @@
* Client to server: delete content. This struct is followed by a
* variable number of bytes of the content that is to be deleted.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
} CS_fs_request_delete_MESSAGE;
@@ -187,7 +193,8 @@
/**
* Client to server: unindex file.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -206,7 +213,8 @@
/**
* Client to server: test if file is indexed
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
unsigned int reserved;
@@ -225,9 +233,10 @@
* We essentially add the timeout value since that part is supposed to
* be communicated to other peers.
*/
-typedef struct {
+typedef struct
+{
DataContainer dc;
- unsigned int reserved; /* for 64-bit alignment */
+ unsigned int reserved; /* for 64-bit alignment */
unsigned long long timeout;
} GapWrapper;
Modified: GNUnet/src/include/gnunet_blockstore.h
===================================================================
--- GNUnet/src/include/gnunet_blockstore.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_blockstore.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,8 +30,9 @@
#include "gnunet_util.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -39,7 +40,8 @@
/**
* Data stored in the blockstore.
*/
-typedef struct {
+typedef struct
+{
/**
* Size of the data container (in NBO). This field
* is followed by size-sizeof(unsigned int) bytes
@@ -56,9 +58,8 @@
* @param cls argument passed for context (closure)
* @return OK to continue with iteration, SYSERR to abort
*/
-typedef int (*DataProcessor)(const HashCode512 * key,
- const DataContainer * value,
- void * cls);
+typedef int (*DataProcessor) (const HashCode512 * key,
+ const DataContainer * value, void *cls);
/**
* GAP and DHT clients must implement this interface to tell
@@ -76,17 +77,18 @@
* The put method is (ab)used to check an item that is merely routed
* for its integrity.
*/
-typedef struct {
+typedef struct
+{
/**
* First argument to be passed to all functions in this struct.
*/
- void * closure;
+ void *closure;
/**
* Do a quick test if we MAY have the content.
*/
- int (*fast_get)(const HashCode512 * key);
+ int (*fast_get) (const HashCode512 * key);
/**
* Lookup an item in the datastore.
@@ -99,13 +101,12 @@
* @param resCallbackClosure extra argument to resultCallback
* @return number of results, SYSERR on error
*/
- int (*get)(void * closure,
- unsigned int type,
- unsigned int prio,
- unsigned int keyCount,
- const HashCode512 * keys,
- DataProcessor resultCallback,
- void * resCallbackClosure);
+ int (*get) (void *closure,
+ unsigned int type,
+ unsigned int prio,
+ unsigned int keyCount,
+ const HashCode512 * keys,
+ DataProcessor resultCallback, void *resCallbackClosure);
/**
* Store an item in the datastore.
@@ -117,10 +118,9 @@
* NO if the value verifies but is not stored,
* SYSERR if the value is malformed
*/
- int (*put)(void * closure,
- const HashCode512 * key,
- const DataContainer * value,
- unsigned int prio);
+ int (*put) (void *closure,
+ const HashCode512 * key,
+ const DataContainer * value, unsigned int prio);
/**
* Remove an item from the datastore.
@@ -129,9 +129,8 @@
* @param value the value to remove, NULL for all values of the key
* @return OK if the value could be removed, SYSERR if not (i.e. not present)
*/
- int (*del)(void * closure,
- const HashCode512 * key,
- const DataContainer * value);
+ int (*del) (void *closure,
+ const HashCode512 * key, const DataContainer * value);
/**
* Iterate over all keys in the local datastore
@@ -140,13 +139,11 @@
* @param cls argument to processor
* @return number of results, SYSERR on error
*/
- int (*iterate)(void * closure,
- DataProcessor processor,
- void * cls);
+ int (*iterate) (void *closure, DataProcessor processor, void *cls);
} Blockstore;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_bootstrap_service.h
===================================================================
--- GNUnet/src/include/gnunet_bootstrap_service.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/include/gnunet_bootstrap_service.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -30,8 +30,9 @@
#include "gnunet_core.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -40,18 +41,19 @@
* Definition of a callback function that processes
* hello messages generated by the bootstrap API.
*/
-typedef void (*bootstrap_hello_callback)(const P2P_hello_MESSAGE * helo,
- void * arg);
+typedef void (*bootstrap_hello_callback) (const P2P_hello_MESSAGE * helo,
+ void *arg);
/**
* @return YES to continue, NO to abort
*/
-typedef int (*bootstrap_terminate_callback)(void * arg);
+typedef int (*bootstrap_terminate_callback) (void *arg);
/**
* @brief Definition of the bootstrap API.
*/
-typedef struct {
+typedef struct
+{
/**
* Obtain hellos (i.e. by downloading form the web) and call the
@@ -60,15 +62,14 @@
* @param callback the method to call
* @param arg extra argument to the method
*/
- void (*bootstrap)(bootstrap_hello_callback callback,
- void * arg,
- bootstrap_terminate_callback term,
- void * targ);
+ void (*bootstrap) (bootstrap_hello_callback callback,
+ void *arg,
+ bootstrap_terminate_callback term, void *targ);
} Bootstrap_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_collection_lib.h
===================================================================
--- GNUnet/src/include/gnunet_collection_lib.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_collection_lib.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,8 +30,9 @@
#include "gnunet_ecrs_lib.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -39,38 +40,36 @@
/**
* Initialize collection module.
*/
-void CO_init(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+void CO_init (struct GE_Context *ectx, struct GC_Configuration *cfg);
/**
* Shutdown collection module.
*/
-void CO_done(void);
-
+void CO_done (void);
+
/**
* Start a collection (also automatically stops
* an existing collection).
*/
-int CO_startCollection(unsigned int anonymityLevel,
- unsigned int priority,
- TIME_T updateInterval,
- const char * name,
- const struct ECRS_MetaData * meta);
+int CO_startCollection (unsigned int anonymityLevel,
+ unsigned int priority,
+ TIME_T updateInterval,
+ const char *name, const struct ECRS_MetaData *meta);
/**
* Stop collection.
*
* @return OK on success, SYSERR if no collection is active
*/
-int CO_stopCollection(void);
+int CO_stopCollection (void);
/**
* Are we using a collection?
*
* @return NULL if there is no collection, otherwise its name
*/
-char * CO_getCollection(void);
+char *CO_getCollection (void);
/**
* Upload an update of the current collection information to the
@@ -87,7 +86,7 @@
* However, clients may want to call this function if explicit
* publication of an update at another time is desired.
*/
-void CO_publishCollectionNow(void);
+void CO_publishCollectionNow (void);
/**
* If we are currently building a collection, publish the given file
@@ -100,9 +99,9 @@
* maybe useful if you're inserting files using libECRS directly or
* need other ways to explicitly extend a collection.
*/
-void CO_publishToCollection(const ECRS_FileInfo * fi);
+void CO_publishToCollection (const ECRS_FileInfo * fi);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_core.h
===================================================================
--- GNUnet/src/include/gnunet_core.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/include/gnunet_core.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -31,8 +31,9 @@
#include "gnunet_util_cron.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -74,8 +75,9 @@
* Opaque handle for a session representation on the transport
* layer side
*/
-typedef struct {
- void * internal;
+typedef struct
+{
+ void *internal;
PeerIdentity peer;
@@ -91,35 +93,34 @@
/**
* Type of a handler for messages from clients.
*/
-typedef int (*CSHandler)(struct ClientHandle * client,
- const MESSAGE_HEADER * message);
+typedef int (*CSHandler) (struct ClientHandle * client,
+ const MESSAGE_HEADER * message);
/**
* Method called whenever a given client disconnects.
*/
-typedef void (*ClientExitHandler)(struct ClientHandle * client);
+typedef void (*ClientExitHandler) (struct ClientHandle * client);
/**
* Type of a handler for some message type.
*/
-typedef int (*MessagePartHandler)(const PeerIdentity * sender,
- const MESSAGE_HEADER * message);
+typedef int (*MessagePartHandler) (const PeerIdentity * sender,
+ const MESSAGE_HEADER * message);
/**
* Type of a handler for plaintext messages. Since we cannot
* be certain about the sender's identity, it is NOT passed to
* the callback.
*/
-typedef int (*PlaintextMessagePartHandler)(const PeerIdentity * sender,
- const MESSAGE_HEADER * message,
- TSession * session);
+typedef int (*PlaintextMessagePartHandler) (const PeerIdentity * sender,
+ const MESSAGE_HEADER * message,
+ TSession * session);
/**
* Type of a handler for some message type.
* @param identity the id of the node
*/
-typedef void (*PerNodeCallback)(const PeerIdentity * identity,
- void * data);
+typedef void (*PerNodeCallback) (const PeerIdentity * identity, void *data);
/**
* Type of a send callback to fill up buffers.
@@ -131,9 +132,9 @@
* @return the number of bytes written to
* that buffer (must be a positive number).
*/
-typedef unsigned int (*BufferFillCallback)(const PeerIdentity * receiver,
- void * position,
- unsigned int padding);
+typedef unsigned int (*BufferFillCallback) (const PeerIdentity * receiver,
+ void *position,
+ unsigned int padding);
/**
* Callback that is used to fill in a message into the send buffer.
@@ -147,9 +148,8 @@
* to discard the message!
* @return OK on success, SYSERR on error
*/
-typedef int (*BuildMessageCallback)(void * buf,
- void * closure,
- unsigned short len);
+typedef int (*BuildMessageCallback) (void *buf,
+ void *closure, unsigned short len);
/**
* Send a message to the client identified by the handle. Note that
@@ -158,14 +158,15 @@
* on the other hand does NOT confirm delivery since the actual
* transfer happens asynchronously.
*/
-typedef int (*SendToClientCallback)(struct ClientHandle * handle,
- const MESSAGE_HEADER * message);
+typedef int (*SendToClientCallback) (struct ClientHandle * handle,
+ const MESSAGE_HEADER * message);
/**
* GNUnet CORE API for applications and services that are implemented
* on top of the GNUnet core.
*/
-typedef struct {
+typedef struct
+{
/**
* The version of the CORE API. For now, always "0".
@@ -175,27 +176,27 @@
/**
* The identity of the local node.
*/
- PeerIdentity * myIdentity;
+ PeerIdentity *myIdentity;
/**
* System error context
*/
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
/**
* System configuration
*/
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
/**
* System load monitor
*/
- struct LoadMonitor * load_monitor;
+ struct LoadMonitor *load_monitor;
/**
* System cron Manager.
*/
- struct CronManager * cron;
+ struct CronManager *cron;
/* ****************** services and applications **************** */
@@ -210,7 +211,7 @@
*
* @return OK on success, SYSERR on error
*/
- int (*loadApplicationModule)(const char * name);
+ int (*loadApplicationModule) (const char *name);
/**
* Unload an application module. This function must be called
@@ -222,7 +223,7 @@
*
* @return OK on success, SYSERR on error
*/
- int (*unloadApplicationModule)(const char * name);
+ int (*unloadApplicationModule) (const char *name);
/**
* Load a service module of the given name. This function must be
@@ -232,7 +233,7 @@
* loaded or unloaded inside the module initialization or shutdown
* code.
*/
- void * (*requestService)(const char * name);
+ void *(*requestService) (const char *name);
/**
* Notification that the given service is no longer required. This
@@ -244,7 +245,7 @@
*
* @return OK if service was successfully released, SYSERR on error
*/
- int (*releaseService)(void * service);
+ int (*releaseService) (void *service);
/* ****************** P2P data exchange **************** */
@@ -260,9 +261,8 @@
* @param msg the message to transmit, should contain MESSAGE_HEADERs
* @return OK on success, SYSERR on failure
*/
- int (*sendPlaintext)(TSession * session,
- const char * msg,
- unsigned int size);
+ int (*sendPlaintext) (TSession * session,
+ const char *msg, unsigned int size);
/**
* Send an encrypted message to another node.
@@ -273,10 +273,9 @@
* @param importance how important is the message?
* @param maxdelay how long can the message be delayed?
*/
- void (*unicast)(const PeerIdentity * receiver,
- const MESSAGE_HEADER * msg,
- unsigned int importance,
- unsigned int maxdelay);
+ void (*unicast) (const PeerIdentity * receiver,
+ const MESSAGE_HEADER * msg,
+ unsigned int importance, unsigned int maxdelay);
/**
* Send an encrypted, on-demand build message to another node.
@@ -288,12 +287,11 @@
* @param importance how important is the message?
* @param maxdelay how long can the message wait?
*/
- void (*unicastCallback)(const PeerIdentity * receiver,
- BuildMessageCallback callback,
- void * closure,
- unsigned short len,
- unsigned int importance,
- unsigned int maxdelay);
+ void (*unicastCallback) (const PeerIdentity * receiver,
+ BuildMessageCallback callback,
+ void *closure,
+ unsigned short len,
+ unsigned int importance, unsigned int maxdelay);
/**
* Perform an operation for all connected hosts.
@@ -303,8 +301,7 @@
* @param arg the second argument to the method
* @return the number of connected hosts
*/
- int (*forAllConnectedNodes)(PerNodeCallback method,
- void * arg);
+ int (*forAllConnectedNodes) (PerNodeCallback method, void *arg);
/**
* Register a callback method that should be invoked whenever a message
@@ -326,15 +323,15 @@
* that buffer (must be a positive number).
* @return OK if the handler was registered, SYSERR on error
*/
- int (*registerSendCallback)(const unsigned int minimumPadding,
- BufferFillCallback callback);
+ int (*registerSendCallback) (const unsigned int minimumPadding,
+ BufferFillCallback callback);
/**
* Unregister a handler that was registered with registerSendCallback.
* @return OK if the handler was removed, SYSERR on error
*/
- int (*unregisterSendCallback)(const unsigned int minimumPadding,
- BufferFillCallback callback);
+ int (*unregisterSendCallback) (const unsigned int minimumPadding,
+ BufferFillCallback callback);
/**
* Register a handler that is to be called for each
@@ -344,7 +341,7 @@
* P2P message part that is transmitted
* @return OK on success, SYSERR if there is a problem
*/
- int (*registerSendNotify)(MessagePartHandler callback);
+ int (*registerSendNotify) (MessagePartHandler callback);
/**
* Unregister a handler that is to be called for each
@@ -354,7 +351,7 @@
* P2P message part that is transmitted
* @return OK on success, SYSERR if there is a problem
*/
- int (*unregisterSendNotify)(MessagePartHandler callback);
+ int (*unregisterSendNotify) (MessagePartHandler callback);
/* ********************* handlers ***************** */
@@ -368,8 +365,7 @@
* @return OK on success, SYSERR if there is already a
* handler for that type
*/
- int (*registerHandler)(unsigned short type,
- MessagePartHandler callback);
+ int (*registerHandler) (unsigned short type, MessagePartHandler callback);
/**
* Unregister a method as a handler for specific message
@@ -380,8 +376,7 @@
* @return OK on success, SYSERR if there is a different
* handler for that type
*/
- int (*unregisterHandler)(unsigned short type,
- MessagePartHandler callback);
+ int (*unregisterHandler) (unsigned short type, MessagePartHandler callback);
/**
* Is a handler registered for messages of the given type?
@@ -394,8 +389,8 @@
* @return number of handlers registered, 0 for none,
* SYSERR for invalid value of handlerType
*/
- int (*isHandlerRegistered)(unsigned short type,
- unsigned short handlerType);
+ int (*isHandlerRegistered) (unsigned short type,
+ unsigned short handlerType);
/**
* Register a method as a handler for specific message
@@ -406,8 +401,8 @@
* @return OK on success, SYSERR if there is already a
* handler for that type
*/
- int (*registerPlaintextHandler)(unsigned short type,
- PlaintextMessagePartHandler callback);
+ int (*registerPlaintextHandler) (unsigned short type,
+ PlaintextMessagePartHandler callback);
/**
* Unregister a method as a handler for specific message
@@ -419,8 +414,8 @@
* @return OK on success, SYSERR if there is a different
* handler for that type
*/
- int (*unregisterPlaintextHandler)(unsigned short type,
- PlaintextMessagePartHandler callback);
+ int (*unregisterPlaintextHandler) (unsigned short type,
+ PlaintextMessagePartHandler callback);
/* ***************** traffic management ******************* */
@@ -433,8 +428,7 @@
* use it after this call. If the core does not want/need
* the session, it will also be disconnected.
*/
- void (*offerTSessionFor)(const PeerIdentity * peer,
- TSession * session);
+ void (*offerTSessionFor) (const PeerIdentity * peer, TSession * session);
/**
* Assign a session key for traffic from or to a given peer.
@@ -446,10 +440,9 @@
* @param forSending NO if it is the key for receiving,
* YES if it is the key for sending
*/
- void (*assignSessionKey)(const SESSIONKEY * key,
- const PeerIdentity * peer,
- TIME_T age,
- int forSending);
+ void (*assignSessionKey) (const SESSIONKEY * key,
+ const PeerIdentity * peer,
+ TIME_T age, int forSending);
/**
* Obtain the session key used for traffic from or to a given peer.
@@ -462,10 +455,9 @@
* @return SYSERR if no sessionkey is known to the core,
* OK if the sessionkey was set.
*/
- int (*getCurrentSessionKey)(const PeerIdentity * peer,
- SESSIONKEY * key,
- TIME_T * age,
- int forSending);
+ int (*getCurrentSessionKey) (const PeerIdentity * peer,
+ SESSIONKEY * key,
+ TIME_T * age, int forSending);
/**
* We have confirmed that the other peer is communicating with us,
@@ -474,7 +466,7 @@
* this could happen if in between the core has discarded
* the session information).
*/
- void (*confirmSessionUp)(const PeerIdentity * peer);
+ void (*confirmSessionUp) (const PeerIdentity * peer);
/**
* Increase the preference for traffic from some other peer.
@@ -482,8 +474,7 @@
* @param node the identity of the other peer
* @param preference how much should the traffic preference be increased?
*/
- void (*preferTrafficFrom)(const PeerIdentity * node,
- double preference);
+ void (*preferTrafficFrom) (const PeerIdentity * node, double preference);
/**
* Query how much bandwidth is availabe FROM the given node to
@@ -493,9 +484,8 @@
* @param last_seen set to last time peer was confirmed up
* @return OK on success, SYSERR if if we are NOT connected
*/
- int (*queryPeerStatus)(const PeerIdentity * node,
- unsigned int * bpm,
- cron_t * last_seen);
+ int (*queryPeerStatus) (const PeerIdentity * node,
+ unsigned int *bpm, cron_t * last_seen);
/**
* Disconnect a particular peer. Sends a HANGUP message to the other
@@ -503,7 +493,7 @@
*
* @param peer the peer to disconnect
*/
- void (*disconnectFromPeer)(const PeerIdentity *peer);
+ void (*disconnectFromPeer) (const PeerIdentity * peer);
/* **************** Client-server interaction **************** */
@@ -514,8 +504,7 @@
* on the other hand does NOT confirm delivery since the actual
* transfer happens asynchronously.
*/
- int (*sendValueToClient)(struct ClientHandle * handle,
- int value);
+ int (*sendValueToClient) (struct ClientHandle * handle, int value);
/**
* Send a message to the client identified by the handle. Note that
@@ -535,8 +524,7 @@
* @return OK on success, SYSERR if there is already a
* handler for that type
*/
- int (*registerClientHandler)(unsigned short type,
- CSHandler callback);
+ int (*registerClientHandler) (unsigned short type, CSHandler callback);
/**
* Remove a method as a handler for specific message
@@ -547,8 +535,7 @@
* @return OK on success, SYSERR if there is a different
* handler for that type
*/
- int (*unregisterClientHandler)(unsigned short type,
- CSHandler callback);
+ int (*unregisterClientHandler) (unsigned short type, CSHandler callback);
/**
* Register a handler to call if any client exits.
@@ -556,7 +543,7 @@
* of every client that disconnected.
* @return OK on success, SYSERR on error
*/
- int (*registerClientExitHandler)(ClientExitHandler callback);
+ int (*registerClientExitHandler) (ClientExitHandler callback);
/**
* Unregister a handler to call if any client exits.
@@ -564,13 +551,13 @@
* of every client that disconnected.
* @return OK on success, SYSERR on error
*/
- int (*unregisterClientExitHandler)(ClientExitHandler callback);
+ int (*unregisterClientExitHandler) (ClientExitHandler callback);
/**
* Terminate the connection with the given client (asynchronous
* detection of a protocol violation).
*/
- void (*terminateClientConnection)(struct ClientHandle * handle);
+ void (*terminateClientConnection) (struct ClientHandle * handle);
/* ************************ MISC ************************ */
@@ -585,36 +572,35 @@
* @param session for plaintext messages, the
* assumed transport session. Maybe NULL.
*/
- void (*injectMessage)(const PeerIdentity * sender,
- const char * msg,
- unsigned int size,
- int wasEncrypted,
- TSession * session);
+ void (*injectMessage) (const PeerIdentity * sender,
+ const char *msg,
+ unsigned int size,
+ int wasEncrypted, TSession * session);
/**
* Compute the index (small, positive, pseudo-unique identification
* number) of a hostId.
*/
- unsigned int (*computeIndex)(const PeerIdentity * hostId);
+ unsigned int (*computeIndex) (const PeerIdentity * hostId);
/**
* The the lock of the connection module. A module that registers
* callbacks may need this.
*/
- struct MUTEX * (*getConnectionModuleLock)(void);
+ struct MUTEX *(*getConnectionModuleLock) (void);
/**
* Get the current number of slots in the connection table (as computed
* from the available bandwidth).
*/
- int (*getSlotCount)(void);
+ int (*getSlotCount) (void);
/**
* Is the given slot used?
* @return 0 if not, otherwise number of peers in
* the slot
*/
- int (*isSlotUsed)(int slot);
+ int (*isSlotUsed) (int slot);
/**
* Get the time of the last encrypted message that was received
@@ -622,8 +608,7 @@
* @param time updated with the time
* @return SYSERR if we are not connected to the peer at the moment
*/
- int (*getLastActivityOf)(const PeerIdentity * peer,
- cron_t * time);
+ int (*getLastActivityOf) (const PeerIdentity * peer, cron_t * time);
/* here for binary compatibility (for now) */
@@ -634,12 +619,11 @@
* on the other hand does NOT confirm delivery since the actual
* transfer happens asynchronously.
*/
- int (*sendErrorMessageToClient)(struct ClientHandle * handle,
- GE_KIND kind,
- const char * value);
+ int (*sendErrorMessageToClient) (struct ClientHandle * handle,
+ GE_KIND kind, const char *value);
- struct GE_Context * (*createClientLogContext)(GE_KIND mask,
- struct ClientHandle * handle);
+ struct GE_Context *(*createClientLogContext) (GE_KIND mask,
+ struct ClientHandle * handle);
} CoreAPIForApplication;
@@ -655,7 +639,7 @@
* Type of the shutdown method implemented by GNUnet protocol
* plugins.
*/
-typedef void (*ApplicationDoneMethod)(void);
+typedef void (*ApplicationDoneMethod) (void);
/**
* Type of the initialization method implemented by GNUnet service
@@ -663,13 +647,13 @@
*
* @param capi the core API
*/
-typedef void * (*ServiceInitMethod)(CoreAPIForApplication * capi);
+typedef void *(*ServiceInitMethod) (CoreAPIForApplication * capi);
/**
* Type of the shutdown method implemented by GNUnet service
* plugins.
*/
-typedef void (*ServiceDoneMethod)(void);
+typedef void (*ServiceDoneMethod) (void);
@@ -680,22 +664,23 @@
* will then call that function to allow the module to perform the
* necessary updates.
*/
-typedef struct {
+typedef struct
+{
/**
* System error context
*/
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
/**
* System configuration
*/
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
/**
* Trigger updates for another module.
*/
- int (*updateModule)(const char * module);
+ int (*updateModule) (const char *module);
/**
* Load a service module of the given name. This function must be
@@ -705,7 +690,7 @@
* loaded or unloaded inside the module initialization or shutdown
* code.
*/
- void * (*requestService)(const char * name);
+ void *(*requestService) (const char *name);
/**
* Notification that the given service is no longer required. This
@@ -717,15 +702,15 @@
*
* @return OK if service was successfully released, SYSERR on error
*/
- int (*releaseService)(void * service);
+ int (*releaseService) (void *service);
} UpdateAPI;
-typedef void (*UpdateMethod)(UpdateAPI * uapi);
+typedef void (*UpdateMethod) (UpdateAPI * uapi);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_datastore_service.h
===================================================================
--- GNUnet/src/include/gnunet_datastore_service.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/include/gnunet_datastore_service.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -34,8 +34,9 @@
#include "gnunet_core.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -43,7 +44,8 @@
/**
* A value in the datastore.
*/
-typedef struct {
+typedef struct
+{
/**
* The total size of the Value, including this header, in network
@@ -84,7 +86,8 @@
/**
* An entry (key-value pair) in the datastore.
*/
-typedef struct {
+typedef struct
+{
/**
* A key (not unique) that can be used to lookup this Datum in the
@@ -106,9 +109,8 @@
* @param closure user-defined extra argument
* @return SYSERR to abort the iteration, OK to continue.
*/
-typedef int (*Datum_Iterator)(const HashCode512 * key,
- const Datastore_Value * value,
- void * closure);
+typedef int (*Datum_Iterator) (const HashCode512 * key,
+ const Datastore_Value * value, void *closure);
/**
@@ -129,12 +131,13 @@
* Once GNUnet has IO load management the DS should integrate with
* that and refuse IO if the load is too high.
*/
-typedef struct {
+typedef struct
+{
/**
* Get the current on-disk size of the datastore.
*/
- unsigned long long (*getSize)(void);
+ unsigned long long (*getSize) (void);
/**
* Store an item in the datastore. If the item is
@@ -145,8 +148,7 @@
* to justify removing something else, SYSERR on
* other serious error (i.e. IO permission denied)
*/
- int (*put)(const HashCode512 * key,
- const Datastore_Value * value);
+ int (*put) (const HashCode512 * key, const Datastore_Value * value);
/**
* Store an item in the datastore. If the item is already present,
@@ -158,8 +160,7 @@
* to justify removing something else, SYSERR on
* other serious error (i.e. IO permission denied)
*/
- int (*putUpdate)(const HashCode512 * key,
- const Datastore_Value * value);
+ int (*putUpdate) (const HashCode512 * key, const Datastore_Value * value);
/**
* Iterate over the results for a particular key
@@ -174,15 +175,13 @@
* 0 if no matches were found. May NOT return
* SYSERR unless the iterator aborted!
*/
- int (*get)(const HashCode512 * key,
- unsigned int type,
- Datum_Iterator iter,
- void * closure);
+ int (*get) (const HashCode512 * key,
+ unsigned int type, Datum_Iterator iter, void *closure);
/**
* Do a quick test if we MAY have the content.
*/
- int (*fast_get)(const HashCode512 * key);
+ int (*fast_get) (const HashCode512 * key);
/**
* Get a random value from the datastore that has
@@ -196,11 +195,10 @@
* for any type.
* @return OK if a value was found, SYSERR if not
*/
- int (*getRandom)(const HashCode512 * approx,
- unsigned int sizeLimit,
- HashCode512 * key,
- Datastore_Value ** value,
- unsigned int type);
+ int (*getRandom) (const HashCode512 * approx,
+ unsigned int sizeLimit,
+ HashCode512 * key,
+ Datastore_Value ** value, unsigned int type);
/**
* Delete an item from the datastore.
@@ -210,12 +208,11 @@
* @return the number of items deleted, 0 if
* none were found, SYSERR on errors
*/
- int (*del)(const HashCode512 * key,
- const Datastore_Value * value);
+ int (*del) (const HashCode512 * key, const Datastore_Value * value);
} Datastore_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_dht_lib.h
===================================================================
--- GNUnet/src/include/gnunet_dht_lib.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/include/gnunet_dht_lib.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -31,8 +31,9 @@
#include "gnunet_dht_service.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -49,14 +50,13 @@
* SYSERR
* @return number of results on success, SYSERR on error (i.e. timeout)
*/
-int DHT_LIB_get(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- unsigned int type,
- const HashCode512 * key,
- cron_t timeout,
- DataProcessor resultCallback,
- void * resCallbackClosure);
-
+int DHT_LIB_get (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ unsigned int type,
+ const HashCode512 * key,
+ cron_t timeout,
+ DataProcessor resultCallback, void *resCallbackClosure);
+
/**
* Perform a synchronous put operation.
*
@@ -65,14 +65,13 @@
* @param value what to store
* @return OK on success, SYSERR on error
*/
-int DHT_LIB_put(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const HashCode512 * key,
- unsigned int type,
- cron_t expire,
- const DataContainer * value);
+int DHT_LIB_put (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const HashCode512 * key,
+ unsigned int type,
+ cron_t expire, const DataContainer * value);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_dht_service.h
===================================================================
--- GNUnet/src/include/gnunet_dht_service.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_dht_service.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,8 +35,9 @@
#include "gnunet_blockstore.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -46,12 +47,13 @@
/**
* DHT operation 'complete' (i.e timed out).
*/
-typedef void (*DHT_OP_Complete)(void * closure);
+typedef void (*DHT_OP_Complete) (void *closure);
/**
* Functions of the DHT Service API.
*/
-typedef struct {
+typedef struct
+{
/**
* Perform an asynchronous GET operation on the DHT identified by
@@ -66,18 +68,18 @@
* @param closure extra argument to callback
* @return handle to stop the async get
*/
- struct DHT_GET_RECORD * (*get_start)(unsigned int type,
- const HashCode512 * key,
- cron_t timeout,
- DataProcessor callback,
- void * cls,
- DHT_OP_Complete callbackComplete,
- void * closure);
+ struct DHT_GET_RECORD *(*get_start) (unsigned int type,
+ const HashCode512 * key,
+ cron_t timeout,
+ DataProcessor callback,
+ void *cls,
+ DHT_OP_Complete callbackComplete,
+ void *closure);
/**
* Stop async DHT-get. Frees associated resources.
*/
- int (*get_stop)(struct DHT_GET_RECORD * record);
+ int (*get_stop) (struct DHT_GET_RECORD * record);
/**
* Perform a PUT operation on the DHT identified by 'table' storing
@@ -86,15 +88,13 @@
*
* @param key the key to store under
*/
- void (*put)(const HashCode512 * key,
- unsigned int type,
- unsigned int size,
- cron_t expire,
- const char * data);
+ void (*put) (const HashCode512 * key,
+ unsigned int type,
+ unsigned int size, cron_t expire, const char *data);
} DHT_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_dstore_service.h
===================================================================
--- GNUnet/src/include/gnunet_dstore_service.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_dstore_service.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,33 +35,32 @@
#include "gnunet_core.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
-typedef void (*ResultHandler)(const HashCode512 * key,
- unsigned int type,
- unsigned int size,
- const char * data,
- void * cls);
+typedef void (*ResultHandler) (const HashCode512 * key,
+ unsigned int type,
+ unsigned int size,
+ const char *data, void *cls);
/**
* @brief Definition of the SQ-Store API.
*/
-typedef struct {
+typedef struct
+{
/**
* Store an item in the datastore.
*
* @return OK on success, SYSERR on error
*/
- int (*put)(const HashCode512 * key,
- unsigned int type,
- cron_t discard_time,
- unsigned int size,
- const char * data);
+ int (*put) (const HashCode512 * key,
+ unsigned int type,
+ cron_t discard_time, unsigned int size, const char *data);
/**
* Iterate over the results for a particular key
@@ -73,14 +72,12 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
- int (*get)(const HashCode512 * key,
- unsigned int type,
- ResultHandler handler,
- void * closure);
+ int (*get) (const HashCode512 * key,
+ unsigned int type, ResultHandler handler, void *closure);
} Dstore_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_ecrs_lib.h
===================================================================
--- GNUnet/src/include/gnunet_ecrs_lib.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_ecrs_lib.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -32,8 +32,9 @@
#include <extractor.h>
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -89,77 +90,72 @@
* Iterator over meta data.
* @return OK to continue to iterate, SYSERR to abort
*/
-typedef int (*ECRS_MetaDataIterator)(EXTRACTOR_KeywordType type,
- const char * data,
- void * closure);
+typedef int (*ECRS_MetaDataIterator) (EXTRACTOR_KeywordType type,
+ const char *data, void *closure);
/**
* Iterator over keywords
* @return OK to continue to iterate, SYSERR to abort
*/
-typedef int (*ECRS_KeywordIterator)(const char * data,
- void * closure);
+typedef int (*ECRS_KeywordIterator) (const char *data, void *closure);
/**
* Create a fresh MetaData token.
*/
-struct ECRS_MetaData * ECRS_createMetaData(void);
+struct ECRS_MetaData *ECRS_createMetaData (void);
/**
* Duplicate a MetaData token.
*/
-struct ECRS_MetaData * ECRS_dupMetaData(const struct ECRS_MetaData * meta);
+struct ECRS_MetaData *ECRS_dupMetaData (const struct ECRS_MetaData *meta);
/**
* Free meta data.
*/
-void ECRS_freeMetaData(struct ECRS_MetaData * md);
+void ECRS_freeMetaData (struct ECRS_MetaData *md);
/**
* Test if two MDs are equal.
*/
-int ECRS_equalsMetaData(const struct ECRS_MetaData * md1,
- const struct ECRS_MetaData * md2);
-
+int ECRS_equalsMetaData (const struct ECRS_MetaData *md1,
+ const struct ECRS_MetaData *md2);
+
/**
* Extend metadata.
* @return OK on success, SYSERR if this entry already exists
*/
-int ECRS_addToMetaData(struct ECRS_MetaData * md,
- EXTRACTOR_KeywordType type,
- const char * data);
+int ECRS_addToMetaData (struct ECRS_MetaData *md,
+ EXTRACTOR_KeywordType type, const char *data);
/**
* Remove an item.
* @return OK on success, SYSERR if the item does not exist in md
*/
-int ECRS_delFromMetaData(struct ECRS_MetaData * md,
- EXTRACTOR_KeywordType type,
- const char * data);
+int ECRS_delFromMetaData (struct ECRS_MetaData *md,
+ EXTRACTOR_KeywordType type, const char *data);
/**
* Add the current time as the publication date
* to the meta-data.
*/
-void ECRS_addPublicationDateToMetaData(struct ECRS_MetaData * md);
+void ECRS_addPublicationDateToMetaData (struct ECRS_MetaData *md);
/**
* Iterate over MD entries, excluding thumbnails.
*
* @return number of entries
*/
-int ECRS_getMetaData(const struct ECRS_MetaData * md,
- ECRS_MetaDataIterator iterator,
- void * closure);
+int ECRS_getMetaData (const struct ECRS_MetaData *md,
+ ECRS_MetaDataIterator iterator, void *closure);
/**
* Get the first MD entry of the given type.
* @return NULL if we do not have any such entry,
* otherwise client is responsible for freeing the value!
*/
-char * ECRS_getFromMetaData(const struct ECRS_MetaData * md,
- EXTRACTOR_KeywordType type);
+char *ECRS_getFromMetaData (const struct ECRS_MetaData *md,
+ EXTRACTOR_KeywordType type);
/**
* Get the first matching MD entry of the given types.
@@ -167,8 +163,7 @@
* @return NULL if we do not have any such entry,
* otherwise client is responsible for freeing the value!
*/
-char * ECRS_getFirstFromMetaData(const struct ECRS_MetaData * md,
- ...);
+char *ECRS_getFirstFromMetaData (const struct ECRS_MetaData *md, ...);
/**
* Get a thumbnail from the meta-data (if present).
@@ -177,19 +172,19 @@
* freed by the caller!
* @return number of bytes in thumbnail, 0 if not available
*/
-size_t ECRS_getThumbnailFromMetaData(const struct ECRS_MetaData * md,
- unsigned char ** thumb);
-
+size_t ECRS_getThumbnailFromMetaData (const struct ECRS_MetaData *md,
+ unsigned char **thumb);
+
/**
* Extract meta-data from a file.
*
* @return SYSERR on error, otherwise the number
* of meta-data items obtained
*/
-int ECRS_extractMetaData(struct GE_Context * ectx,
- struct ECRS_MetaData * md,
- const char * filename,
- EXTRACTOR_ExtractorList * extractors);
+int ECRS_extractMetaData (struct GE_Context *ectx,
+ struct ECRS_MetaData *md,
+ const char *filename,
+ EXTRACTOR_ExtractorList * extractors);
/* = 0 */
#define ECRS_SERIALIZE_FULL NO
@@ -212,19 +207,16 @@
* SYSERR on error (typically: not enough
* space)
*/
-int ECRS_serializeMetaData(struct GE_Context * ectx,
- const struct ECRS_MetaData * md,
- char * target,
- unsigned int size,
- int part);
+int ECRS_serializeMetaData (struct GE_Context *ectx,
+ const struct ECRS_MetaData *md,
+ char *target, unsigned int size, int part);
/**
* Compute size of the meta-data in
* serialized form.
* @part flags (partial ok, may compress?)
*/
-unsigned int ECRS_sizeofMetaData(const struct ECRS_MetaData * md,
- int part);
+unsigned int ECRS_sizeofMetaData (const struct ECRS_MetaData *md, int part);
/**
* Deserialize meta-data. Initializes md.
@@ -232,10 +224,9 @@
* @return MD on success, NULL on error (i.e.
* bad format)
*/
-struct ECRS_MetaData *
-ECRS_deserializeMetaData(struct GE_Context * ectx,
- const char * input,
- unsigned int size);
+struct ECRS_MetaData *ECRS_deserializeMetaData (struct GE_Context *ectx,
+ const char *input,
+ unsigned int size);
/**
* Does the meta-data claim that this is a directory?
@@ -244,14 +235,13 @@
* @return YES if it is, NO if it is not, SYSERR if
* we have no mime-type information (treat as 'NO')
*/
-int ECRS_isDirectory(const struct ECRS_MetaData * md);
+int ECRS_isDirectory (const struct ECRS_MetaData *md);
/**
* Suggest a better filename for a file (and do the
* renaming).
*/
-char * ECRS_suggestFilename(struct GE_Context * ectx,
- const char * filename);
+char *ECRS_suggestFilename (struct GE_Context *ectx, const char *filename);
/* ******************** URI (uri.c) ************************ */
@@ -263,65 +253,58 @@
/**
* Convert a URI to a UTF-8 String.
*/
-char * ECRS_uriToString(const struct ECRS_URI * uri);
+char *ECRS_uriToString (const struct ECRS_URI *uri);
/**
* Convert a NULL-terminated array of keywords
* to an ECRS URI.
*/
-struct ECRS_URI *
-ECRS_keywordsToUri(const char * keyword[]);
+struct ECRS_URI *ECRS_keywordsToUri (const char *keyword[]);
/**
* Convert a UTF-8 String to a URI.
*/
-struct ECRS_URI *
-ECRS_stringToUri(struct GE_Context * ectx,
- const char * uri);
+struct ECRS_URI *ECRS_stringToUri (struct GE_Context *ectx, const char *uri);
/**
* Free URI.
*/
-void ECRS_freeUri(struct ECRS_URI * uri);
+void ECRS_freeUri (struct ECRS_URI *uri);
/**
* How many keywords are ANDed in this keyword URI?
* @return 0 if this is not a keyword URI
*/
-unsigned int ECRS_countKeywordsOfUri(const struct ECRS_URI * uri);
+unsigned int ECRS_countKeywordsOfUri (const struct ECRS_URI *uri);
/**
* Iterate over all keywords in this keyword URI?
* @return -1 if this is not a keyword URI, otherwise number of
* keywords iterated over until iterator aborted
*/
-int ECRS_getKeywordsFromUri(const struct ECRS_URI * uri,
- ECRS_KeywordIterator iterator,
- void * cls);
+int ECRS_getKeywordsFromUri (const struct ECRS_URI *uri,
+ ECRS_KeywordIterator iterator, void *cls);
/**
* Obtain the identity of the peer offering the data
* @return -1 if this is not a location URI, otherwise OK
*/
-int ECRS_getPeerFromUri(const struct ECRS_URI * uri,
- PeerIdentity * peer);
+int ECRS_getPeerFromUri (const struct ECRS_URI *uri, PeerIdentity * peer);
/**
* Obtain the URI of the content itself.
*
* @return NULL if argument is not a location URI
*/
-struct ECRS_URI *
-ECRS_getContentUri(const struct ECRS_URI * uri);
+struct ECRS_URI *ECRS_getContentUri (const struct ECRS_URI *uri);
/**
* Function that produces a signature for
* a particular piece of content.
*/
-typedef int (*ECRS_SignFunction)(void * cls,
- unsigned short size,
- const void * data,
- Signature * result);
+typedef int (*ECRS_SignFunction) (void *cls,
+ unsigned short size,
+ const void *data, Signature * result);
/**
* Construct a location URI.
@@ -333,26 +316,24 @@
* RSA signatures for "sender".
* @return the location URI
*/
-struct ECRS_URI *
-ECRS_uriFromLocation(const struct ECRS_URI * baseUri,
- const PublicKey * peer,
- TIME_T expirationTime,
- ECRS_SignFunction signer,
- void * signer_cls);
+struct ECRS_URI *ECRS_uriFromLocation (const struct ECRS_URI *baseUri,
+ const PublicKey * peer,
+ TIME_T expirationTime,
+ ECRS_SignFunction signer,
+ void *signer_cls);
/**
* Duplicate URI.
*/
-struct ECRS_URI * ECRS_dupUri(const struct ECRS_URI * uri);
+struct ECRS_URI *ECRS_dupUri (const struct ECRS_URI *uri);
/**
* Expand a keyword-URI by duplicating all keywords,
* adding the current date (YYYY-MM-DD) after each
* keyword.
*/
-struct ECRS_URI *
-ECRS_dateExpandKeywordUri(const struct ECRS_URI * uri);
+struct ECRS_URI *ECRS_dateExpandKeywordUri (const struct ECRS_URI *uri);
/**
* Create an ECRS URI from a single user-supplied string of keywords.
@@ -362,9 +343,7 @@
* @return an ECRS URI for the given keywords, NULL
* if keywords is not legal (i.e. empty).
*/
-struct ECRS_URI *
-ECRS_parseCharKeywordURI(struct GE_Context * ectx,
- const char * keywords); /* helper.c */
+struct ECRS_URI *ECRS_parseCharKeywordURI (struct GE_Context *ectx, const char
*keywords); /* helper.c */
/**
* Create an ECRS URI from a user-supplied command line of keywords.
@@ -374,10 +353,7 @@
* @return an ECRS URI for the given keywords, NULL
* if keywords is not legal (i.e. empty).
*/
-struct ECRS_URI *
-ECRS_parseArgvKeywordURI(struct GE_Context * ectx,
- unsigned int argc,
- const char ** argv); /* helper.c */
+struct ECRS_URI *ECRS_parseArgvKeywordURI (struct GE_Context *ectx, unsigned
int argc, const char **argv); /* helper.c */
/**
* Create an ECRS URI from a user-supplied list of keywords.
@@ -387,21 +363,19 @@
* @return an ECRS URI for the given keywords, NULL
* if keywords is not legal (i.e. empty).
*/
-struct ECRS_URI *
-ECRS_parseListKeywordURI(struct GE_Context * ectx,
- unsigned int num_keywords,
- const char ** keywords);
+struct ECRS_URI *ECRS_parseListKeywordURI (struct GE_Context *ectx,
+ unsigned int num_keywords,
+ const char **keywords);
/**
* Test if two URIs are equal.
*/
-int ECRS_equalsUri(const struct ECRS_URI * u1,
- const struct ECRS_URI * u2);
+int ECRS_equalsUri (const struct ECRS_URI *u1, const struct ECRS_URI *u2);
/**
* Is this a namespace URI?
*/
-int ECRS_isNamespaceUri(const struct ECRS_URI * uri);
+int ECRS_isNamespaceUri (const struct ECRS_URI *uri);
/**
* Get the (globally unique) name for the given
@@ -410,41 +384,39 @@
* @return the name (hash) of the namespace, caller
* must free it.
*/
-char * ECRS_getNamespaceName(const HashCode512 * nsid);
+char *ECRS_getNamespaceName (const HashCode512 * nsid);
/**
* Get the ID of a namespace from the given
* namespace URI.
*/
-int ECRS_getNamespaceId(const struct ECRS_URI * uri,
- HashCode512 * nsid);
+int ECRS_getNamespaceId (const struct ECRS_URI *uri, HashCode512 * nsid);
/**
* Get the content ID of an SKS URI.
*/
-int ECRS_getSKSContentHash(const struct ECRS_URI * uri,
- HashCode512 * nsid);
+int ECRS_getSKSContentHash (const struct ECRS_URI *uri, HashCode512 * nsid);
/**
* Is this a keyword URI?
*/
-int ECRS_isKeywordUri(const struct ECRS_URI * uri);
+int ECRS_isKeywordUri (const struct ECRS_URI *uri);
/**
* Is this a file (or directory) URI?
*/
-int ECRS_isFileUri(const struct ECRS_URI * uri);
+int ECRS_isFileUri (const struct ECRS_URI *uri);
/**
* What is the size of the file that this URI
* refers to?
*/
-unsigned long long ECRS_fileSize(const struct ECRS_URI * uri);
+unsigned long long ECRS_fileSize (const struct ECRS_URI *uri);
/**
* Is this a location URI?
*/
-int ECRS_isLocationUri(const struct ECRS_URI * uri);
+int ECRS_isLocationUri (const struct ECRS_URI *uri);
@@ -453,31 +425,31 @@
* in the meta-data and construct one large keyword URI
* that lists all keywords that can be found in the meta-data).
*/
-struct ECRS_URI *
-ECRS_metaDataToUri(const struct ECRS_MetaData * md);
+struct ECRS_URI *ECRS_metaDataToUri (const struct ECRS_MetaData *md);
-typedef struct {
- struct ECRS_MetaData * meta;
- struct ECRS_URI * uri;
+typedef struct
+{
+ struct ECRS_MetaData *meta;
+ struct ECRS_URI *uri;
} ECRS_FileInfo;
/**
* @param scls must be of type "struct ECRS_URI **"
*/
-int gnunet_getopt_configure_set_keywords(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value);
+int gnunet_getopt_configure_set_keywords (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option,
+ const char *value);
/**
* @param scls must be of type "struct ECRS_MetaData **"
*/
-int gnunet_getopt_configure_set_metadata(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value);
+int gnunet_getopt_configure_set_metadata (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option,
+ const char *value);
@@ -493,9 +465,7 @@
*/
typedef void (*ECRS_UploadProgressCallback)
(unsigned long long totalBytes,
- unsigned long long completedBytes,
- cron_t eta,
- void * closure);
+ unsigned long long completedBytes, cron_t eta, void *closure);
/**
* Should the operation be aborted? Callback used by many functions
@@ -510,7 +480,7 @@
* @return OK to continue, SYSERR to abort with deleting
* temporary files, NO to abort without deleting temporary files
*/
-typedef int (*ECRS_TestTerminate)(void * closure);
+typedef int (*ECRS_TestTerminate) (void *closure);
/**
* Index or insert a file.
@@ -523,18 +493,8 @@
* @return SYSERR if the upload failed (i.e. not enough space
* or gnunetd not running)
*/
-int ECRS_uploadFile(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * filename,
- int doIndex,
- unsigned int anonymityLevel,
- unsigned int priority,
- cron_t expirationTime, /* absolute time */
- ECRS_UploadProgressCallback upcb,
- void * upcbClosure,
- ECRS_TestTerminate tt,
- void * ttClosure,
- struct ECRS_URI ** uri); /* upload.c */
+int ECRS_uploadFile (struct GE_Context *ectx, struct GC_Configuration *cfg,
const char *filename, int doIndex, unsigned int anonymityLevel, unsigned int
priority, cron_t expirationTime, /* absolute time */
+ ECRS_UploadProgressCallback upcb, void *upcbClosure,
ECRS_TestTerminate tt, void *ttClosure, struct ECRS_URI **uri); /*
upload.c */
/**
* Test if a file is indexed.
@@ -545,15 +505,13 @@
* in either case, if SYSERR is returned the user should probably
* be notified that 'something is wrong')
*/
-int ECRS_isFileIndexed(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * filename);
+int ECRS_isFileIndexed (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, const char *filename);
/**
* @return OK to continue iteration, SYSERR to abort
*/
-typedef int (*ECRS_FileIterator)(const char * filename,
- void * cls);
+typedef int (*ECRS_FileIterator) (const char *filename, void *cls);
/**
* Iterate over all indexed files.
@@ -567,23 +525,16 @@
*
* @return number of files indexed, SYSERR if iterator aborted
*/
-int ECRS_iterateIndexedFiles(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- ECRS_FileIterator iterator,
- void * closure);
+int ECRS_iterateIndexedFiles (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ ECRS_FileIterator iterator, void *closure);
/**
* Unindex a file.
*
* @return SYSERR if the unindexing failed (i.e. not indexed)
*/
-int ECRS_unindexFile(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * filename,
- ECRS_UploadProgressCallback upcb,
- void * upcbClosure,
- ECRS_TestTerminate tt,
- void * ttClosure); /* unindex.c */
+int ECRS_unindexFile (struct GE_Context *ectx, struct GC_Configuration *cfg,
const char *filename, ECRS_UploadProgressCallback upcb, void *upcbClosure,
ECRS_TestTerminate tt, void *ttClosure); /* unindex.c */
/**
@@ -606,16 +557,7 @@
*
* @return URI on success, NULL on error (namespace already exists)
*/
-struct ECRS_URI *
-ECRS_createNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name,
- const struct ECRS_MetaData * meta,
- unsigned int anonymityLevel,
- unsigned int priority,
- cron_t expiration,
- const struct ECRS_URI * advertisementURI,
- const HashCode512 * rootEntry); /* namespace.c */
+struct ECRS_URI *ECRS_createNamespace (struct GE_Context *ectx, struct
GC_Configuration *cfg, const char *name, const struct ECRS_MetaData *meta,
unsigned int anonymityLevel, unsigned int priority, cron_t expiration, const
struct ECRS_URI *advertisementURI, const HashCode512 * rootEntry); /*
namespace.c */
/**
* Check if the given namespace exists (locally).
@@ -623,10 +565,9 @@
* hc of the public key
* @return OK if the namespace exists, SYSERR if not
*/
-int ECRS_testNamespaceExists(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name,
- const HashCode512 * hc);
+int ECRS_testNamespaceExists (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *name, const HashCode512 * hc);
/**
* Delete a local namespace. Only prevents future insertions
@@ -635,18 +576,15 @@
*
* @return OK on success, SYSERR on error
*/
-int ECRS_deleteNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * namespaceName); /* namespace.c */
+int ECRS_deleteNamespace (struct GE_Context *ectx, struct GC_Configuration
*cfg, const char *namespaceName); /* namespace.c */
/**
* Callback with information about local (!) namespaces.
* Contains the name of the local namespace and the global
* ID.
*/
-typedef int (*ECRS_NamespaceInfoCallback)(const HashCode512 * id,
- const char * name,
- void * closure);
+typedef int (*ECRS_NamespaceInfoCallback) (const HashCode512 * id,
+ const char *name, void *closure);
/**
* Build a list of all available local (!) namespaces
@@ -656,10 +594,7 @@
* @param list where to store the names (is allocated, caller frees)
* @return SYSERR on error, otherwise the number of pseudonyms in list
*/
-int ECRS_listNamespaces(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- ECRS_NamespaceInfoCallback cb,
- void * cls); /* namespace.c */
+int ECRS_listNamespaces (struct GE_Context *ectx, struct GC_Configuration
*cfg, ECRS_NamespaceInfoCallback cb, void *cls); /* namespace.c */
/**
* Add an entry into a namespace.
@@ -671,19 +606,7 @@
* entry?
* @return URI on success, NULL on error
*/
-struct ECRS_URI *
-ECRS_addToNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name,
- unsigned int anonymityLevel,
- unsigned int priority,
- cron_t expirationTime,
- TIME_T creationTime,
- TIME_T updateInterval,
- const HashCode512 * thisId,
- const HashCode512 * nextId,
- const struct ECRS_URI * dst,
- const struct ECRS_MetaData * md); /* namespace.c */
+struct ECRS_URI *ECRS_addToNamespace (struct GE_Context *ectx, struct
GC_Configuration *cfg, const char *name, unsigned int anonymityLevel, unsigned
int priority, cron_t expirationTime, TIME_T creationTime, TIME_T
updateInterval, const HashCode512 * thisId, const HashCode512 * nextId, const
struct ECRS_URI *dst, const struct ECRS_MetaData *md); /* namespace.c */
/**
* Add an entry into the K-space (keyword space).
@@ -694,14 +617,7 @@
* @param md what meta-data should be associated with the
* entry?
*/
-int ECRS_addToKeyspace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri,
- unsigned int anonymityLevel,
- unsigned int priority,
- cron_t expirationTime,
- const struct ECRS_URI * dst,
- const struct ECRS_MetaData * md); /* keyspace.c */
+int ECRS_addToKeyspace (struct GE_Context *ectx, struct GC_Configuration *cfg,
const struct ECRS_URI *uri, unsigned int anonymityLevel, unsigned int priority,
cron_t expirationTime, const struct ECRS_URI *dst, const struct ECRS_MetaData
*md); /* keyspace.c */
/**
* The search has found another result. Callback to notify
@@ -716,9 +632,7 @@
*/
typedef int (*ECRS_SearchProgressCallback)
(const ECRS_FileInfo * fi,
- const HashCode512 * key,
- int isRoot,
- void * closure);
+ const HashCode512 * key, int isRoot, void *closure);
/**
* Search for content.
@@ -727,15 +641,7 @@
* @param uri specifies the search parameters
* @param uri set to the URI of the uploaded file
*/
-int ECRS_search(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri,
- unsigned int anonymityLevel,
- cron_t timeout,
- ECRS_SearchProgressCallback spcb,
- void * spcbClosure,
- ECRS_TestTerminate tt,
- void * ttClosure); /* search.c */
+int ECRS_search (struct GE_Context *ectx, struct GC_Configuration *cfg, const
struct ECRS_URI *uri, unsigned int anonymityLevel, cron_t timeout,
ECRS_SearchProgressCallback spcb, void *spcbClosure, ECRS_TestTerminate tt,
void *ttClosure); /* search.c */
/**
* Notification of ECRS to a client about the progress of an insertion
@@ -756,9 +662,7 @@
unsigned long long completedBytes,
cron_t eta,
unsigned long long lastBlockOffset,
- const char * lastBlock,
- unsigned int lastBlockSize,
- void * closure);
+ const char *lastBlock, unsigned int lastBlockSize, void *closure);
/**
* Download a file.
@@ -766,15 +670,7 @@
* @param uri the URI of the file (determines what to download)
* @param filename where to store the file
*/
-int ECRS_downloadFile(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri,
- const char * filename,
- unsigned int anonymityLevel,
- ECRS_DownloadProgressCallback dpcb,
- void * dpcbClosure,
- ECRS_TestTerminate tt,
- void * ttClosure); /* download.c */
+int ECRS_downloadFile (struct GE_Context *ectx, struct GC_Configuration *cfg,
const struct ECRS_URI *uri, const char *filename, unsigned int anonymityLevel,
ECRS_DownloadProgressCallback dpcb, void *dpcbClosure, ECRS_TestTerminate tt,
void *ttClosure); /* download.c */
/**
* Download parts of a file. Note that this will store
@@ -795,18 +691,7 @@
* @param start starting offset
* @param length length of the download (starting at offset)
*/
-int ECRS_downloadPartialFile(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri,
- const char * filename,
- unsigned long long offset,
- unsigned long long length,
- unsigned int anonymityLevel,
- int no_temporaries,
- ECRS_DownloadProgressCallback dpcb,
- void * dpcbClosure,
- ECRS_TestTerminate tt,
- void * ttClosure); /* download.c */
+int ECRS_downloadPartialFile (struct GE_Context *ectx, struct GC_Configuration
*cfg, const struct ECRS_URI *uri, const char *filename, unsigned long long
offset, unsigned long long length, unsigned int anonymityLevel, int
no_temporaries, ECRS_DownloadProgressCallback dpcb, void *dpcbClosure,
ECRS_TestTerminate tt, void *ttClosure); /* download.c */
/**
* Iterate over all entries in a directory. Note that directories
@@ -822,12 +707,7 @@
* @return number of entries on success, SYSERR if the
* directory is malformed
*/
-int ECRS_listDirectory(struct GE_Context * ectx,
- const char * data,
- unsigned long long len,
- struct ECRS_MetaData ** md,
- ECRS_SearchProgressCallback spcb,
- void * spcbClosure); /* directory.c */
+int ECRS_listDirectory (struct GE_Context *ectx, const char *data, unsigned
long long len, struct ECRS_MetaData **md, ECRS_SearchProgressCallback spcb,
void *spcbClosure); /* directory.c */
/**
* Create a directory.
@@ -842,14 +722,9 @@
* is extended with the mime-type for a GNUnet directory.
* @return OK on success, SYSERR on error
*/
-int ECRS_createDirectory(struct GE_Context * ectx,
- char ** data,
- unsigned long long * len,
- unsigned int count,
- const ECRS_FileInfo * fis,
- struct ECRS_MetaData * meta); /* directory.c */
+int ECRS_createDirectory (struct GE_Context *ectx, char **data, unsigned long
long *len, unsigned int count, const ECRS_FileInfo * fis, struct ECRS_MetaData
*meta); /* directory.c */
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_fragmentation_service.h
===================================================================
--- GNUnet/src/include/gnunet_fragmentation_service.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/include/gnunet_fragmentation_service.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -29,8 +29,9 @@
#include "gnunet_util.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -38,7 +39,8 @@
/**
* @brief Definition of the fragmentation API.
*/
-typedef struct {
+typedef struct
+{
/**
* Fragment an over-sized message.
@@ -51,18 +53,17 @@
* @param bmc callback to construct the message
* @param bmcClosure argument to bmc
*/
- void (*fragment)(const PeerIdentity * peer,
- unsigned int mtu,
- unsigned int prio,
- unsigned int targetTime,
- unsigned int len,
- BuildMessageCallback bmc,
- void * bmcClosure);
+ void (*fragment) (const PeerIdentity * peer,
+ unsigned int mtu,
+ unsigned int prio,
+ unsigned int targetTime,
+ unsigned int len,
+ BuildMessageCallback bmc, void *bmcClosure);
} Fragmentation_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
@@ -71,4 +72,3 @@
/* end of gnunet_fragmentation_service.h */
#endif
-
Modified: GNUnet/src/include/gnunet_fs_lib.h
===================================================================
--- GNUnet/src/include/gnunet_fs_lib.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/include/gnunet_fs_lib.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -36,8 +36,9 @@
#include "gnunet_datastore_service.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -45,12 +46,11 @@
struct FS_SEARCH_CONTEXT;
-struct FS_SEARCH_CONTEXT *
-FS_SEARCH_makeContext(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct MUTEX * lock);
+struct FS_SEARCH_CONTEXT *FS_SEARCH_makeContext (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct MUTEX *lock);
-void FS_SEARCH_destroyContext(struct FS_SEARCH_CONTEXT * ctx);
+void FS_SEARCH_destroyContext (struct FS_SEARCH_CONTEXT *ctx);
struct FS_SEARCH_HANDLE;
@@ -66,29 +66,28 @@
* @param callback method to call for each result
* @param prio priority to use for the search
*/
-struct FS_SEARCH_HANDLE *
-FS_start_search(struct FS_SEARCH_CONTEXT * ctx,
- const PeerIdentity * target,
- unsigned int type,
- unsigned int keyCount,
- const HashCode512 * keys,
- unsigned int anonymityLevel,
- unsigned int prio,
- cron_t timeout,
- Datum_Iterator callback,
- void * closure);
+struct FS_SEARCH_HANDLE *FS_start_search (struct FS_SEARCH_CONTEXT *ctx,
+ const PeerIdentity * target,
+ unsigned int type,
+ unsigned int keyCount,
+ const HashCode512 * keys,
+ unsigned int anonymityLevel,
+ unsigned int prio,
+ cron_t timeout,
+ Datum_Iterator callback,
+ void *closure);
/**
* Stop searching.
*/
-void FS_stop_search(struct FS_SEARCH_CONTEXT * ctx,
- struct FS_SEARCH_HANDLE * handle);
+void FS_stop_search (struct FS_SEARCH_CONTEXT *ctx,
+ struct FS_SEARCH_HANDLE *handle);
/**
* What is the current average priority of entries
* in the routing table like? Returns -1 on error.
*/
-int FS_getAveragePriority(struct ClientServerConnection * sock);
+int FS_getAveragePriority (struct ClientServerConnection *sock);
/**
* Insert a block. Note that while the API is VERY similar to
@@ -99,16 +98,15 @@
* @return OK on success, SYSERR on error
* @see ecrs_core.h::fileBlockEncode
*/
-int FS_insert(struct ClientServerConnection * sock,
- const Datastore_Value * block);
+int FS_insert (struct ClientServerConnection *sock,
+ const Datastore_Value * block);
/**
* Initialize to index a file. Tries to do the symlinking.
*/
-int FS_initIndex(struct ClientServerConnection * sock,
- const HashCode512 * fileHc,
- const char * fn);
+int FS_initIndex (struct ClientServerConnection *sock,
+ const HashCode512 * fileHc, const char *fn);
/**
* Index a block. Note that while the API is VERY similar to
@@ -120,10 +118,9 @@
* @param offset the offset of the block into the file
* @return OK on success, SYSERR on error
*/
-int FS_index(struct ClientServerConnection * sock,
- const HashCode512 * fileHc,
- const Datastore_Value * block,
- unsigned long long offset);
+int FS_index (struct ClientServerConnection *sock,
+ const HashCode512 * fileHc,
+ const Datastore_Value * block, unsigned long long offset);
/**
* Delete a block. The arguments are the same as the ones for
@@ -133,8 +130,8 @@
* @return number of items deleted on success,
* SYSERR on error
*/
-int FS_delete(struct ClientServerConnection * sock,
- const Datastore_Value * block);
+int FS_delete (struct ClientServerConnection *sock,
+ const Datastore_Value * block);
/**
* Unindex a file.
@@ -142,9 +139,8 @@
* @param hc the hash of the entire file
* @return OK on success, SYSERR on error
*/
-int FS_unindex(struct ClientServerConnection * sock,
- unsigned int blocksize,
- const HashCode512 * hc);
+int FS_unindex (struct ClientServerConnection *sock,
+ unsigned int blocksize, const HashCode512 * hc);
/**
* Test if a file of the given hash is indexed.
@@ -152,10 +148,10 @@
* @param hc the hash of the entire file
* @return YES if so, NO if not, SYSERR on error
*/
-int FS_testIndexed(struct ClientServerConnection * sock,
- const HashCode512 * hc);
+int FS_testIndexed (struct ClientServerConnection *sock,
+ const HashCode512 * hc);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_fsui_lib.h
===================================================================
--- GNUnet/src/include/gnunet_fsui_lib.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_fsui_lib.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -87,8 +87,9 @@
#include "gnunet_ecrs_lib.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -123,7 +124,8 @@
* Searches "complete" if they time out or the maximum
* number of results has been found.
*/
-enum FSUI_EventType {
+enum FSUI_EventType
+{
FSUI_search_started,
FSUI_search_stopped,
FSUI_search_result,
@@ -204,7 +206,8 @@
* immediately because "threadPoolSize" will be 0 until FSUI
* resumes).
*/
-typedef enum {
+typedef enum
+{
FSUI_PENDING = 0,
FSUI_ACTIVE = 1,
FSUI_COMPLETED = 2,
@@ -223,82 +226,89 @@
* are not top-level, also gives the handle
* and client context for the parent download.
*/
-typedef struct {
+typedef struct
+{
/**
* What file in the download tree are we
* refering to?
*/
- struct FSUI_DownloadList * pos;
+ struct FSUI_DownloadList *pos;
- void * cctx;
+ void *cctx;
/**
* What is our parent download in the download tree?
* NULL if this is the top-level download.
*/
- struct FSUI_DownloadList * ppos;
+ struct FSUI_DownloadList *ppos;
- void * pcctx;
+ void *pcctx;
/**
* If this download is associated with a search,
* what is the search?
*/
- struct FSUI_SearchList * spos;
+ struct FSUI_SearchList *spos;
/**
* If this download is associated with a search,
* what is the client context for the search?
*/
- void * sctx;
+ void *sctx;
} FSUI_DownloadContext;
-typedef struct {
+typedef struct
+{
/**
* What file in the upload tree are we
* refering to?
*/
- struct FSUI_UploadList * pos;
+ struct FSUI_UploadList *pos;
- void * cctx;
+ void *cctx;
/**
* What is our parent upload in the upload tree?
* NULL if this is the top-level upload.
*/
- struct FSUI_UploadList * ppos;
+ struct FSUI_UploadList *ppos;
- void * pcctx;
+ void *pcctx;
} FSUI_UploadContext;
-typedef struct {
+typedef struct
+{
- struct FSUI_SearchList * pos;
+ struct FSUI_SearchList *pos;
- void * cctx;
+ void *cctx;
} FSUI_SearchContext;
-typedef struct {
+typedef struct
+{
- struct FSUI_UnindexList * pos;
+ struct FSUI_UnindexList *pos;
- void * cctx;
+ void *cctx;
} FSUI_UnindexContext;
/**
* @brief FSUI Event.
*/
-typedef struct {
+typedef struct
+{
enum FSUI_EventType type;
- union {
+ union
+ {
- struct {
+ struct
+ {
FSUI_SearchContext sc;
@@ -311,44 +321,49 @@
* The URI of the search for which data was
* found.
*/
- const struct ECRS_URI * searchURI;
+ const struct ECRS_URI *searchURI;
} SearchResult;
- struct {
+ struct
+ {
FSUI_SearchContext sc;
} SearchCompleted;
- struct {
+ struct
+ {
FSUI_SearchContext sc;
} SearchAborted;
- struct {
+ struct
+ {
FSUI_SearchContext sc;
- const char * message;
+ const char *message;
} SearchError;
- struct {
+ struct
+ {
FSUI_SearchContext sc;
} SearchSuspended;
- struct {
+ struct
+ {
FSUI_SearchContext sc;
- struct ECRS_URI * searchURI;
+ struct ECRS_URI *searchURI;
- const ECRS_FileInfo * fis;
+ const ECRS_FileInfo *fis;
unsigned int anonymityLevel;
@@ -358,17 +373,19 @@
} SearchResumed;
- struct {
+ struct
+ {
FSUI_SearchContext sc;
- const struct ECRS_URI * searchURI;
+ const struct ECRS_URI *searchURI;
unsigned int anonymityLevel;
} SearchStarted;
- struct {
+ struct
+ {
FSUI_SearchContext sc;
@@ -376,7 +393,8 @@
- struct {
+ struct
+ {
FSUI_DownloadContext dc;
@@ -404,17 +422,17 @@
/**
* Information about the download.
*/
- const char * filename;
+ const char *filename;
/**
* Original URI.
*/
- const struct ECRS_URI * uri;
+ const struct ECRS_URI *uri;
/**
* The last block (in plaintext)
*/
- const void * last_block;
+ const void *last_block;
/**
* Size of the last block
@@ -424,7 +442,8 @@
} DownloadProgress;
- struct {
+ struct
+ {
FSUI_DownloadContext dc;
@@ -437,50 +456,55 @@
/**
* Information about the download.
*/
- const char * filename;
+ const char *filename;
/**
* Original URI.
*/
- const struct ECRS_URI * uri;
+ const struct ECRS_URI *uri;
} DownloadCompleted;
- struct {
+ struct
+ {
FSUI_DownloadContext dc;
/**
* Error message.
*/
- const char * message;
+ const char *message;
} DownloadError;
- struct {
+ struct
+ {
FSUI_DownloadContext dc;
} DownloadAborted;
- struct {
+ struct
+ {
FSUI_DownloadContext dc;
} DownloadStopped;
- struct {
+ struct
+ {
FSUI_DownloadContext dc;
} DownloadSuspended;
- struct {
+ struct
+ {
FSUI_DownloadContext dc;
@@ -493,7 +517,7 @@
/**
* Information about the download.
*/
- const char * filename;
+ const char *filename;
/**
* Original URI.
@@ -504,7 +528,8 @@
} DownloadStarted;
- struct {
+ struct
+ {
FSUI_DownloadContext dc;
@@ -527,7 +552,7 @@
/**
* Information about the download.
*/
- const char * filename;
+ const char *filename;
ECRS_FileInfo fi;
@@ -538,7 +563,8 @@
} DownloadResumed;
- struct {
+ struct
+ {
FSUI_UploadContext uc;
@@ -560,12 +586,13 @@
/**
* Information about the upload.
*/
- const char * filename;
+ const char *filename;
} UploadProgress;
- struct {
+ struct
+ {
FSUI_UploadContext uc;
@@ -577,45 +604,50 @@
/**
* Which file was uploaded?
*/
- const char * filename;
+ const char *filename;
/**
* URI of the uploaded file.
*/
- struct ECRS_URI * uri;
+ struct ECRS_URI *uri;
} UploadCompleted;
- struct {
+ struct
+ {
FSUI_UploadContext uc;
} UploadAborted;
- struct {
+ struct
+ {
FSUI_UploadContext uc;
- const char * message;
+ const char *message;
} UploadError;
- struct {
+ struct
+ {
FSUI_UploadContext uc;
} UploadSuspended;
- struct {
+ struct
+ {
FSUI_UploadContext uc;
} UploadStopped;
- struct {
+ struct
+ {
FSUI_UploadContext uc;
@@ -629,11 +661,12 @@
/**
* Information about the upload.
*/
- const char * filename;
+ const char *filename;
} UploadStarted;
- struct {
+ struct
+ {
FSUI_UploadContext uc;
@@ -655,7 +688,7 @@
/**
* Information about the upload.
*/
- const char * filename;
+ const char *filename;
unsigned int anonymityLevel;
@@ -665,12 +698,13 @@
* Set to the URI of the upload if upload is
* complete. Otherwise NULL.
*/
- struct ECRS_URI * uri;
+ struct ECRS_URI *uri;
} UploadResumed;
- struct {
+ struct
+ {
FSUI_UnindexContext uc;
@@ -680,43 +714,48 @@
cron_t eta;
- const char * filename;
+ const char *filename;
} UnindexProgress;
- struct {
+ struct
+ {
FSUI_UnindexContext uc;
unsigned long long total;
- const char * filename;
+ const char *filename;
} UnindexCompleted;
- struct {
+ struct
+ {
FSUI_UnindexContext uc;
} UnindexAborted;
- struct {
+ struct
+ {
FSUI_UnindexContext uc;
} UnindexStopped;
- struct {
+ struct
+ {
FSUI_UnindexContext uc;
} UnindexSuspended;
- struct {
+ struct
+ {
FSUI_UnindexContext uc;
@@ -726,28 +765,30 @@
cron_t eta;
- const char * filename;
+ const char *filename;
FSUI_State state;
} UnindexResumed;
- struct {
+ struct
+ {
FSUI_UnindexContext uc;
unsigned long long total;
- const char * filename;
+ const char *filename;
} UnindexStarted;
- struct {
+ struct
+ {
FSUI_UnindexContext uc;
- const char * message;
+ const char *message;
} UnindexError;
@@ -771,8 +812,7 @@
*
* @return cctx for resume events, otherwise NULL
*/
-typedef void * (*FSUI_EventCallback)(void * cls,
- const FSUI_Event * event);
+typedef void *(*FSUI_EventCallback) (void *cls, const FSUI_Event * event);
/**
* @brief Start the FSUI manager. Use the given progress callback to
@@ -805,14 +845,7 @@
* @param closure extra argument to cb
* @return NULL on error
*/
-struct FSUI_Context *
-FSUI_start(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name,
- unsigned int threadPoolSize,
- int doResume,
- FSUI_EventCallback cb,
- void * closure); /* fsui.c */
+struct FSUI_Context *FSUI_start (struct GE_Context *ectx, struct
GC_Configuration *cfg, const char *name, unsigned int threadPoolSize, int
doResume, FSUI_EventCallback cb, void *closure); /* fsui.c */
/**
* Stop all processes under FSUI control (may serialize
@@ -820,7 +853,7 @@
* uninterruptable activities complete (you may want to
* signal the user that this may take a while).
*/
-void FSUI_stop(struct FSUI_Context * ctx); /* fsui.c */
+void FSUI_stop (struct FSUI_Context *ctx); /* fsui.c */
/**
@@ -828,43 +861,28 @@
*
* @return NULL on error
*/
-struct FSUI_SearchList *
-FSUI_startSearch(struct FSUI_Context * ctx,
- unsigned int anonymityLevel,
- unsigned int maxResults,
- cron_t timeout,
- const struct ECRS_URI * uri); /* search.c */
+struct FSUI_SearchList *FSUI_startSearch (struct FSUI_Context *ctx, unsigned
int anonymityLevel, unsigned int maxResults, cron_t timeout, const struct
ECRS_URI *uri); /* search.c */
/**
* Abort a search.
*
* @return SYSERR if such a search is not known
*/
-int FSUI_abortSearch(struct FSUI_Context * ctx,
- struct FSUI_SearchList * sl); /* search.c */
+int FSUI_abortSearch (struct FSUI_Context *ctx, struct FSUI_SearchList *sl);
/* search.c */
/**
* Stop a search.
*
* @return SYSERR if such a search is not known
*/
-int FSUI_stopSearch(struct FSUI_Context * ctx,
- struct FSUI_SearchList * sl); /* search.c */
+int FSUI_stopSearch (struct FSUI_Context *ctx, struct FSUI_SearchList *sl);
/* search.c */
/**
* Start to download a file or directory.
*
* @return NULL on error
*/
-struct FSUI_DownloadList *
-FSUI_startDownload(struct FSUI_Context * ctx,
- unsigned int anonymityLevel,
- int doRecursive,
- const struct ECRS_URI * uri,
- const struct ECRS_MetaData * meta,
- const char * filename,
- struct FSUI_SearchList * parentSearch,
- struct FSUI_DownloadList * parentDownload); /* download.c */
+struct FSUI_DownloadList *FSUI_startDownload (struct FSUI_Context *ctx,
unsigned int anonymityLevel, int doRecursive, const struct ECRS_URI *uri, const
struct ECRS_MetaData *meta, const char *filename, struct FSUI_SearchList
*parentSearch, struct FSUI_DownloadList *parentDownload); /* download.c */
/**
* Abort a download. If the dl is for a recursive
@@ -872,8 +890,7 @@
*
* @return SYSERR on error
*/
-int FSUI_abortDownload(struct FSUI_Context * ctx,
- struct FSUI_DownloadList * dl); /* download.c */
+int FSUI_abortDownload (struct FSUI_Context *ctx, struct FSUI_DownloadList
*dl); /* download.c */
/**
* Stop a download. If the dl is for a recursive
@@ -881,8 +898,7 @@
*
* @return SYSERR on error
*/
-int FSUI_stopDownload(struct FSUI_Context * ctx,
- struct FSUI_DownloadList * dl); /* download.c */
+int FSUI_stopDownload (struct FSUI_Context *ctx, struct FSUI_DownloadList
*dl); /* download.c */
/**
* Method that can be used to select files that
@@ -892,10 +908,10 @@
* select all files of the directory for the
* upload.
*/
-typedef int (*DirectoryScanCallback)(void * data,
- const char * filename,
- DirectoryEntryCallback dec,
- void * decClosure);
+typedef int (*DirectoryScanCallback) (void *data,
+ const char *filename,
+ DirectoryEntryCallback dec,
+ void *decClosure);
/**
* Start uploading a file or directory.
@@ -911,20 +927,20 @@
* @param keyURI keywords for top-level file
* @return NULL on error
*/
-struct FSUI_UploadList *
-FSUI_startUpload(struct FSUI_Context * ctx,
- const char * filename,
- DirectoryScanCallback dsc,
- void * dscClosure,
- unsigned int anonymityLevel,
- unsigned int priority,
- int doIndex,
- int doExtract,
- int individualKeywords,
- cron_t expiration,
- const struct ECRS_MetaData * topLevelMetaData,
- const struct ECRS_URI * globalURI,
- const struct ECRS_URI * keyUri);
+struct FSUI_UploadList *FSUI_startUpload (struct FSUI_Context *ctx,
+ const char *filename,
+ DirectoryScanCallback dsc,
+ void *dscClosure,
+ unsigned int anonymityLevel,
+ unsigned int priority,
+ int doIndex,
+ int doExtract,
+ int individualKeywords,
+ cron_t expiration,
+ const struct ECRS_MetaData
+ *topLevelMetaData,
+ const struct ECRS_URI *globalURI,
+ const struct ECRS_URI *keyUri);
/**
@@ -933,8 +949,7 @@
*
* @return SYSERR on error
*/
-int FSUI_abortUpload(struct FSUI_Context * ctx,
- struct FSUI_UploadList * ul);
+int FSUI_abortUpload (struct FSUI_Context *ctx, struct FSUI_UploadList *ul);
/**
* Stop an upload. Only to be called for the top-level
@@ -942,8 +957,7 @@
*
* @return SYSERR on error
*/
-int FSUI_stopUpload(struct FSUI_Context * ctx,
- struct FSUI_UploadList * ul);
+int FSUI_stopUpload (struct FSUI_Context *ctx, struct FSUI_UploadList *ul);
/**
@@ -952,9 +966,8 @@
*
* @return NULL on error
*/
-struct FSUI_UnindexList *
-FSUI_startUnindex(struct FSUI_Context * ctx,
- const char * filename);
+struct FSUI_UnindexList *FSUI_startUnindex (struct FSUI_Context *ctx,
+ const char *filename);
/**
@@ -962,8 +975,7 @@
*
* @return SYSERR on error
*/
-int FSUI_abortUnindex(struct FSUI_Context * ctx,
- struct FSUI_UnindexList * ul);
+int FSUI_abortUnindex (struct FSUI_Context *ctx, struct FSUI_UnindexList *ul);
/**
@@ -971,11 +983,10 @@
*
* @return SYSERR on error
*/
-int FSUI_stopUnindex(struct FSUI_Context * ctx,
- struct FSUI_UnindexList * ul);
+int FSUI_stopUnindex (struct FSUI_Context *ctx, struct FSUI_UnindexList *ul);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_gap_service.h
===================================================================
--- GNUnet/src/include/gnunet_gap_service.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_gap_service.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,8 +35,9 @@
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -53,23 +54,24 @@
* request.
* @param verify check that content is valid? (YES/NO)
*/
-typedef int (*UniqueReplyIdentifier)(const DataContainer * content,
- unsigned int query_type,
- int verify,
- const HashCode512 * primaryKey);
+typedef int (*UniqueReplyIdentifier) (const DataContainer * content,
+ unsigned int query_type,
+ int verify,
+ const HashCode512 * primaryKey);
/**
* Given some content, compute the unique
* hash of the content that can then be used
* to sort out duplicates.
*/
-typedef int (*ReplyHashFunction)(const DataContainer * data,
- HashCode512 * hc);
+typedef int (*ReplyHashFunction) (const DataContainer * data,
+ HashCode512 * hc);
/**
* Functions of the GAP Service API.
*/
-typedef struct {
+typedef struct
+{
/**
* Start GAP.
@@ -77,9 +79,8 @@
* @param datastore the storage callbacks to use for storing data
* @return SYSERR on error, OK on success
*/
- int (*init)(Blockstore * datastore,
- UniqueReplyIdentifier uri,
- ReplyHashFunction rhf);
+ int (*init) (Blockstore * datastore,
+ UniqueReplyIdentifier uri, ReplyHashFunction rhf);
/**
* Perform a GET operation using 'key' as the key. Note that no
@@ -95,22 +96,20 @@
* @return OK if we will start to query, SYSERR if all of our
* buffers are full or other error
*/
- int (*get_start)(const PeerIdentity * target,
- unsigned int type,
- unsigned int anonymityLevel,
- unsigned int keyCount,
- const HashCode512 * keys,
- cron_t timeout,
- unsigned int prio);
+ int (*get_start) (const PeerIdentity * target,
+ unsigned int type,
+ unsigned int anonymityLevel,
+ unsigned int keyCount,
+ const HashCode512 * keys,
+ cron_t timeout, unsigned int prio);
/**
* Stop sending out queries for a given key. GAP will automatically
* stop sending queries at some point, but this method can be used
* to stop it earlier.
*/
- int (*get_stop)(unsigned int type,
- unsigned int keyCount,
- const HashCode512 * keys);
+ int (*get_stop) (unsigned int type,
+ unsigned int keyCount, const HashCode512 * keys);
/**
* Try to migrate the given content.
@@ -121,21 +120,20 @@
* @return the number of bytes written to
* that buffer (must be a positive number).
*/
- unsigned int (*tryMigrate)(const DataContainer * data,
- const HashCode512 * primaryKey,
- char * position,
- unsigned int padding);
+ unsigned int (*tryMigrate) (const DataContainer * data,
+ const HashCode512 * primaryKey,
+ char *position, unsigned int padding);
/**
* What is the average priority of requests that we
* are currently routing?
*/
- unsigned int (*getAvgPriority)(void);
+ unsigned int (*getAvgPriority) (void);
} GAP_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_getoption_lib.h
===================================================================
--- GNUnet/src/include/gnunet_getoption_lib.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_getoption_lib.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,8 +30,9 @@
#include "gnunet_util_network_client.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -40,11 +41,10 @@
* Obtain option value from a peer.
* @return NULL on error
*/
-char * getConfigurationOptionValue(struct ClientServerConnection * sock,
- const char * section,
- const char * option);
+char *getConfigurationOptionValue (struct ClientServerConnection *sock,
+ const char *section, const char *option);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_identity_lib.h
===================================================================
--- GNUnet/src/include/gnunet_identity_lib.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_identity_lib.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -31,8 +31,9 @@
#include "gnunet_util_network_client.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -46,17 +47,16 @@
* @param sock socket to talk to gnunetd over
* @return OK on success, SYSERR on error
*/
-int gnunet_identity_peer_add(struct ClientServerConnection * sock,
- const P2P_hello_MESSAGE * hello);
+int gnunet_identity_peer_add (struct ClientServerConnection *sock,
+ const P2P_hello_MESSAGE * hello);
/**
* Function to request the peer to sign something
* with the private key of the peer.
*/
-int gnunet_identity_sign_function(struct ClientServerConnection * sock,
- unsigned short size,
- const void * data,
- Signature * result);
+int gnunet_identity_sign_function (struct ClientServerConnection *sock,
+ unsigned short size,
+ const void *data, Signature * result);
/**
* Function to request one of the peer's identities
@@ -64,8 +64,8 @@
*
* @return SYSERR on error, OK on success
*/
-int gnunet_identity_get_self(struct ClientServerConnection * sock,
- P2P_hello_MESSAGE ** hello);
+int gnunet_identity_get_self (struct ClientServerConnection *sock,
+ P2P_hello_MESSAGE ** hello);
/**
@@ -73,8 +73,8 @@
* @return SYSERR on error, YES if connection is now there
* NO if connection is not yet present
*/
-int gnunet_identity_request_connect(struct ClientServerConnection * sock,
- const PeerIdentity * peer);
+int gnunet_identity_request_connect (struct ClientServerConnection *sock,
+ const PeerIdentity * peer);
/**
@@ -93,13 +93,13 @@
* @param identity the id of the node
* @return OK to continue to iterate, SYSERR to abort
*/
-typedef int (*GNUnetIdentityPeerInfoCallback)(void * data,
- const PeerIdentity * identity,
- const void * address,
- unsigned int addr_len,
- cron_t last_message,
- unsigned int trust,
- unsigned int bpmFromPeer);
+typedef int (*GNUnetIdentityPeerInfoCallback) (void *data,
+ const PeerIdentity * identity,
+ const void *address,
+ unsigned int addr_len,
+ cron_t last_message,
+ unsigned int trust,
+ unsigned int bpmFromPeer);
/**
* Request information about all known peers
@@ -107,12 +107,12 @@
* @return SYSERR if iteration was aborted,
* otherwise number of peers known
*/
-int gnunet_identity_request_peer_infos(struct ClientServerConnection * sock,
- GNUnetIdentityPeerInfoCallback callback,
- void * cls);
+int gnunet_identity_request_peer_infos (struct ClientServerConnection *sock,
+ GNUnetIdentityPeerInfoCallback
+ callback, void *cls);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_identity_service.h
===================================================================
--- GNUnet/src/include/gnunet_identity_service.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/include/gnunet_identity_service.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -33,8 +33,9 @@
#include "gnunet_core.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -57,22 +58,22 @@
* @param data callback closure
* @return OK to continue iteration
*/
-typedef int (*HostIterator)(const PeerIdentity * identity,
- unsigned short protocol,
- int confirmed,
- void * data);
+typedef int (*HostIterator) (const PeerIdentity * identity,
+ unsigned short protocol,
+ int confirmed, void *data);
/**
* @brief Definition of the Identity API.
*/
-typedef struct {
+typedef struct
+{
/**
* Get the public key of this peer.
*
* @return reference to the public key. Do not free it!
*/
- const PublicKey * (*getPublicPrivateKey)(void);
+ const PublicKey *(*getPublicPrivateKey) (void);
/**
* Obtain identity from publicPrivateKey.
@@ -80,8 +81,7 @@
* @param pubKey the public key of the host
* @param result address where to write the identity of the node
*/
- void (*getPeerIdentity)(const PublicKey * pubKey,
- PeerIdentity * result);
+ void (*getPeerIdentity) (const PublicKey * pubKey, PeerIdentity * result);
/**
@@ -91,9 +91,7 @@
* @param result where to store the result
* @returns SYSERR on failure, OK on success
*/
- int (*signData)(const void * data,
- unsigned short size,
- Signature * result);
+ int (*signData) (const void *data, unsigned short size, Signature * result);
/**
* Decrypt a given block with the hostkey.
@@ -103,26 +101,25 @@
* the decrypted block is bigger, an error is returned
* @returns the size of the decrypted block, -1 on error
*/
- int (*decryptData)(const RSAEncryptedData * block,
- void * result,
- unsigned int max);
+ int (*decryptData) (const RSAEncryptedData * block,
+ void *result, unsigned int max);
/**
* Delete a host from the list
*/
- void (*delHostFromKnown)(const PeerIdentity * identity,
- unsigned short protocol);
+ void (*delHostFromKnown) (const PeerIdentity * identity,
+ unsigned short protocol);
/**
* Add a host to the temporary list.
*/
- void (*addHostTemporarily)(const P2P_hello_MESSAGE * tmp);
+ void (*addHostTemporarily) (const P2P_hello_MESSAGE * tmp);
/**
* Add a host to the persistent list.
* @param msg the verified (!) hello message
*/
- void (*addHost)(const P2P_hello_MESSAGE * msg);
+ void (*addHost) (const P2P_hello_MESSAGE * msg);
/**
* Call a method for each known host.
@@ -132,9 +129,7 @@
* @param data an argument to pass to the method
* @return the number of known hosts matching
*/
- int (*forEachHost)(cron_t now,
- HostIterator callback,
- void * data);
+ int (*forEachHost) (cron_t now, HostIterator callback, void *data);
/**
* Obtain the public key and address of a known host. If no specific
@@ -146,9 +141,9 @@
* ANY_PROTOCOL_NUMBER if we do not care which protocol
* @return NULL on failure, the hello on success
*/
- P2P_hello_MESSAGE * (*identity2Hello)(const PeerIdentity * hostId,
- unsigned short protocol,
- int tryTemporaryList);
+ P2P_hello_MESSAGE *(*identity2Hello) (const PeerIdentity * hostId,
+ unsigned short protocol,
+ int tryTemporaryList);
/**
*
@@ -159,10 +154,9 @@
* @param sig the signature
* @return OK on success, SYSERR on error (verification failed)
*/
- int (*verifyPeerSignature)(const PeerIdentity * signer,
- const void * message,
- int size,
- const Signature * sig);
+ int (*verifyPeerSignature) (const PeerIdentity * signer,
+ const void *message,
+ int size, const Signature * sig);
/**
* Blacklist a host. This method is called if a host
@@ -178,9 +172,8 @@
* for back-off and limiting is applied.
* @return OK on success SYSERR on error
*/
- int (*blacklistHost)(const PeerIdentity * identity,
- unsigned int desperation,
- int strict);
+ int (*blacklistHost) (const PeerIdentity * identity,
+ unsigned int desperation, int strict);
/**
* Is the node currently 'strictly' blacklisted, that is, the node
@@ -189,7 +182,7 @@
* @param identity node to check
* @return YES if true, else NO
*/
- int (*isBlacklistedStrict)(const PeerIdentity * identity);
+ int (*isBlacklistedStrict) (const PeerIdentity * identity);
/**
* Whitelist a host. This method is called if a host
@@ -198,7 +191,7 @@
*
* @return OK on success SYSERR on error
*/
- int (*whitelistHost)(const PeerIdentity * identity);
+ int (*whitelistHost) (const PeerIdentity * identity);
/**
* Change the host trust by a value.
@@ -207,17 +200,16 @@
* @param value is the int value by which the host credit is to be increased
* @returns the new credit
*/
- int (*changeHostTrust)(const PeerIdentity * hostId,
- int value);
+ int (*changeHostTrust) (const PeerIdentity * hostId, int value);
/**
* Obtain the trust record of the host.
*/
- unsigned int (*getHostTrust)(const PeerIdentity * hostId);
+ unsigned int (*getHostTrust) (const PeerIdentity * hostId);
} Identity_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_kvstore_service.h
===================================================================
--- GNUnet/src/include/gnunet_kvstore_service.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_kvstore_service.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -31,8 +31,9 @@
#include "gnunet_core.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -40,9 +41,10 @@
/**
* @brief Handle to a Key/Value-Table
*/
-typedef struct {
- char * table;
- char * db;
+typedef struct
+{
+ char *table;
+ char *db;
} KVHandle;
/**
@@ -52,22 +54,20 @@
* @param vallen the length von val
* @return OK on success
*/
-typedef int (*KVCallback)(void *closure,
- void *val,
- int vallen);
+typedef int (*KVCallback) (void *closure, void *val, int vallen);
/**
* @brief Definition of the KV-Store API.
*/
-typedef struct {
+typedef struct
+{
/**
* @brief Open a Key/Value-Table
* @param table the name of the Key/Value-Table
* @return a handle
*/
- KVHandle *(*getTable)(const char *database,
- const char *table);
+ KVHandle *(*getTable) (const char *database, const char *table);
/**
* @brief Get data from a Key/Value-Table
@@ -79,13 +79,11 @@
* @param handler callback function to be called for every result (may be
NULL)
* @param closure optional parameter for handler
*/
- void * (*get)(KVHandle *kv,
- void *key,
- int keylen,
- unsigned int sort,
- unsigned int limit,
- KVCallback handler,
- void *closure);
+ void *(*get) (KVHandle * kv,
+ void *key,
+ int keylen,
+ unsigned int sort,
+ unsigned int limit, KVCallback handler, void *closure);
/**
* @brief Store Key/Value-Pair in a table
@@ -97,12 +95,9 @@
* @param optional creation time
* @return OK on success, SYSERR otherwise
*/
- int (* put)(KVHandle *kv,
- void *key,
- int keylen,
- void *val,
- int vallen,
- unsigned long long age);
+ int (*put) (KVHandle * kv,
+ void *key,
+ int keylen, void *val, int vallen, unsigned long long age);
/**
* @brief Delete values from a Key/Value-Table
@@ -111,32 +106,29 @@
* @param age age of the items to delete (may be 0)
* @return OK on success, SYSERR otherwise
*/
- int (* del)(KVHandle *kv,
- void *key,
- int keylen,
- unsigned long long age);
+ int (*del) (KVHandle * kv, void *key, int keylen, unsigned long long age);
/**
* @brief Close a handle to a Key/Value-Table
* @param kv the handle to close
*/
- void (* closeTable)(KVHandle *kv);
+ void (*closeTable) (KVHandle * kv);
/**
* @brief Drop a Key/Value-Table
* @param the handle to the table
* @return OK on success, SYSERR otherwise
*/
- int (* dropTable)(KVHandle *kv);
+ int (*dropTable) (KVHandle * kv);
/**
* @brief Delete the database.
*/
- void (* dropDatabase)(const char *name);
+ void (*dropDatabase) (const char *name);
} KVstore_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_namespace_lib.h
===================================================================
--- GNUnet/src/include/gnunet_namespace_lib.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_namespace_lib.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,8 +30,9 @@
#include "gnunet_ecrs_lib.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -42,11 +43,11 @@
* @param rating the local rating of the namespace
* @return OK to continue iteration, SYSERR to abort
*/
-typedef int (*NS_NamespaceIterator)(void * cls,
- const char * namespaceName,
- const HashCode512 * namespaceId,
- const struct ECRS_MetaData * md,
- int rating);
+typedef int (*NS_NamespaceIterator) (void *cls,
+ const char *namespaceName,
+ const HashCode512 * namespaceId,
+ const struct ECRS_MetaData * md,
+ int rating);
/**
* Iterator over all updateable content.
@@ -59,12 +60,12 @@
* next update (0 for sporadic updates)
* @return OK to continue iteration, SYSERR to abort
*/
-typedef int (*NS_UpdateIterator)(void * cls,
- const ECRS_FileInfo * uri,
- const HashCode512 * lastId,
- const HashCode512 * nextId,
- TIME_T publicationFrequency,
- TIME_T nextPublicationTime);
+typedef int (*NS_UpdateIterator) (void *cls,
+ const ECRS_FileInfo * uri,
+ const HashCode512 * lastId,
+ const HashCode512 * nextId,
+ TIME_T publicationFrequency,
+ TIME_T nextPublicationTime);
/**
* Create a new namespace (and publish an advertismement).
@@ -74,16 +75,7 @@
* @param meta meta-data about the namespace (maybe NULL)
* @return URI on success, NULL on error (namespace already exists)
*/
-struct ECRS_URI *
-NS_createNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- unsigned int anonymityLevel,
- unsigned int insertPriority,
- cron_t insertExpiration,
- const char * namespaceName,
- const struct ECRS_MetaData * meta,
- const struct ECRS_URI * advertisementURI,
- const HashCode512 * rootEntry); /* namespace_info.c */
+struct ECRS_URI *NS_createNamespace (struct GE_Context *ectx, struct
GC_Configuration *cfg, unsigned int anonymityLevel, unsigned int
insertPriority, cron_t insertExpiration, const char *namespaceName, const
struct ECRS_MetaData *meta, const struct ECRS_URI *advertisementURI, const
HashCode512 * rootEntry); /* namespace_info.c */
/**
* Delete a local namespace. Only prevents future insertions into the
@@ -91,9 +83,7 @@
*
* @return OK on success, SYSERR on error
*/
-int NS_deleteNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * namespaceName); /* namespace.c */
+int NS_deleteNamespace (struct GE_Context *ectx, struct GC_Configuration *cfg,
const char *namespaceName); /* namespace.c */
/**
* Change the ranking of a (non-local) namespace.
@@ -104,10 +94,7 @@
* changed?
* @return new rating of the namespace
*/
-int NS_rankNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * ns,
- int delta); /* namespace_info.c */
+int NS_rankNamespace (struct GE_Context *ectx, struct GC_Configuration *cfg,
const char *ns, int delta); /* namespace_info.c */
/**
* Add a namespace to the set of known namespaces. For all namespace
@@ -116,46 +103,42 @@
*
* @param ns the namespace identifier
*/
-void NS_addNamespaceInfo(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri,
- const struct ECRS_MetaData * meta);
+void NS_addNamespaceInfo (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const struct ECRS_URI *uri,
+ const struct ECRS_MetaData *meta);
/**
* Get the root of the namespace (if we have one).
* @return SYSERR on error, OK on success
*/
-int NS_getNamespaceRoot(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * ns,
- HashCode512 * root);
+int NS_getNamespaceRoot (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *ns, HashCode512 * root);
-void NS_setNamespaceRoot(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri);
+void NS_setNamespaceRoot (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const struct ECRS_URI *uri);
/**
* List all available (local or non-local) namespaces.
*/
-int NS_listNamespaces(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- NS_NamespaceIterator iterator,
- void * closure); /* namespace_info.c */
+int NS_listNamespaces (struct GE_Context *ectx, struct GC_Configuration *cfg,
NS_NamespaceIterator iterator, void *closure); /* namespace_info.c */
/**
* Register callback to be invoked whenever we discover
* a new namespace.
*/
-int NS_registerDiscoveryCallback(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- NS_NamespaceIterator iterator,
- void * closure);
+int NS_registerDiscoveryCallback (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ NS_NamespaceIterator iterator,
+ void *closure);
/**
* Unregister namespace discovery callback.
*/
-int NS_unregisterDiscoveryCallback(NS_NamespaceIterator iterator,
- void * closure);
+int NS_unregisterDiscoveryCallback (NS_NamespaceIterator iterator,
+ void *closure);
@@ -198,19 +181,7 @@
* entry?
* @return the resulting URI, NULL on error
*/
-struct ECRS_URI *
-NS_addToNamespace(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- unsigned int anonymityLevel,
- unsigned int insertPriority,
- cron_t insertExpiration,
- const char * name,
- TIME_T updateInterval,
- const HashCode512 * lastId,
- const HashCode512 * thisId,
- const HashCode512 * nextId,
- const struct ECRS_URI * dst,
- const struct ECRS_MetaData * md); /* namespace_info.c */
+struct ECRS_URI *NS_addToNamespace (struct GE_Context *ectx, struct
GC_Configuration *cfg, unsigned int anonymityLevel, unsigned int
insertPriority, cron_t insertExpiration, const char *name, TIME_T
updateInterval, const HashCode512 * lastId, const HashCode512 * thisId, const
HashCode512 * nextId, const struct ECRS_URI *dst, const struct ECRS_MetaData
*md); /* namespace_info.c */
/**
* Compute the next ID for peridodically updated content.
@@ -218,27 +189,22 @@
* @param thisId MUST be known to NS
* @return OK on success, SYSERR on error
*/
-int NS_computeNextId(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name,
- const HashCode512 * lastId,
- const HashCode512 * thisId,
- TIME_T updateInterval,
- HashCode512 * nextId);
+int NS_computeNextId (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *name,
+ const HashCode512 * lastId,
+ const HashCode512 * thisId,
+ TIME_T updateInterval, HashCode512 * nextId);
/**
* List all updateable content in a given namespace.
*/
-int NS_listNamespaceContent(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * name,
- NS_UpdateIterator iterator,
- void * closure); /* namespace_info.c */
+int NS_listNamespaceContent (struct GE_Context *ectx, struct GC_Configuration
*cfg, const char *name, NS_UpdateIterator iterator, void *closure); /*
namespace_info.c */
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_peerinfo_lib.h
===================================================================
--- GNUnet/src/include/gnunet_peerinfo_lib.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_peerinfo_lib.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -31,8 +31,9 @@
#include "gnunet_util_network_client.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -46,10 +47,9 @@
*
* @return OK to continue, SYSERR to abort iteration
*/
-typedef int (*PEERINFO_PeerProcessor)(const char * name,
- const PeerIdentity * id,
- unsigned int trust,
- void * cls);
+typedef int (*PEERINFO_PeerProcessor) (const char *name,
+ const PeerIdentity * id,
+ unsigned int trust, void *cls);
/**
* Request information about peers.
@@ -59,13 +59,12 @@
* @param connected_only only list currently connected peers
* @return OK on success, SYSERR on error
*/
-int PEERINFO_getInfo(struct GE_Context * ectx,
- struct ClientServerConnection * sock,
- int connected_only,
- PEERINFO_PeerProcessor processor,
- void * cls);
+int PEERINFO_getInfo (struct GE_Context *ectx,
+ struct ClientServerConnection *sock,
+ int connected_only,
+ PEERINFO_PeerProcessor processor, void *cls);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_pingpong_service.h
===================================================================
--- GNUnet/src/include/gnunet_pingpong_service.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/include/gnunet_pingpong_service.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -24,8 +24,9 @@
#include "gnunet_core.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -39,7 +40,8 @@
/**
* @brief PingPong API.
*/
-typedef struct {
+typedef struct
+{
/**
* Ping a host an call a method if a reply comes back. Uses
@@ -52,11 +54,8 @@
* NULL and the ping does not come back, ping will FREE data!
* @returns OK on success, SYSERR on error
*/
- int (*ping)(const PeerIdentity * receiver,
- CronJob method,
- void * data,
- int usePlaintext,
- int challenge);
+ int (*ping) (const PeerIdentity * receiver,
+ CronJob method, void *data, int usePlaintext, int challenge);
/**
* Ping a host an call a method if a reply comes back.
@@ -70,18 +69,16 @@
* NULL and the ping does not come back, ping will FREE data!
* @returns NULL on error, otherwise the PING message
*/
- MESSAGE_HEADER * (*pingUser)(const PeerIdentity * receiver,
- CronJob method,
- void * data,
- int plaintext,
- int challenge);
+ MESSAGE_HEADER *(*pingUser) (const PeerIdentity * receiver,
+ CronJob method,
+ void *data, int plaintext, int challenge);
unsigned int ping_size;
} Pingpong_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_protocols.h
===================================================================
--- GNUnet/src/include/gnunet_protocols.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_protocols.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,8 +35,9 @@
#define GNUNET_PROTOCOLS_H
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -429,13 +430,13 @@
/* ************* p2p VPN messages ************* */
-#define P2P_PROTO_aip_IP 64 /* contains IPv6 frame */
+#define P2P_PROTO_aip_IP 64 /* contains IPv6 frame */
-#define P2P_PROTO_aip_ROUTE 65 /* a route to a node */
+#define P2P_PROTO_aip_ROUTE 65 /* a route to a node */
#define P2P_PROTO_aip_ROUTES 66 /* no more routes in my table */
-#define P2P_PROTO_aip_GETROUTE 67 /* request for a table entry from a peer */
+#define P2P_PROTO_aip_GETROUTE 67 /* request for a table entry from a
peer */
#define P2P_PROTO_MAX_USED 68
@@ -491,7 +492,7 @@
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_rpc_service.h
===================================================================
--- GNUnet/src/include/gnunet_rpc_service.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_rpc_service.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -32,8 +32,9 @@
#include "gnunet_blockstore.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -78,9 +79,8 @@
/**
* Prototype for synchronous RPC functions.
*/
-typedef void (*RPC_Function)(const PeerIdentity * caller,
- RPC_Param * arguments,
- RPC_Param * results);
+typedef void (*RPC_Function) (const PeerIdentity * caller,
+ RPC_Param * arguments, RPC_Param * results);
/**
* Opaque RPC internal per-RPC data.
@@ -91,67 +91,62 @@
* Signature of the callback function for the ASYNC_RPC to
* be called upon completion of the ASYNC function.
*/
-typedef void (*Async_RPC_Complete_Callback)(RPC_Param * results,
- int errorCode,
- struct CallInstance * context);
+typedef void (*Async_RPC_Complete_Callback) (RPC_Param * results,
+ int errorCode,
+ struct CallInstance * context);
/**
* Prototype for asynchronous RPC functions.
*/
-typedef void (*ASYNC_RPC_Function)(const PeerIdentity * caller,
- RPC_Param * arguments,
- Async_RPC_Complete_Callback callback,
- struct CallInstance * context);
+typedef void (*ASYNC_RPC_Function) (const PeerIdentity * caller,
+ RPC_Param * arguments,
+ Async_RPC_Complete_Callback callback,
+ struct CallInstance * context);
/**
* Function to call once an asynchronous RPC completes.
*/
-typedef void (*RPC_Complete)(const PeerIdentity * responder,
- RPC_Param * results,
- void * closure);
+typedef void (*RPC_Complete) (const PeerIdentity * responder,
+ RPC_Param * results, void *closure);
struct RPC_Record;
/**
* The RPC service API.
*/
-typedef struct {
+typedef struct
+{
/**
* Perform a synchronous RPC.
*/
- int (*RPC_execute)(const PeerIdentity * receiver,
- const char * name,
- RPC_Param * request_param,
- RPC_Param * return_param,
- unsigned int importance,
- cron_t timeout);
+ int (*RPC_execute) (const PeerIdentity * receiver,
+ const char *name,
+ RPC_Param * request_param,
+ RPC_Param * return_param,
+ unsigned int importance, cron_t timeout);
/**
* Register a synchronous RPC function.
*/
- int (*RPC_register)(const char * name,
- RPC_Function func);
+ int (*RPC_register) (const char *name, RPC_Function func);
/**
* Unregister a synchronous RPC function.
*/
- int (*RPC_unregister)(const char * name,
- RPC_Function func);
+ int (*RPC_unregister) (const char *name, RPC_Function func);
/**
* Register an asynchronous RPC function.
*/
- int (*RPC_register_async)(const char * name,
- ASYNC_RPC_Function func);
+ int (*RPC_register_async) (const char *name, ASYNC_RPC_Function func);
/**
* Unregister an asynchronous RPC function.
*/
- int (*RPC_unregister_async)(const char * name,
- ASYNC_RPC_Function func);
+ int (*RPC_unregister_async) (const char *name, ASYNC_RPC_Function func);
/**
* Start an asynchronous RPC.
@@ -163,13 +158,12 @@
* @return value required to stop the RPC (and the RPC must
* be explicitly stopped to free resources!)
*/
- struct RPC_Record * (*RPC_start)(const PeerIdentity * receiver,
- const char * name,
- RPC_Param * request_param,
- unsigned int importance,
- cron_t timeout,
- RPC_Complete callback,
- void * closure);
+ struct RPC_Record *(*RPC_start) (const PeerIdentity * receiver,
+ const char *name,
+ RPC_Param * request_param,
+ unsigned int importance,
+ cron_t timeout,
+ RPC_Complete callback, void *closure);
/**
* Stop an asynchronous RPC.
@@ -177,7 +171,7 @@
* @param record the return value from RPC_start
* @return RPC_ERROR_OK if the RPC was successful
*/
- int (*RPC_stop)(struct RPC_Record * record);
+ int (*RPC_stop) (struct RPC_Record * record);
} RPC_ServiceAPI;
@@ -187,42 +181,36 @@
/**
* RPC argument handling helper functions.
*/
-RPC_Param * RPC_paramNew(void);
+RPC_Param *RPC_paramNew (void);
-void RPC_paramFree(RPC_Param * param);
+void RPC_paramFree (RPC_Param * param);
-unsigned int RPC_paramCount(RPC_Param *param);
+unsigned int RPC_paramCount (RPC_Param * param);
-void RPC_paramAdd(RPC_Param * param,
- const char * name,
- unsigned int dataLength,
- const void * data);
+void RPC_paramAdd (RPC_Param * param,
+ const char *name,
+ unsigned int dataLength, const void *data);
-void RPC_paramAddDataContainer(RPC_Param * param,
- const char * name,
- const DataContainer * data);
+void RPC_paramAddDataContainer (RPC_Param * param,
+ const char *name, const DataContainer * data);
-const char * RPC_paramName(RPC_Param * param,
- unsigned int i);
+const char *RPC_paramName (RPC_Param * param, unsigned int i);
-unsigned int RPC_paramIndex(RPC_Param * param,
- const char * name);
+unsigned int RPC_paramIndex (RPC_Param * param, const char *name);
/**
* @return OK on success, SYSERR on error
*/
-int RPC_paramValueByName(RPC_Param * param,
- const char * name,
- unsigned int * dataLength,
- void ** data);
+int RPC_paramValueByName (RPC_Param * param,
+ const char *name,
+ unsigned int *dataLength, void **data);
/**
* @return OK on success, SYSERR on error
*/
-int RPC_paramValueByPosition(RPC_Param * param,
- unsigned int i,
- unsigned int * dataLength,
- void ** data);
+int RPC_paramValueByPosition (RPC_Param * param,
+ unsigned int i,
+ unsigned int *dataLength, void **data);
/**
* Return the value of the given parameter in the RPC parameter structure.
@@ -230,9 +218,8 @@
* @param param Target RPC parameter structure
* @param value set to the value of the parameter
*/
-DataContainer *
-RPC_paramDataContainerByPosition(RPC_Param *param,
- unsigned int i);
+DataContainer *RPC_paramDataContainerByPosition (RPC_Param * param,
+ unsigned int i);
/**
* Return the value of the named parameter in the RPC parameter
@@ -242,29 +229,27 @@
* @param value set to the value of the named parameter
* @return SYSERR on error
*/
-DataContainer * RPC_paramDataContainerByName(RPC_Param *param,
- const char *name);
+DataContainer *RPC_paramDataContainerByName (RPC_Param * param,
+ const char *name);
/**
* Serialize the param array. target must point to at least
* RPC_paramSize(param) bytes of memory.
*/
-void RPC_paramSerialize(RPC_Param * param,
- char * target);
+void RPC_paramSerialize (RPC_Param * param, char *target);
/**
* Deserialize parameters from buffer.
*/
-RPC_Param * RPC_paramDeserialize(char * buffer,
- size_t size);
+RPC_Param *RPC_paramDeserialize (char *buffer, size_t size);
/**
* How many bytes are required to serialize the param array?
*/
-size_t RPC_paramSize(RPC_Param * param);
+size_t RPC_paramSize (RPC_Param * param);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_session_service.h
===================================================================
--- GNUnet/src/include/gnunet_session_service.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_session_service.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,8 +30,9 @@
#include "gnunet_util.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -42,7 +43,8 @@
* Session is responsible for establishing a session with another
* peer (SKEY exchange).
*/
-typedef struct {
+typedef struct
+{
/**
* Try to connect to the given peer.
@@ -51,11 +53,11 @@
* YES if a connection is established upon return,
* NO if we're going to try to establish one asynchronously
*/
- int (*tryConnect)(const PeerIdentity * peer);
+ int (*tryConnect) (const PeerIdentity * peer);
} Session_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
@@ -64,4 +66,3 @@
#endif
/* end of gnunet_session_service.h */
-
Modified: GNUnet/src/include/gnunet_setup_lib.h
===================================================================
--- GNUnet/src/include/gnunet_setup_lib.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_setup_lib.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -48,43 +48,44 @@
/**
* Types of nodes and values in the configuration tree.
*/
-typedef enum {
- GNS_Root = 0,
- GNS_Node = 1,
- GNS_Leaf = 2,
+typedef enum
+{
+ GNS_Root = 0,
+ GNS_Node = 1,
+ GNS_Leaf = 2,
GNS_KindMask = 3,
/**
* Binary type (yes/no).
*/
- GNS_Boolean = 4,
+ GNS_Boolean = 4,
/**
* Unsigned integer type.
*/
- GNS_UInt64 = 8,
+ GNS_UInt64 = 8,
/**
* Double value type.
*/
- GNS_Double = 16,
+ GNS_Double = 16,
/**
* Free-form string (possibly with suggestions)
*/
- GNS_String = 32,
+ GNS_String = 32,
/**
* Multiple choice (results in space-seperated
* strings, one for each choice).
*/
- GNS_MC = 64,
+ GNS_MC = 64,
/**
* Single choice (results in individual string
* representing the choice).
*/
- GNS_SC = 128,
+ GNS_SC = 128,
GNS_TypeMask = 252,
} GNS_Type;
@@ -95,22 +96,26 @@
* A configuration value does not only specify a value
* but also the legal range of values.
*/
-typedef union {
+typedef union
+{
- struct {
+ struct
+ {
int val;
int def;
} Boolean;
- struct {
+ struct
+ {
unsigned long long val;
unsigned long long min;
unsigned long long max;
unsigned long long def;
} UInt64;
- struct {
+ struct
+ {
double val;
double def;
} Double;
@@ -118,19 +123,20 @@
/**
* Data for GNS_String, GNS_MC and GNS_SC.
*/
- struct {
+ struct
+ {
/**
* 0-terminated string, never NULL
*/
- char * val;
+ char *val;
- char * def;
+ char *def;
/**
* Set of legal or suggested values for
* "val", NULL termianted.
*/
- char ** legalRange;
+ char **legalRange;
} String;
@@ -146,33 +152,34 @@
* may change are the concrete values and the visibility
* attribute, but not the overall tree structure.
*/
-typedef struct GNS_Tree {
+typedef struct GNS_Tree
+{
/**
* Section for this node (maybe NULL)
*/
- char * section;
+ char *section;
/**
* Option name for this node (maybe NULL)
*/
- char * option;
+ char *option;
/**
* Description for this node (never NULL)
*/
- char * description;
+ char *description;
/**
* Helptext for this node (never NULL)
*/
- char * help;
+ char *help;
/**
* NULL-terminated list of subnodes (must be empty for
* nodes of type "leaf")
*/
- struct GNS_Tree ** children;
+ struct GNS_Tree **children;
/**
* Is this node visible to the user at this point?
@@ -206,10 +213,9 @@
* @param specification name of the guile file containing the spec
* @return NULL on error (i.e. specification file not found)
*/
-struct GNS_Context *
-GNS_load_specification(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * specification);
+struct GNS_Context *GNS_load_specification (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *specification);
/**
* Obtain the GNS_Tree from the GNS system. The tree is only valid
@@ -219,14 +225,12 @@
*
* @return NULL on error
*/
-struct GNS_Tree *
-GNS_get_tree(struct GNS_Context * ctx);
+struct GNS_Tree *GNS_get_tree (struct GNS_Context *ctx);
/**
* Free resources associated with the GNS context.
*/
-void
-GNS_free_specification(struct GNS_Context * ctx);
+void GNS_free_specification (struct GNS_Context *ctx);
/**
* Callback that GNS will call whenever the GNS_Tree
@@ -234,8 +238,8 @@
*
* @param node the node that has changed
*/
-typedef void (*GNS_TreeChangeListener)(const struct GNS_Tree * node,
- void * cls);
+typedef void (*GNS_TreeChangeListener) (const struct GNS_Tree * node,
+ void *cls);
/**
* Register a tree change listener with GNS.
@@ -243,18 +247,18 @@
* @param listener callback to call whenever the tree changes
*/
void
-GNS_register_tree_change_listener(struct GNS_Context * ctx,
- GNS_TreeChangeListener listener,
- void * cls);
+GNS_register_tree_change_listener (struct GNS_Context *ctx,
+ GNS_TreeChangeListener listener,
+ void *cls);
/**
* Release a tree change listener from GNS (do not call the listener
* in the future for change events).
*/
void
-GNS_unregister_tree_change_listener(struct GNS_Context * ctx,
- GNS_TreeChangeListener listener,
- void * cls);
+GNS_unregister_tree_change_listener (struct GNS_Context *ctx,
+ GNS_TreeChangeListener listener,
+ void *cls);
/**
* Convert the default value of the given tree entry to
@@ -262,8 +266,7 @@
*
* @return NULL on error
*/
-char *
-GNS_get_default_value_as_string(GNS_Type type,
- const GNS_Value * value);
+char *GNS_get_default_value_as_string (GNS_Type type,
+ const GNS_Value * value);
#endif
Modified: GNUnet/src/include/gnunet_sqstore_service.h
===================================================================
--- GNUnet/src/include/gnunet_sqstore_service.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_sqstore_service.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -38,8 +38,9 @@
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -47,7 +48,8 @@
/**
* @brief Definition of the SQ-Store API.
*/
-typedef struct {
+typedef struct
+{
/**
* Get the current on-disk size of the SQ store.
@@ -55,15 +57,14 @@
* available.
* @return number of bytes used on disk
*/
- unsigned long long (*getSize)(void);
+ unsigned long long (*getSize) (void);
/**
* Store an item in the datastore.
*
* @return OK on success, SYSERR on error, NO on temporary error
*/
- int (*put)(const HashCode512 * key,
- const Datastore_Value * value);
+ int (*put) (const HashCode512 * key, const Datastore_Value * value);
/**
* Iterate over the results for a particular key
@@ -76,10 +77,8 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
- int (*get)(const HashCode512 * key,
- unsigned int type,
- Datum_Iterator iter,
- void * closure);
+ int (*get) (const HashCode512 * key,
+ unsigned int type, Datum_Iterator iter, void *closure);
/**
* Update the priority for a particular key in the datastore. If
@@ -106,10 +105,8 @@
* @return OK if a match was found and the update
* was successful, SYSERR on error
*/
- int (*update)(const HashCode512 * key,
- const Datastore_Value * value,
- int delta,
- cron_t expire);
+ int (*update) (const HashCode512 * key,
+ const Datastore_Value * value, int delta, cron_t expire);
/**
* Iterate over the items in the datastore in ascending
@@ -121,9 +118,8 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
- int (*iterateLowPriority)(unsigned int type,
- Datum_Iterator iter,
- void * closure);
+ int (*iterateLowPriority) (unsigned int type,
+ Datum_Iterator iter, void *closure);
/**
* Iterate over content with anonymity zero.
@@ -136,10 +132,9 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
- int (*iterateNonAnonymous)(unsigned int type,
- int on_demand,
- Datum_Iterator iter,
- void * closure);
+ int (*iterateNonAnonymous) (unsigned int type,
+ int on_demand,
+ Datum_Iterator iter, void *closure);
/**
* Iterate over the items in the datastore in ascending
@@ -151,9 +146,8 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
- int (*iterateExpirationTime)(unsigned int type,
- Datum_Iterator iter,
- void * closure);
+ int (*iterateExpirationTime) (unsigned int type,
+ Datum_Iterator iter, void *closure);
/**
@@ -164,8 +158,7 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
- int (*iterateMigrationOrder)(Datum_Iterator iter,
- void * closure);
+ int (*iterateMigrationOrder) (Datum_Iterator iter, void *closure);
/**
* Iterate over all the items in the datastore
@@ -177,8 +170,7 @@
* @return the number of results, SYSERR if the
* iter is non-NULL and aborted the iteration
*/
- int (*iterateAllNow)(Datum_Iterator iter,
- void * closure);
+ int (*iterateAllNow) (Datum_Iterator iter, void *closure);
/**
* Delete an item from the datastore.
@@ -204,18 +196,17 @@
* also be rare).
* 0 if no matching items were found, SYSERR on errors
*/
- int (*del)(const HashCode512 * key,
- const Datastore_Value * value);
+ int (*del) (const HashCode512 * key, const Datastore_Value * value);
/**
* Delete the database. The next operation is
* guaranteed to be unloading of the module.
*/
- void (*drop)(void);
+ void (*drop) (void);
} SQstore_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_state_service.h
===================================================================
--- GNUnet/src/include/gnunet_state_service.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_state_service.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -29,8 +29,9 @@
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -38,7 +39,8 @@
/**
* @brief API to the stats service
*/
-typedef struct {
+typedef struct
+{
/**
* Read the contents of a bucket to a buffer.
@@ -48,9 +50,7 @@
* (*result should be NULL, sufficient space is allocated)
* @return the number of bytes read on success, -1 on failure
*/
- int (*read)(struct GE_Context * ectx,
- const char * name,
- void ** result);
+ int (*read) (struct GE_Context * ectx, const char *name, void **result);
/**
* Append content to file.
@@ -60,10 +60,8 @@
* @param block the data to store
* @return SYSERR on error, OK if ok.
*/
- int (*append)(struct GE_Context * ectx,
- const char * name,
- int len,
- const void * block);
+ int (*append) (struct GE_Context * ectx,
+ const char *name, int len, const void *block);
/**
* Write content to a file.
@@ -73,22 +71,19 @@
* @param block the data to store
* @return SYSERR on error, OK if ok.
*/
- int (*write)(struct GE_Context * ectx,
- const char * name,
- int len,
- const void * block);
+ int (*write) (struct GE_Context * ectx,
+ const char *name, int len, const void *block);
/**
* Free space in the database by removing one file
* @param name the hashcode representing the name of the file
* (without directory)
*/
- int (*unlink)(struct GE_Context * ectx,
- const char * name);
+ int (*unlink) (struct GE_Context * ectx, const char *name);
} State_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_stats_lib.h
===================================================================
--- GNUnet/src/include/gnunet_stats_lib.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_stats_lib.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -31,8 +31,9 @@
#include "gnunet_util_network_client.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -42,21 +43,20 @@
/**
* Return a descriptive name for a p2p message type
*/
-const char * STATS_p2pMessageName(unsigned short type);
+const char *STATS_p2pMessageName (unsigned short type);
/**
* Return a descriptive name for a client server message type
*/
-const char * STATS_csMessageName(unsigned short type);
+const char *STATS_csMessageName (unsigned short type);
/**
* @param name the name of the datum
* @param value the value
* @return OK to continue, SYSERR to abort iteration
*/
-typedef int (*STATS_StatProcessor)(const char * name,
- unsigned long long value,
- void * cls);
+typedef int (*STATS_StatProcessor) (const char *name,
+ unsigned long long value, void *cls);
/**
* Request statistics from TCP socket.
@@ -64,19 +64,17 @@
* @param processor function to call on each value
* @return OK on success, SYSERR on error
*/
-int STATS_getStatistics(struct GE_Context * ectx,
- struct ClientServerConnection * sock,
- STATS_StatProcessor processor,
- void * cls);
+int STATS_getStatistics (struct GE_Context *ectx,
+ struct ClientServerConnection *sock,
+ STATS_StatProcessor processor, void *cls);
/**
* @param type the type ID of the message
* @param isP2P YES for P2P, NO for CS types
* @return OK to continue, SYSERR to abort iteration
*/
-typedef int (*STATS_ProtocolProcessor)(unsigned short type,
- int isP2P,
- void * cls);
+typedef int (*STATS_ProtocolProcessor) (unsigned short type,
+ int isP2P, void *cls);
/**
* Request available protocols from TCP socket.
@@ -84,12 +82,12 @@
* @param processor function to call on each value
* @return OK on success, SYSERR on error
*/
-int STATS_getAvailableProtocols(struct GE_Context * ectx,
- struct ClientServerConnection * sock,
- STATS_ProtocolProcessor processor,
- void * cls);
+int STATS_getAvailableProtocols (struct GE_Context *ectx,
+ struct ClientServerConnection *sock,
+ STATS_ProtocolProcessor processor,
+ void *cls);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_stats_service.h
===================================================================
--- GNUnet/src/include/gnunet_stats_service.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_stats_service.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -29,8 +29,9 @@
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -38,7 +39,8 @@
/**
* @brief API to the stats service
*/
-typedef struct {
+typedef struct
+{
/**
* Get a handle to a statistical entity.
@@ -46,7 +48,7 @@
* @param name a description of the entity
* @return a handle for updating the associated value
*/
- int (*create)(const char * name);
+ int (*create) (const char *name);
/**
* Manipulate statistics. Sets the core-statistics associated with
@@ -55,15 +57,14 @@
* @param handle the handle for the value to change
* @param value to what the value should be set
*/
- void (*set)(const int handle,
- const unsigned long long value);
+ void (*set) (const int handle, const unsigned long long value);
/**
* Get statistics associated with the handle.
* @param handle the handle for the value to get
* @return value associated with the handle
*/
- unsigned long long (*get)(const int handle);
+ unsigned long long (*get) (const int handle);
/**
* Manipulate statistics. Changes the statistics associated
@@ -72,12 +73,11 @@
* @param handle the handle for the value to change
* @param delta by how much should the value be changed
*/
- void (*change)(const int handle,
- const int delta);
+ void (*change) (const int handle, const int delta);
} Stats_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_testing_lib.h
===================================================================
--- GNUnet/src/include/gnunet_testing_lib.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_testing_lib.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,8 +35,9 @@
#include "gnunet_util.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -53,14 +54,13 @@
* @param peer identity of the peer (set)
* @return OK on success, SYSERR on error
*/
-int gnunet_testing_start_daemon(unsigned short app_port,
- unsigned short tra_offset,
- const char * gnunetd_home,
- const char * transports,
- const char * applications,
- pid_t * pid,
- PeerIdentity * peer,
- char ** configFile);
+int gnunet_testing_start_daemon (unsigned short app_port,
+ unsigned short tra_offset,
+ const char *gnunetd_home,
+ const char *transports,
+ const char *applications,
+ pid_t * pid,
+ PeerIdentity * peer, char **configFile);
/**
* Establish a connection between two GNUnet daemons
@@ -70,8 +70,8 @@
* @param port2 client port of the second daemon
* @return OK on success, SYSERR on failure
*/
-int gnunet_testing_connect_daemons(unsigned short port1,
- unsigned short port2);
+int gnunet_testing_connect_daemons (unsigned short port1,
+ unsigned short port2);
/**
@@ -80,19 +80,19 @@
*
* @return OK on success, SYSERR on failure
*/
-int gnunet_testing_stop_daemon(unsigned short port,
- pid_t pid);
+int gnunet_testing_stop_daemon (unsigned short port, pid_t pid);
/**
* Linked list of information about daemon processes.
*/
-struct DaemonContext {
- struct DaemonContext * next;
+struct DaemonContext
+{
+ struct DaemonContext *next;
PeerIdentity peer;
pid_t pid;
unsigned short port;
- char * configFile;
+ char *configFile;
};
@@ -104,22 +104,23 @@
*
* @return handle used to stop the daemons, NULL on error
*/
-struct DaemonContext *
-gnunet_testing_start_daemons(const char * transports,
- const char * applications,
- const char * gnunetd_home_prefix,
- unsigned short app_baseport,
- unsigned short delta,
- unsigned int count);
+struct DaemonContext *gnunet_testing_start_daemons (const char *transports,
+ const char *applications,
+ const char
+ *gnunetd_home_prefix,
+ unsigned short
+ app_baseport,
+ unsigned short delta,
+ unsigned int count);
/**
* Stop all of the daemons started with the start function.
* @return OK on success, SYSERR on error
*/
-int gnunet_testing_stop_daemons(struct DaemonContext * peers);
-
+int gnunet_testing_stop_daemons (struct DaemonContext *peers);
-#if 0 /* keep Emacsens' auto-indent happy */
+
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_topology_service.h
===================================================================
--- GNUnet/src/include/gnunet_topology_service.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/include/gnunet_topology_service.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -30,8 +30,9 @@
#include "gnunet_util.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -57,31 +58,32 @@
* Topology relies on advertising to learn about other peers, and
* on session for establishing sessions.
*/
-typedef struct {
+typedef struct
+{
/**
* Get an estimate of the network size.
* @return the estimated number of nodes, SYSERR on error
*/
- int (*estimateNetworkSize)(void);
+ int (*estimateNetworkSize) (void);
/**
* How big is our current desire to connect to other peers?
* @return 1 for ideal, 0 for maximum desire, > 1 for too many
* connections (percent of desired number of connections)
*/
- double (*getSaturation)(void);
+ double (*getSaturation) (void);
/**
* Will the topology allow a connection from the specified peer?
* @return OK if a connection maybe established, SYSERR if not.
*/
- int (*allowConnectionFrom)(const PeerIdentity * peer);
+ int (*allowConnectionFrom) (const PeerIdentity * peer);
} Topology_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
@@ -90,4 +92,3 @@
#endif
/* end of gnunet_topology_service.h */
-
Modified: GNUnet/src/include/gnunet_traffic_lib.h
===================================================================
--- GNUnet/src/include/gnunet_traffic_lib.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_traffic_lib.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -32,8 +32,9 @@
#include "gnunet_traffic_service.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -53,16 +54,15 @@
* highest bit is current time-unit, bit 1 is 32 time-units ago (set)
* @return OK on success, SYSERR on error
*/
-int gnunet_traffic_poll(struct ClientServerConnection * sock,
- unsigned int timeframe,
- unsigned short type,
- unsigned short direction,
- unsigned int * count,
- unsigned int * avg_size,
- unsigned int * peers,
- unsigned int * time);
+int gnunet_traffic_poll (struct ClientServerConnection *sock,
+ unsigned int timeframe,
+ unsigned short type,
+ unsigned short direction,
+ unsigned int *count,
+ unsigned int *avg_size,
+ unsigned int *peers, unsigned int *time);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_traffic_service.h
===================================================================
--- GNUnet/src/include/gnunet_traffic_service.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_traffic_service.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,8 +30,9 @@
#include "gnunet_core.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -68,7 +69,8 @@
* type has recently been transmitted or received by this
* peer.
*/
-typedef struct {
+typedef struct
+{
/**
* Get statistics over the number of messages that
@@ -85,17 +87,16 @@
* highest bit is current time-unit, bit 1 is 32 time-units ago (set)
* @return OK on success, SYSERR on error
*/
- int (*get)(unsigned int timeframe,
- unsigned short type,
- unsigned short direction,
- unsigned int * msgCount,
- unsigned int * peerCount,
- unsigned int * avg_size,
- unsigned int * time);
+ int (*get) (unsigned int timeframe,
+ unsigned short type,
+ unsigned short direction,
+ unsigned int *msgCount,
+ unsigned int *peerCount,
+ unsigned int *avg_size, unsigned int *time);
} Traffic_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_transport.h
===================================================================
--- GNUnet/src/include/gnunet_transport.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_transport.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,8 +30,9 @@
#include "gnunet_core.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -52,14 +53,15 @@
/**
* Type of a struct passed to receive.
*/
-typedef struct {
+typedef struct
+{
/**
* The session associated with the message
* on the transport layer side. Maybe passed to "associate"
* in order to send replies on a bi-directional pipe (if
* possible).
*/
- TSession * tsession;
+ TSession *tsession;
/**
* The identity of the sender node
@@ -70,7 +72,7 @@
* The message itself. The GNUnet core will call 'FREE' once
* processing of msg is complete.
*/
- char * msg;
+ char *msg;
/**
* The size of the message
@@ -85,7 +87,7 @@
*
* @param mp the message, freed by the callee once processed!
*/
-typedef void (*P2P_PACKETProcessor)(P2P_PACKET * mp);
+typedef void (*P2P_PACKETProcessor) (P2P_PACKET * mp);
/**
* This header file contains a draft for the gnunetd
@@ -95,7 +97,8 @@
* A pointer to an instance of this struct is passed
* to the init method of each Transport API.
*/
-typedef struct {
+typedef struct
+{
/**
* The version of the CORE API. For now, always "1".
@@ -105,27 +108,27 @@
/**
* The identity of the local node.
*/
- PeerIdentity * myIdentity;
+ PeerIdentity *myIdentity;
/**
* System error context
*/
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
/**
* System configuration
*/
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
/**
* System load monitor
*/
- struct LoadMonitor * load_monitor;
+ struct LoadMonitor *load_monitor;
/**
* System cron Manager.
*/
- struct CronManager * cron;
+ struct CronManager *cron;
/**
* Data was received (potentially encrypted), make the core process
@@ -141,7 +144,7 @@
* loaded or unloaded inside the module initialization or shutdown
* code.
*/
- void * (*requestService)(const char * name);
+ void *(*requestService) (const char *name);
/**
* Notification that the given service is no longer required. This
@@ -153,7 +156,7 @@
*
* @return OK if service was successfully released, SYSERR on error
*/
- int (*releaseService)(void * service);
+ int (*releaseService) (void *service);
} CoreAPIForTransport;
@@ -177,20 +180,21 @@
*
* The type of inittransport_XXX is TransportMainMethod.
*/
-typedef struct {
+typedef struct
+{
/**
* This field is used by the core internally;
* the transport should never do ANYTHING
* with it.
*/
- struct PluginHandle * libHandle;
+ struct PluginHandle *libHandle;
/**
* The name of the transport, set by the
* core. Read only for the service itself!
*/
- char * transName;
+ char *transName;
/**
* This field holds a cached hello for this
@@ -199,7 +203,7 @@
* idea. The field is updated by a cron job
* periodically.
*/
- P2P_hello_MESSAGE * hello;
+ P2P_hello_MESSAGE *hello;
/**
* The number of the protocol that is supported by this transport
@@ -230,7 +234,7 @@
* (the signature/crc have been verified before)
* @return OK if the helo is well-formed
*/
- int (*verifyHello)(const P2P_hello_MESSAGE * hello);
+ int (*verifyHello) (const P2P_hello_MESSAGE * hello);
/**
* Create a hello-Message for the current node. The hello is
@@ -243,7 +247,7 @@
* @return OK on success, SYSERR on error (e.g. send-only
* transports return SYSERR here)
*/
- P2P_hello_MESSAGE * (*createhello)(void);
+ P2P_hello_MESSAGE *(*createhello) (void);
/**
* Establish a connection to a remote node.
@@ -252,8 +256,7 @@
* @param tsession the session handle that is to be set
* @return OK on success, SYSERR if the operation failed
*/
- int (*connect)(const P2P_hello_MESSAGE * hello,
- TSession ** tsession);
+ int (*connect) (const P2P_hello_MESSAGE * hello, TSession ** tsession);
/**
* Send a message to the specified remote node.
@@ -269,10 +272,8 @@
* using the session afterwards (useful if the other
* side closed the connection).
*/
- int (*send)(TSession * tsession,
- const void * msg,
- unsigned int size,
- int important);
+ int (*send) (TSession * tsession,
+ const void *msg, unsigned int size, int important);
/**
* A (core) Session is to be associated with a transport session. The
@@ -293,7 +294,7 @@
* @return OK if the session could be associated,
* SYSERR if not.
*/
- int (*associate)(TSession * tsession);
+ int (*associate) (TSession * tsession);
/**
* Disconnect from a remote node. A session can be closed
@@ -308,27 +309,26 @@
* @param tsession the session that is to be closed
* @return OK on success, SYSERR if the operation failed
*/
- int (*disconnect)(TSession * tsession);
+ int (*disconnect) (TSession * tsession);
/**
* Start the server process to receive inbound traffic.
* @return OK on success, SYSERR if the operation failed
*/
- int (*startTransportServer)(void);
+ int (*startTransportServer) (void);
/**
* Shutdown the server process (stop receiving inbound
* traffic). Maybe restarted later!
*/
- int (*stopTransportServer)(void);
+ int (*stopTransportServer) (void);
/**
* Convert hello to network address.
* @return OK on success, SYSERR on error
*/
- int (*helloToAddress)(const P2P_hello_MESSAGE * hello,
- void ** sa,
- unsigned int * sa_len);
+ int (*helloToAddress) (const P2P_hello_MESSAGE * hello,
+ void **sa, unsigned int *sa_len);
/**
* Test if the transport would even try to send
@@ -343,9 +343,7 @@
* NO if the transport would just drop the message,
* SYSERR if the size/session is invalid
*/
- int (*testWouldTry)(TSession * tsession,
- unsigned int size,
- int important);
+ int (*testWouldTry) (TSession * tsession, unsigned int size, int important);
} TransportAPI;
@@ -368,9 +366,9 @@
*
* The type of inittransport_XXX is TransportMainMethod.
*/
-typedef TransportAPI * (*TransportMainMethod)(CoreAPIForTransport *);
+typedef TransportAPI *(*TransportMainMethod) (CoreAPIForTransport *);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_transport_service.h
===================================================================
--- GNUnet/src/include/gnunet_transport_service.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/include/gnunet_transport_service.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -30,8 +30,9 @@
#include "gnunet_transport.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -39,35 +40,35 @@
/**
* Type of the per-transport callback method.
*/
-typedef void (*TransportCallback)(TransportAPI * tapi,
- void * data);
+typedef void (*TransportCallback) (TransportAPI * tapi, void *data);
/**
* @brief Transport service definition.
*/
-typedef struct {
+typedef struct
+{
/**
* Actually start the transport services and begin
* receiving messages.
*/
- void (*start)(P2P_PACKETProcessor mpp);
+ void (*start) (P2P_PACKETProcessor mpp);
/**
* Stop the transport services, stop receiving messages.
*/
- void (*stop)(void);
+ void (*stop) (void);
/**
* Is this transport mechanism available (for sending)?
* @return YES or NO
*/
- int (*isAvailable)(unsigned short ttype);
+ int (*isAvailable) (unsigned short ttype);
/**
* Add an implementation of a transport protocol.
*/
- int (*add)(TransportAPI * tapi);
+ int (*add) (TransportAPI * tapi);
/**
* Iterate over all available transport mechanisms.
@@ -75,8 +76,7 @@
* @param data second argument to callback
* @return number of transports, SYSERR on error
*/
- int (*forEach)(TransportCallback callback,
- void * data);
+ int (*forEach) (TransportCallback callback, void *data);
/**
* Connect to a remote host using the advertised transport
@@ -86,7 +86,7 @@
* @param hello the hello of the target node
* @return session handle on success, NULL on error
*/
- TSession * (*connect)(const P2P_hello_MESSAGE * hello);
+ TSession *(*connect) (const P2P_hello_MESSAGE * hello);
/**
* Connect to another peer, picking any transport that
@@ -97,8 +97,7 @@
* not yet been confirmed?
* @return session handle on success, NULL on error
*/
- TSession * (*connectFreely)(const PeerIdentity * peer,
- int allowTempList);
+ TSession *(*connectFreely) (const PeerIdentity * peer, int allowTempList);
/**
* A (core) Session is to be associated with a transport session. The
@@ -113,12 +112,12 @@
* @return OK if the session could be associated,
* SYSERR if not.
*/
- int (*associate)(TSession * tsession);
+ int (*associate) (TSession * tsession);
/**
* Get the cost of a message in for the given transport mechanism.
*/
- unsigned int (*getCost)(int ttype);
+ unsigned int (*getCost) (int ttype);
/**
* Send a message. Drop if the operation would block.
@@ -130,10 +129,8 @@
* @return OK on success, SYSERR on persistent error, NO on
* temporary error
*/
- int (*send)(TSession * session,
- const void * msg,
- unsigned int size,
- int important);
+ int (*send) (TSession * session,
+ const void *msg, unsigned int size, int important);
/**
* Close the session with the remote node. May only be called on
@@ -141,7 +138,7 @@
*
* @return OK on success, SYSERR on error
*/
- int (*disconnect)(TSession * session);
+ int (*disconnect) (TSession * session);
/**
* Verify that a hello is ok. Call a method
@@ -149,27 +146,26 @@
* @return OK if the attempt to verify is on the way,
* SYSERR if the transport mechanism is not supported
*/
- int (*verifyhello)(const P2P_hello_MESSAGE * hello);
+ int (*verifyhello) (const P2P_hello_MESSAGE * hello);
/**
* Get the network address from a HELLO.
*
* @return OK on success, SYSERR on error
*/
- int (*helloToAddress)(const P2P_hello_MESSAGE * hello,
- void ** sa,
- unsigned int * sa_len);
+ int (*helloToAddress) (const P2P_hello_MESSAGE * hello,
+ void **sa, unsigned int *sa_len);
/**
* Get the MTU for a given transport type.
*/
- int (*getMTU)(unsigned short ttype);
+ int (*getMTU) (unsigned short ttype);
/**
* Create a hello advertisement for the given
* transport type for this node.
*/
- P2P_hello_MESSAGE * (*createhello)(unsigned short ttype);
+ P2P_hello_MESSAGE *(*createhello) (unsigned short ttype);
/**
* Get a message consisting of (if possible) all addresses that this
@@ -184,8 +180,7 @@
* @param buff where to write the hello messages
* @return the number of bytes written to buff, -1 on error
*/
- int (*getAdvertisedhellos)(unsigned int maxLen,
- char * buff);
+ int (*getAdvertisedhellos) (unsigned int maxLen, char *buff);
/**
* Test if the transport would even try to send
@@ -200,14 +195,12 @@
* NO if the transport would just drop the message,
* SYSERR if the size/session is invalid
*/
- int (*testWouldTry)(TSession * tsession,
- unsigned int size,
- int important);
+ int (*testWouldTry) (TSession * tsession, unsigned int size, int important);
} Transport_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_upnp_service.h
===================================================================
--- GNUnet/src/include/gnunet_upnp_service.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_upnp_service.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,8 +30,9 @@
#include "gnunet_util.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -39,7 +40,8 @@
/**
* @brief UPNP API
*/
-typedef struct {
+typedef struct
+{
/**
* Get the external IP address for the local machine.
@@ -47,14 +49,12 @@
*
* @return SYSERR on error, OK on success
*/
- int (*get_ip)(unsigned short port,
- const char * protocol,
- IPaddr * address);
+ int (*get_ip) (unsigned short port, const char *protocol, IPaddr * address);
} UPnP_ServiceAPI;
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_uritrack_lib.h
===================================================================
--- GNUnet/src/include/gnunet_uritrack_lib.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_uritrack_lib.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,8 +30,9 @@
#include "gnunet_ecrs_lib.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -42,32 +43,26 @@
* @param onOff YES to enable tracking, NO to disable
* disabling tracking
*/
-void URITRACK_trackURIS(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- int onOff); /* file_info.c */
+void URITRACK_trackURIS (struct GE_Context *ectx, struct GC_Configuration
*cfg, int onOff); /* file_info.c */
/**
* Deletes all entries in the URITRACK tracking cache.
*/
-void URITRACK_clearTrackedURIS(struct GE_Context * ectx,
- struct GC_Configuration * cfg); /* file_info.c */
+void URITRACK_clearTrackedURIS (struct GE_Context *ectx, struct
GC_Configuration *cfg); /* file_info.c */
/**
* Get the URITRACK URI tracking status.
*
* @return YES of tracking is enabled, NO if not
*/
-int URITRACK_trackStatus(struct GE_Context * ectx,
- struct GC_Configuration * cfg); /* file_info.c */
+int URITRACK_trackStatus (struct GE_Context *ectx, struct GC_Configuration
*cfg); /* file_info.c */
/**
* Makes a URI available for directory building. This function is
* automatically called by all URITRACK functions and only in the
* interface for clients that call ECRS directly.
*/
-void URITRACK_trackURI(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const ECRS_FileInfo * fi); /* file_info.c */
+void URITRACK_trackURI (struct GE_Context *ectx, struct GC_Configuration *cfg,
const ECRS_FileInfo * fi); /* file_info.c */
/**
* List all URIs.
@@ -75,11 +70,7 @@
* @param need_metadata YES if metadata should be
* provided, NO if metadata is not needed (faster)
*/
-int URITRACK_listURIs(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- int need_metadata,
- ECRS_SearchProgressCallback iterator,
- void * closure); /* file_info.c */
+int URITRACK_listURIs (struct GE_Context *ectx, struct GC_Configuration *cfg,
int need_metadata, ECRS_SearchProgressCallback iterator, void *closure); /*
file_info.c */
/**
* Register a handler that is called whenever
@@ -87,32 +78,29 @@
* the database, the callback will be called
* for all existing URIs as well.
*/
-int URITRACK_registerTrackCallback(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- ECRS_SearchProgressCallback iterator,
- void * closure); /* callbacks.c */
+int URITRACK_registerTrackCallback (struct GE_Context *ectx, struct
GC_Configuration *cfg, ECRS_SearchProgressCallback iterator, void *closure);
/* callbacks.c */
/**
* Unregister a URI callback.
*/
-int URITRACK_unregisterTrackCallback(ECRS_SearchProgressCallback iterator,
- void * closure); /* callbacks.c */
+int URITRACK_unregisterTrackCallback (ECRS_SearchProgressCallback iterator,
void *closure); /* callbacks.c */
/**
* Possible ways in which a given URI has been used or encountered.
* Note that we only have 8-bits when storing this on the disk,
* so do not add additional entries (without changing uri_info).
*/
-enum URITRACK_STATE {
- URITRACK_FRESH = 0,
- URITRACK_INSERTED = 1,
- URITRACK_INDEXED = 2,
- URITRACK_DIRECTORY_ADDED = 4,
- URITRACK_DOWNLOAD_STARTED = 8,
- URITRACK_DOWNLOAD_ABORTED = 16,
- URITRACK_DOWNLOAD_COMPLETED = 32,
- URITRACK_SEARCH_RESULT = 64,
- URITRACK_DIRECTORY_FOUND = 128,
+enum URITRACK_STATE
+{
+ URITRACK_FRESH = 0,
+ URITRACK_INSERTED = 1,
+ URITRACK_INDEXED = 2,
+ URITRACK_DIRECTORY_ADDED = 4,
+ URITRACK_DOWNLOAD_STARTED = 8,
+ URITRACK_DOWNLOAD_ABORTED = 16,
+ URITRACK_DOWNLOAD_COMPLETED = 32,
+ URITRACK_SEARCH_RESULT = 64,
+ URITRACK_DIRECTORY_FOUND = 128,
};
/**
@@ -125,19 +113,18 @@
* return information from the wrong URI without detecting it).
*/
enum URITRACK_STATE
-URITRACK_getState(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri);
+URITRACK_getState (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, const struct ECRS_URI *uri);
/**
* Add additional information about a given URI's past.
*/
-void URITRACK_addState(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const struct ECRS_URI * uri,
- enum URITRACK_STATE state);
+void URITRACK_addState (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const struct ECRS_URI *uri,
+ enum URITRACK_STATE state);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util.h
===================================================================
--- GNUnet/src/include/gnunet_util.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/include/gnunet_util.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -57,8 +57,9 @@
#include "gnunet_util_os.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -77,7 +78,7 @@
*/
#define GNUNET_UTIL_VERSION 0x00070201
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_boot.h
===================================================================
--- GNUnet/src/include/gnunet_util_boot.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_boot.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -29,8 +29,9 @@
#define GNUNET_UTIL_BOOT_H
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -50,27 +51,25 @@
* command-line argument to be processed in argv
* otherwise
*/
-int GNUNET_init(int argc,
- char * const * argv,
- const char * binaryName,
- char ** configurationFileName,
- const struct CommandLineOption * options,
- struct GE_Context ** ectx,
- struct GC_Configuration ** cfg);
+int GNUNET_init (int argc,
+ char *const *argv,
+ const char *binaryName,
+ char **configurationFileName,
+ const struct CommandLineOption *options,
+ struct GE_Context **ectx, struct GC_Configuration **cfg);
/**
* Free resources allocated during GNUnet_init.
*/
-void GNUNET_fini(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+void GNUNET_fini (struct GE_Context *ectx, struct GC_Configuration *cfg);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
}
#endif
-
+
/* ifndef GNUNET_UTIL_GETOPT_H */
#endif
/* end of gnunet_util_boot.h */
Modified: GNUnet/src/include/gnunet_util_common.h
===================================================================
--- GNUnet/src/include/gnunet_util_common.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_common.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -39,4 +39,4 @@
#define YES 1
#define NO 0
-#endif /*GNUNET_UTIL_COMMON_H_*/
+#endif /*GNUNET_UTIL_COMMON_H_ */
Modified: GNUnet/src/include/gnunet_util_config.h
===================================================================
--- GNUnet/src/include/gnunet_util_config.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_config.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -33,15 +33,16 @@
#define GNUNET_CONFIG_VERSION 0x00000000
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
struct GC_Configuration;
-void GC_free(struct GC_Configuration * cfg);
+void GC_free (struct GC_Configuration *cfg);
/**
* Set the context for reporting configuration IO errors
@@ -55,30 +56,30 @@
* @param ectx may be NULL, in that case errors will no longer
* be reported
*/
-void GC_set_error_context(struct GC_Configuration * cfg,
- struct GE_Context * ectx);
+void GC_set_error_context (struct GC_Configuration *cfg,
+ struct GE_Context *ectx);
/**
* Parse a configuration file, add all of the options in the
* file to the configuration environment.
* @return 0 on success, -1 on error
*/
-int GC_parse_configuration(struct GC_Configuration * cfg,
- const char * filename);
+int GC_parse_configuration (struct GC_Configuration *cfg,
+ const char *filename);
/**
* Test if there are configuration options that were
* changed since the last save.
* @return 0 if clean, 1 if dirty, -1 on error (i.e. last save failed)
*/
-int GC_test_dirty(struct GC_Configuration * cfg);
+int GC_test_dirty (struct GC_Configuration *cfg);
/**
* Write configuration file.
* @return 0 on success, -1 on error
*/
-int GC_write_configuration(struct GC_Configuration * cfg,
- const char * filename);
+int GC_write_configuration (struct GC_Configuration *cfg,
+ const char *filename);
/**
* Get a configuration value that should be a number.
@@ -87,21 +88,20 @@
* @param default default value (use indicated by return value)
* @return 0 on success, -1 on error, 1 for default
*/
-int GC_get_configuration_value_number(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- unsigned long long min,
- unsigned long long max,
- unsigned long long def,
- unsigned long long * number);
+int GC_get_configuration_value_number (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ unsigned long long min,
+ unsigned long long max,
+ unsigned long long def,
+ unsigned long long *number);
/**
* Test if we have a value for a particular option
* @return YES if so, NO if not.
*/
-int GC_have_configuration_value(struct GC_Configuration * cfg,
- const char * section,
- const char * option);
+int GC_have_configuration_value (struct GC_Configuration *cfg,
+ const char *section, const char *option);
/**
* Get a configuration value that should be a string.
@@ -111,11 +111,10 @@
* value, or NULL if option is not specified and no default given
* @return 0 on success, -1 on error, 1 for default
*/
-int GC_get_configuration_value_string(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char * def,
- char ** value);
+int GC_get_configuration_value_string (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ const char *def, char **value);
/**
* Get a configuration value that should be the name of a file
@@ -127,11 +126,10 @@
* value, or NULL if option is not specified and no default given
* @return 0 on success, -1 on error, 1 for default
*/
-int GC_get_configuration_value_filename(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char * def,
- char ** value);
+int GC_get_configuration_value_filename (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ const char *def, char **value);
/**
* Get a configuration value that should be in a set of
@@ -144,12 +142,11 @@
* or NULL if option is not specified and no default given
* @return 0 on success, -1 on error, 1 for default
*/
-int GC_get_configuration_value_choice(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char ** choices,
- const char * def,
- const char ** value);
+int GC_get_configuration_value_choice (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ const char **choices,
+ const char *def, const char **value);
/**
* Get a configuration value that should be in a set of
@@ -159,10 +156,9 @@
* will NOT be aliased, maybe NULL)
* @return YES, NO or SYSERR
*/
-int GC_get_configuration_value_yesno(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- int def);
+int GC_get_configuration_value_yesno (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option, int def);
/**
* Expand an expression of the form "$FOO/BAR" to "DIRECTORY/BAR"
@@ -172,19 +168,19 @@
* @param old string to $-expand (will be freed!)
* @return $-expanded string
*/
-char * GC_configuration_expand_dollar(struct GC_Configuration * cfg,
- char * old);
+char *GC_configuration_expand_dollar (struct GC_Configuration *cfg,
+ char *old);
/**
* Set a configuration value that should be a number.
* @return 0 on success, -1 on error (i.e. out of memory,
* or update refused by registered callback)
*/
-int GC_set_configuration_value_number(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option,
- unsigned long long number);
+int GC_set_configuration_value_number (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section,
+ const char *option,
+ unsigned long long number);
/**
@@ -193,11 +189,10 @@
* @return 0 on success, -1 on error (i.e. out of memory,
* or update refused by registered callback)
*/
-int GC_set_configuration_value_string(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option,
- const char * value);
+int GC_set_configuration_value_string (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section,
+ const char *option, const char *value);
/**
* Set a configuration value that should be in a set of
@@ -206,11 +201,11 @@
* @return 0 on success, -1 on error (i.e. out of memory,
* or update refused by registered callback)
*/
-int GC_set_configuration_value_choice(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option,
- const char * choice);
+int GC_set_configuration_value_choice (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section,
+ const char *option,
+ const char *choice);
/**
* Callback function that is called if a configuration option
@@ -221,11 +216,10 @@
* @return 0 if the change is ok, -1 if the change must be
* refused
*/
-typedef int (*GC_ChangeListener)(void * ctx,
- struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option);
+typedef int (*GC_ChangeListener) (void *ctx,
+ struct GC_Configuration * cfg,
+ struct GE_Context * ectx,
+ const char *section, const char *option);
/**
* Attach a callback that is notified whenever a
@@ -233,21 +227,19 @@
*
* @return 0 on success, -1 on error
*/
-int GC_attach_change_listener(struct GC_Configuration * cfg,
- GC_ChangeListener callback,
- void * ctx);
+int GC_attach_change_listener (struct GC_Configuration *cfg,
+ GC_ChangeListener callback, void *ctx);
/**
* Attach a callback that is notified whenever a
* configuration option changes.
* @return 0 on success, -1 on error, 1 for no such handler registered
*/
-int GC_detach_change_listener(struct GC_Configuration * cfg,
- GC_ChangeListener callback,
- void * ctx);
+int GC_detach_change_listener (struct GC_Configuration *cfg,
+ GC_ChangeListener callback, void *ctx);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_config_impl.h
===================================================================
--- GNUnet/src/include/gnunet_util_config_impl.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/include/gnunet_util_config_impl.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -31,22 +31,24 @@
#include "gnunet_util_config.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
struct GC_ConfigurationData;
-typedef struct GC_Configuration {
+typedef struct GC_Configuration
+{
/**
* Internal configuration data.
*/
- struct GC_ConfigurationData * data;
+ struct GC_ConfigurationData *data;
- void (*free)(struct GC_Configuration * cfg);
+ void (*free) (struct GC_Configuration * cfg);
/**
* Set the context for reporting configuration IO errors
@@ -60,31 +62,31 @@
* @parm ectx maybe NULL, in that case errors will no longer
* be reported
*/
- void (*set_error_context)(struct GC_Configuration * cfg,
- struct GE_Context * ectx);
+ void (*set_error_context) (struct GC_Configuration * cfg,
+ struct GE_Context * ectx);
/**
* Parse a configuration file, add all of the options in the
* file to the configuration environment.
* @return 0 on success, -1 on error
*/
- int (*parse_configuration)(struct GC_Configuration * cfg,
- const char * filename);
+ int (*parse_configuration) (struct GC_Configuration * cfg,
+ const char *filename);
/**
* Test if there are configuration options that were
* changed since the last save.
* @return 0 if clean, 1 if dirty, -1 on error (i.e. last save failed)
*/
- int (*test_dirty)(struct GC_Configuration * cfg);
+ int (*test_dirty) (struct GC_Configuration * cfg);
/**
* Write configuration file.
* @return 0 on success, -1 on error
*/
- int (*write_configuration)(struct GC_Configuration * cfg,
- const char * filename);
+ int (*write_configuration) (struct GC_Configuration * cfg,
+ const char *filename);
/**
@@ -95,8 +97,8 @@
* @param old string to $-expand (will be freed!)
* @return $-expanded string
*/
- char * (*configuration_expand_dollar)(struct GC_Configuration * cfg,
- char * old);
+ char *(*configuration_expand_dollar) (struct GC_Configuration * cfg,
+ char *old);
/**
* Get a configuration value that should be a number.
@@ -105,13 +107,13 @@
* @param def default value (use indicated by return value)
* @return 0 on success, -1 on error, 1 for default
*/
- int (*get_configuration_value_number)(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- unsigned long long min,
- unsigned long long max,
- unsigned long long def,
- unsigned long long * number);
+ int (*get_configuration_value_number) (struct GC_Configuration * cfg,
+ const char *section,
+ const char *option,
+ unsigned long long min,
+ unsigned long long max,
+ unsigned long long def,
+ unsigned long long *number);
/**
@@ -122,11 +124,10 @@
* value, or NULL if option is not specified and no default given
* @return 0 on success, -1 on error, 1 for default
*/
- int (*get_configuration_value_string)(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char * def,
- char ** value);
+ int (*get_configuration_value_string) (struct GC_Configuration * cfg,
+ const char *section,
+ const char *option,
+ const char *def, char **value);
/**
* Get a configuration value that should be a file name.
@@ -136,11 +137,10 @@
* value, or NULL if option is not specified and no default given
* @return 0 on success, -1 on error, 1 for default
*/
- int (*get_configuration_value_filename)(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char * def,
- char ** value);
+ int (*get_configuration_value_filename) (struct GC_Configuration * cfg,
+ const char *section,
+ const char *option,
+ const char *def, char **value);
/**
* Get a configuration value that should be in a set of
@@ -153,23 +153,22 @@
* or NULL if option is not specified and no default given
* @return 0 on success, -1 on error, 1 for default
*/
- int (*get_configuration_value_choice)(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char ** choices,
- const char * def,
- const char ** value);
+ int (*get_configuration_value_choice) (struct GC_Configuration * cfg,
+ const char *section,
+ const char *option,
+ const char **choices,
+ const char *def, const char **value);
/**
* Set a configuration value that should be a number.
* @return 0 on success, -1 on error (i.e. out of memory,
* or update refused by registered callback)
*/
- int (*set_configuration_value_number)(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option,
- unsigned long long number);
+ int (*set_configuration_value_number) (struct GC_Configuration * cfg,
+ struct GE_Context * ectx,
+ const char *section,
+ const char *option,
+ unsigned long long number);
/**
@@ -178,11 +177,11 @@
* @return 0 on success, -1 on error (i.e. out of memory,
* or update refused by registered callback)
*/
- int (*set_configuration_value_string)(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option,
- const char * value);
+ int (*set_configuration_value_string) (struct GC_Configuration * cfg,
+ struct GE_Context * ectx,
+ const char *section,
+ const char *option,
+ const char *value);
/**
* Set a configuration value that should be in a set of
@@ -191,43 +190,40 @@
* @return 0 on success, -1 on error (i.e. out of memory,
* or update refused by registered callback)
*/
- int (*set_configuration_value_choice)(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option,
- const char * choice);
+ int (*set_configuration_value_choice) (struct GC_Configuration * cfg,
+ struct GE_Context * ectx,
+ const char *section,
+ const char *option,
+ const char *choice);
/**
* Attach a callback that is notified whenever a
* configuration option changes.
* @return 0 on success, -1 on error
*/
- int (*attach_change_listener)(struct GC_Configuration * cfg,
- GC_ChangeListener callback,
- void * ctx);
+ int (*attach_change_listener) (struct GC_Configuration * cfg,
+ GC_ChangeListener callback, void *ctx);
/**
* Attach a callback that is notified whenever a
* configuration option changes.
* @return 0 on success, -1 on error, 1 for no such handler registered
*/
- int (*detach_change_listener)(struct GC_Configuration * cfg,
- GC_ChangeListener callback,
- void * ctx);
+ int (*detach_change_listener) (struct GC_Configuration * cfg,
+ GC_ChangeListener callback, void *ctx);
- int (*have_configuration_value)(struct GC_Configuration * cfg,
- const char * section,
- const char * option);
+ int (*have_configuration_value) (struct GC_Configuration * cfg,
+ const char *section, const char *option);
} GC_Configuration;
/**
* Create a GC_Configuration (C implementation).
*/
-GC_Configuration * GC_create_C_impl(void);
+GC_Configuration *GC_create_C_impl (void);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_containers.h
===================================================================
--- GNUnet/src/include/gnunet_util_containers.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_containers.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -40,8 +40,9 @@
#include "gnunet_util_crypto.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -54,7 +55,7 @@
/**
* Iterator over all HashCodes stored in a Bloomfilter.
*/
-typedef HashCode512 * (*ElementIterator)(void * arg);
+typedef HashCode512 *(*ElementIterator) (void *arg);
/**
* @brief a Vector (ordered variable size set of elements), opaque
@@ -75,10 +76,9 @@
* element (number of bits set per element in the set)
* @return the bloomfilter
*/
-struct Bloomfilter * loadBloomfilter(struct GE_Context * ectx,
- const char * filename,
- unsigned int size,
- unsigned int k);
+struct Bloomfilter *loadBloomfilter (struct GE_Context *ectx,
+ const char *filename,
+ unsigned int size, unsigned int k);
/**
* Test if an element is in the filter.
@@ -86,24 +86,21 @@
* @param bf the filter
* @return YES if the element is in the filter, NO if not
*/
-int testBloomfilter(struct Bloomfilter * bf,
- const HashCode512 * e);
+int testBloomfilter (struct Bloomfilter *bf, const HashCode512 * e);
/**
* Add an element to the filter
* @param bf the filter
* @param e the element
*/
-void addToBloomfilter(struct Bloomfilter * bf,
- const HashCode512 * e);
+void addToBloomfilter (struct Bloomfilter *bf, const HashCode512 * e);
/**
* Remove an element from the filter.
* @param bf the filter
* @param e the element to remove
*/
-void delFromBloomfilter(struct Bloomfilter * bf,
- const HashCode512 * e);
+void delFromBloomfilter (struct Bloomfilter *bf, const HashCode512 * e);
/**
* Free the space associcated with a filter
@@ -111,13 +108,13 @@
* free the space on the drive)
* @param bf the filter
*/
-void freeBloomfilter(struct Bloomfilter * bf);
+void freeBloomfilter (struct Bloomfilter *bf);
/**
* Reset a bloom filter to empty.
* @param bf the filter
*/
-void resetBloomfilter(struct Bloomfilter * bf);
+void resetBloomfilter (struct Bloomfilter *bf);
/**
* Resize a bloom filter. Note that this operation
@@ -130,16 +127,15 @@
* @param size the new size for the filter
* @param k the new number of hash-function to apply per element
*/
-void resizeBloomfilter(struct Bloomfilter * bf,
- ElementIterator iterator,
- void * iterator_arg,
- unsigned int size,
- unsigned int k);
+void resizeBloomfilter (struct Bloomfilter *bf,
+ ElementIterator iterator,
+ void *iterator_arg,
+ unsigned int size, unsigned int k);
/**
* A debug function that dumps the vector to stderr.
*/
-void vectorDump(struct Vector *v);
+void vectorDump (struct Vector *v);
/**
* @param vss Size of the VectorSegment data area. The "correct" value for this
@@ -149,112 +145,101 @@
* or otherwise the increased length of the linked list will become a
* bottleneck for operations that are performed on arbitrary indexes.
*/
-struct Vector * vectorNew(unsigned int vss);
+struct Vector *vectorNew (unsigned int vss);
/**
* Free vector structure including its data segments, but _not_ including the
* stored void pointers. It is the user's responsibility to empty the vector
* when necessary to avoid memory leakage.
*/
-void vectorFree(struct Vector * v);
+void vectorFree (struct Vector *v);
-size_t vectorSize(struct Vector * v);
+size_t vectorSize (struct Vector *v);
/**
* Insert a new element in the vector at given index.
* @return OK on success, SYSERR if the index is out of bounds.
*/
-int vectorInsertAt(struct Vector * v,
- void * object,
- unsigned int index);
+int vectorInsertAt (struct Vector *v, void *object, unsigned int index);
/**
* Insert a new element at the end of the vector.
*/
-void vectorInsertLast(struct Vector * v, void * object);
+void vectorInsertLast (struct Vector *v, void *object);
/**
* Return the element at given index in the vector or NULL if the index is out
* of bounds. The iterator is set to point to the returned element.
*/
-void * vectorGetAt(struct Vector * v,
- unsigned int index);
+void *vectorGetAt (struct Vector *v, unsigned int index);
/**
* Return the first element in the vector, whose index is 0, or NULL if the
* vector is empty. The iterator of the vector is set to point to the first
* element.
*/
-void * vectorGetFirst(struct Vector * v);
+void *vectorGetFirst (struct Vector *v);
/**
* Return the last element in the vector or NULL if the vector is empty. The
* iterator of the vector is set to point to the last element.
*/
-void * vectorGetLast(struct Vector * v);
+void *vectorGetLast (struct Vector *v);
/**
* Return the next element in the vector, as called after vector_get_at() or
* vector_get_first(). The return value is NULL if there are no more elements
* in the vector or if the iterator has not been set.
*/
-void * vectorGetNext(struct Vector * v);
+void *vectorGetNext (struct Vector *v);
/**
* Return the previous element in the vector, as called after vector_get_at()
* or vector_get_last(). The return value is NULL if there are no more
* elements in the vector or if the iterator has not been set.
*/
-void * vectorGetPrevious(struct Vector * v);
+void *vectorGetPrevious (struct Vector *v);
/**
* Delete and return the element at given index. NULL is returned if index is
* out of bounds.
*/
-void * vectorRemoveAt(struct Vector * v,
- unsigned int index);
+void *vectorRemoveAt (struct Vector *v, unsigned int index);
/**
* Delete and return the last element in the vector, or NULL if the vector
* is empty.
*/
-void * vectorRemoveLast(struct Vector * v);
+void *vectorRemoveLast (struct Vector *v);
/**
* Delete and return given object from the vector, or return NULL if the object
* is not found.
*/
-void * vectorRemoveObject(struct Vector * v, void * object);
+void *vectorRemoveObject (struct Vector *v, void *object);
/**
* Set the given index in the vector. The old value of the index is
* returned, or NULL if the index is out of bounds.
*/
-void * vectorSetAt(struct Vector * v,
- void * object,
- unsigned int index);
+void *vectorSetAt (struct Vector *v, void *object, unsigned int index);
/**
* Set the index occupied by the given object to point to the new object.
* The old object is returned, or NULL if it's not found.
*/
-void * vectorSetObject(struct Vector * v,
- void * object,
- void * old_object);
+void *vectorSetObject (struct Vector *v, void *object, void *old_object);
/**
* Swaps the contents of index1 and index2. Return value is OK
* on success, SYSERR if either index is out of bounds.
*/
-int vectorSwap(struct Vector * v,
- unsigned int index1,
- unsigned int index2);
+int vectorSwap (struct Vector *v, unsigned int index1, unsigned int index2);
/**
* Return the index of given element or -1 if the element is not found.
*/
-unsigned int vectorIndexOf(struct Vector * v,
- void * object);
+unsigned int vectorIndexOf (struct Vector *v, void *object);
/**
* Return the data stored in the vector as a single dynamically
@@ -263,7 +248,7 @@
* you really need to access everything in the vector as fast as
* possible.
*/
-void ** vectorElements(struct Vector * v);
+void **vectorElements (struct Vector *v);
/**
* @brief creates a new HashTable
@@ -282,13 +267,13 @@
* passes the thresholds set by ht_setIdealRatio().
* @return a new Hashtable, or NULL on error
*/
-struct HashTable *ht_create(long numOfBuckets);
+struct HashTable *ht_create (long numOfBuckets);
/**
* @brief destroys an existing HashTable
* @param hashTable the HashTable to destroy
*/
-void ht_destroy(struct HashTable *hashTable);
+void ht_destroy (struct HashTable *hashTable);
/**
* @brief checks the existence of a key in a HashTable
@@ -297,7 +282,8 @@
* @return whether or not the specified HashTable contains the
* specified key
*/
-int ht_containsKey(const struct HashTable *hashTable, const void *key, const
unsigned int keylen);
+int ht_containsKey (const struct HashTable *hashTable, const void *key,
+ const unsigned int keylen);
/**
* @brief checks the existence of a value in a HashTable
@@ -306,7 +292,8 @@
* @return whether or not the specified HashTable contains the
* specified value
*/
-int ht_containsValue(const struct HashTable *hashTable, const void *value,
const unsigned int valuelen);
+int ht_containsValue (const struct HashTable *hashTable, const void *value,
+ const unsigned int valuelen);
/**
* @brief adds a key/value pair to a HashTable
@@ -315,11 +302,10 @@
* @param value the value associated with the key
* @return 0 if successful, -1 if an error was encountered
*/
-int ht_put(struct HashTable *hashTable,
- const void *key,
- const unsigned int keylen,
- void *value,
- const unsigned int valuelen);
+int ht_put (struct HashTable *hashTable,
+ const void *key,
+ const unsigned int keylen,
+ void *value, const unsigned int valuelen);
/**
* @brief retrieves the value of a key in a HashTable
@@ -329,26 +315,23 @@
* @param valuelen the length of the value
* @return YES if found, NO otherwise
*/
-int ht_get(const struct HashTable *hashTable,
- const void *key,
- const unsigned int keylen,
- void **value,
- unsigned int *valuelen);
+int ht_get (const struct HashTable *hashTable,
+ const void *key,
+ const unsigned int keylen, void **value, unsigned int *valuelen);
/**
* @brief removes a key/value pair from a HashTable
* @param hashTable the HashTable to remove the key/value pair from
* @param key the key specifying the key/value pair to be removed
*/
-void ht_remove(struct HashTable *hashTable,
- const void *key,
- const unsigned int keylen);
+void ht_remove (struct HashTable *hashTable,
+ const void *key, const unsigned int keylen);
/**
* @brief removes all key/value pairs from a HashTable
* @param hashTable the HashTable to remove all key/value pairs from
*/
-void ht_removeAll(struct HashTable *hashTable);
+void ht_removeAll (struct HashTable *hashTable);
/**
* @brief returns the number of elements in a HashTable
@@ -356,7 +339,7 @@
* @return the number of key/value pairs that are present in
* the specified HashTable
*/
-long ht_size(const struct HashTable *hashTable);
+long ht_size (const struct HashTable *hashTable);
/**
* @brief returns the number of buckets in a HashTable
@@ -364,7 +347,7 @@
* @return the number of buckets that are in the specified
* HashTable
*/
-long ht_buckets(const struct HashTable *hashTable);
+long ht_buckets (const struct HashTable *hashTable);
/**
* @brief reorganizes a HashTable to be more efficient
@@ -378,8 +361,7 @@
* specified, an appropriate number of buckets is
* automatically calculated.
*/
-void ht_rehash(struct HashTable *hashTable,
- long numOfBuckets);
+void ht_rehash (struct HashTable *hashTable, long numOfBuckets);
/**
* @brief sets the ideal element-to-bucket ratio of a HashTable
@@ -407,10 +389,10 @@
* is considered unacceptably high, a value of 0.0 can
* be specified.
*/
-void ht_setIdealRatio(struct HashTable *hashTable,
- float idealRatio,
- float lowerRehashThreshold,
- float upperRehashThreshold);
+void ht_setIdealRatio (struct HashTable *hashTable,
+ float idealRatio,
+ float lowerRehashThreshold,
+ float upperRehashThreshold);
#define HT_PUT(ht, key, val) ht_put(ht, key, sizeof(key), val, sizeof(val))
#define HT_GET(ht, key, val, vallen) ht_get(ht, key, sizeof(key), val, vallen)
@@ -418,7 +400,7 @@
#define HT_CONTAINS_VALUE(ht, value) ht_containsValue(ht, value, sizeof(value))
#define HT_REMOVE(ht, key) ht_remove(ht, key, sizeof(key))
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_core.h
===================================================================
--- GNUnet/src/include/gnunet_util_core.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_core.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -42,7 +42,8 @@
* and includes the senderAddress. Since the senderAddress may be
* long, what is actually signed is the hash of these bytes.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
Modified: GNUnet/src/include/gnunet_util_cron.h
===================================================================
--- GNUnet/src/include/gnunet_util_cron.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_cron.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -31,8 +31,9 @@
#define GNUNET_UTIL_CRON_H
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -42,17 +43,17 @@
/**
* Type of a cron-job method.
*/
-typedef void (*CronJob)(void *);
+typedef void (*CronJob) (void *);
struct CronManager;
-struct CronManager * cron_create(struct GE_Context * ectx);
+struct CronManager *cron_create (struct GE_Context *ectx);
-void cron_destroy(struct CronManager * mgr);
+void cron_destroy (struct CronManager *mgr);
-void cron_start(struct CronManager * mgr);
+void cron_start (struct CronManager *mgr);
-void cron_stop(struct CronManager * mgr);
+void cron_stop (struct CronManager *mgr);
/**
* Stop running cron-jobs for a short time. This method may only be
@@ -63,8 +64,7 @@
*
* @param checkself, if YES and this thread is the cron thread, do nothing
*/
-void cron_suspend(struct CronManager * mgr,
- int checkself);
+void cron_suspend (struct CronManager *mgr, int checkself);
/**
* Resume running cron-jobs. Call must be matched by
@@ -73,13 +73,12 @@
*
* @param checkself, if YES and this thread is the cron thread, do nothing
*/
-void cron_resume_jobs(struct CronManager * mgr,
- int checkself);
+void cron_resume_jobs (struct CronManager *mgr, int checkself);
/**
* Is the cron-thread currently running?
*/
-int cron_test_running(struct CronManager * mgr);
+int cron_test_running (struct CronManager *mgr);
/**
* Add a cron-job to the delta list.
@@ -89,11 +88,9 @@
* the runs, otherwise 0.
* @param data argument to pass to the method
*/
-void cron_add_job(struct CronManager * mgr,
- CronJob method,
- unsigned int delta,
- unsigned int deltaRepeat,
- void * data);
+void cron_add_job (struct CronManager *mgr,
+ CronJob method,
+ unsigned int delta, unsigned int deltaRepeat, void *data);
/**
* If the specified cron-job exists in th delta-list, move it to the
@@ -107,10 +104,8 @@
* non-null and cron is shutdown before the job is
* run and/or delCronJob is called
*/
-void cron_advance_job(struct CronManager * mgr,
- CronJob method,
- unsigned int deltaRepeat,
- void * data);
+void cron_advance_job (struct CronManager *mgr,
+ CronJob method, unsigned int deltaRepeat, void *data);
/**
* Remove first matching cron-job from the list. This method should
@@ -125,12 +120,10 @@
* @param data what was the data given to the method
* @return the number of jobs removed (0 or 1)
*/
-int cron_del_job(struct CronManager * mgr,
- CronJob method,
- unsigned int repeat,
- void * data);
+int cron_del_job (struct CronManager *mgr,
+ CronJob method, unsigned int repeat, void *data);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_crypto.h
===================================================================
--- GNUnet/src/include/gnunet_util_crypto.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_crypto.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,8 +35,9 @@
#include "gnunet_util.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -74,7 +75,8 @@
/**
* @brief 0-terminated ASCII encoding of a HashCode512.
*/
-typedef struct {
+typedef struct
+{
unsigned char encoding[104];
} EncName;
@@ -85,32 +87,35 @@
* to serialize a private RSA key (typically when
* writing it to disk).
*/
-typedef struct {
+typedef struct
+{
/**
* Total size of the structure, in bytes, in big-endian!
*/
unsigned short len;
- unsigned short sizen;/* in big-endian! */
- unsigned short sizee;/* in big-endian! */
- unsigned short sized;/* in big-endian! */
- unsigned short sizep;/* in big-endian! */
- unsigned short sizeq;/* in big-endian! */
- unsigned short sizedmp1;/* in big-endian! */
- unsigned short sizedmq1;/* in big-endian! */
+ unsigned short sizen; /* in big-endian! */
+ unsigned short sizee; /* in big-endian! */
+ unsigned short sized; /* in big-endian! */
+ unsigned short sizep; /* in big-endian! */
+ unsigned short sizeq; /* in big-endian! */
+ unsigned short sizedmp1; /* in big-endian! */
+ unsigned short sizedmq1; /* in big-endian! */
/* followed by the actual values */
} PrivateKeyEncoded;
/**
* @brief an RSA signature
*/
-typedef struct {
+typedef struct
+{
unsigned char sig[RSA_ENC_LEN];
} Signature;
/**
* @brief A public key.
*/
-typedef struct {
+typedef struct
+{
/**
* In big-endian, must be RSA_KEY_LEN+2
*/
@@ -132,16 +137,18 @@
/**
* RSA Encrypted data.
*/
-typedef struct {
+typedef struct
+{
unsigned char encoding[RSA_ENC_LEN];
} RSAEncryptedData;
/**
* @brief type for session keys
*/
-typedef struct {
+typedef struct
+{
unsigned char key[SESSIONKEY_LEN];
- int crc32; /* checksum! */
+ int crc32; /* checksum! */
} SESSIONKEY;
/**
@@ -150,8 +157,9 @@
* NOTE: must be smaller (!) in size than the
* HashCode512.
*/
-typedef struct {
- unsigned char iv[SESSIONKEY_LEN/2];
+typedef struct
+{
+ unsigned char iv[SESSIONKEY_LEN / 2];
} INITVECTOR;
/* **************** Functions and Macros ************* */
@@ -164,7 +172,7 @@
* @param len the length of the buffer in bytes
* @return the resulting CRC32 checksum
*/
-int crc32N(const void * buf, int len);
+int crc32N (const void *buf, int len);
/**
* Produce a random value.
@@ -172,15 +180,15 @@
* @param i the upper limit (exclusive) for the random number
* @return a random value in the interval [0,i[.
*/
-unsigned int randomi(unsigned int i);
+unsigned int randomi (unsigned int i);
/**
* Random on unsigned 64-bit values. We break them down into signed
* 32-bit values and reassemble the 64-bit random value bit-wise.
*/
-unsigned long long randomi64(unsigned long long u);
+unsigned long long randomi64 (unsigned long long u);
-unsigned long long weak_randomi64(unsigned long long u);
+unsigned long long weak_randomi64 (unsigned long long u);
/**
* Get an array with a random permutation of the
@@ -189,7 +197,7 @@
* @param n the size of the array
* @return the permutation array (allocated from heap)
*/
-int * permute(int mode, int n);
+int *permute (int mode, int n);
/**
* Produce a cryptographically weak random value.
@@ -197,12 +205,12 @@
* @param i the upper limit (exclusive) for the random number
* @return a random value in the interval [0,i[.
*/
-unsigned int weak_randomi(unsigned int i);
+unsigned int weak_randomi (unsigned int i);
/**
* Create a new Session key.
*/
-void makeSessionkey(SESSIONKEY * key);
+void makeSessionkey (SESSIONKEY * key);
/**
* Encrypt a block with the public key of another
@@ -214,11 +222,10 @@
* for streams.
* @returns the size of the encrypted block, -1 for errors
*/
-int encryptBlock(const void * block,
- unsigned short len,
- const SESSIONKEY * sessionkey,
- const INITVECTOR * iv,
- void * result);
+int encryptBlock (const void *block,
+ unsigned short len,
+ const SESSIONKEY * sessionkey,
+ const INITVECTOR * iv, void *result);
/**
* Decrypt a given block with the sessionkey.
@@ -229,11 +236,9 @@
* @param result address to store the result at
* @return -1 on failure, size of decrypted block on success
*/
-int decryptBlock(const SESSIONKEY * sessionkey,
- const void * block,
- unsigned short size,
- const INITVECTOR * iv,
- void * result);
+int decryptBlock (const SESSIONKEY * sessionkey,
+ const void *block,
+ unsigned short size, const INITVECTOR * iv, void *result);
/**
* Convert hash to ASCII encoding.
@@ -241,8 +246,7 @@
* @param result where to store the encoding (EncName can be
* safely cast to char*, a '\0' termination is set).
*/
-void hash2enc(const HashCode512 * block,
- EncName * result);
+void hash2enc (const HashCode512 * block, EncName * result);
/**
* Convert ASCII encoding back to hash
@@ -250,8 +254,7 @@
* @param result where to store the hash code
* @return OK on success, SYSERR if result has the wrong encoding
*/
-int enc2hash(const char * enc,
- HashCode512 * result);
+int enc2hash (const char *enc, HashCode512 * result);
/**
* Compute the distance between 2 hashcodes.
@@ -261,56 +264,47 @@
* result should be a positive number.
* @return number between 0 and 65536
*/
-unsigned int distanceHashCode512(const HashCode512 * a,
- const HashCode512 * b);
+unsigned int distanceHashCode512 (const HashCode512 * a,
+ const HashCode512 * b);
/**
* compare two hashcodes.
*/
-int equalsHashCode512(const HashCode512 * a,
- const HashCode512 * b);
+int equalsHashCode512 (const HashCode512 * a, const HashCode512 * b);
/**
* Hash block of given size.
* @param block the data to hash, length is given as a second argument
* @param ret pointer to where to write the hashcode
*/
-void hash(const void * block,
- unsigned int size,
- HashCode512 * ret);
+void hash (const void *block, unsigned int size, HashCode512 * ret);
/**
* Compute the hash of an entire file.
* @return OK on success, SYSERR on error
*/
-int getFileHash(struct GE_Context * ectx,
- const char * filename,
- HashCode512 * ret);
+int getFileHash (struct GE_Context *ectx,
+ const char *filename, HashCode512 * ret);
-void makeRandomId(HashCode512 * result);
+void makeRandomId (HashCode512 * result);
/* compute result(delta) = b - a */
-void deltaId(const HashCode512 * a,
- const HashCode512 * b,
- HashCode512 * result);
+void deltaId (const HashCode512 * a,
+ const HashCode512 * b, HashCode512 * result);
/* compute result(b) = a + delta */
-void addHashCodes(const HashCode512 * a,
- const HashCode512 * delta,
- HashCode512 * result);
+void addHashCodes (const HashCode512 * a,
+ const HashCode512 * delta, HashCode512 * result);
/* compute result = a ^ b */
-void xorHashCodes(const HashCode512 * a,
- const HashCode512 * b,
- HashCode512 * result);
+void xorHashCodes (const HashCode512 * a,
+ const HashCode512 * b, HashCode512 * result);
/**
* Convert a hashcode into a key.
*/
-void hashToKey(const HashCode512 * hc,
- SESSIONKEY * skey,
- INITVECTOR * iv);
+void hashToKey (const HashCode512 * hc, SESSIONKEY * skey, INITVECTOR * iv);
/**
* Obtain a bit from a hashcode.
@@ -318,49 +312,46 @@
* @param bit index into the hashcode, [0...159]
* @return Bit \a bit from hashcode \a code, -1 for invalid index
*/
-int getHashCodeBit(const HashCode512 * code,
- unsigned int bit);
+int getHashCodeBit (const HashCode512 * code, unsigned int bit);
/**
* Compare function for HashCodes, producing a total ordering
* of all hashcodes.
* @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
*/
-int hashCodeCompare(const HashCode512 * h1,
- const HashCode512 * h2);
+int hashCodeCompare (const HashCode512 * h1, const HashCode512 * h2);
/**
* Find out which of the two hash codes is closer to target
* in the XOR metric (Kademlia).
* @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
*/
-int hashCodeCompareDistance(const HashCode512 * h1,
- const HashCode512 * h2,
- const HashCode512 * target);
+int hashCodeCompareDistance (const HashCode512 * h1,
+ const HashCode512 * h2,
+ const HashCode512 * target);
/**
* create a new hostkey. Callee must free return value.
*/
-struct PrivateKey * makePrivateKey(void);
+struct PrivateKey *makePrivateKey (void);
/**
* Deterministically (!) create a hostkey using only the
* given HashCode as input to the PRNG.
*/
-struct PrivateKey * makeKblockKey(const HashCode512 * input);
+struct PrivateKey *makeKblockKey (const HashCode512 * input);
/**
* Free memory occupied by hostkey
* @param hostkey pointer to the memory to free
*/
-void freePrivateKey(struct PrivateKey * hostkey);
+void freePrivateKey (struct PrivateKey *hostkey);
/**
* Extract the public key of the host.
* @param result where to write the result.
*/
-void getPublicKey(const struct PrivateKey * hostkey,
- PublicKey * result);
+void getPublicKey (const struct PrivateKey *hostkey, PublicKey * result);
/**
* Encode the private key in a format suitable for
@@ -368,7 +359,7 @@
* @param hostkey the hostkey to use
* @returns encoding of the private key.
*/
-PrivateKeyEncoded * encodePrivateKey(const struct PrivateKey * hostkey);
+PrivateKeyEncoded *encodePrivateKey (const struct PrivateKey *hostkey);
/**
* Decode the private key from the file-format back
@@ -376,7 +367,7 @@
* @param encoded the encoded hostkey
* @returns the decoded hostkey
*/
-struct PrivateKey * decodePrivateKey(const PrivateKeyEncoded * encoding);
+struct PrivateKey *decodePrivateKey (const PrivateKeyEncoded * encoding);
/**
* Encrypt a block with the public key of another host that uses the
@@ -388,10 +379,10 @@
* @param target where to store the encrypted block
* @returns SYSERR on error, OK if ok
*/
-int encryptPrivateKey(const void * block,
- unsigned short size,
- const PublicKey * publicKey,
- RSAEncryptedData * target);
+int encryptPrivateKey (const void *block,
+ unsigned short size,
+ const PublicKey * publicKey,
+ RSAEncryptedData * target);
/**
* Decrypt a given block with the hostkey.
@@ -402,10 +393,9 @@
* @param size how many bytes of a result are expected? Must be exact.
* @returns the size of the decrypted block (that is, size) or -1 on error
*/
-int decryptPrivateKey(const struct PrivateKey * key,
- const RSAEncryptedData * block,
- void * result,
- unsigned short size);
+int decryptPrivateKey (const struct PrivateKey *key,
+ const RSAEncryptedData * block,
+ void *result, unsigned short size);
/**
* Sign a given block.
@@ -415,10 +405,8 @@
* @param result where to write the signature
* @return SYSERR on error, OK on success
*/
-int sign(const struct PrivateKey * key,
- unsigned short size,
- const void * block,
- Signature * result);
+int sign (const struct PrivateKey *key,
+ unsigned short size, const void *block, Signature * result);
/**
* Verify signature.
@@ -428,12 +416,11 @@
* @param publicKey public key of the signer
* @returns OK if ok, SYSERR if invalid
*/
-int verifySig(const void * block,
- unsigned short len,
- const Signature * sig,
- const PublicKey * publicKey);
+int verifySig (const void *block,
+ unsigned short len,
+ const Signature * sig, const PublicKey * publicKey);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_disk.h
===================================================================
--- GNUnet/src/include/gnunet_util_disk.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_disk.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,8 +35,9 @@
#include <stdlib.h>
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -48,8 +49,7 @@
* @param part a file on the partition to check
* @return -1 on errors, otherwise the number of free blocks
*/
-long disk_get_blocks_available(struct GE_Context * ectx,
- const char * part);
+long disk_get_blocks_available (struct GE_Context *ectx, const char *part);
/**
* Check that fil corresponds to a filename
@@ -58,8 +58,7 @@
* @returns YES if yes, NO if not a file, SYSERR if something
* else (will print an error message in that case, too).
*/
-int disk_file_test(struct GE_Context * ectx,
- const char * fil);
+int disk_file_test (struct GE_Context *ectx, const char *fil);
/**
* Get the size of the file (or directory)
@@ -70,27 +69,22 @@
*
* @return OK on success, SYSERR on error
*/
-int disk_file_size(struct GE_Context * ectx,
- const char * filename,
- unsigned long long * size,
- int includeSymLinks);
+int disk_file_size (struct GE_Context *ectx,
+ const char *filename,
+ unsigned long long *size, int includeSymLinks);
/**
* Wrapper around "open()". Opens a file.
*
* @return file handle, -1 on error
*/
-int disk_file_open(struct GE_Context * ectx,
- const char * filename,
- int oflag,
- ...);
+int disk_file_open (struct GE_Context *ectx,
+ const char *filename, int oflag, ...);
/**
* Wrapper around "close()". Closes a file.
*/
-void disk_file_close(struct GE_Context * ectx,
- const char * filename,
- int fd);
+void disk_file_close (struct GE_Context *ectx, const char *filename, int fd);
/**
* Read the contents of a binary file into a buffer.
@@ -100,10 +94,8 @@
* @param result the buffer to write the result to
* @return the number of bytes read on success, -1 on failure
*/
-int disk_file_read(struct GE_Context * ectx,
- const char * fileName,
- int len,
- void * result);
+int disk_file_read (struct GE_Context *ectx,
+ const char *fileName, int len, void *result);
/**
* Write a buffer to a file.
@@ -113,28 +105,24 @@
* @param mode the mode for file permissions
* @return OK on success, SYSERR on error
*/
-int disk_file_write(struct GE_Context * ectx,
- const char * fileName,
- const void * buffer,
- unsigned int n,
- const char * mode);
+int disk_file_write (struct GE_Context *ectx,
+ const char *fileName,
+ const void *buffer, unsigned int n, const char *mode);
/**
* Copy a file.
* @return OK on success, SYSERR on error
*/
-int disk_file_copy(struct GE_Context * ectx,
- const char * src,
- const char * dst);
+int disk_file_copy (struct GE_Context *ectx,
+ const char *src, const char *dst);
/**
* Function called on each file in a directory.
* @return OK to continue to iterate,
* SYSERR to abort iteration with error!
*/
-typedef int (*DirectoryEntryCallback)(const char * filename,
- const char * dirName,
- void * data);
+typedef int (*DirectoryEntryCallback) (const char *filename,
+ const char *dirName, void *data);
/**
* Scan a directory for files. The name of the directory
@@ -145,10 +133,9 @@
* @param data argument to pass to callback
* @return the number of files found, -1 on error
*/
-int disk_directory_scan(struct GE_Context * ectx,
- const char * dirName,
- DirectoryEntryCallback callback,
- void * data);
+int disk_directory_scan (struct GE_Context *ectx,
+ const char *dirName,
+ DirectoryEntryCallback callback, void *data);
/**
@@ -158,8 +145,8 @@
* @param filename name of a file in the directory
* @returns OK on success, SYSERR on failure
*/
-int disk_directory_create_for_file(struct GE_Context * ectx,
- const char * filename);
+int disk_directory_create_for_file (struct GE_Context *ectx,
+ const char *filename);
/**
* Test if fil is a directory that can be accessed.
@@ -170,8 +157,7 @@
* @return YES if yes, NO if does not exist, SYSERR
* on any error and if exists but not directory
*/
-int disk_directory_test(struct GE_Context * ectx,
- const char * fil);
+int disk_directory_test (struct GE_Context *ectx, const char *fil);
/**
* Remove all files in a directory (rm -rf). Call with
@@ -180,8 +166,7 @@
* @param fileName the file to remove
* @return OK on success, SYSERR on error
*/
-int disk_directory_remove(struct GE_Context * ectx,
- const char * fileName);
+int disk_directory_remove (struct GE_Context *ectx, const char *fileName);
/**
* Implementation of "mkdir -p"
@@ -189,16 +174,15 @@
* @param dir the directory to create
* @returns SYSERR on failure, OK otherwise
*/
-int disk_directory_create(struct GE_Context * ectx,
- const char * dir);
+int disk_directory_create (struct GE_Context *ectx, const char *dir);
/**
* @brief Removes special characters as ':' from a filename.
* @param fn the filename to canonicalize
*/
-void disk_filename_canonicalize(char *fn);
+void disk_filename_canonicalize (char *fn);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_error.h
===================================================================
--- GNUnet/src/include/gnunet_util_error.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_error.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -31,8 +31,9 @@
#define GNUNET_UTIL_ERROR_VERSION 0x00000000
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -47,16 +48,17 @@
/**
* Classes of log messages.
*/
-typedef enum {
- GE_NOTHING = 0x00000000,
+typedef enum
+{
+ GE_NOTHING = 0x00000000,
/* type of event */
- GE_FATAL = 0x00000001, /* FATAL/FAILURE/NOTHING */
- GE_ERROR = 0x00000002,
- GE_WARNING = 0x00000004,
- GE_INFO = 0x00000008, /* normal program response */
- GE_STATUS = 0x00000010, /* status message */
- GE_DEBUG = 0x00000020, /* DEBUG/CRON/EVERYTHING */
- GE_EVENTKIND = 0x000000FF, /* bitmask */
+ GE_FATAL = 0x00000001, /* FATAL/FAILURE/NOTHING */
+ GE_ERROR = 0x00000002,
+ GE_WARNING = 0x00000004,
+ GE_INFO = 0x00000008, /* normal program response */
+ GE_STATUS = 0x00000010, /* status message */
+ GE_DEBUG = 0x00000020, /* DEBUG/CRON/EVERYTHING */
+ GE_EVENTKIND = 0x000000FF, /* bitmask */
/* who should see the message? */
/**
@@ -65,82 +67,78 @@
* daemon, messages tagged just as GE_USER will
* be discarded.
*/
- GE_USER = 0x01000000, /* current user, if possible */
+ GE_USER = 0x01000000, /* current user, if possible */
/**
* These messages are sent to the logfile for the
* administrator. Note that normal users may not
* always look there.
*/
- GE_ADMIN = 0x02000000, /* system administrator */
+ GE_ADMIN = 0x02000000, /* system administrator */
/**
* These messages are usually not logged or given
* to the user. They can be obtained when the tool
* is run in debug mode.
*/
- GE_DEVELOPER = 0x04000000, /* GNUnet developers (bug!) */
+ GE_DEVELOPER = 0x04000000, /* GNUnet developers (bug!) */
/**
* Mask for the type of user that should see the
* message.
*/
- GE_USERKIND = 0x0F000000, /* bitmask */
+ GE_USERKIND = 0x0F000000, /* bitmask */
/* how event should be routed */
/**
* The message should only be shown upon specific
* request.
*/
- GE_REQUEST = 0x20000000, /* display on request only (i.e. low-priority
log, user demands verbose events) */
+ GE_REQUEST = 0x20000000, /* display on request only (i.e. low-priority
log, user demands verbose events) */
/**
* This type of message is not urgent and is likely
* to occur in bulk. Suitable for logging to a file
* or in a generic, scrolling message window.
*/
- GE_BULK = 0x40000000, /* display in bulk output (i.e. log-file, scroll
window, console) */
+ GE_BULK = 0x40000000, /* display in bulk output (i.e. log-file,
scroll window, console) */
/**
* This is a message that is urgent and should be
* communicated as soon as possible. Sending an
* e-mail alert or opening a pop-up window maybe
* appropriate.
*/
- GE_IMMEDIATE = 0x80000000, /* display immediately (i.e. pop-up, e-mail) */
+ GE_IMMEDIATE = 0x80000000, /* display immediately (i.e. pop-up, e-mail) */
/**
* Mask for the routing type.
*/
- GE_ROUTEKIND = 0xF0000000, /* bitmask */
- GE_ALL = 0xFFFFFFFF,
- GE_INVALID = 0x08000000, /* unused bit */
+ GE_ROUTEKIND = 0xF0000000, /* bitmask */
+ GE_ALL = 0xFFFFFFFF,
+ GE_INVALID = 0x08000000, /* unused bit */
} GE_KIND;
-void GE_LOG(struct GE_Context * ctx,
- GE_KIND kind,
- const char * message,
- ...);
+void GE_LOG (struct GE_Context *ctx, GE_KIND kind, const char *message, ...);
/**
* @brief Get user confirmation (e.g. before the app shuts down and closes the
* error message
*/
-void GE_CONFIRM(struct GE_Context * ctx);
+void GE_CONFIRM (struct GE_Context *ctx);
-void GE_setDefaultContext(struct GE_Context * ctx);
+void GE_setDefaultContext (struct GE_Context *ctx);
/**
* User-defined handler for log events.
*/
-typedef void (*GE_LogHandler)(void * ctx,
- GE_KIND kind,
- const char * date,
- const char * msg);
+typedef void (*GE_LogHandler) (void *ctx,
+ GE_KIND kind,
+ const char *date, const char *msg);
/**
* User-defined method to free handler context.
*/
-typedef void (*GE_CtxFree)(void * ctx);
+typedef void (*GE_CtxFree) (void *ctx);
/**
* User-defined method to wait for user confirmation
*/
-typedef void (*GE_Confirm)(void * ctx);
+typedef void (*GE_Confirm) (void *ctx);
/**
* Create a log context that calls a callback function
@@ -151,17 +149,16 @@
* to be passed to this handler
* @param liberator callback to free ctx, maybe NULL
*/
-struct GE_Context *
-GE_create_context_callback(GE_KIND mask,
- GE_LogHandler handler,
- void * ctx,
- GE_CtxFree liberator,
- GE_Confirm confirm);
+struct GE_Context *GE_create_context_callback (GE_KIND mask,
+ GE_LogHandler handler,
+ void *ctx,
+ GE_CtxFree liberator,
+ GE_Confirm confirm);
/**
* Free a log context.
*/
-void GE_free_context(struct GE_Context * ctx);
+void GE_free_context (struct GE_Context *ctx);
/**
* Does the given event match the mask?
@@ -170,8 +167,7 @@
* @param mask the filter mask
* @return YES or NO
*/
-int GE_applies(GE_KIND have,
- GE_KIND mask);
+int GE_applies (GE_KIND have, GE_KIND mask);
/**
* Would an event of this kind be possibly
@@ -181,30 +177,28 @@
* @param have the kind of event
* @return YES or NO
*/
-int GE_isLogged(struct GE_Context * ctx,
- GE_KIND kind);
+int GE_isLogged (struct GE_Context *ctx, GE_KIND kind);
/**
* Convert a textual description of a loglevel
* to the respective GE_KIND.
* @returns GE_INVALID if log does not parse
*/
-GE_KIND GE_getKIND(const char * log);
+GE_KIND GE_getKIND (const char *log);
/**
* Convert KIND to String
*/
-const char * GE_kindToString(GE_KIND kind);
+const char *GE_kindToString (GE_KIND kind);
/**
* Create a context that sends events to two other contexts.
* Note that the client must stop using ctx1/ctx2 henceforth.
*/
-struct GE_Context *
-GE_create_context_multiplexer(struct GE_Context * ctx1,
- struct GE_Context * ctx2);
+struct GE_Context *GE_create_context_multiplexer (struct GE_Context *ctx1,
+ struct GE_Context *ctx2);
-const char *GE_strerror(int errnum);
+const char *GE_strerror (int errnum);
/**
* If this context would log an event of the given kind,
@@ -284,7 +278,7 @@
#define GE_DIE_STRERROR_FILE(ctx, level, cmd, filename) do { GE_LOG(ctx,
level, _("`%s' failed on file `%s' at %s:%d in %s with error: %s\n"), cmd,
filename,__FILE__, __LINE__, __FUNCTION__, STRERROR(errno)); GE_CONFIRM(ctx);
abort(); } while(0)
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_error_loggers.h
===================================================================
--- GNUnet/src/include/gnunet_util_error_loggers.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/include/gnunet_util_error_loggers.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -29,8 +29,9 @@
#define GNUNET_UTIL_ERROR_LOGGERS_H
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -51,12 +52,10 @@
* value specifies after how many days logs should be deleted)
* (use 0 for no rotation)
*/
-struct GE_Context *
-GE_create_context_logfile(struct GE_Context * ectx,
- GE_KIND mask,
- const char * filename,
- int logDate,
- int logrotate);
+struct GE_Context *GE_create_context_logfile (struct GE_Context *ectx,
+ GE_KIND mask,
+ const char *filename,
+ int logDate, int logrotate);
/**
@@ -64,26 +63,21 @@
*
* @param mask which events should be logged?
*/
-struct GE_Context *
-GE_create_context_stderr(int logDate,
- GE_KIND mask);
+struct GE_Context *GE_create_context_stderr (int logDate, GE_KIND mask);
/**
* Create a logger that writes events to stderr
*
* @param mask which events should be logged?
*/
-struct GE_Context *
-GE_create_context_stdout(int logDate,
- GE_KIND mask);
+struct GE_Context *GE_create_context_stdout (int logDate, GE_KIND mask);
/**
* Create a logger that keeps events in memory (to be
* queried later in bulk).
*/
-struct GE_Context *
-GE_create_context_memory(GE_KIND mask,
- struct GE_Memory * memory);
+struct GE_Context *GE_create_context_memory (GE_KIND mask,
+ struct GE_Memory *memory);
#if FICTION
/**
@@ -95,14 +89,13 @@
* @param bulkSize for GE_BULK messages, how many lines of messages
* should be accumulated before an e-mail is transmitted?
*/
-struct GE_Context *
-GE_create_context_email(struct GE_Context * ectx,
- GE_KIND mask,
- const char * address,
- const char * server,
- unsigned short port,
- int logDate,
- unsigned int bulkSize);
+struct GE_Context *GE_create_context_email (struct GE_Context *ectx,
+ GE_KIND mask,
+ const char *address,
+ const char *server,
+ unsigned short port,
+ int logDate,
+ unsigned int bulkSize);
#endif
/**
@@ -116,30 +109,26 @@
* (if more than maxSize messages are received, message number maxSize
* will be set to a corresponding warning)
*/
-struct GE_Memory *
-GE_memory_create(unsigned int maxSize);
+struct GE_Memory *GE_memory_create (unsigned int maxSize);
/**
* For all messages stored in the memory, call the handler.
* Also clears the memory.
*/
-void GE_memory_poll(struct GE_Memory * memory,
- GE_LogHandler handler,
- void * ctx);
+void GE_memory_poll (struct GE_Memory *memory,
+ GE_LogHandler handler, void *ctx);
-void GE_memory_reset(struct GE_Memory * memory);
+void GE_memory_reset (struct GE_Memory *memory);
/**
* Get a particular log message from the store.
*/
-const char *
-GE_memory_get(struct GE_Memory * memory,
- unsigned int index);
+const char *GE_memory_get (struct GE_Memory *memory, unsigned int index);
-void GE_memory_free(struct GE_Memory * memory);
+void GE_memory_free (struct GE_Memory *memory);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_getopt.h
===================================================================
--- GNUnet/src/include/gnunet_util_getopt.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_getopt.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -29,8 +29,9 @@
#define GNUNET_UTIL_GETOPT_H
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -40,27 +41,28 @@
/**
* @brief General context for command line processors.
*/
-typedef struct {
+typedef struct
+{
/**
* Name of the application
*/
- const char * binaryName;
+ const char *binaryName;
/**
* Name of application with option summary
*/
- const char * binaryOptions;
+ const char *binaryOptions;
/**
* Array with all command line options.
*/
- const struct CommandLineOption * allOptions;
+ const struct CommandLineOption *allOptions;
/**
* Original command line
*/
- char * const * argv;
+ char *const *argv;
/**
* Total number of argv's.
@@ -75,12 +77,12 @@
/**
* For logging errors
*/
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
/**
* For configuration
*/
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
} CommandLineProcessorContext;
@@ -93,15 +95,16 @@
* @param value argument, NULL if none was given
* @return OK to continue processing other options, SYSERR to abort
*/
-typedef int (*CommandLineOptionProcessor)(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value);
-
+typedef int (*CommandLineOptionProcessor) (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option,
+ const char *value);
+
/**
* @brief Definition of a command line option.
*/
-typedef struct CommandLineOption {
+typedef struct CommandLineOption
+{
/**
* Short name of the option (use '\0' for none).
@@ -111,17 +114,17 @@
/**
* Long name of the option (may not be NULL)
*/
- const char * name;
+ const char *name;
/**
* Name of the argument for the user in help text
*/
- const char * argumentHelp;
+ const char *argumentHelp;
/**
* Help text for the option (description)
*/
- const char * description;
+ const char *description;
/**
* Is an argument required? 0: NO (includes optional), 1: YES.
@@ -136,7 +139,7 @@
/**
* Specific closure to pass to the processor.
*/
- void * scls;
+ void *scls;
} CommandLineOption;
@@ -200,56 +203,50 @@
* @return index into argv with first non-option
* argument, or -1 on error
*/
-int gnunet_parse_options(const char * binaryName,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const CommandLineOption * allOptions,
- unsigned int argc,
- char * const * argv);
+int gnunet_parse_options (const char *binaryName,
+ struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const CommandLineOption * allOptions,
+ unsigned int argc, char *const *argv);
-int gnunet_getopt_configure_set_option(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value);
+int gnunet_getopt_configure_set_option (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option,
+ const char *value);
-int gnunet_getopt_configure_set_ulong(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value);
+int gnunet_getopt_configure_set_ulong (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option, const char *value);
-int gnunet_getopt_configure_set_uint(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value);
+int gnunet_getopt_configure_set_uint (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option, const char *value);
-int gnunet_getopt_configure_set_one(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value);
+int gnunet_getopt_configure_set_one (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option, const char *value);
-int gnunet_getopt_configure_set_string(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value);
+int gnunet_getopt_configure_set_string (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option,
+ const char *value);
-int gnunet_getopt_configure_increment_value(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value);
+int gnunet_getopt_configure_increment_value (CommandLineProcessorContext *
+ ctx, void *scls,
+ const char *option,
+ const char *value);
/* *************** internal prototypes - use macros above! ************* */
-int gnunet_getopt_format_help(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value);
+int gnunet_getopt_format_help (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option, const char *value);
-int gnunet_getopt_print_version(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value);
+int gnunet_getopt_print_version (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option, const char *value);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_network.h
===================================================================
--- GNUnet/src/include/gnunet_util_network.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_network.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -38,8 +38,9 @@
#include "gnunet_util_threads.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -52,7 +53,8 @@
/**
* @brief Specify low-level network IO behavior
*/
-typedef enum {
+typedef enum
+{
/**
* Do not block.
@@ -62,13 +64,13 @@
/**
* Call may block.
*/
- NC_Blocking = 0x001,
+ NC_Blocking = 0x001,
/**
* Ignore interrupts (re-try if operation
* was aborted due to interrupt)
*/
- NC_IgnoreInt = 0x010,
+ NC_IgnoreInt = 0x010,
/**
* Always try to read/write the maximum
@@ -76,29 +78,32 @@
* calls). Only return on non-interrupt
* error or if completely done.
*/
- NC_Complete = 0x111,
+ NC_Complete = 0x111,
} NC_KIND;
/**
* @brief 512-bit hashcode
*/
-typedef struct {
- unsigned int bits[512 / 8 / sizeof(unsigned int)]; /* = 16 */
+typedef struct
+{
+ unsigned int bits[512 / 8 / sizeof (unsigned int)]; /* = 16 */
} HashCode512;
/**
* The identity of the host (basically the SHA-512 hashcode of
* it's public key).
*/
-typedef struct {
+typedef struct
+{
HashCode512 hashPubKey;
} PeerIdentity;
/**
* Header for all Client-Server communications.
*/
-typedef struct {
+typedef struct
+{
/**
* The length of the struct (in bytes, including the length field itself)
@@ -115,7 +120,8 @@
/**
* Client-server communication: simple return value
*/
-typedef struct {
+typedef struct
+{
/**
* The CS header (values: sizeof(CS_returnvalue_MESSAGE) + error-size,
CS_PROTO_RETURN_VALUE)
@@ -132,7 +138,8 @@
/**
* Client-server communication: simple error message
*/
-typedef struct {
+typedef struct
+{
/**
* The CS header (values: sizeof(CS_returnvalue_MESSAGE) + error-size,
CS_PROTO_RETURN_VALUE)
@@ -150,7 +157,8 @@
/**
* @brief an IPv4 address
*/
-typedef struct {
+typedef struct
+{
/**
* struct in_addr
*/
@@ -165,7 +173,8 @@
/**
* @brief an IPV6 address.
*/
-typedef struct {
+typedef struct
+{
/**
* struct in6_addr addr;
*/
@@ -195,11 +204,11 @@
* @return OK if message was valid, SYSERR if corresponding
* socket should be closed
*/
-typedef int (*SelectMessageHandler)(void * mh_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * sock_ctx,
- const MESSAGE_HEADER * msg);
+typedef int (*SelectMessageHandler) (void *mh_cls,
+ struct SelectHandle * sh,
+ struct SocketHandle * sock,
+ void *sock_ctx,
+ const MESSAGE_HEADER * msg);
/**
* We've accepted a connection, check that
@@ -212,20 +221,20 @@
* @return NULL to reject connection, otherwise value of sock_ctx
* for the new connection
*/
-typedef void * (*SelectAcceptHandler)(void * ah_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- const void * addr,
- unsigned int addr_len);
+typedef void *(*SelectAcceptHandler) (void *ah_cls,
+ struct SelectHandle * sh,
+ struct SocketHandle * sock,
+ const void *addr,
+ unsigned int addr_len);
/**
* Select has been forced to close a connection.
* Free the associated context.
*/
-typedef void (*SelectCloseHandler)(void * ch_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * sock_ctx);
+typedef void (*SelectCloseHandler) (void *ch_cls,
+ struct SelectHandle * sh,
+ struct SocketHandle * sock,
+ void *sock_ctx);
/* *********************** endianess conversion ************* */
@@ -234,14 +243,14 @@
* @param n the value in network byte order
* @return the same value in host byte order
*/
-unsigned long long ntohll(unsigned long long n);
+unsigned long long ntohll (unsigned long long n);
/**
* Convert a long long to network-byte-order.
* @param n the value in host byte order
* @return the same value in network byte order
*/
-unsigned long long htonll(unsigned long long n);
+unsigned long long htonll (unsigned long long n);
/* ***************** basic parsing **************** */
@@ -256,9 +265,8 @@
* @param routeList a string specifying the forbidden networks
* @return the converted list, NULL if the synatx is flawed
*/
-struct CIDRNetwork *
-parse_ipv4_network_specification(struct GE_Context * ectx,
- const char * routeList);
+struct CIDRNetwork *parse_ipv4_network_specification (struct GE_Context *ectx,
+ const char *routeList);
/**
* Parse a network specification. The argument specifies
@@ -271,9 +279,9 @@
* @param routeList a string specifying the forbidden networks
* @return the converted list, NULL if the synatx is flawed
*/
-struct CIDR6Network *
-parse_ipv6_network_specification(struct GE_Context * ectx,
- const char * routeList);
+struct CIDR6Network *parse_ipv6_network_specification (struct GE_Context
+ *ectx,
+ const char *routeList);
/**
* Check if the given IP address is in the list of
@@ -282,8 +290,7 @@
* @param ip the IP to check (in network byte order)
* @return NO if the IP is not in the list, YES if it it is
*/
-int check_ipv4_listed(const struct CIDRNetwork * list,
- IPaddr ip);
+int check_ipv4_listed (const struct CIDRNetwork *list, IPaddr ip);
/**
* Check if the given IP address is in the list of
@@ -292,8 +299,7 @@
* @param ip the IP to check (in network byte order)
* @return NO if the IP is not in the list, YES if it it is
*/
-int check_ipv6_listed(const struct CIDR6Network * list,
- IP6addr ip);
+int check_ipv6_listed (const struct CIDR6Network *list, IP6addr ip);
#define PRIP(ip) (unsigned int)(((unsigned int)(ip))>>24), \
(unsigned int)((((unsigned)(ip)))>>16 & 255), \
@@ -305,9 +311,8 @@
*
* @return OK on success, SYSERR on error
*/
-int get_host_by_name(struct GE_Context * ectx,
- const char * hostname,
- IPaddr * ip);
+int get_host_by_name (struct GE_Context *ectx,
+ const char *hostname, IPaddr * ip);
/* ********************* low-level socket operations **************** */
@@ -316,20 +321,18 @@
* The OS socket should henceforth be no longer used
* directly. socket_destroy will close it.
*/
-struct SocketHandle *
-socket_create(struct GE_Context * ectx,
- struct LoadMonitor * mon,
- int osSocket);
+struct SocketHandle *socket_create (struct GE_Context *ectx,
+ struct LoadMonitor *mon, int osSocket);
/**
* Close the socket (does NOT destroy it)
*/
-void socket_close(struct SocketHandle * s);
+void socket_close (struct SocketHandle *s);
/**
* Destroy the socket (also closes it).
*/
-void socket_destroy(struct SocketHandle * s);
+void socket_destroy (struct SocketHandle *s);
/**
* Depending on doBlock, enable or disable the nonblocking mode
@@ -338,15 +341,14 @@
* @return Upon successful completion, it returns zero.
* @return Otherwise -1 is returned.
*/
-int socket_set_blocking(struct SocketHandle * s,
- int doBlock);
+int socket_set_blocking (struct SocketHandle *s, int doBlock);
/**
* Check whether the socket is blocking
* @param s the socket
* @return YES if blocking, NO non-blocking
*/
-int socket_test_blocking(struct SocketHandle * s);
+int socket_test_blocking (struct SocketHandle *s);
/**
* Do a read on the given socket.
@@ -361,19 +363,14 @@
* @return SYSERR on error, YES on success or NO if the operation
* would have blocked
*/
-int socket_recv(struct SocketHandle * s,
- NC_KIND nc,
- void * buf,
- size_t max,
- size_t * read);
+int socket_recv (struct SocketHandle *s,
+ NC_KIND nc, void *buf, size_t max, size_t * read);
-int socket_recv_from(struct SocketHandle * s,
- NC_KIND nc,
- void * buf,
- size_t max,
- size_t * read,
- char * from,
- unsigned int * fromlen);
+int socket_recv_from (struct SocketHandle *s,
+ NC_KIND nc,
+ void *buf,
+ size_t max,
+ size_t * read, char *from, unsigned int *fromlen);
/**
* Do a write on the given socket.
@@ -386,25 +383,20 @@
* @return SYSERR on error, YES on success or
* NO if the operation would have blocked.
*/
-int socket_send(struct SocketHandle * s,
- NC_KIND nc,
- const void * buf,
- size_t max,
- size_t * sent);
+int socket_send (struct SocketHandle *s,
+ NC_KIND nc, const void *buf, size_t max, size_t * sent);
-int socket_send_to(struct SocketHandle * s,
- NC_KIND nc,
- const void * buf,
- size_t max,
- size_t * sent,
- const char * dst,
- unsigned int dstlen);
+int socket_send_to (struct SocketHandle *s,
+ NC_KIND nc,
+ const void *buf,
+ size_t max,
+ size_t * sent, const char *dst, unsigned int dstlen);
/**
* Check if socket is valid
* @return YES if valid, NO otherwise
*/
-int socket_test_valid(struct SocketHandle * s);
+int socket_test_valid (struct SocketHandle *s);
/* ********************* select operations **************** */
@@ -428,28 +420,27 @@
* accept at most? 0 for unbounded
* @return NULL on error
*/
-struct SelectHandle *
-select_create(const char * desc,
- int is_udp,
- struct GE_Context * ectx,
- struct LoadMonitor * mon,
- int sock,
- unsigned int max_addr_len,
- cron_t timeout,
- SelectMessageHandler mh,
- void * mh_cls,
- SelectAcceptHandler ah,
- void * ah_cls,
- SelectCloseHandler ch,
- void * ch_cls,
- unsigned int memory_quota,
- int socket_quota);
+struct SelectHandle *select_create (const char *desc,
+ int is_udp,
+ struct GE_Context *ectx,
+ struct LoadMonitor *mon,
+ int sock,
+ unsigned int max_addr_len,
+ cron_t timeout,
+ SelectMessageHandler mh,
+ void *mh_cls,
+ SelectAcceptHandler ah,
+ void *ah_cls,
+ SelectCloseHandler ch,
+ void *ch_cls,
+ unsigned int memory_quota,
+ int socket_quota);
/**
* Terminate the select thread, close the socket and
* all associated connections.
*/
-void select_destroy(struct SelectHandle * sh);
+void select_destroy (struct SelectHandle *sh);
/**
* Queue the given message with the select thread.
@@ -462,11 +453,9 @@
* NO if there was not enough memory to queue it,
* SYSERR if the sock does not belong with this select
*/
-int select_write(struct SelectHandle * sh,
- struct SocketHandle * sock,
- const MESSAGE_HEADER * msg,
- int mayBlock,
- int force);
+int select_write (struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ const MESSAGE_HEADER * msg, int mayBlock, int force);
/**
@@ -481,19 +470,16 @@
* NO if there was not enough memory to queue it,
* SYSERR if the sock does not belong with this select
*/
-int select_would_try(struct SelectHandle * sh,
- struct SocketHandle * sock,
- unsigned int size,
- int mayBlock,
- int force);
+int select_would_try (struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ unsigned int size, int mayBlock, int force);
/**
* Add another (already connected) socket to the set of
* sockets managed by the select.
*/
-int select_connect(struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * sock_ctx);
+int select_connect (struct SelectHandle *sh,
+ struct SocketHandle *sock, void *sock_ctx);
/**
@@ -501,23 +487,20 @@
* value. Use 0 to use the default timeout for
* this select.
*/
-int select_change_timeout(struct SelectHandle * sh,
- struct SocketHandle * sock,
- cron_t timeout);
+int select_change_timeout (struct SelectHandle *sh,
+ struct SocketHandle *sock, cron_t timeout);
/**
*/
-int select_update_closure(struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * old_sock_ctx,
- void * new_sock_ctx);
+int select_update_closure (struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ void *old_sock_ctx, void *new_sock_ctx);
/**
* Close the associated socket and remove it from the
* set of sockets managed by select.
*/
-int select_disconnect(struct SelectHandle * sh,
- struct SocketHandle * sock);
+int select_disconnect (struct SelectHandle *sh, struct SocketHandle *sock);
/**
@@ -528,21 +511,19 @@
*
* @param sa should be of type "struct sockaddr*"
*/
-char * network_get_ip_as_string(const void * sa,
- unsigned int salen,
- int do_resolve);
+char *network_get_ip_as_string (const void *sa,
+ unsigned int salen, int do_resolve);
/**
* Get the IP address for the local machine.
* @return NULL on error, IP as string otherwise
*/
-char * network_get_local_ip(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- IPaddr * addr);
+char *network_get_local_ip (struct GC_Configuration *cfg,
+ struct GE_Context *ectx, IPaddr * addr);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_network_client.h
===================================================================
--- GNUnet/src/include/gnunet_util_network_client.h 2007-07-10 04:03:47 UTC
(rev 5294)
+++ GNUnet/src/include/gnunet_util_network_client.h 2007-07-10 08:36:37 UTC
(rev 5295)
@@ -35,8 +35,9 @@
#include "gnunet_util_network.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -46,9 +47,11 @@
/**
* Get a connection with gnunetd.
*/
-struct ClientServerConnection *
-client_connection_create(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+struct ClientServerConnection *client_connection_create (struct GE_Context
+ *ectx,
+ struct
+ GC_Configuration
+ *cfg);
/**
* Close a GNUnet TCP socket for now (use to temporarily close
@@ -59,7 +62,7 @@
* Also, you must still call connection_destroy to free all
* resources associated with the connection.
*/
-void connection_close_temporarily(struct ClientServerConnection * sock);
+void connection_close_temporarily (struct ClientServerConnection *sock);
/**
* Close a GNUnet TCP socket forever.
@@ -68,13 +71,13 @@
* Also, you must still call connection_destroy to free all
* resources associated with the connection.
*/
-void connection_close_forever(struct ClientServerConnection * sock);
+void connection_close_forever (struct ClientServerConnection *sock);
/**
* Destroy connection between gnunetd and clients.
* Also closes the connection if it is still active.
*/
-void connection_destroy(struct ClientServerConnection * con);
+void connection_destroy (struct ClientServerConnection *con);
/**
* Check if a socket is open. Will ALWAYS return 'true' for a valid
@@ -83,7 +86,7 @@
*
* @return 1 if open, 0 if closed
*/
-int connection_test_open(struct ClientServerConnection * sock);
+int connection_test_open (struct ClientServerConnection *sock);
/**
* Check a socket, open and connect if it is closed and it is a
@@ -91,7 +94,7 @@
*
* @return OK if the socket is now open, SYSERR if not
*/
-int connection_ensure_connected(struct ClientServerConnection * sock);
+int connection_ensure_connected (struct ClientServerConnection *sock);
/**
* Read from a GNUnet client-server connection.
@@ -105,8 +108,8 @@
* read/write call will automatically attempt
* to re-establish the connection).
*/
-int connection_read(struct ClientServerConnection * sock,
- MESSAGE_HEADER ** buffer);
+int connection_read (struct ClientServerConnection *sock,
+ MESSAGE_HEADER ** buffer);
/**
* Write to a GNUnet TCP socket.
@@ -116,8 +119,8 @@
* @return OK if the write was sucessful,
* SYSERR if the write failed (error will be logged)
*/
-int connection_write(struct ClientServerConnection * sock,
- const MESSAGE_HEADER * buffer);
+int connection_write (struct ClientServerConnection *sock,
+ const MESSAGE_HEADER * buffer);
/**
* Obtain a simple return value from the connection.
@@ -131,8 +134,7 @@
* @return SYSERR on error, OK if the return value was
* read successfully
*/
-int connection_read_result(struct ClientServerConnection * sock,
- int * ret);
+int connection_read_result (struct ClientServerConnection *sock, int *ret);
/**
* Send a simple return value to the other side.
@@ -142,8 +144,7 @@
* @return SYSERR on error, OK if the return value was
* send successfully
*/
-int connection_write_result(struct ClientServerConnection * sock,
- int ret);
+int connection_write_result (struct ClientServerConnection *sock, int ret);
/**
* Stop gnunetd
@@ -163,7 +164,7 @@
*
* @return OK successfully stopped, SYSERR: error
*/
-int connection_request_shutdown(struct ClientServerConnection * sock);
+int connection_request_shutdown (struct ClientServerConnection *sock);
/**
* Checks if gnunetd is running
@@ -173,8 +174,8 @@
*
* @return OK if gnunetd is running, SYSERR if not
*/
-int connection_test_running(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+int connection_test_running (struct GE_Context *ectx,
+ struct GC_Configuration *cfg);
/**
* Wait until the gnunet daemon is
@@ -183,11 +184,11 @@
* @param timeout how long to wait at most in ms
* @return OK if gnunetd is now running
*/
-int connection_wait_for_running(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- cron_t timeout);
+int connection_wait_for_running (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ cron_t timeout);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_os.h
===================================================================
--- GNUnet/src/include/gnunet_util_os.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/include/gnunet_util_os.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -36,8 +36,9 @@
#include "gnunet_util_config.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -60,52 +61,49 @@
/**
* TIME prototype. "man time".
*/
-TIME_T TIME(TIME_T * t);
+TIME_T TIME (TIME_T * t);
/**
* "man ctime_r".
* @return character sequence describing the time,
* must be freed by caller
*/
-char * GN_CTIME(const TIME_T * t);
+char *GN_CTIME (const TIME_T * t);
/**
* @param isDefault is this presumably the default interface
* @return OK to continue iteration, SYSERR to abort
*/
-typedef int (*NetworkIfcProcessor)(const char * name,
- int isDefault,
- void * cls);
+typedef int (*NetworkIfcProcessor) (const char *name,
+ int isDefault, void *cls);
-typedef enum {
+typedef enum
+{
Download,
Upload,
} NetworkDirection;
struct LoadMonitor;
-struct IPC_SEMAPHORE *
-IPC_SEMAPHORE_CREATE(struct GE_Context * ectx,
- const char * basename,
- unsigned int initialValue);
+struct IPC_SEMAPHORE *IPC_SEMAPHORE_CREATE (struct GE_Context *ectx,
+ const char *basename,
+ unsigned int initialValue);
-void IPC_SEMAPHORE_DESTROY(struct IPC_SEMAPHORE * sem);
+void IPC_SEMAPHORE_DESTROY (struct IPC_SEMAPHORE *sem);
-void IPC_SEMAPHORE_UP(struct IPC_SEMAPHORE * sem);
+void IPC_SEMAPHORE_UP (struct IPC_SEMAPHORE *sem);
/**
* @return OK on success, SYSERR if would block
*/
-int IPC_SEMAPHORE_DOWN(struct IPC_SEMAPHORE * sem,
- int mayBlock);
+int IPC_SEMAPHORE_DOWN (struct IPC_SEMAPHORE *sem, int mayBlock);
/**
* Load plugin
*/
-struct PluginHandle *
-os_plugin_load(struct GE_Context * ectx,
- const char * libprefix,
- const char * dsoname);
+struct PluginHandle *os_plugin_load (struct GE_Context *ectx,
+ const char *libprefix,
+ const char *dsoname);
/**
* Try resolving a function provided by the plugin
@@ -116,18 +114,15 @@
* with the respective dsoname of the plugin
* @return NULL on error, otherwise pointer to the function
*/
-void *
-os_plugin_resolve_function(struct PluginHandle * plugin,
- const char * methodprefix,
- int logError);
+void *os_plugin_resolve_function (struct PluginHandle *plugin,
+ const char *methodprefix, int logError);
-void os_plugin_unload(struct PluginHandle * plugin);
+void os_plugin_unload (struct PluginHandle *plugin);
-struct LoadMonitor *
-os_network_monitor_create(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+struct LoadMonitor *os_network_monitor_create (struct GE_Context *ectx,
+ struct GC_Configuration *cfg);
-void os_network_monitor_destroy(struct LoadMonitor * mon);
+void os_network_monitor_destroy (struct LoadMonitor *mon);
/**
* Get the load of the network relative to what is allowed.
@@ -135,8 +130,8 @@
* @return the network load as a percentage of allowed
* (100 is equivalent to full load)
*/
-int os_network_monitor_get_load(struct LoadMonitor * monitor,
- NetworkDirection dir);
+int os_network_monitor_get_load (struct LoadMonitor *monitor,
+ NetworkDirection dir);
/**
* Get the total amoung of bandwidth this load monitor allows
@@ -144,37 +139,34 @@
*
* @return the maximum bandwidth in bytes per second, -1 for no limit
*/
-unsigned long long os_network_monitor_get_limit(struct LoadMonitor * monitor,
- NetworkDirection dir);
+unsigned long long os_network_monitor_get_limit (struct LoadMonitor *monitor,
+ NetworkDirection dir);
/**
* Tell monitor to increment the number of bytes sent/received
*/
-void os_network_monitor_notify_transmission(struct LoadMonitor * monitor,
- NetworkDirection dir,
- unsigned long long delta);
+void os_network_monitor_notify_transmission (struct LoadMonitor *monitor,
+ NetworkDirection dir,
+ unsigned long long delta);
/**
* @brief Enumerate all network interfaces
* @param callback the callback function
*/
-void os_list_network_interfaces(struct GE_Context * ectx,
- NetworkIfcProcessor proc,
- void * cls);
+void os_list_network_interfaces (struct GE_Context *ectx,
+ NetworkIfcProcessor proc, void *cls);
/**
* @brief Set maximum number of open file descriptors
* @return OK on success, SYSERR on error
*/
-int os_set_fd_limit(struct GE_Context * ectx,
- int n);
+int os_set_fd_limit (struct GE_Context *ectx, int n);
/**
* Set our process priority
* @return OK on success, SYSERR on error
*/
-int os_set_process_priority(struct GE_Context * ectx,
- const char * str);
+int os_set_process_priority (struct GE_Context *ectx, const char *str);
/**
* @brief Make "application" start automatically
@@ -206,12 +198,11 @@
* Unix
* 2 startup script could not be opened
*/
-int os_modify_autostart(struct GE_Context * ectx,
- int testCapability,
- int doAutoStart,
- const char * application,
- const char * username,
- const char * groupname);
+int os_modify_autostart (struct GE_Context *ectx,
+ int testCapability,
+ int doAutoStart,
+ const char *application,
+ const char *username, const char *groupname);
/**
* @brief Add or remove a service account for GNUnet
@@ -230,25 +221,21 @@
* @param group name of the group
* @return OK on success, SYSERR on error
*/
-int os_modify_user(int testCapability,
- int doAdd,
- const char * name,
- const char * group);
+int os_modify_user (int testCapability,
+ int doAdd, const char *name, const char *group);
/**
* Change current process to run as the given
* user
* @return OK on success, SYSERR on error
*/
-int os_change_user(struct GE_Context * ectx,
- const char * user);
+int os_change_user (struct GE_Context *ectx, const char *user);
/**
* @brief Change owner of a file
*/
-int os_change_owner(struct GE_Context * ectx,
- const char * filename,
- const char * user);
+int os_change_owner (struct GE_Context *ectx,
+ const char *filename, const char *user);
/**
* Get the current CPU load.
@@ -257,8 +244,7 @@
* @return -1 on error, otherwise load value (between 0 and 100,
* (100 is equivalent to full load for one CPU)
*/
-int os_cpu_get_load(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+int os_cpu_get_load (struct GE_Context *ectx, struct GC_Configuration *cfg);
/**
* Get the current IO load.
@@ -269,8 +255,7 @@
* 100 means that we spend all of our cycles waiting for
* the disk)
*/
-int os_disk_get_load(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+int os_disk_get_load (struct GE_Context *ectx, struct GC_Configuration *cfg);
/**
* Start gnunetd process
@@ -280,10 +265,9 @@
* @return pid_t of gnunetd if NOT daemonized, 0 if
* daemonized sucessfully, -1 on error
*/
-int os_daemon_start(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * cfgFile,
- int daemonize);
+int os_daemon_start (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *cfgFile, int daemonize);
/**
* Wait until the gnunet daemon (or any other CHILD process for that
@@ -296,13 +280,13 @@
* failed, NO if gnunetd shutdown with
* some error
*/
-int os_daemon_stop(struct GE_Context * ectx,
- int pid);
+int os_daemon_stop (struct GE_Context *ectx, int pid);
/**
* List of install paths
*/
-enum InstallPathKind {
+enum InstallPathKind
+{
IPK_PREFIX,
IPK_BINDIR,
IPK_LIBDIR,
@@ -317,7 +301,7 @@
* @param cfg the context to get configuration values from
* @return a pointer to the dir path (to be freed by the caller)
*/
-char * os_get_installation_path(enum InstallPathKind dirkind);
+char *os_get_installation_path (enum InstallPathKind dirkind);
/**
* Write our process ID to the pid file. Use only
@@ -326,16 +310,15 @@
*
* @return OK on success, SYSERR on error
*/
-int os_write_pid_file(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- unsigned int pid);
+int os_write_pid_file (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, unsigned int pid);
/**
* Delete the PID file (to be called when the daemon
* shuts down)
*/
-int os_delete_pid_file(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+int os_delete_pid_file (struct GE_Context *ectx,
+ struct GC_Configuration *cfg);
/**
@@ -346,26 +329,24 @@
* @param filedes pointer to an array of 2 file descriptors
* to complete the detachment protocol (handshake)
*/
-int os_terminal_detach(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- int * filedes);
+int os_terminal_detach (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, int *filedes);
/**
* Complete the handshake of detaching from the terminal.
* @param success use NO for error, YES for successful start
*/
-void os_terminal_detach_complete(struct GE_Context * ectx,
- int * filedes,
- int success);
+void os_terminal_detach_complete (struct GE_Context *ectx,
+ int *filedes, int success);
/**
* @brief Perform OS specific initalization
* @param ectx logging context, NULL means stderr
* @returns OK on success, SYSERR otherwise
*/
-int os_init(struct GE_Context *ectx);
+int os_init (struct GE_Context *ectx);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_string.h
===================================================================
--- GNUnet/src/include/gnunet_util_string.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_string.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -40,8 +40,9 @@
#include <stdlib.h>
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -161,21 +162,18 @@
/**
* Like snprintf, just aborts if the buffer is of insufficient size.
*/
-int SNPRINTF(char * buf,
- size_t size,
- const char * format,
- ...);
+int SNPRINTF (char *buf, size_t size, const char *format, ...);
/**
* Give relative time in human-readable fancy format.
* @param delta time in milli seconds
*/
-char * string_get_fancy_time_interval(unsigned long long delta);
+char *string_get_fancy_time_interval (unsigned long long delta);
/**
* Convert a given filesize into a fancy human-readable format.
*/
-char * string_get_fancy_byte_size(unsigned long long size);
+char *string_get_fancy_byte_size (unsigned long long size);
/**
* Convert the len characters long character sequence
@@ -184,10 +182,9 @@
*
* @return the converted string (0-terminated)
*/
-char * string_convertToUtf8(struct GE_Context * ectx,
- const char * input,
- size_t len,
- const char * charset);
+char *string_convertToUtf8 (struct GE_Context *ectx,
+ const char *input,
+ size_t len, const char *charset);
/**
* Complete filename (a la shell) from abbrevition.
@@ -197,22 +194,17 @@
* @returns the full file name,
* NULL is returned on error
*/
-char * string_expandFileName(struct GE_Context * ectx,
- const char * fil);
+char *string_expandFileName (struct GE_Context *ectx, const char *fil);
/**
* String functions
*/
#if !HAVE_STRLCPY
-size_t strlcpy(char *dest,
- const char *src,
- size_t size);
+size_t strlcpy (char *dest, const char *src, size_t size);
#endif
#if !HAVE_STRLCAT
-size_t strlcat(char *dest,
- const char *src,
- size_t count);
+size_t strlcat (char *dest, const char *src, size_t count);
#endif
@@ -223,10 +215,8 @@
* memory is available. Don't use xmalloc_ directly. Use the
* MALLOC macro.
*/
-void * xmalloc_(size_t size,
- const char * filename,
- int linenumber,
- const char * function);
+void *xmalloc_ (size_t size,
+ const char *filename, int linenumber, const char *function);
/**
* Allocate memory. This function does not check if the
@@ -234,39 +224,32 @@
* allocations larger than 40 MB. If you don't expect the
* possibility of very large allocations, use MALLOC instead.
*/
-void * xmalloc_unchecked_(size_t size,
- const char * filename,
- int linenumber,
- const char * function);
+void *xmalloc_unchecked_ (size_t size,
+ const char *filename,
+ int linenumber, const char *function);
/**
* Reallocate memory. Checks the return value, aborts if no more
* memory is available.
*/
-void * xrealloc_(void * ptr,
- const size_t n,
- const char * filename,
- int linenumber,
- const char * function);
+void *xrealloc_ (void *ptr,
+ const size_t n,
+ const char *filename, int linenumber, const char *function);
/**
* Free memory. Merely a wrapper for the case that we
* want to keep track of allocations. Don't use xfree_
* directly. Use the FREE macro.
*/
-void xfree_(void * ptr,
- const char * filename,
- int linenumber,
- const char * function);
+void xfree_ (void *ptr,
+ const char *filename, int linenumber, const char *function);
/**
* Dup a string. Don't call xstrdup_ directly. Use the STRDUP macro.
*/
-char * xstrdup_(const char * str,
- const char * filename,
- int linenumber,
- const char * function);
+char *xstrdup_ (const char *str,
+ const char *filename, int linenumber, const char *function);
/**
* Dup a string. Don't call xstrdup_ directly. Use the STRDUP macro.
@@ -277,11 +260,9 @@
* @param linenumber where in the code was the call to GROW
* @return strdup(str)
*/
-char * xstrndup_(const char * str,
- const size_t n,
- const char * filename,
- int linenumber,
- const char * function);
+char *xstrndup_ (const char *str,
+ const size_t n,
+ const char *filename, int linenumber, const char *function);
/**
* Grow an array, the new elements are zeroed out.
@@ -296,15 +277,13 @@
* @param oldCount address of the number of elements in the *old array
* @param newCount number of elements in the new array, may be 0 (then *old
will be NULL afterwards)
*/
-void xgrow_(void ** old,
- size_t elementSize,
- unsigned int * oldCount,
- unsigned int newCount,
- const char * filename,
- int linenumber,
- const char * function);
+void xgrow_ (void **old,
+ size_t elementSize,
+ unsigned int *oldCount,
+ unsigned int newCount,
+ const char *filename, int linenumber, const char *function);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/gnunet_util_threads.h
===================================================================
--- GNUnet/src/include/gnunet_util_threads.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/include/gnunet_util_threads.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -33,8 +33,9 @@
#define GNUNET_UTIL_THREADS_H
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -67,7 +68,7 @@
/**
* Main method of a thread.
*/
-typedef void * (*PThreadMain)(void*);
+typedef void *(*PThreadMain) (void *);
/**
* @brief Encapsulation of a pthread handle.
@@ -87,18 +88,18 @@
/**
* Returns YES if pt is the handle for THIS thread.
*/
-int PTHREAD_TEST_SELF(struct PTHREAD * pt);
+int PTHREAD_TEST_SELF (struct PTHREAD *pt);
/**
* Get the handle for THIS thread.
*/
-struct PTHREAD * PTHREAD_GET_SELF(void);
+struct PTHREAD *PTHREAD_GET_SELF (void);
/**
* Release handle for a thread (should have been
* obtained using PTHREAD_GET_SELF).
*/
-void PTHREAD_REL_SELF(struct PTHREAD * pt);
+void PTHREAD_REL_SELF (struct PTHREAD *pt);
/**
* Create a thread. Use this method instead of pthread_create since
@@ -111,9 +112,8 @@
* will just segfault and gdb will give a messed-up stacktrace.
* @return the handle
*/
-struct PTHREAD * PTHREAD_CREATE(PThreadMain main,
- void * arg,
- unsigned int stackSize);
+struct PTHREAD *PTHREAD_CREATE (PThreadMain main,
+ void *arg, unsigned int stackSize);
@@ -123,10 +123,8 @@
*
* @param ret set to the return value of the other thread.
*/
-void PTHREAD_JOIN_FL(struct PTHREAD * handle,
- void ** ret,
- const char * file,
- unsigned int line);
+void PTHREAD_JOIN_FL (struct PTHREAD *handle,
+ void **ret, const char *file, unsigned int line);
/**
* Wait for the other thread to terminate. May only be called
@@ -143,35 +141,33 @@
*
* @param time how long to sleep (in milli seconds)
*/
-void PTHREAD_SLEEP(cron_t time);
+void PTHREAD_SLEEP (cron_t time);
/**
* Get the current time (in cron-units).
*
* @return the current time
*/
-cron_t get_time(void);
+cron_t get_time (void);
/**
* Stop the sleep of anothe thread.
*/
-void PTHREAD_STOP_SLEEP(struct PTHREAD * handle);
+void PTHREAD_STOP_SLEEP (struct PTHREAD *handle);
-struct MUTEX * MUTEX_CREATE(int isRecursive);
+struct MUTEX *MUTEX_CREATE (int isRecursive);
-void MUTEX_DESTROY(struct MUTEX * mutex);
+void MUTEX_DESTROY (struct MUTEX *mutex);
-void MUTEX_LOCK_FL(struct MUTEX * mutex,
- const char * file,
- unsigned int line);
+void MUTEX_LOCK_FL (struct MUTEX *mutex, const char *file, unsigned int line);
#define MUTEX_LOCK(mutex) MUTEX_LOCK_FL(mutex, __FILE__, __LINE__)
-void MUTEX_UNLOCK(struct MUTEX * mutex);
+void MUTEX_UNLOCK (struct MUTEX *mutex);
-struct SEMAPHORE * SEMAPHORE_CREATE(int value);
+struct SEMAPHORE *SEMAPHORE_CREATE (int value);
-void SEMAPHORE_DESTROY(struct SEMAPHORE * sem);
+void SEMAPHORE_DESTROY (struct SEMAPHORE *sem);
/**
* @param block set to NO to never block (and
@@ -179,11 +175,9 @@
* @return SYSERR if would block, otherwise
* new count value after change
*/
-int SEMAPHORE_DOWN_FL(struct SEMAPHORE * sem,
- int mayblock,
- int longwait,
- const char * file,
- unsigned int line);
+int SEMAPHORE_DOWN_FL (struct SEMAPHORE *sem,
+ int mayblock,
+ int longwait, const char *file, unsigned int line);
/**
@@ -214,19 +208,19 @@
*
* @return new count value of the semaphore after increment
*/
-int SEMAPHORE_UP(struct SEMAPHORE * sem);
+int SEMAPHORE_UP (struct SEMAPHORE *sem);
/**
* Programatically shutdown the application.
*/
-void GNUNET_SHUTDOWN_INITIATE(void);
+void GNUNET_SHUTDOWN_INITIATE (void);
/**
* Test if the shutdown has been initiated.
*
* @return YES if we are shutting down, NO otherwise
*/
-int GNUNET_SHUTDOWN_TEST(void);
+int GNUNET_SHUTDOWN_TEST (void);
/**
* Wait until the shutdown has been initiated. This
@@ -234,7 +228,7 @@
* nothing better to do) to wait for a user signal
* (or other thread) to initiate the shutdown.
*/
-void GNUNET_SHUTDOWN_WAITFOR(void);
+void GNUNET_SHUTDOWN_WAITFOR (void);
struct SignalHandlerContext;
@@ -246,20 +240,20 @@
* the implementation must guarantee that this handler is not called
* for signals other than the one that it has been registered for.
*/
-typedef void (*SignalHandler)(void);
+typedef void (*SignalHandler) (void);
/**
* Install a signal handler that will be run if the
* given signal is received.
*/
-struct SignalHandlerContext * signal_handler_install(int signal,
- SignalHandler handler);
+struct SignalHandlerContext *signal_handler_install (int signal,
+ SignalHandler handler);
-void signal_handler_uninstall(int signal,
- SignalHandler handler,
- struct SignalHandlerContext * ctx);
+void signal_handler_uninstall (int signal,
+ SignalHandler handler,
+ struct SignalHandlerContext *ctx);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/include/platform.h
===================================================================
--- GNUnet/src/include/platform.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/include/platform.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -65,30 +65,30 @@
#define VERBOSE_STATS 0
#ifdef CYGWIN
- #include <sys/reent.h>
- #define _REENT_ONLY
+#include <sys/reent.h>
+#define _REENT_ONLY
#endif
#ifdef CYGWIN
- #undef _REENT_ONLY
+#undef _REENT_ONLY
#endif
#ifdef _MSC_VER
- #include <Winsock2.h>
+#include <Winsock2.h>
#else
#ifndef MINGW
- #include <netdb.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <netinet/tcp.h>
- #include <netinet/in.h>
- #include <pwd.h>
- #include <sys/ioctl.h>
- #include <sys/wait.h>
- #include <grp.h>
+#include <netdb.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <netinet/tcp.h>
+#include <netinet/in.h>
+#include <pwd.h>
+#include <sys/ioctl.h>
+#include <sys/wait.h>
+#include <grp.h>
#else
- #include "winproc.h"
+#include "winproc.h"
#endif
#endif
@@ -97,17 +97,17 @@
#include <stdlib.h>
#include <stdarg.h>
#ifndef _MSC_VER
-#include <ltdl.h> /* KLB_FIX */
+#include <ltdl.h> /* KLB_FIX */
#endif
#include <errno.h>
#include <signal.h>
#ifndef _MSC_VER
-#include <unistd.h> /* KLB_FIX */
+#include <unistd.h> /* KLB_FIX */
#endif
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _MSC_VER
-#include <dirent.h> /* KLB_FIX */
+#include <dirent.h> /* KLB_FIX */
#endif
#include <fcntl.h>
#include <math.h>
@@ -126,10 +126,10 @@
#endif
#ifdef SOMEBSD
- #include <net/if.h>
+#include <net/if.h>
#endif
#ifdef FREEBSD
- #include <semaphore.h>
+#include <semaphore.h>
#endif
#ifdef OSX
#include <dlfcn.h>
@@ -173,9 +173,9 @@
#define _(String) dgettext("GNUnet",String)
#ifdef CYGWIN
- #define SIOCGIFCONF _IOW('s', 100, struct ifconf) /* get if list */
- #define SIOCGIFFLAGS _IOW('s', 101, struct ifreq) /* Get if flags */
- #define SIOCGIFADDR _IOW('s', 102, struct ifreq) /* Get if addr */
+#define SIOCGIFCONF _IOW('s', 100, struct ifconf) /* get if list */
+#define SIOCGIFFLAGS _IOW('s', 101, struct ifreq) /* Get if flags */
+#define SIOCGIFADDR _IOW('s', 102, struct ifreq) /* Get if addr */
#endif
#ifndef MINGW
@@ -183,17 +183,17 @@
#endif
#ifdef OSX
- #define socklen_t unsigned int
- #define __BYTE_ORDER BYTE_ORDER
- #define __BIG_ENDIAN BIG_ENDIAN
+#define socklen_t unsigned int
+#define __BYTE_ORDER BYTE_ORDER
+#define __BIG_ENDIAN BIG_ENDIAN
/* not available on OS X, override configure */
- #undef HAVE_STAT64
- #undef HAVE_MREMAP
+#undef HAVE_STAT64
+#undef HAVE_MREMAP
#endif
#if !HAVE_ATOLL
-long long atoll(const char *nptr);
+long long atoll (const char *nptr);
#endif
#if ENABLE_NLS
Modified: GNUnet/src/include/plibc.h
===================================================================
--- GNUnet/src/include/plibc.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/include/plibc.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -29,21 +29,22 @@
#define _PLIBC_H_
#ifndef SIGALRM
- #define SIGALRM 14
+#define SIGALRM 14
#endif
#ifdef __cplusplus
-extern "C" {
+extern "C"
+{
#endif
#ifdef Q_OS_WIN32
- #define WINDOWS 1
+#define WINDOWS 1
#endif
#ifdef WINDOWS
#if ENABLE_NLS
- #include "langinfo.h"
+#include "langinfo.h"
#endif
#include <windows.h>
@@ -75,8 +76,8 @@
#define int64_t long long
#define int32_t long
-struct stat64
-{
+ struct stat64
+ {
_dev_t st_dev;
_ino_t st_ino;
_mode_t st_mode;
@@ -88,112 +89,112 @@
__time64_t st_atime;
__time64_t st_mtime;
__time64_t st_ctime;
-};
+ };
#ifndef pid_t
- #define pid_t int
+#define pid_t int
#endif
#ifndef WEXITSTATUS
- #define WEXITSTATUS(status) (((status) & 0xff00) >> 8)
+#define WEXITSTATUS(status) (((status) & 0xff00) >> 8)
#endif
/* Thanks to the Cygwin project */
-#define ENOCSI 43 /* No CSI structure available */
-#define EL2HLT 44 /* Level 2 halted */
+#define ENOCSI 43 /* No CSI structure available */
+#define EL2HLT 44 /* Level 2 halted */
#ifndef EDEADLK
- #define EDEADLK 45 /* Deadlock condition */
+#define EDEADLK 45 /* Deadlock condition */
#endif
#ifndef ENOLCK
- #define ENOLCK 46 /* No record locks available */
+#define ENOLCK 46 /* No record locks available */
#endif
-#define EBADE 50 /* Invalid exchange */
-#define EBADR 51 /* Invalid request descriptor */
-#define EXFULL 52 /* Exchange full */
-#define ENOANO 53 /* No anode */
-#define EBADRQC 54 /* Invalid request code */
-#define EBADSLT 55 /* Invalid slot */
+#define EBADE 50 /* Invalid exchange */
+#define EBADR 51 /* Invalid request descriptor */
+#define EXFULL 52 /* Exchange full */
+#define ENOANO 53 /* No anode */
+#define EBADRQC 54 /* Invalid request code */
+#define EBADSLT 55 /* Invalid slot */
#ifndef EDEADLOCK
- #define EDEADLOCK EDEADLK /* File locking deadlock error */
+#define EDEADLOCK EDEADLK /* File locking deadlock error */
#endif
-#define EBFONT 57 /* Bad font file fmt */
-#define ENOSTR 60 /* Device not a stream */
-#define ENODATA 61 /* No data (for no delay io) */
-#define ETIME 62 /* Timer expired */
-#define ENOSR 63 /* Out of streams resources */
-#define ENONET 64 /* Machine is not on the network */
-#define ENOPKG 65 /* Package not installed */
-#define EREMOTE 66 /* The object is remote */
-#define ENOLINK 67 /* The link has been severed */
-#define EADV 68 /* Advertise error */
-#define ESRMNT 69 /* Srmount error */
-#define ECOMM 70 /* Communication error on send */
-#define EPROTO 71 /* Protocol error */
-#define EMULTIHOP 74 /* Multihop attempted */
-#define ELBIN 75 /* Inode is remote (not really error) */
-#define EDOTDOT 76 /* Cross mount point (not really error) */
-#define EBADMSG 77 /* Trying to read unreadable message */
-#define ENOTUNIQ 80 /* Given log. name not unique */
-#define EBADFD 81 /* f.d. invalid for this operation */
-#define EREMCHG 82 /* Remote address changed */
-#define ELIBACC 83 /* Can't access a needed shared lib */
-#define ELIBBAD 84 /* Accessing a corrupted shared lib */
-#define ELIBSCN 85 /* .lib section in a.out corrupted */
-#define ELIBMAX 86 /* Attempting to link in too many libs */
-#define ELIBEXEC 87 /* Attempting to exec a shared library */
+#define EBFONT 57 /* Bad font file fmt */
+#define ENOSTR 60 /* Device not a stream */
+#define ENODATA 61 /* No data (for no delay io) */
+#define ETIME 62 /* Timer expired */
+#define ENOSR 63 /* Out of streams resources */
+#define ENONET 64 /* Machine is not on the network */
+#define ENOPKG 65 /* Package not installed */
+#define EREMOTE 66 /* The object is remote */
+#define ENOLINK 67 /* The link has been severed */
+#define EADV 68 /* Advertise error */
+#define ESRMNT 69 /* Srmount error */
+#define ECOMM 70 /* Communication error on send */
+#define EPROTO 71 /* Protocol error */
+#define EMULTIHOP 74 /* Multihop attempted */
+#define ELBIN 75 /* Inode is remote (not really error) */
+#define EDOTDOT 76 /* Cross mount point (not really error) */
+#define EBADMSG 77 /* Trying to read unreadable message */
+#define ENOTUNIQ 80 /* Given log. name not unique */
+#define EBADFD 81 /* f.d. invalid for this operation */
+#define EREMCHG 82 /* Remote address changed */
+#define ELIBACC 83 /* Can't access a needed shared lib */
+#define ELIBBAD 84 /* Accessing a corrupted shared lib */
+#define ELIBSCN 85 /* .lib section in a.out corrupted */
+#define ELIBMAX 86 /* Attempting to link in too many libs */
+#define ELIBEXEC 87 /* Attempting to exec a shared library */
#ifndef ENOSYS
- #define ENOSYS 88 /* Function not implemented */
+#define ENOSYS 88 /* Function not implemented */
#endif
-#define ENMFILE 89 /* No more files */
+#define ENMFILE 89 /* No more files */
#ifndef ENOTEMPTY
- #define ENOTEMPTY 90 /* Directory not empty */
+#define ENOTEMPTY 90 /* Directory not empty */
#endif
#ifndef ENAMETOOLONG
- #define ENAMETOOLONG 91 /* File or path name too long */
+#define ENAMETOOLONG 91 /* File or path name too long */
#endif
-#define ELOOP 92 /* Too many symbolic links */
-#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */
-#define EPFNOSUPPORT 96 /* Protocol family not supported */
-#define ECONNRESET 104 /* Connection reset by peer */
-#define ENOBUFS 105 /* No buffer space available */
-#define EAFNOSUPPORT 106 /* Address family not supported by protocol family */
-#define EPROTOTYPE 107 /* Protocol wrong type for socket */
-#define ENOTSOCK 108 /* Socket operation on non-socket */
-#define ENOPROTOOPT 109 /* Protocol not available */
-#define ESHUTDOWN 110 /* Can't send after socket shutdown */
-#define ECONNREFUSED 111 /* Connection refused */
-#define EADDRINUSE 112 /* Address already in use */
-#define ECONNABORTED 113 /* Connection aborted */
-#define ENETUNREACH 114 /* Network is unreachable */
-#define ENETDOWN 115 /* Network interface is not configured */
+#define ELOOP 92 /* Too many symbolic links */
+#define EOPNOTSUPP 95 /* Operation not supported on transport
endpoint */
+#define EPFNOSUPPORT 96 /* Protocol family not supported */
+#define ECONNRESET 104 /* Connection reset by peer */
+#define ENOBUFS 105 /* No buffer space available */
+#define EAFNOSUPPORT 106 /* Address family not supported by protocol
family */
+#define EPROTOTYPE 107 /* Protocol wrong type for socket */
+#define ENOTSOCK 108 /* Socket operation on non-socket */
+#define ENOPROTOOPT 109 /* Protocol not available */
+#define ESHUTDOWN 110 /* Can't send after socket shutdown */
+#define ECONNREFUSED 111 /* Connection refused */
+#define EADDRINUSE 112 /* Address already in use */
+#define ECONNABORTED 113 /* Connection aborted */
+#define ENETUNREACH 114 /* Network is unreachable */
+#define ENETDOWN 115 /* Network interface is not configured */
#ifndef ETIMEDOUT
- #define ETIMEDOUT 116 /* Connection timed out */
+#define ETIMEDOUT 116 /* Connection timed out */
#endif
-#define EHOSTDOWN 117 /* Host is down */
-#define EHOSTUNREACH 118 /* Host is unreachable */
-#define EINPROGRESS 119 /* Connection already in progress */
-#define EALREADY 120 /* Socket already connected */
-#define EDESTADDRREQ 121 /* Destination address required */
-#define EMSGSIZE 122 /* Message too long */
-#define EPROTONOSUPPORT 123 /* Unknown protocol */
-#define ESOCKTNOSUPPORT 124 /* Socket type not supported */
-#define EADDRNOTAVAIL 125 /* Address not available */
-#define ENETRESET 126 /* Connection aborted by network */
-#define EISCONN 127 /* Socket is already connected */
-#define ENOTCONN 128 /* Socket is not connected */
-#define ETOOMANYREFS 129 /* Too many references: cannot splice */
-#define EPROCLIM 130 /* Too many processes */
-#define EUSERS 131 /* Too many users */
-#define EDQUOT 132 /* Disk quota exceeded */
-#define ESTALE 133 /* Unknown error */
+#define EHOSTDOWN 117 /* Host is down */
+#define EHOSTUNREACH 118 /* Host is unreachable */
+#define EINPROGRESS 119 /* Connection already in progress */
+#define EALREADY 120 /* Socket already connected */
+#define EDESTADDRREQ 121 /* Destination address required */
+#define EMSGSIZE 122 /* Message too long */
+#define EPROTONOSUPPORT 123 /* Unknown protocol */
+#define ESOCKTNOSUPPORT 124 /* Socket type not supported */
+#define EADDRNOTAVAIL 125 /* Address not available */
+#define ENETRESET 126 /* Connection aborted by network */
+#define EISCONN 127 /* Socket is already connected */
+#define ENOTCONN 128 /* Socket is not connected */
+#define ETOOMANYREFS 129 /* Too many references: cannot splice */
+#define EPROCLIM 130 /* Too many processes */
+#define EUSERS 131 /* Too many users */
+#define EDQUOT 132 /* Disk quota exceeded */
+#define ESTALE 133 /* Unknown error */
#ifndef ENOTSUP
- #define ENOTSUP 134 /* Not supported */
+#define ENOTSUP 134 /* Not supported */
#endif
-#define ENOMEDIUM 135 /* No medium (in tape drive) */
-#define ENOSHARE 136 /* No such host or network path */
-#define ECASECLASH 137 /* Filename exists with different case */
-#define EWOULDBLOCK EAGAIN /* Operation would block */
-#define EOVERFLOW 139 /* Value too large for defined data type */
+#define ENOMEDIUM 135 /* No medium (in tape drive) */
+#define ENOSHARE 136 /* No such host or network path */
+#define ECASECLASH 137 /* Filename exists with different case */
+#define EWOULDBLOCK EAGAIN /* Operation would block */
+#define EOVERFLOW 139 /* Value too large for defined data type */
#undef HOST_NOT_FOUND
#define HOST_NOT_FOUND 1
@@ -207,65 +208,65 @@
#define PROT_READ 0x1
#define PROT_WRITE 0x2
#define MAP_SHARED 0x1
-#define MAP_PRIVATE 0x2 /* unsupported */
+#define MAP_PRIVATE 0x2 /* unsupported */
#define MAP_FIXED 0x10
#define MAP_FAILED ((void *)-1)
-struct statfs
-{
- long f_type; /* type of filesystem (see below) */
- long f_bsize; /* optimal transfer block size */
- long f_blocks; /* total data blocks in file system */
- long f_bfree; /* free blocks in fs */
- long f_bavail; /* free blocks avail to non-superuser */
- long f_files; /* total file nodes in file system */
- long f_ffree; /* free file nodes in fs */
- long f_fsid; /* file system id */
- long f_namelen; /* maximum length of filenames */
- long f_spare[6]; /* spare for later */
-};
+ struct statfs
+ {
+ long f_type; /* type of filesystem (see below) */
+ long f_bsize; /* optimal transfer block size */
+ long f_blocks; /* total data blocks in file system */
+ long f_bfree; /* free blocks in fs */
+ long f_bavail; /* free blocks avail to non-superuser */
+ long f_files; /* total file nodes in file system */
+ long f_ffree; /* free file nodes in fs */
+ long f_fsid; /* file system id */
+ long f_namelen; /* maximum length of filenames */
+ long f_spare[6]; /* spare for later */
+ };
/* Taken from the Wine project <http://www.winehq.org>
/wine/include/winternl.h */
-enum SYSTEM_INFORMATION_CLASS
-{
- SystemBasicInformation = 0,
- Unknown1,
- SystemPerformanceInformation = 2,
- SystemTimeOfDayInformation = 3, /* was SystemTimeInformation */
- Unknown4,
- SystemProcessInformation = 5,
- Unknown6,
- Unknown7,
- SystemProcessorPerformanceInformation = 8,
- Unknown9,
- Unknown10,
- SystemDriverInformation,
- Unknown12,
- Unknown13,
- Unknown14,
- Unknown15,
- SystemHandleList,
- Unknown17,
- Unknown18,
- Unknown19,
- Unknown20,
- SystemCacheInformation,
- Unknown22,
- SystemInterruptInformation = 23,
- SystemExceptionInformation = 33,
- SystemRegistryQuotaInformation = 37,
- SystemLookasideInformation = 45
-};
+ enum SYSTEM_INFORMATION_CLASS
+ {
+ SystemBasicInformation = 0,
+ Unknown1,
+ SystemPerformanceInformation = 2,
+ SystemTimeOfDayInformation = 3, /* was SystemTimeInformation */
+ Unknown4,
+ SystemProcessInformation = 5,
+ Unknown6,
+ Unknown7,
+ SystemProcessorPerformanceInformation = 8,
+ Unknown9,
+ Unknown10,
+ SystemDriverInformation,
+ Unknown12,
+ Unknown13,
+ Unknown14,
+ Unknown15,
+ SystemHandleList,
+ Unknown17,
+ Unknown18,
+ Unknown19,
+ Unknown20,
+ SystemCacheInformation,
+ Unknown22,
+ SystemInterruptInformation = 23,
+ SystemExceptionInformation = 33,
+ SystemRegistryQuotaInformation = 37,
+ SystemLookasideInformation = 45
+ };
-typedef struct
-{
+ typedef struct
+ {
LARGE_INTEGER IdleTime;
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER Reserved1[2];
ULONG Reserved2;
-} SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION;
+ } SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION;
#define sleep(secs) (Sleep(secs * 1000))
@@ -282,11 +283,11 @@
#define SHUT_RDWR SD_BOTH
/* Operations for flock() */
-#define LOCK_SH 1 /* shared lock */
-#define LOCK_EX 2 /* exclusive lock */
-#define LOCK_NB 4 /* or'd with one of the above to prevent
- blocking */
-#define LOCK_UN 8 /* remove lock */
+#define LOCK_SH 1 /* shared lock */
+#define LOCK_EX 2 /* exclusive lock */
+#define LOCK_NB 4 /* or'd with one of the above to prevent
+ blocking */
+#define LOCK_UN 8 /* remove lock */
/* Not supported under MinGW */
#define S_IRGRP 0
@@ -312,273 +313,274 @@
*/
#define index(s, c) strchr(s, c)
-BOOL _plibc_CreateShortcut(const char *pszSrc, const char *pszDest);
-BOOL _plibc_DereferenceShortcut(char *pszShortcut);
-char *plibc_ChooseDir(char *pszTitle, unsigned long ulFlags);
-char *plibc_ChooseFile(char *pszTitle, unsigned long ulFlags);
-long QueryRegistry(HKEY hMainKey, char *pszKey, char *pszSubKey,
- char *pszBuffer, long *pdLength);
+ BOOL _plibc_CreateShortcut (const char *pszSrc, const char *pszDest);
+ BOOL _plibc_DereferenceShortcut (char *pszShortcut);
+ char *plibc_ChooseDir (char *pszTitle, unsigned long ulFlags);
+ char *plibc_ChooseFile (char *pszTitle, unsigned long ulFlags);
+ long QueryRegistry (HKEY hMainKey, char *pszKey, char *pszSubKey,
+ char *pszBuffer, long *pdLength);
-BOOL __win_IsHandleMarkedAsBlocking(SOCKET hHandle);
-void __win_SetHandleBlockingMode(SOCKET s, BOOL bBlocking);
-void __win_DiscardHandleBlockingMode(SOCKET s);
-int _win_isSocketValid(int s);
-int plibc_conv_to_win_path(const char *pszUnix, char *pszWindows);
+ BOOL __win_IsHandleMarkedAsBlocking (SOCKET hHandle);
+ void __win_SetHandleBlockingMode (SOCKET s, BOOL bBlocking);
+ void __win_DiscardHandleBlockingMode (SOCKET s);
+ int _win_isSocketValid (int s);
+ int plibc_conv_to_win_path (const char *pszUnix, char *pszWindows);
-typedef void (*TPanicProc) (int, char *);
-void plibc_set_panic_proc(TPanicProc proc);
+ typedef void (*TPanicProc) (int, char *);
+ void plibc_set_panic_proc (TPanicProc proc);
-int flock(int fd, int operation);
-int fsync(int fildes);
-int inet_pton(int af, const char *src, void *dst);
-int inet_pton4(const char *src, u_char *dst, int pton);
+ int flock (int fd, int operation);
+ int fsync (int fildes);
+ int inet_pton (int af, const char *src, void *dst);
+ int inet_pton4 (const char *src, u_char * dst, int pton);
#if USE_IPV6
-int inet_pton6(const char *src, u_char *dst);
+ int inet_pton6 (const char *src, u_char * dst);
#endif
-int truncate(const char *fname, int distance);
-int statfs(const char *path, struct statfs *buf);
-const char *hstrerror(int err);
-void gettimeofday(struct timeval *tp, void *tzp);
-int mkstemp(char *tmplate);
-char *strptime (const char *buf, const char *format, struct tm *tm);
-char *ctime(const time_t *clock);
-char *ctime_r(const time_t *clock, char *buf);
-const char *inet_ntop(int af, const void *src, char *dst, size_t size);
-int plibc_init(char *pszOrg, char *pszApp);
-void plibc_shutdown();
-int plibc_initialized();
-int plibc_conv_to_win_path_ex(const char *pszUnix, char *pszWindows, int
derefLinks);
-void _SetErrnoFromWinError(long lWinError, char *pszCaller, int iLine);
-void SetErrnoFromWinsockError(long lWinError);
-void SetHErrnoFromWinError(long lWinError);
-void SetErrnoFromHRESULT(HRESULT hRes);
-FILE *_win_fopen(const char *filename, const char *mode);
-DIR *_win_opendir(const char *dirname);
-int _win_open(const char *filename, int oflag, ...);
+ int truncate (const char *fname, int distance);
+ int statfs (const char *path, struct statfs *buf);
+ const char *hstrerror (int err);
+ void gettimeofday (struct timeval *tp, void *tzp);
+ int mkstemp (char *tmplate);
+ char *strptime (const char *buf, const char *format, struct tm *tm);
+ char *ctime (const time_t * clock);
+ char *ctime_r (const time_t * clock, char *buf);
+ const char *inet_ntop (int af, const void *src, char *dst, size_t size);
+ int plibc_init (char *pszOrg, char *pszApp);
+ void plibc_shutdown ();
+ int plibc_initialized ();
+ int plibc_conv_to_win_path_ex (const char *pszUnix, char *pszWindows,
+ int derefLinks);
+ void _SetErrnoFromWinError (long lWinError, char *pszCaller, int iLine);
+ void SetErrnoFromWinsockError (long lWinError);
+ void SetHErrnoFromWinError (long lWinError);
+ void SetErrnoFromHRESULT (HRESULT hRes);
+ FILE *_win_fopen (const char *filename, const char *mode);
+ DIR *_win_opendir (const char *dirname);
+ int _win_open (const char *filename, int oflag, ...);
#ifdef ENABLE_NLS
-char *_win_bindtextdomain(const char *domainname, const char *dirname);
+ char *_win_bindtextdomain (const char *domainname, const char *dirname);
#endif
-int _win_chdir(const char *path);
-int _win_close(int fd);
-int _win_creat(const char *path, mode_t mode);
-int _win_fstat(int handle, struct stat *buffer);
-int _win_pipe(int *phandles);
-int _win_rmdir(const char *path);
-int _win_access( const char *path, int mode );
-int _win_chmod(const char *filename, int pmode);
-char *realpath(const char *file_name, char *resolved_name);
-long _win_random(void);
-int _win_remove(const char *path);
-int _win_rename(const char *oldname, const char *newname);
-int _win_stat(const char *path, struct stat *buffer);
-int _win_stat64(const char *path, struct stat64 *buffer);
-int _win_unlink(const char *filename);
-int _win_write(int fildes, const void *buf, size_t nbyte);
-int _win_read(int fildes, void *buf, size_t nbyte);
-size_t _win_fwrite(const void *buffer, size_t size, size_t count, FILE
*stream);
-size_t _win_fread( void *buffer, size_t size, size_t count, FILE *stream );
-int _win_symlink(const char *path1, const char *path2);
-void *_win_mmap(void *start, size_t len, int access, int flags, int fd,
- unsigned long long offset);
-int _win_munmap(void *start, size_t length);
-int _win_lstat(const char *path, struct stat *buf);
-int _win_lstat64(const char *path, struct stat64 *buf);
-int _win_readlink(const char *path, char *buf, size_t bufsize);
-int _win_accept(SOCKET s, struct sockaddr *addr, int *addrlen);
-int _win_printf(const char *format,...);
-int _win_fprintf(FILE *f,const char *format,...);
-int _win_vprintf(const char *format, va_list ap);
-int _win_vfprintf(FILE *stream, const char *format, va_list arg_ptr);
-int _win_vsprintf(char *dest,const char *format, va_list arg_ptr);
-int _win_vsnprintf(char* str, size_t size, const char *format, va_list
arg_ptr);
-int _win_snprintf(char *str,size_t size,const char *format,...);
-int _win_sprintf(char *dest,const char *format,...);
-int _win_vsscanf(const char* str, const char* format, va_list arg_ptr);
-int _win_sscanf(const char *str, const char *format, ...);
-int _win_vfscanf(FILE *stream, const char *format, va_list arg_ptr);
-int _win_vscanf(const char *format, va_list arg_ptr);
-int _win_scanf(const char *format, ...);
-int _win_fscanf(FILE *stream, const char *format, ...);
-pid_t _win_waitpid(pid_t pid, int *stat_loc, int options);
-int _win_bind(SOCKET s, const struct sockaddr *name, int namelen);
-int _win_connect(SOCKET s,const struct sockaddr *name, int namelen);
-int _win_getpeername(SOCKET s, struct sockaddr *name,
- int *namelen);
-int _win_getsockname(SOCKET s, struct sockaddr *name,
- int *namelen);
-int _win_getsockopt(SOCKET s, int level, int optname, char *optval,
- int *optlen);
-int _win_listen(SOCKET s, int backlog);
-int _win_recv(SOCKET s, char *buf, int len, int flags);
-int _win_recvfrom(SOCKET s, void *buf, int len, int flags,
- struct sockaddr *from, int *fromlen);
-int _win_select(int max_fd, fd_set * rfds, fd_set * wfds, fd_set * efds,
- const struct timeval *tv);
-int _win_send(SOCKET s, const char *buf, int len, int flags);
-int _win_sendto(SOCKET s, const char *buf, int len, int flags,
- const struct sockaddr *to, int tolen);
-int _win_setsockopt(SOCKET s, int level, int optname, const void *optval,
- int optlen);
-int _win_shutdown(SOCKET s, int how);
-SOCKET _win_socket(int af, int type, int protocol);
-struct hostent *_win_gethostbyaddr(const char *addr, int len, int type);
-struct hostent *_win_gethostbyname(const char *name);
-char *_win_strerror(int errnum);
-int IsWinNT();
+ int _win_chdir (const char *path);
+ int _win_close (int fd);
+ int _win_creat (const char *path, mode_t mode);
+ int _win_fstat (int handle, struct stat *buffer);
+ int _win_pipe (int *phandles);
+ int _win_rmdir (const char *path);
+ int _win_access (const char *path, int mode);
+ int _win_chmod (const char *filename, int pmode);
+ char *realpath (const char *file_name, char *resolved_name);
+ long _win_random (void);
+ int _win_remove (const char *path);
+ int _win_rename (const char *oldname, const char *newname);
+ int _win_stat (const char *path, struct stat *buffer);
+ int _win_stat64 (const char *path, struct stat64 *buffer);
+ int _win_unlink (const char *filename);
+ int _win_write (int fildes, const void *buf, size_t nbyte);
+ int _win_read (int fildes, void *buf, size_t nbyte);
+ size_t _win_fwrite (const void *buffer, size_t size, size_t count,
+ FILE * stream);
+ size_t _win_fread (void *buffer, size_t size, size_t count, FILE * stream);
+ int _win_symlink (const char *path1, const char *path2);
+ void *_win_mmap (void *start, size_t len, int access, int flags, int fd,
+ unsigned long long offset);
+ int _win_munmap (void *start, size_t length);
+ int _win_lstat (const char *path, struct stat *buf);
+ int _win_lstat64 (const char *path, struct stat64 *buf);
+ int _win_readlink (const char *path, char *buf, size_t bufsize);
+ int _win_accept (SOCKET s, struct sockaddr *addr, int *addrlen);
+ int _win_printf (const char *format, ...);
+ int _win_fprintf (FILE * f, const char *format, ...);
+ int _win_vprintf (const char *format, va_list ap);
+ int _win_vfprintf (FILE * stream, const char *format, va_list arg_ptr);
+ int _win_vsprintf (char *dest, const char *format, va_list arg_ptr);
+ int _win_vsnprintf (char *str, size_t size, const char *format,
+ va_list arg_ptr);
+ int _win_snprintf (char *str, size_t size, const char *format, ...);
+ int _win_sprintf (char *dest, const char *format, ...);
+ int _win_vsscanf (const char *str, const char *format, va_list arg_ptr);
+ int _win_sscanf (const char *str, const char *format, ...);
+ int _win_vfscanf (FILE * stream, const char *format, va_list arg_ptr);
+ int _win_vscanf (const char *format, va_list arg_ptr);
+ int _win_scanf (const char *format, ...);
+ int _win_fscanf (FILE * stream, const char *format, ...);
+ pid_t _win_waitpid (pid_t pid, int *stat_loc, int options);
+ int _win_bind (SOCKET s, const struct sockaddr *name, int namelen);
+ int _win_connect (SOCKET s, const struct sockaddr *name, int namelen);
+ int _win_getpeername (SOCKET s, struct sockaddr *name, int *namelen);
+ int _win_getsockname (SOCKET s, struct sockaddr *name, int *namelen);
+ int _win_getsockopt (SOCKET s, int level, int optname, char *optval,
+ int *optlen);
+ int _win_listen (SOCKET s, int backlog);
+ int _win_recv (SOCKET s, char *buf, int len, int flags);
+ int _win_recvfrom (SOCKET s, void *buf, int len, int flags,
+ struct sockaddr *from, int *fromlen);
+ int _win_select (int max_fd, fd_set * rfds, fd_set * wfds, fd_set * efds,
+ const struct timeval *tv);
+ int _win_send (SOCKET s, const char *buf, int len, int flags);
+ int _win_sendto (SOCKET s, const char *buf, int len, int flags,
+ const struct sockaddr *to, int tolen);
+ int _win_setsockopt (SOCKET s, int level, int optname, const void *optval,
+ int optlen);
+ int _win_shutdown (SOCKET s, int how);
+ SOCKET _win_socket (int af, int type, int protocol);
+ struct hostent *_win_gethostbyaddr (const char *addr, int len, int type);
+ struct hostent *_win_gethostbyname (const char *name);
+ char *_win_strerror (int errnum);
+ int IsWinNT ();
#if !HAVE_STRNDUP
-char *strndup (const char *s, size_t n);
+ char *strndup (const char *s, size_t n);
#endif
#if !HAVE_STRNLEN
-size_t strnlen (const char *str, size_t maxlen);
+ size_t strnlen (const char *str, size_t maxlen);
#endif
#define strcasecmp(a, b) stricmp(a, b)
#define strncasecmp(a, b, c) strnicmp(a, b, c)
-#endif /* WINDOWS */
+#endif /* WINDOWS */
#ifndef WINDOWS
- #define DIR_SEPARATOR '/'
- #define DIR_SEPARATOR_STR "/"
- #define PATH_SEPARATOR ';'
- #define PATH_SEPARATOR_STR ";"
- #define NEWLINE "\n"
+#define DIR_SEPARATOR '/'
+#define DIR_SEPARATOR_STR "/"
+#define PATH_SEPARATOR ';'
+#define PATH_SEPARATOR_STR ";"
+#define NEWLINE "\n"
#ifdef ENABLE_NLS
- #define BINDTEXTDOMAIN(d, n) bindtextdomain(d, n)
+#define BINDTEXTDOMAIN(d, n) bindtextdomain(d, n)
#endif
- #define CREAT(p, m) creat(p, m)
- #undef FOPEN
- #define FOPEN(f, m) fopen(f, m)
- #define OPENDIR(d) opendir(d)
- #define OPEN(f) open(f)
- #define CHDIR(d) chdir(d)
- #define CLOSE(f) close(f)
- #define RMDIR(f) rmdir(f)
- #define ACCESS(p, m) access(p, m)
- #define CHMOD(f, p) chmod(f, p)
- #define FSTAT(h, b) fstat(h, b)
- #define PIPE(h) pipe(h)
- #define REMOVE(p) remove(p)
- #define RENAME(o, n) rename(o, n)
- #define STAT(p, b) stat(p, b)
- #define STAT64(p, b) stat64(p, b)
- #define UNLINK(f) unlink(f)
- #define WRITE(f, b, n) write(f, b, n)
- #define READ(f, b, n) read(f, b, n)
- #define GN_FREAD(b, s, c, f) fread(b, s, c, f)
- #define GN_FWRITE(b, s, c, f) fwrite(b, s, c, f)
- #define SYMLINK(a, b) symlink(a, b)
- #define MMAP(s, l, p, f, d, o) mmap(s, l, p, f, d, o)
- #define MUNMAP(s, l) munmap(s, l)
- #define STRERROR(i) strerror(i)
- #define RANDOM() random()
- #define READLINK(p, b, s) readlink(p, b, s)
- #define LSTAT(p, b) lstat(p, b)
- #define LSTAT64(p, b) lstat64(p, b)
- #define PRINTF printf
- #define FPRINTF fprintf
- #define VPRINTF(f, a) vprintf(f, a)
- #define VFPRINTF(s, f, a) vfprintf(s, f, a)
- #define VSPRINTF(d, f, a) vsprintf(d, f, a)
- #define VSNPRINTF(str, size, fmt, a) vsnprintf(str, size, fmt, a)
- #define _REAL_SNPRINTF snprintf
- #define SPRINTF sprintf
- #define VSSCANF(s, f, a) vsscanf(s, f, a)
- #define SSCANF sscanf
- #define VFSCANF(s, f, a) vfscanf(s, f, a)
- #define VSCANF(f, a) vscanf(f, a)
- #define SCANF scanf
- #define FSCANF fscanf
- #define WAITPID(p, s, o) waitpid(p, s, o)
- #define ACCEPT(s, a, l) accept(s, a, l)
- #define BIND(s, n, l) bind(s, n, l)
- #define CONNECT(s, n, l) connect(s, n, l)
- #define GETPEERNAME(s, n, l) getpeername(s, n, l)
- #define GETSOCKNAME(s, n, l) getsockname(s, n, l)
- #define GETSOCKOPT(s, l, o, v, p) getsockopt(s, l, o, v, p)
- #define LISTEN(s, b) listen(s, b)
- #define RECV(s, b, l, f) recv(s, b, l, f)
- #define RECVFROM(s, b, l, f, r, o) recvfrom(s, b, l, f, r, o)
- #define SELECT(n, r, w, e, t) select(n, r, w, e, t)
- #define SEND(s, b, l, f) send(s, b, l, f)
- #define SENDTO(s, b, l, f, o, n) sendto(s, b, l, f, o, n)
- #define SETSOCKOPT(s, l, o, v, n) setsockopt(s, l, o, v, n)
- #define SHUTDOWN(s, h) shutdown(s, h)
- #define SOCKET(a, t, p) socket(a, t, p)
- #define GETHOSTBYADDR(a, l, t) gethostbyname(a, l, t)
- #define GETHOSTBYNAME(n) gethostbyname(n)
+#define CREAT(p, m) creat(p, m)
+#undef FOPEN
+#define FOPEN(f, m) fopen(f, m)
+#define OPENDIR(d) opendir(d)
+#define OPEN(f) open(f)
+#define CHDIR(d) chdir(d)
+#define CLOSE(f) close(f)
+#define RMDIR(f) rmdir(f)
+#define ACCESS(p, m) access(p, m)
+#define CHMOD(f, p) chmod(f, p)
+#define FSTAT(h, b) fstat(h, b)
+#define PIPE(h) pipe(h)
+#define REMOVE(p) remove(p)
+#define RENAME(o, n) rename(o, n)
+#define STAT(p, b) stat(p, b)
+#define STAT64(p, b) stat64(p, b)
+#define UNLINK(f) unlink(f)
+#define WRITE(f, b, n) write(f, b, n)
+#define READ(f, b, n) read(f, b, n)
+#define GN_FREAD(b, s, c, f) fread(b, s, c, f)
+#define GN_FWRITE(b, s, c, f) fwrite(b, s, c, f)
+#define SYMLINK(a, b) symlink(a, b)
+#define MMAP(s, l, p, f, d, o) mmap(s, l, p, f, d, o)
+#define MUNMAP(s, l) munmap(s, l)
+#define STRERROR(i) strerror(i)
+#define RANDOM() random()
+#define READLINK(p, b, s) readlink(p, b, s)
+#define LSTAT(p, b) lstat(p, b)
+#define LSTAT64(p, b) lstat64(p, b)
+#define PRINTF printf
+#define FPRINTF fprintf
+#define VPRINTF(f, a) vprintf(f, a)
+#define VFPRINTF(s, f, a) vfprintf(s, f, a)
+#define VSPRINTF(d, f, a) vsprintf(d, f, a)
+#define VSNPRINTF(str, size, fmt, a) vsnprintf(str, size, fmt, a)
+#define _REAL_SNPRINTF snprintf
+#define SPRINTF sprintf
+#define VSSCANF(s, f, a) vsscanf(s, f, a)
+#define SSCANF sscanf
+#define VFSCANF(s, f, a) vfscanf(s, f, a)
+#define VSCANF(f, a) vscanf(f, a)
+#define SCANF scanf
+#define FSCANF fscanf
+#define WAITPID(p, s, o) waitpid(p, s, o)
+#define ACCEPT(s, a, l) accept(s, a, l)
+#define BIND(s, n, l) bind(s, n, l)
+#define CONNECT(s, n, l) connect(s, n, l)
+#define GETPEERNAME(s, n, l) getpeername(s, n, l)
+#define GETSOCKNAME(s, n, l) getsockname(s, n, l)
+#define GETSOCKOPT(s, l, o, v, p) getsockopt(s, l, o, v, p)
+#define LISTEN(s, b) listen(s, b)
+#define RECV(s, b, l, f) recv(s, b, l, f)
+#define RECVFROM(s, b, l, f, r, o) recvfrom(s, b, l, f, r, o)
+#define SELECT(n, r, w, e, t) select(n, r, w, e, t)
+#define SEND(s, b, l, f) send(s, b, l, f)
+#define SENDTO(s, b, l, f, o, n) sendto(s, b, l, f, o, n)
+#define SETSOCKOPT(s, l, o, v, n) setsockopt(s, l, o, v, n)
+#define SHUTDOWN(s, h) shutdown(s, h)
+#define SOCKET(a, t, p) socket(a, t, p)
+#define GETHOSTBYADDR(a, l, t) gethostbyname(a, l, t)
+#define GETHOSTBYNAME(n) gethostbyname(n)
#else
- #define DIR_SEPARATOR '\\'
- #define DIR_SEPARATOR_STR "\\"
- #define PATH_SEPARATOR ':'
- #define PATH_SEPARATOR_STR ":"
- #define NEWLINE "\r\n"
+#define DIR_SEPARATOR '\\'
+#define DIR_SEPARATOR_STR "\\"
+#define PATH_SEPARATOR ':'
+#define PATH_SEPARATOR_STR ":"
+#define NEWLINE "\r\n"
#ifdef ENABLE_NLS
- #define BINDTEXTDOMAIN(d, n) _win_bindtextdomain(d, n)
+#define BINDTEXTDOMAIN(d, n) _win_bindtextdomain(d, n)
#endif
- #define CREAT(p, m) _win_creat(p, m)
- #define FOPEN(f, m) _win_fopen(f, m)
- #define OPENDIR(d) _win_opendir(d)
- #define OPEN(f) _win_open(f)
- #define CHDIR(d) _win_chdir(d)
- #define CLOSE(f) _win_close(f)
- #define FSTAT(h, b) _win_fstat(h, b)
- #define RMDIR(f) _win_rmdir(f)
- #define ACCESS(p, m) _win_access(p, m)
- #define CHMOD(f, p) _win_chmod(f, p)
- #define PIPE(h) _win_pipe(h)
- #define RANDOM() _win_random()
- #define REMOVE(p) _win_remove(p)
- #define RENAME(o, n) _win_rename(o, n)
- #define STAT(p, b) _win_stat(p, b)
- #define STAT64(p, b) _win_stat64(p, b)
- #define UNLINK(f) _win_unlink(f)
- #define WRITE(f, b, n) _win_write(f, b, n)
- #define READ(f, b, n) _win_read(f, b, n)
- #define GN_FREAD(b, s, c, f) _win_fread(b, s, c, f)
- #define GN_FWRITE(b, s, c, f) _win_fwrite(b, s, c, f)
- #define SYMLINK(a, b) _win_symlink(a, b)
- #define MMAP(s, l, p, f, d, o) _win_mmap(s, l, p, f, d, o)
- #define MUNMAP(s, l) _win_munmap(s, l)
- #define STRERROR(i) _win_strerror(i)
- #define READLINK(p, b, s) _win_readlink(p, b, s)
- #define LSTAT(p, b) _win_lstat(p, b)
- #define LSTAT64(p, b) _win_lstat64(p, b)
- #define PRINTF(f, ...) _win_printf(f , __VA_ARGS__)
- #define FPRINTF(fil, fmt, ...) _win_fprintf(fil, fmt, __VA_ARGS__)
- #define VPRINTF(f, a) _win_vprintf(f, a)
- #define VFPRINTF(s, f, a) _win_vfprintf(s, f, a)
- #define VSPRINTF(d, f, a) _win_vsprintf(d, f, a)
- #define VSNPRINTF(str, size, fmt, a) _win_vsnprintf(str, size, fmt, a)
- #define _REAL_SNPRINTF(str, size, fmt, ...) _win_snprintf(str, size, fmt,
__VA_ARGS__)
- #define SPRINTF(d, f, ...) _win_sprintf(d, f, __VA_ARGS__)
- #define VSSCANF(s, f, a) _win_vsscanf(s, f, a)
- #define SSCANF(s, f, ...) _win_sscanf(s, f, __VA_ARGS__)
- #define VFSCANF(s, f, a) _win_vfscanf(s, f, a)
- #define VSCANF(f, a) _win_vscanf(f, a)
- #define SCANF(f, ...) _win_scanf(f, __VA_ARGS__)
- #define FSCANF(s, f, ...) _win_fscanf(s, f, __VA_ARGS__)
- #define WAITPID(p, s, o) _win_waitpid(p, s, o)
- #define ACCEPT(s, a, l) _win_accept(s, a, l)
- #define BIND(s, n, l) _win_bind(s, n, l)
- #define CONNECT(s, n, l) _win_connect(s, n, l)
- #define GETPEERNAME(s, n, l) _win_getpeername(s, n, l)
- #define GETSOCKNAME(s, n, l) _win_getsockname(s, n, l)
- #define GETSOCKOPT(s, l, o, v, p) _win_getsockopt(s, l, o, v, p)
- #define LISTEN(s, b) _win_listen(s, b)
- #define RECV(s, b, l, f) _win_recv(s, b, l, f)
- #define RECVFROM(s, b, l, f, r, o) _win_recvfrom(s, b, l, f, r, o)
- #define SELECT(n, r, w, e, t) _win_select(n, r, w, e, t)
- #define SEND(s, b, l, f) _win_send(s, b, l, f)
- #define SENDTO(s, b, l, f, o, n) _win_sendto(s, b, l, f, o, n)
- #define SETSOCKOPT(s, l, o, v, n) _win_setsockopt(s, l, o, v, n)
- #define SHUTDOWN(s, h) _win_shutdown(s, h)
- #define SOCKET(a, t, p) _win_socket(a, t, p)
- #define GETHOSTBYADDR(a, l, t) _win_gethostbyname(a, l, t)
- #define GETHOSTBYNAME(n) _win_gethostbyname(n)
+#define CREAT(p, m) _win_creat(p, m)
+#define FOPEN(f, m) _win_fopen(f, m)
+#define OPENDIR(d) _win_opendir(d)
+#define OPEN(f) _win_open(f)
+#define CHDIR(d) _win_chdir(d)
+#define CLOSE(f) _win_close(f)
+#define FSTAT(h, b) _win_fstat(h, b)
+#define RMDIR(f) _win_rmdir(f)
+#define ACCESS(p, m) _win_access(p, m)
+#define CHMOD(f, p) _win_chmod(f, p)
+#define PIPE(h) _win_pipe(h)
+#define RANDOM() _win_random()
+#define REMOVE(p) _win_remove(p)
+#define RENAME(o, n) _win_rename(o, n)
+#define STAT(p, b) _win_stat(p, b)
+#define STAT64(p, b) _win_stat64(p, b)
+#define UNLINK(f) _win_unlink(f)
+#define WRITE(f, b, n) _win_write(f, b, n)
+#define READ(f, b, n) _win_read(f, b, n)
+#define GN_FREAD(b, s, c, f) _win_fread(b, s, c, f)
+#define GN_FWRITE(b, s, c, f) _win_fwrite(b, s, c, f)
+#define SYMLINK(a, b) _win_symlink(a, b)
+#define MMAP(s, l, p, f, d, o) _win_mmap(s, l, p, f, d, o)
+#define MUNMAP(s, l) _win_munmap(s, l)
+#define STRERROR(i) _win_strerror(i)
+#define READLINK(p, b, s) _win_readlink(p, b, s)
+#define LSTAT(p, b) _win_lstat(p, b)
+#define LSTAT64(p, b) _win_lstat64(p, b)
+#define PRINTF(f, ...) _win_printf(f , __VA_ARGS__)
+#define FPRINTF(fil, fmt, ...) _win_fprintf(fil, fmt, __VA_ARGS__)
+#define VPRINTF(f, a) _win_vprintf(f, a)
+#define VFPRINTF(s, f, a) _win_vfprintf(s, f, a)
+#define VSPRINTF(d, f, a) _win_vsprintf(d, f, a)
+#define VSNPRINTF(str, size, fmt, a) _win_vsnprintf(str, size, fmt, a)
+#define _REAL_SNPRINTF(str, size, fmt, ...) _win_snprintf(str, size, fmt,
__VA_ARGS__)
+#define SPRINTF(d, f, ...) _win_sprintf(d, f, __VA_ARGS__)
+#define VSSCANF(s, f, a) _win_vsscanf(s, f, a)
+#define SSCANF(s, f, ...) _win_sscanf(s, f, __VA_ARGS__)
+#define VFSCANF(s, f, a) _win_vfscanf(s, f, a)
+#define VSCANF(f, a) _win_vscanf(f, a)
+#define SCANF(f, ...) _win_scanf(f, __VA_ARGS__)
+#define FSCANF(s, f, ...) _win_fscanf(s, f, __VA_ARGS__)
+#define WAITPID(p, s, o) _win_waitpid(p, s, o)
+#define ACCEPT(s, a, l) _win_accept(s, a, l)
+#define BIND(s, n, l) _win_bind(s, n, l)
+#define CONNECT(s, n, l) _win_connect(s, n, l)
+#define GETPEERNAME(s, n, l) _win_getpeername(s, n, l)
+#define GETSOCKNAME(s, n, l) _win_getsockname(s, n, l)
+#define GETSOCKOPT(s, l, o, v, p) _win_getsockopt(s, l, o, v, p)
+#define LISTEN(s, b) _win_listen(s, b)
+#define RECV(s, b, l, f) _win_recv(s, b, l, f)
+#define RECVFROM(s, b, l, f, r, o) _win_recvfrom(s, b, l, f, r, o)
+#define SELECT(n, r, w, e, t) _win_select(n, r, w, e, t)
+#define SEND(s, b, l, f) _win_send(s, b, l, f)
+#define SENDTO(s, b, l, f, o, n) _win_sendto(s, b, l, f, o, n)
+#define SETSOCKOPT(s, l, o, v, n) _win_setsockopt(s, l, o, v, n)
+#define SHUTDOWN(s, h) _win_shutdown(s, h)
+#define SOCKET(a, t, p) _win_socket(a, t, p)
+#define GETHOSTBYADDR(a, l, t) _win_gethostbyname(a, l, t)
+#define GETHOSTBYNAME(n) _win_gethostbyname(n)
#endif
@@ -587,6 +589,6 @@
#endif
-#endif //_PLIBC_H_
+#endif //_PLIBC_H_
/* end of plibc.h */
Modified: GNUnet/src/include/winproc.h
===================================================================
--- GNUnet/src/include/winproc.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/include/winproc.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -40,7 +40,7 @@
#include <iphlpapi.h>
#include <shlobj.h>
#include <objbase.h>
-#include <sys/param.h> /* #define BYTE_ORDER */
+#include <sys/param.h> /* #define BYTE_ORDER */
#include <Ntsecapi.h>
#include <lm.h>
#include <Aclapi.h>
@@ -48,126 +48,167 @@
#include "platform.h"
#ifdef __cplusplus
-extern "C" {
+extern "C"
+{
#endif
#ifndef MAX_NAME_LENGTH
- #define MAX_NAME_LENGTH 25
+#define MAX_NAME_LENGTH 25
#endif
-typedef DWORD WINAPI (*TNtQuerySystemInformation) (int, PVOID, ULONG, PULONG);
-typedef DWORD WINAPI (*TGetIfEntry) (PMIB_IFROW pIfRow);
-typedef DWORD WINAPI (*TGetIpAddrTable) (PMIB_IPADDRTABLE pIpAddrTable,
- PULONG pdwSize, BOOL bOrder);
-typedef DWORD WINAPI (*TGetIfTable) (PMIB_IFTABLE pIfTable, PULONG pdwSize,
- BOOL bOrder);
-typedef DWORD WINAPI (*TCreateHardLink) (LPCTSTR lpFileName,
- LPCTSTR lpExistingFileName, LPSECURITY_ATTRIBUTES
- lpSecurityAttributes);
-typedef SC_HANDLE WINAPI (*TOpenSCManager) (LPCTSTR lpMachineName,
- LPCTSTR lpDatabaseName, DWORD dwDesiredAccess);
-typedef SC_HANDLE WINAPI (*TCreateService) (SC_HANDLE hSCManager,
- LPCTSTR lpServiceName, LPCTSTR lpDisplayName,
- DWORD dwDesiredAccess, DWORD dwServiceType,
- DWORD dwStartType, DWORD dwErrorControl,
- LPCTSTR lpBinaryPathName, LPCTSTR lpLoadOrderGroup,
- LPDWORD lpdwTagId, LPCTSTR lpDependencies,
- LPCTSTR lpServiceStartName, LPCTSTR lpPassword);
-typedef BOOL WINAPI (*TCloseServiceHandle) (SC_HANDLE hSCObject);
-typedef BOOL WINAPI (*TDeleteService) (SC_HANDLE hService);
-typedef SERVICE_STATUS_HANDLE WINAPI (*TRegisterServiceCtrlHandler) (
- LPCTSTR lpServiceName,
- LPHANDLER_FUNCTION lpHandlerProc);
-typedef BOOL WINAPI (*TSetServiceStatus) (SERVICE_STATUS_HANDLE hServiceStatus,
- LPSERVICE_STATUS lpServiceStatus);
-typedef BOOL WINAPI (*TStartServiceCtrlDispatcher) (const LPSERVICE_TABLE_ENTRY
- lpServiceTable);
-typedef BOOL WINAPI (*TControlService) (SC_HANDLE hService, DWORD dwControl,
- LPSERVICE_STATUS lpServiceStatus);
-typedef SC_HANDLE WINAPI (*TOpenService) (SC_HANDLE hSCManager, LPCTSTR
lpServiceName,
- DWORD dwDesiredAccess);
-typedef DWORD WINAPI (*TGetBestInterface) (IPAddr dwDestAddr, PDWORD
pdwBestIfIndex);
-typedef DWORD WINAPI (*TGetAdaptersInfo) (PIP_ADAPTER_INFO pAdapterInfo,
PULONG pOutBufLen);
-typedef NET_API_STATUS WINAPI (*TNetUserAdd) (LPCWSTR,DWORD,PBYTE,PDWORD);
-typedef NET_API_STATUS WINAPI (*TNetUserSetInfo) (LPCWSTR servername, LPCWSTR
username,
- DWORD level, LPBYTE buf, LPDWORD parm_err);
-typedef NTSTATUS NTAPI (*TLsaOpenPolicy) (PLSA_UNICODE_STRING,
PLSA_OBJECT_ATTRIBUTES,
- ACCESS_MASK,PLSA_HANDLE);
-typedef NTSTATUS NTAPI (*TLsaAddAccountRights)
(LSA_HANDLE,PSID,PLSA_UNICODE_STRING,ULONG);
-typedef NTSTATUS NTAPI (*TLsaRemoveAccountRights) (LSA_HANDLE,PSID,BOOLEAN,
- PLSA_UNICODE_STRING,ULONG);
-typedef NTSTATUS NTAPI (*TLsaClose) (LSA_HANDLE);
-typedef BOOL WINAPI (*TLookupAccountName) (LPCTSTR lpSystemName, LPCTSTR
lpAccountName,
- PSID Sid, LPDWORD cbSid, LPTSTR ReferencedDomainName,
- LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse);
-
-typedef BOOL WINAPI (*TGetFileSecurity) (LPCTSTR lpFileName,
- SECURITY_INFORMATION RequestedInformation, PSECURITY_DESCRIPTOR
pSecurityDescriptor,
- DWORD nLength, LPDWORD lpnLengthNeeded);
-typedef BOOL WINAPI (*TInitializeSecurityDescriptor) (PSECURITY_DESCRIPTOR
pSecurityDescriptor,
- DWORD dwRevision);
-typedef BOOL WINAPI (*TGetSecurityDescriptorDacl) (PSECURITY_DESCRIPTOR
pSecurityDescriptor,
- LPBOOL lpbDaclPresent, PACL* pDacl, LPBOOL lpbDaclDefaulted);
-typedef BOOL WINAPI (*TGetAclInformation) (PACL pAcl, LPVOID pAclInformation,
- DWORD nAclInformationLength, ACL_INFORMATION_CLASS dwAclInformationClass);
-typedef BOOL WINAPI (*TInitializeAcl) (PACL pAcl, DWORD nAclLength, DWORD
dwAclRevision);
-typedef BOOL WINAPI (*TGetAce) (PACL pAcl, DWORD dwAceIndex, LPVOID* pAce);
-typedef BOOL WINAPI (*TEqualSid) (PSID pSid1, PSID pSid2);
-typedef BOOL WINAPI (*TAddAce) (PACL pAcl, DWORD dwAceRevision, DWORD
dwStartingAceIndex,
- LPVOID pAceList, DWORD nAceListLength);
-typedef BOOL WINAPI (*TAddAccessAllowedAce) (PACL pAcl, DWORD dwAceRevision,
- DWORD AccessMask, PSID pSid);
-typedef BOOL WINAPI (*TSetNamedSecurityInfo) (LPTSTR pObjectName,
SE_OBJECT_TYPE ObjectType,
- SECURITY_INFORMATION SecurityInfo, PSID psidOwner, PSID psidGroup, PACL
pDacl,
- PACL pSacl);
+ typedef DWORD WINAPI (*TNtQuerySystemInformation) (int, PVOID, ULONG,
+ PULONG);
+ typedef DWORD WINAPI (*TGetIfEntry) (PMIB_IFROW pIfRow);
+ typedef DWORD WINAPI (*TGetIpAddrTable) (PMIB_IPADDRTABLE pIpAddrTable,
+ PULONG pdwSize, BOOL bOrder);
+ typedef DWORD WINAPI (*TGetIfTable) (PMIB_IFTABLE pIfTable, PULONG pdwSize,
+ BOOL bOrder);
+ typedef DWORD WINAPI (*TCreateHardLink) (LPCTSTR lpFileName,
+ LPCTSTR lpExistingFileName,
+ LPSECURITY_ATTRIBUTES
+ lpSecurityAttributes);
+ typedef SC_HANDLE WINAPI (*TOpenSCManager) (LPCTSTR lpMachineName,
+ LPCTSTR lpDatabaseName,
+ DWORD dwDesiredAccess);
+ typedef SC_HANDLE WINAPI (*TCreateService) (SC_HANDLE hSCManager,
+ LPCTSTR lpServiceName,
+ LPCTSTR lpDisplayName,
+ DWORD dwDesiredAccess,
+ DWORD dwServiceType,
+ DWORD dwStartType,
+ DWORD dwErrorControl,
+ LPCTSTR lpBinaryPathName,
+ LPCTSTR lpLoadOrderGroup,
+ LPDWORD lpdwTagId,
+ LPCTSTR lpDependencies,
+ LPCTSTR lpServiceStartName,
+ LPCTSTR lpPassword);
+ typedef BOOL WINAPI (*TCloseServiceHandle) (SC_HANDLE hSCObject);
+ typedef BOOL WINAPI (*TDeleteService) (SC_HANDLE hService);
+ typedef SERVICE_STATUS_HANDLE WINAPI (*TRegisterServiceCtrlHandler) (LPCTSTR
+
lpServiceName,
+
LPHANDLER_FUNCTION
+
lpHandlerProc);
+ typedef BOOL WINAPI (*TSetServiceStatus) (SERVICE_STATUS_HANDLE
+ hServiceStatus,
+ LPSERVICE_STATUS lpServiceStatus);
+ typedef BOOL WINAPI (*TStartServiceCtrlDispatcher) (const
+ LPSERVICE_TABLE_ENTRY
+ lpServiceTable);
+ typedef BOOL WINAPI (*TControlService) (SC_HANDLE hService, DWORD dwControl,
+ LPSERVICE_STATUS lpServiceStatus);
+ typedef SC_HANDLE WINAPI (*TOpenService) (SC_HANDLE hSCManager,
+ LPCTSTR lpServiceName,
+ DWORD dwDesiredAccess);
+ typedef DWORD WINAPI (*TGetBestInterface) (IPAddr dwDestAddr,
+ PDWORD pdwBestIfIndex);
+ typedef DWORD WINAPI (*TGetAdaptersInfo) (PIP_ADAPTER_INFO pAdapterInfo,
+ PULONG pOutBufLen);
+ typedef NET_API_STATUS WINAPI (*TNetUserAdd) (LPCWSTR, DWORD, PBYTE,
+ PDWORD);
+ typedef NET_API_STATUS WINAPI (*TNetUserSetInfo) (LPCWSTR servername,
+ LPCWSTR username,
+ DWORD level, LPBYTE buf,
+ LPDWORD parm_err);
+ typedef NTSTATUS NTAPI (*TLsaOpenPolicy) (PLSA_UNICODE_STRING,
+ PLSA_OBJECT_ATTRIBUTES,
+ ACCESS_MASK, PLSA_HANDLE);
+ typedef NTSTATUS NTAPI (*TLsaAddAccountRights) (LSA_HANDLE, PSID,
+ PLSA_UNICODE_STRING, ULONG);
+ typedef NTSTATUS NTAPI (*TLsaRemoveAccountRights) (LSA_HANDLE, PSID,
+ BOOLEAN,
+ PLSA_UNICODE_STRING,
+ ULONG);
+ typedef NTSTATUS NTAPI (*TLsaClose) (LSA_HANDLE);
+ typedef BOOL WINAPI (*TLookupAccountName) (LPCTSTR lpSystemName,
+ LPCTSTR lpAccountName, PSID Sid,
+ LPDWORD cbSid,
+ LPTSTR ReferencedDomainName,
+ LPDWORD cchReferencedDomainName,
+ PSID_NAME_USE peUse);
-extern TNtQuerySystemInformation GNNtQuerySystemInformation;
-extern TGetIfEntry GNGetIfEntry;
-extern TGetIpAddrTable GNGetIpAddrTable;
-extern TGetIfTable GNGetIfTable;
-extern TCreateHardLink GNCreateHardLink;
-extern TOpenSCManager GNOpenSCManager;
-extern TCreateService GNCreateService;
-extern TCloseServiceHandle GNCloseServiceHandle;
-extern TDeleteService GNDeleteService;
-extern TRegisterServiceCtrlHandler GNRegisterServiceCtrlHandler;
-extern TSetServiceStatus GNSetServiceStatus;
-extern TStartServiceCtrlDispatcher GNStartServiceCtrlDispatcher;
-extern TControlService GNControlService;
-extern TOpenService GNOpenService;
-extern TGetBestInterface GNGetBestInterface;
-extern TGetAdaptersInfo GGetAdaptersInfo;
-extern TNetUserAdd GNNetUserAdd;
-extern TNetUserSetInfo GNNetUserSetInfo;
-extern TLsaOpenPolicy GNLsaOpenPolicy;
-extern TLsaAddAccountRights GNLsaAddAccountRights;
-extern TLsaRemoveAccountRights GNLsaRemoveAccountRights;
-extern TLsaClose GNLsaClose;
-extern TLookupAccountName GNLookupAccountName;
-extern TGetFileSecurity GNGetFileSecurity;
-extern TInitializeSecurityDescriptor GNInitializeSecurityDescriptor;
-extern TGetSecurityDescriptorDacl GNGetSecurityDescriptorDacl;
-extern TGetAclInformation GNGetAclInformation;
-extern TInitializeAcl GNInitializeAcl;
-extern TGetAce GNGetAce;
-extern TEqualSid GNEqualSid;
-extern TAddAce GNAddAce;
-extern TAddAccessAllowedAce GNAddAccessAllowedAce;
-extern TSetNamedSecurityInfo GNSetNamedSecurityInfo;
+ typedef BOOL WINAPI (*TGetFileSecurity) (LPCTSTR lpFileName,
+ SECURITY_INFORMATION
+ RequestedInformation,
+ PSECURITY_DESCRIPTOR
+ pSecurityDescriptor, DWORD nLength,
+ LPDWORD lpnLengthNeeded);
+ typedef BOOL WINAPI (*TInitializeSecurityDescriptor) (PSECURITY_DESCRIPTOR
+ pSecurityDescriptor,
+ DWORD dwRevision);
+ typedef BOOL WINAPI (*TGetSecurityDescriptorDacl) (PSECURITY_DESCRIPTOR
+ pSecurityDescriptor,
+ LPBOOL lpbDaclPresent,
+ PACL * pDacl,
+ LPBOOL lpbDaclDefaulted);
+ typedef BOOL WINAPI (*TGetAclInformation) (PACL pAcl,
+ LPVOID pAclInformation,
+ DWORD nAclInformationLength,
+ ACL_INFORMATION_CLASS
+ dwAclInformationClass);
+ typedef BOOL WINAPI (*TInitializeAcl) (PACL pAcl, DWORD nAclLength,
+ DWORD dwAclRevision);
+ typedef BOOL WINAPI (*TGetAce) (PACL pAcl, DWORD dwAceIndex, LPVOID * pAce);
+ typedef BOOL WINAPI (*TEqualSid) (PSID pSid1, PSID pSid2);
+ typedef BOOL WINAPI (*TAddAce) (PACL pAcl, DWORD dwAceRevision,
+ DWORD dwStartingAceIndex, LPVOID pAceList,
+ DWORD nAceListLength);
+ typedef BOOL WINAPI (*TAddAccessAllowedAce) (PACL pAcl, DWORD dwAceRevision,
+ DWORD AccessMask, PSID pSid);
+ typedef BOOL WINAPI (*TSetNamedSecurityInfo) (LPTSTR pObjectName,
+ SE_OBJECT_TYPE ObjectType,
+ SECURITY_INFORMATION
+ SecurityInfo, PSID psidOwner,
+ PSID psidGroup, PACL pDacl,
+ PACL pSacl);
+ extern TNtQuerySystemInformation GNNtQuerySystemInformation;
+ extern TGetIfEntry GNGetIfEntry;
+ extern TGetIpAddrTable GNGetIpAddrTable;
+ extern TGetIfTable GNGetIfTable;
+ extern TCreateHardLink GNCreateHardLink;
+ extern TOpenSCManager GNOpenSCManager;
+ extern TCreateService GNCreateService;
+ extern TCloseServiceHandle GNCloseServiceHandle;
+ extern TDeleteService GNDeleteService;
+ extern TRegisterServiceCtrlHandler GNRegisterServiceCtrlHandler;
+ extern TSetServiceStatus GNSetServiceStatus;
+ extern TStartServiceCtrlDispatcher GNStartServiceCtrlDispatcher;
+ extern TControlService GNControlService;
+ extern TOpenService GNOpenService;
+ extern TGetBestInterface GNGetBestInterface;
+ extern TGetAdaptersInfo GGetAdaptersInfo;
+ extern TNetUserAdd GNNetUserAdd;
+ extern TNetUserSetInfo GNNetUserSetInfo;
+ extern TLsaOpenPolicy GNLsaOpenPolicy;
+ extern TLsaAddAccountRights GNLsaAddAccountRights;
+ extern TLsaRemoveAccountRights GNLsaRemoveAccountRights;
+ extern TLsaClose GNLsaClose;
+ extern TLookupAccountName GNLookupAccountName;
+ extern TGetFileSecurity GNGetFileSecurity;
+ extern TInitializeSecurityDescriptor GNInitializeSecurityDescriptor;
+ extern TGetSecurityDescriptorDacl GNGetSecurityDescriptorDacl;
+ extern TGetAclInformation GNGetAclInformation;
+ extern TInitializeAcl GNInitializeAcl;
+ extern TGetAce GNGetAce;
+ extern TEqualSid GNEqualSid;
+ extern TAddAce GNAddAce;
+ extern TAddAccessAllowedAce GNAddAccessAllowedAce;
+ extern TSetNamedSecurityInfo GNSetNamedSecurityInfo;
-BOOL CreateShortcut(const char *pszSrc, const char *pszDest);
-BOOL DereferenceShortcut(char *pszShortcut);
-long QueryRegistry(HKEY hMainKey, char *pszKey, char *pszSubKey,
- char *pszBuffer, long *pdLength);
-int ListNICs(void (*callback) (const char *, int, void *), void * cls);
-BOOL AddPathAccessRights(char *lpszFileName, char *lpszAccountName,
- DWORD dwAccessMask);
-char *winErrorStr(const char *prefix, int dwErr);
-void GNInitWinEnv();
-void GNShutdownWinEnv();
+ BOOL CreateShortcut (const char *pszSrc, const char *pszDest);
+ BOOL DereferenceShortcut (char *pszShortcut);
+ long QueryRegistry (HKEY hMainKey, char *pszKey, char *pszSubKey,
+ char *pszBuffer, long *pdLength);
+ int ListNICs (void (*callback) (const char *, int, void *), void *cls);
+ BOOL AddPathAccessRights (char *lpszFileName, char *lpszAccountName,
+ DWORD dwAccessMask);
+ char *winErrorStr (const char *prefix, int dwErr);
+ void GNInitWinEnv ();
+ void GNShutdownWinEnv ();
+
#ifdef __cplusplus
}
#endif
Modified: GNUnet/src/server/connection.c
===================================================================
--- GNUnet/src/server/connection.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/connection.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -236,7 +236,8 @@
* Type of the linked list of send callbacks (to
* implement a round-robbin invocation chain).
*/
-typedef struct SendCallbackList__ {
+typedef struct SendCallbackList__
+{
/**
* Did we say that this is a linked list?
@@ -257,7 +258,8 @@
} SendCallbackList;
-typedef struct fENHWrap {
+typedef struct fENHWrap
+{
PerNodeCallback method;
void *arg;
} fENHWrap;
@@ -274,7 +276,8 @@
* side (can happen anyway, so this is just an optimization between
* well-behaved, non-malicious nodes that like each other).
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
PeerIdentity sender;
} P2P_hangup_MESSAGE;
@@ -297,7 +300,8 @@
* fill in the actual message and a closure (argument to the
* callback).
*/
-typedef struct {
+typedef struct
+{
/**
* how long is this message part expected to be?
@@ -328,7 +332,7 @@
* argument to callback, call FREENONNULL(closure) if we
* can not transmit this MessagePart.
*/
- void * closure;
+ void *closure;
/**
* YES if selected by knapsack for sending
@@ -341,7 +345,8 @@
* API to refer to a connection of the transport
* layer.
*/
-typedef struct {
+typedef struct
+{
/**
* To whom are we connected with this session?
*/
@@ -363,7 +368,8 @@
/**
* Type of the connection table.
*/
-typedef struct BufferEntry_ {
+typedef struct BufferEntry_
+{
/**
* Session for the connection
*/
@@ -498,7 +504,8 @@
} BufferEntry;
-typedef struct {
+typedef struct
+{
BufferEntry **e;
unsigned int pos;
} UTL_Closure;
@@ -508,8 +515,7 @@
* @param be the buffer entry
* @param data context for callee
*/
-typedef void (*BufferEntryCallback) (BufferEntry * be,
- void *data);
+typedef void (*BufferEntryCallback) (BufferEntry * be, void *data);
/* ***************** globals ********************** */
@@ -568,7 +574,7 @@
/**
* Lock for the connection module.
*/
-static struct MUTEX * lock;
+static struct MUTEX *lock;
/**
* What is the available downstream bandwidth (in bytes
@@ -587,13 +593,13 @@
*/
static MessagePartHandler *rsns;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static struct LoadMonitor * load_monitor;
+static struct LoadMonitor *load_monitor;
-static struct CronManager * cron;
+static struct CronManager *cron;
/**
@@ -635,11 +641,13 @@
* This allocates and initializes a BufferEntry.
* @return the initialized BufferEntry
*/
-static BufferEntry * initBufferEntry() {
- BufferEntry * be;
+static BufferEntry *
+initBufferEntry ()
+{
+ BufferEntry *be;
- be = MALLOC(sizeof(BufferEntry));
- memset(be, 0, sizeof(BufferEntry));
+ be = MALLOC (sizeof (BufferEntry));
+ memset (be, 0, sizeof (BufferEntry));
be->isAlive = 0;
be->status = STAT_DOWN;
be->sendBuffer = NULL;
@@ -654,7 +662,7 @@
be->max_transmitted_limit = MIN_BPM_PER_PEER;
be->lastSendAttempt = 0; /* never */
be->inSendBuffer = NO;
- be->last_bps_update = get_time(); /* now */
+ be->last_bps_update = get_time (); /* now */
return be;
}
@@ -662,38 +670,36 @@
* Update available_send_window. Call only when already synchronized.
* @param be the connection for which to update available_send_window
*/
-void updateCurBPS(BufferEntry * be) {
+void
+updateCurBPS (BufferEntry * be)
+{
cron_t now;
cron_t delta;
long long increment;
long long limit;
- now = get_time();
+ now = get_time ();
if (now <= be->last_bps_update)
return;
delta = now - be->last_bps_update;
increment = (long long) be->max_bpm * delta / cronMINUTES;
if (increment < 100)
- return; /* avoid loosing > 1% due to rounding */
+ return; /* avoid loosing > 1% due to rounding */
if (stats != NULL)
- stats->change(stat_total_allowed_inc,
- increment);
- be->available_send_window
- += increment;
+ stats->change (stat_total_allowed_inc, increment);
+ be->available_send_window += increment;
#if 0
- printf("Have %u bpm over %llu ms, adding %lld bytes\n",
- be->max_bpm,
- delta,
- increment);
+ printf ("Have %u bpm over %llu ms, adding %lld bytes\n",
+ be->max_bpm, delta, increment);
#endif
limit = (long long) be->max_bpm * MAX_BUF_FACT;
- if (be->available_send_window > limit) {
- if (stats != NULL)
- stats->change(stat_total_lost_sent,
- be->available_send_window
- - limit);
- be->available_send_window = limit;
- }
+ if (be->available_send_window > limit)
+ {
+ if (stats != NULL)
+ stats->change (stat_total_lost_sent,
+ be->available_send_window - limit);
+ be->available_send_window = limit;
+ }
be->last_bps_update = now;
}
@@ -705,12 +711,15 @@
* @param b
* @return gcd(a,b)
*/
-static int gcd(int a, int b) {
- while(a != 0) {
- int t = a;
- a = b % a;
- b = t;
- }
+static int
+gcd (int a, int b)
+{
+ while (a != 0)
+ {
+ int t = a;
+ a = b % a;
+ b = t;
+ }
return b;
}
@@ -729,8 +738,8 @@
* @return the overall priority that was achieved
*/
static unsigned int
-approximateKnapsack(BufferEntry * be,
- unsigned int available) {
+approximateKnapsack (BufferEntry * be, unsigned int available)
+{
unsigned int i;
unsigned int count;
SendEntry **entries;
@@ -742,15 +751,19 @@
left = available;
max = 0;
- for(i = 0; i < count; i++) {
- if (entries[i]->len <= left) {
- entries[i]->knapsackSolution = YES;
- left -= entries[i]->len;
- max += entries[i]->pri;
- } else {
- entries[i]->knapsackSolution = NO;
+ for (i = 0; i < count; i++)
+ {
+ if (entries[i]->len <= left)
+ {
+ entries[i]->knapsackSolution = YES;
+ left -= entries[i]->len;
+ max += entries[i]->pri;
+ }
+ else
+ {
+ entries[i]->knapsackSolution = NO;
+ }
}
- }
return max;
}
@@ -767,100 +780,112 @@
* @param available what is the maximum length available?
* @return the overall priority that was achieved
*/
-static unsigned int solveKnapsack(BufferEntry * be,
- unsigned int available) {
+static unsigned int
+solveKnapsack (BufferEntry * be, unsigned int available)
+{
unsigned int i;
int j;
int max;
long long *v;
int *efflen;
- SendEntry ** entries;
+ SendEntry **entries;
unsigned int count;
#define VARR(i,j) v[(i)+(j)*(count+1)]
- ENTRY();
+ ENTRY ();
entries = be->sendBuffer;
count = be->sendBufferSize;
/* fast test: schedule everything? */
max = 0;
- for (i=0;i<count;i++)
+ for (i = 0; i < count; i++)
max += entries[i]->len;
- if (max <= available) {
- /* short cut: take everything! */
- for (i = 0; i < count; i++)
- entries[i]->knapsackSolution = YES;
- max = 0;
- for(i = 0; i < count; i++)
- max += entries[i]->pri;
- return max;
- }
+ if (max <= available)
+ {
+ /* short cut: take everything! */
+ for (i = 0; i < count; i++)
+ entries[i]->knapsackSolution = YES;
+ max = 0;
+ for (i = 0; i < count; i++)
+ max += entries[i]->pri;
+ return max;
+ }
/* division of sizes & available by gcd(sizes,available)
to reduce cost to O(count*available/gcd) in terms of
CPU and memory. Since gcd is almost always at least
4, this is probably a good idea (TM) :-) */
- efflen = MALLOC(sizeof(int) * count);
+ efflen = MALLOC (sizeof (int) * count);
max = available;
- for(i = 0; i < count; i++)
+ for (i = 0; i < count; i++)
if (entries[i]->len > 0)
- max = gcd(max, entries[i]->len);
- GE_ASSERT(ectx, max != 0);
+ max = gcd (max, entries[i]->len);
+ GE_ASSERT (ectx, max != 0);
available = available / max;
- for(i = 0; i < count; i++)
+ for (i = 0; i < count; i++)
efflen[i] = entries[i]->len / max;
/* dynamic programming:
VARR(i,j) stores the maximum value of any subset
of objects {1, ... i} that can fit into a knapsack
of weight j. */
- v = MALLOC(sizeof(long long) * (count + 1) * (available + 1));
- memset(v, 0, sizeof(long long) * (count + 1) * (available + 1));
- for(j = 1; j <= available; j++)
- VARR(0, j) = -1;
- for(i = 1; i <= count; i++) {
- for(j = 0; j <= available; j++) {
- int take_val;
- int leave_val;
+ v = MALLOC (sizeof (long long) * (count + 1) * (available + 1));
+ memset (v, 0, sizeof (long long) * (count + 1) * (available + 1));
+ for (j = 1; j <= available; j++)
+ VARR (0, j) = -1;
+ for (i = 1; i <= count; i++)
+ {
+ for (j = 0; j <= available; j++)
+ {
+ int take_val;
+ int leave_val;
- take_val = -1;
- leave_val = VARR(i - 1, j);
- if(j >= efflen[i - 1]) {
- take_val = entries[i - 1]->pri + VARR(i - 1, j - efflen[i - 1]);
- if(leave_val > take_val)
- VARR(i, j) = leave_val;
- else
- VARR(i, j) = take_val;
- }
- else
- VARR(i, j) = leave_val;
+ take_val = -1;
+ leave_val = VARR (i - 1, j);
+ if (j >= efflen[i - 1])
+ {
+ take_val =
+ entries[i - 1]->pri + VARR (i - 1, j - efflen[i - 1]);
+ if (leave_val > take_val)
+ VARR (i, j) = leave_val;
+ else
+ VARR (i, j) = take_val;
+ }
+ else
+ VARR (i, j) = leave_val;
+ }
}
- }
/* find slot with max value, prefer long messages! */
max = 0;
j = -1;
- for(i = 0; (int) i <= available; i++) {
- if(VARR(count, i) >= max) {
- j = i;
- max = VARR(count, i);
+ for (i = 0; (int) i <= available; i++)
+ {
+ if (VARR (count, i) >= max)
+ {
+ j = i;
+ max = VARR (count, i);
+ }
}
- }
/* reconstruct selection */
- for(i = 0; i < count; i++)
+ for (i = 0; i < count; i++)
entries[i]->knapsackSolution = NO;
- for(i = count; i > 0; i--) {
- if(j >= efflen[i - 1]) {
- if(VARR(i - 1, j - efflen[i - 1]) + entries[i - 1]->pri == VARR(i, j)) {
- j -= efflen[i - 1];
- entries[i - 1]->knapsackSolution = YES;
- }
+ for (i = count; i > 0; i--)
+ {
+ if (j >= efflen[i - 1])
+ {
+ if (VARR (i - 1, j - efflen[i - 1]) + entries[i - 1]->pri ==
+ VARR (i, j))
+ {
+ j -= efflen[i - 1];
+ entries[i - 1]->knapsackSolution = YES;
+ }
+ }
}
- }
- GE_ASSERT(ectx, j == 0);
- FREE(v);
- FREE(efflen);
+ GE_ASSERT (ectx, j == 0);
+ FREE (v);
+ FREE (efflen);
return max;
}
@@ -876,22 +901,24 @@
* (the higher the better)
* @return OK if the packet should be handled, SYSERR if the packet should be
dropped.
*/
-static int outgoingCheck(unsigned int priority,
- unsigned int overhead) {
+static int
+outgoingCheck (unsigned int priority, unsigned int overhead)
+{
int load;
unsigned int delta;
- load = os_network_monitor_get_load(load_monitor, Upload); /* how much free
bandwidth do we have? */
+ load = os_network_monitor_get_load (load_monitor, Upload); /* how much
free bandwidth do we have? */
if (load >= 150)
return SYSERR; /* => always drop */
- if (load > 100) {
- if (priority >= EXTREME_PRIORITY)
- return OK; /* allow administrative msgs */
- else
- return SYSERR; /* but nothing else */
- }
+ if (load > 100)
+ {
+ if (priority >= EXTREME_PRIORITY)
+ return OK; /* allow administrative msgs */
+ else
+ return SYSERR; /* but nothing else */
+ }
if (overhead > 50)
- overhead = 50; /* bound */
+ overhead = 50; /* bound */
if (load <= overhead)
return OK;
/* Suppose overhead = 50, then:
@@ -902,30 +929,27 @@
at 100% require priority >= 125000 = (load-50)^3
(cubic function)
*/
- delta = load - overhead; /* now delta is in [1,50] with 50 ==
100% load */
- if (delta * delta * delta > priority) {
+ delta = load - overhead; /* now delta is in [1,50] with 50 == 100% load
*/
+ if (delta * delta * delta > priority)
+ {
#if DEBUG_POLICY
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Network load is too high (%d%%, priority is %u, require %d), "
- "dropping outgoing.\n",
- load,
- priority,
- delta * delta * delta);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Network load is too high (%d%%, priority is %u, require %d), "
+ "dropping outgoing.\n", load, priority, delta * delta * delta);
#endif
- return SYSERR; /* drop */
- } else {
+ return SYSERR; /* drop */
+ }
+ else
+ {
#if DEBUG_POLICY
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Network load is ok (%d%%, priority is %u >= %d), "
- "sending outgoing.\n",
- load,
- priority,
- delta * delta * delta);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Network load is ok (%d%%, priority is %u >= %d), "
+ "sending outgoing.\n", load, priority, delta * delta * delta);
#endif
- return OK; /* allow */
- }
+ return OK; /* allow */
+ }
}
/**
@@ -934,45 +958,51 @@
*
* @return OK if sending a message now is acceptable
*/
-static int checkSendFrequency(BufferEntry * be) {
+static int
+checkSendFrequency (BufferEntry * be)
+{
cron_t msf;
int load;
unsigned int i;
- for (i=0;i<be->sendBufferSize;i++)
+ for (i = 0; i < be->sendBufferSize; i++)
if (be->sendBuffer[i]->pri >= EXTREME_PRIORITY)
return OK;
if (be->max_bpm == 0)
be->max_bpm = 1;
- if (be->session.mtu == 0) {
- msf = /* ms per message */
- EXPECTED_MTU / (be->max_bpm * cronMINUTES / cronMILLIS); /* bytes per ms
*/
- } else {
- msf = /* ms per message */
- be->session.mtu /* byte per message */
- / (be->max_bpm * cronMINUTES / cronMILLIS); /* bytes per ms */
- }
+ if (be->session.mtu == 0)
+ {
+ msf = /* ms per message */
+ EXPECTED_MTU / (be->max_bpm * cronMINUTES / cronMILLIS); /*
bytes per ms */
+ }
+ else
+ {
+ msf = /* ms per message */
+ be->session.mtu /* byte per message */
+ / (be->max_bpm * cronMINUTES / cronMILLIS); /* bytes per ms */
+ }
/* Also: allow at least 2 * MINIMUM_SAMPLE_COUNT knapsack
solutions for any MIN_SAMPLE_TIME! */
if (msf > 2 * MIN_SAMPLE_TIME / MINIMUM_SAMPLE_COUNT)
msf = 2 * MIN_SAMPLE_TIME / MINIMUM_SAMPLE_COUNT;
- load = os_cpu_get_load(ectx, cfg);
+ load = os_cpu_get_load (ectx, cfg);
if (load == -1)
load = 50;
/* adjust send frequency; if load is smaller
than 25%, decrease frequency, otherwise
increase it (quadratically)! */
msf = msf * load * load / 25 / 25;
- if (be->lastSendAttempt + msf > get_time()) {
+ if (be->lastSendAttempt + msf > get_time ())
+ {
#if DEBUG_CONNECTION
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Send frequency too high (CPU load), send deferred.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Send frequency too high (CPU load), send deferred.\n");
#endif
- return NO; /* frequency too high, wait */
- }
+ return NO; /* frequency too high, wait */
+ }
return OK;
}
@@ -984,8 +1014,8 @@
* including P2P message header.
*/
static unsigned int
-selectMessagesToSend(BufferEntry * be,
- unsigned int *priority) {
+selectMessagesToSend (BufferEntry * be, unsigned int *priority)
+{
unsigned int totalMessageSize;
SendEntry *entry;
int i;
@@ -999,152 +1029,165 @@
for (i = be->sendBufferSize - 1; i >= 0; i--)
be->sendBuffer[i]->knapsackSolution = NO;
- if (be->session.mtu == 0) {
- totalMessageSize = sizeof(P2P_PACKET_HEADER);
- deadline = (cron_t) -1L; /* infinity */
+ if (be->session.mtu == 0)
+ {
+ totalMessageSize = sizeof (P2P_PACKET_HEADER);
+ deadline = (cron_t) - 1L; /* infinity */
- i = 0;
- /* assumes entries are sorted by priority! */
- while (i < be->sendBufferSize) {
- entry = be->sendBuffer[i];
- if ( (totalMessageSize + entry->len < MAX_BUFFER_SIZE - 64) &&
- (entry->pri >= EXTREME_PRIORITY)) {
- entry->knapsackSolution = YES;
- if (entry->transmissionTime < deadline)
- deadline = entry->transmissionTime;
- (*priority) += entry->pri;
- totalMessageSize += entry->len;
- } else {
- entry->knapsackSolution = NO;
- break;
- }
- i++;
- }
- if ( (i == 0) &&
- (be->sendBuffer[i]->len > be->available_send_window)) {
- return 0; /* always wait for the highest-priority
+ i = 0;
+ /* assumes entries are sorted by priority! */
+ while (i < be->sendBufferSize)
+ {
+ entry = be->sendBuffer[i];
+ if ((totalMessageSize + entry->len < MAX_BUFFER_SIZE - 64) &&
+ (entry->pri >= EXTREME_PRIORITY))
+ {
+ entry->knapsackSolution = YES;
+ if (entry->transmissionTime < deadline)
+ deadline = entry->transmissionTime;
+ (*priority) += entry->pri;
+ totalMessageSize += entry->len;
+ }
+ else
+ {
+ entry->knapsackSolution = NO;
+ break;
+ }
+ i++;
+ }
+ if ((i == 0) && (be->sendBuffer[i]->len > be->available_send_window))
+ {
+ return 0; /* always wait for the highest-priority
message (otherwise large messages may
starve! */
- }
- while ( (i < be->sendBufferSize) &&
- (be->available_send_window > totalMessageSize)) {
- entry = be->sendBuffer[i];
- if ( (entry->len + totalMessageSize <= be->available_send_window) &&
- (totalMessageSize + entry->len < MAX_BUFFER_SIZE - 64)) {
- entry->knapsackSolution = YES;
- if (entry->transmissionTime < deadline)
- deadline = entry->transmissionTime;
- totalMessageSize += entry->len;
- (*priority) += entry->pri;
- } else {
- entry->knapsackSolution = NO;
- if (totalMessageSize == sizeof(P2P_PACKET_HEADER)) {
- /* if the highest-priority message does not yet
- fit, wait for send window to grow so that
- we can get it out (otherwise we would starve
- high-priority, large messages) */
+ }
+ while ((i < be->sendBufferSize) &&
+ (be->available_send_window > totalMessageSize))
+ {
+ entry = be->sendBuffer[i];
+ if ((entry->len + totalMessageSize <= be->available_send_window) &&
+ (totalMessageSize + entry->len < MAX_BUFFER_SIZE - 64))
+ {
+ entry->knapsackSolution = YES;
+ if (entry->transmissionTime < deadline)
+ deadline = entry->transmissionTime;
+ totalMessageSize += entry->len;
+ (*priority) += entry->pri;
+ }
+ else
+ {
+ entry->knapsackSolution = NO;
+ if (totalMessageSize == sizeof (P2P_PACKET_HEADER))
+ {
+ /* if the highest-priority message does not yet
+ fit, wait for send window to grow so that
+ we can get it out (otherwise we would starve
+ high-priority, large messages) */
+ return 0;
+ }
+ }
+ i++;
+ }
+ if ((totalMessageSize == sizeof (P2P_PACKET_HEADER)) ||
+ (((*priority) < EXTREME_PRIORITY) &&
+ ((totalMessageSize / sizeof (P2P_PACKET_HEADER)) < 4) &&
+ (deadline > get_time () + 500 * cronMILLIS) &&
+ (weak_randomi (16) != 0)))
+ {
+ /* randomization necessary to ensure we eventually send
+ a small message if there is nothing else to do! */
return 0;
}
- }
- i++;
}
- if ( (totalMessageSize == sizeof(P2P_PACKET_HEADER)) ||
- ( ((*priority) < EXTREME_PRIORITY) &&
- ((totalMessageSize / sizeof(P2P_PACKET_HEADER)) < 4) &&
- (deadline > get_time() + 500 * cronMILLIS) &&
- (weak_randomi(16) != 0) ) ) {
- /* randomization necessary to ensure we eventually send
- a small message if there is nothing else to do! */
- return 0;
- }
- } else { /* if (be->session.mtu == 0) */
- /* solve knapsack problem, compute accumulated priority */
- approxProb = os_cpu_get_load(ectx, cfg);
- if (approxProb < 0)
- approxProb = 50; /* failed to determine load, assume 50% */
- if (approxProb > 50) {
- if(approxProb > 100)
- approxProb = 100;
- approxProb = 100 - approxProb; /* now value between 0 and 50 */
- approxProb *= 2; /* now value between 0 [always approx] and 100
[never approx] */
- /* control CPU load probabilistically! */
- if(weak_randomi(1 + approxProb) == 0) {
- (*priority) = approximateKnapsack(be,
- be->session.mtu -
- sizeof(P2P_PACKET_HEADER));
+ else
+ { /* if (be->session.mtu == 0) */
+ /* solve knapsack problem, compute accumulated priority */
+ approxProb = os_cpu_get_load (ectx, cfg);
+ if (approxProb < 0)
+ approxProb = 50; /* failed to determine load, assume 50% */
+ if (approxProb > 50)
+ {
+ if (approxProb > 100)
+ approxProb = 100;
+ approxProb = 100 - approxProb; /* now value between 0 and 50
*/
+ approxProb *= 2; /* now value between 0 [always approx] and 100
[never approx] */
+ /* control CPU load probabilistically! */
+ if (weak_randomi (1 + approxProb) == 0)
+ {
+ (*priority) = approximateKnapsack (be,
+ be->session.mtu -
+ sizeof (P2P_PACKET_HEADER));
#if DEBUG_COLLECT_PRIO == YES
- FPRINTF(prioFile,
- "%llu 0 %d\n",
- get_time(),
- priority);
+ FPRINTF (prioFile, "%llu 0 %d\n", get_time (), priority);
#endif
- } else {
- (*priority) = solveKnapsack(be,
- be->session.mtu -
- sizeof(P2P_PACKET_HEADER));
+ }
+ else
+ {
+ (*priority) = solveKnapsack (be,
+ be->session.mtu -
+ sizeof (P2P_PACKET_HEADER));
#if DEBUG_COLLECT_PRIO == YES
- FPRINTF(prioFile,
- "%llu 1 %d\n",
- get_time(),
- priority);
+ FPRINTF (prioFile, "%llu 1 %d\n", get_time (), priority);
#endif
- }
- } else { /* never approximate < 50% CPU load */
- (*priority) = solveKnapsack(be,
- be->session.mtu -
- sizeof(P2P_PACKET_HEADER));
+ }
+ }
+ else
+ { /* never approximate < 50% CPU load */
+ (*priority) = solveKnapsack (be,
+ be->session.mtu -
+ sizeof (P2P_PACKET_HEADER));
#if DEBUG_COLLECT_PRIO == YES
- FPRINTF(prioFile,
- "%llu 2 %d\n",
- get_time(),
- priority);
+ FPRINTF (prioFile, "%llu 2 %d\n", get_time (), priority);
#endif
- }
- j = 0;
- totalMessageSize = 0;
- for (i = 0; i < be->sendBufferSize; i++) {
- if (be->sendBuffer[i]->knapsackSolution == YES) {
- totalMessageSize += be->sendBuffer[i]->len;
- j++;
- }
- }
- if ( (j == 0) ||
- (totalMessageSize > be->session.mtu - sizeof(P2P_PACKET_HEADER)) ) {
- GE_BREAK(ectx, 0);
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_DEVELOPER,
- _("`%s' selected %d out of %d messages (MTU: %d).\n"),
- __FUNCTION__,
- j,
- be->sendBufferSize,
- be->session.mtu - sizeof(P2P_PACKET_HEADER));
+ }
+ j = 0;
+ totalMessageSize = 0;
+ for (i = 0; i < be->sendBufferSize; i++)
+ {
+ if (be->sendBuffer[i]->knapsackSolution == YES)
+ {
+ totalMessageSize += be->sendBuffer[i]->len;
+ j++;
+ }
+ }
+ if ((j == 0) ||
+ (totalMessageSize > be->session.mtu - sizeof (P2P_PACKET_HEADER)))
+ {
+ GE_BREAK (ectx, 0);
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_DEVELOPER,
+ _("`%s' selected %d out of %d messages (MTU: %d).\n"),
+ __FUNCTION__,
+ j,
+ be->sendBufferSize,
+ be->session.mtu - sizeof (P2P_PACKET_HEADER));
- for (j = 0; j < be->sendBufferSize; j++)
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_DEVELOPER,
- _("Message details: %u: length %d, priority: %d\n"),
- j,
- be->sendBuffer[j]->len,
- be->sendBuffer[j]->pri);
- return 0;
- }
+ for (j = 0; j < be->sendBufferSize; j++)
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_DEVELOPER,
+ _("Message details: %u: length %d, priority: %d\n"),
+ j, be->sendBuffer[j]->len, be->sendBuffer[j]->pri);
+ return 0;
+ }
- if (be->available_send_window < be->session.mtu) {
- /* if we have a very high priority, we may
- want to ignore bandwidth availability (e.g. for HANGUP,
- which has EXTREME_PRIORITY) */
- if ((*priority) < EXTREME_PRIORITY) {
+ if (be->available_send_window < be->session.mtu)
+ {
+ /* if we have a very high priority, we may
+ want to ignore bandwidth availability (e.g. for HANGUP,
+ which has EXTREME_PRIORITY) */
+ if ((*priority) < EXTREME_PRIORITY)
+ {
#if DEBUG_CONNECTION
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "bandwidth limits prevent sending (send window %u too small).\n",
- be->available_send_window);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "bandwidth limits prevent sending (send window %u too
small).\n",
+ be->available_send_window);
#endif
- return 0; /* can not send, BPS available is too small */
- }
- }
- totalMessageSize = be->session.mtu;
- } /* end MTU > 0 */
+ return 0; /* can not send, BPS available is too small */
+ }
+ }
+ totalMessageSize = be->session.mtu;
+ } /* end MTU > 0 */
return totalMessageSize;
}
@@ -1153,7 +1196,9 @@
* Expire old messages from SendBuffer (to avoid
* running out of memory).
*/
-static void expireSendBufferEntries(BufferEntry * be) {
+static void
+expireSendBufferEntries (BufferEntry * be)
+{
unsigned long long msgCap;
int i;
SendEntry *entry;
@@ -1163,59 +1208,60 @@
int j;
/* if it's more than one connection "lifetime" old, always kill it! */
- be->lastSendAttempt = get_time();
+ be->lastSendAttempt = get_time ();
expired = be->lastSendAttempt - SECONDS_PINGATTEMPT * cronSECONDS;
- load = os_cpu_get_load(ectx, cfg);
+ load = os_cpu_get_load (ectx, cfg);
if (load < 0)
- load = 50; /* failed to determine load, assume 50% */
+ load = 50; /* failed to determine load, assume 50% */
/* cleanup queue: keep enough buffer for one minute */
msgCap = be->max_bpm; /* have minute of msgs */
if (msgCap < EXPECTED_MTU)
- msgCap = EXPECTED_MTU; /* have at least one MTU */
+ msgCap = EXPECTED_MTU; /* have at least one MTU */
if (msgCap > max_bpm_up)
- msgCap = max_bpm_up; /* have no more than max-bpm for entire daemon */
- if (load < 50) { /* afford more if CPU load is low */
- if (load == 0)
- load = 1; /* avoid division by zero */
- msgCap += (MAX_SEND_BUFFER_SIZE - EXPECTED_MTU) / load;
- }
+ msgCap = max_bpm_up; /* have no more than max-bpm for entire daemon
*/
+ if (load < 50)
+ { /* afford more if CPU load is low */
+ if (load == 0)
+ load = 1; /* avoid division by zero */
+ msgCap += (MAX_SEND_BUFFER_SIZE - EXPECTED_MTU) / load;
+ }
usedBytes = 0;
/* allow at least msgCap bytes in buffer */
- for (i = 0; i < be->sendBufferSize; i++) {
- entry = be->sendBuffer[i];
- if (entry == NULL)
- continue;
+ for (i = 0; i < be->sendBufferSize; i++)
+ {
+ entry = be->sendBuffer[i];
+ if (entry == NULL)
+ continue;
- if ( (entry->transmissionTime <= expired) ||
- (usedBytes > msgCap) ) {
+ if ((entry->transmissionTime <= expired) || (usedBytes > msgCap))
+ {
#if DEBUG_CONNECTION
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "expiring message, expired %ds ago, queue size is %llu (bandwidth
stressed)\n",
- (int) ((get_time() - entry->transmissionTime) / cronSECONDS),
- usedBytes);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "expiring message, expired %ds ago, queue size is %llu
(bandwidth stressed)\n",
+ (int) ((get_time () -
+ entry->transmissionTime) / cronSECONDS), usedBytes);
#endif
- if (stats != NULL) {
- stats->change(stat_messagesDropped, 1);
- stats->change(stat_sizeMessagesDropped, entry->len);
- }
- FREENONNULL(entry->closure);
- FREE(entry);
- be->sendBuffer[i] = NULL;
+ if (stats != NULL)
+ {
+ stats->change (stat_messagesDropped, 1);
+ stats->change (stat_sizeMessagesDropped, entry->len);
+ }
+ FREENONNULL (entry->closure);
+ FREE (entry);
+ be->sendBuffer[i] = NULL;
+ }
+ else
+ usedBytes += entry->len;
}
- else
- usedBytes += entry->len;
- }
/* cleanup/compact sendBuffer */
j = 0;
- for(i = 0; i < be->sendBufferSize; i++)
+ for (i = 0; i < be->sendBufferSize; i++)
if (be->sendBuffer[i] != NULL)
be->sendBuffer[j++] = be->sendBuffer[i];
- GROW(be->sendBuffer,
- be->sendBufferSize,
- j);
+ GROW (be->sendBuffer, be->sendBufferSize, j);
}
/**
@@ -1230,55 +1276,59 @@
* @return number of prepared entries
*/
static unsigned int
-prepareSelectedMessages(BufferEntry * be) {
+prepareSelectedMessages (BufferEntry * be)
+{
unsigned int ret;
int i;
char *tmpMsg;
SendEntry *entry;
ret = 0;
- for (i = 0; i < be->sendBufferSize; i++) {
- entry = be->sendBuffer[i];
+ for (i = 0; i < be->sendBufferSize; i++)
+ {
+ entry = be->sendBuffer[i];
- if (entry->knapsackSolution == YES) {
- if (entry->callback != NULL) {
- tmpMsg = MALLOC(entry->len);
- if (OK == entry->callback(tmpMsg,
- entry->closure,
- entry->len)) {
- entry->callback = NULL;
- entry->closure = tmpMsg;
- ret++;
- } else {
- FREE(tmpMsg);
- entry->callback = NULL;
- entry->closure = NULL;
- FREE(entry);
- be->sendBuffer[i] = NULL;
- }
- } else {
- ret++;
- }
+ if (entry->knapsackSolution == YES)
+ {
+ if (entry->callback != NULL)
+ {
+ tmpMsg = MALLOC (entry->len);
+ if (OK == entry->callback (tmpMsg, entry->closure, entry->len))
+ {
+ entry->callback = NULL;
+ entry->closure = tmpMsg;
+ ret++;
+ }
+ else
+ {
+ FREE (tmpMsg);
+ entry->callback = NULL;
+ entry->closure = NULL;
+ FREE (entry);
+ be->sendBuffer[i] = NULL;
+ }
+ }
+ else
+ {
+ ret++;
+ }
#if 0
- {
- MESSAGE_HEADER *hdr;
- EncName enc;
+ {
+ MESSAGE_HEADER *hdr;
+ EncName enc;
- hdr = (MESSAGE_HEADER *) entry->closure;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&be->session.sender.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Core selected message of type %u and size %u for sending to peer
`%s'.\n",
- ntohs(hdr->type),
- ntohs(hdr->size),
- &enc);
- }
+ hdr = (MESSAGE_HEADER *) entry->closure;
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&be->session.sender.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Core selected message of type %u and size %u for sending
to peer `%s'.\n",
+ ntohs (hdr->type), ntohs (hdr->size), &enc);
+ }
#endif
+ }
}
- }
return ret;
}
@@ -1293,62 +1343,67 @@
* permuted SendEntries
*/
static SendEntry **
-permuteSendBuffer(BufferEntry * be,
- unsigned int * selected_total) {
+permuteSendBuffer (BufferEntry * be, unsigned int *selected_total)
+{
unsigned int tailpos;
unsigned int headpos;
unsigned int rnd;
unsigned int i;
unsigned int j;
unsigned int stotal;
- SendEntry ** ret;
- SendEntry * tmp;
+ SendEntry **ret;
+ SendEntry *tmp;
stotal = 0;
- for (i = 0; i < be->sendBufferSize; i++) {
- if (be->sendBuffer[i] == NULL)
- continue;
- if (be->sendBuffer[i]->knapsackSolution == YES)
- stotal++;
- }
+ for (i = 0; i < be->sendBufferSize; i++)
+ {
+ if (be->sendBuffer[i] == NULL)
+ continue;
+ if (be->sendBuffer[i]->knapsackSolution == YES)
+ stotal++;
+ }
*selected_total = stotal;
if (stotal == 0)
return NULL;
- ret = MALLOC(stotal * sizeof(SendEntry *));
+ ret = MALLOC (stotal * sizeof (SendEntry *));
j = 0;
- for (i = 0; i < be->sendBufferSize; i++) {
- if (be->sendBuffer[i] == NULL)
- continue;
- if (be->sendBuffer[i]->knapsackSolution == YES)
- ret[j++] = be->sendBuffer[i];
- }
- for (j=0;j<stotal;j++) {
- rnd = weak_randomi(stotal);
- tmp = ret[j];
- ret[j] = ret[rnd];
- ret[rnd] = tmp;
- }
+ for (i = 0; i < be->sendBufferSize; i++)
+ {
+ if (be->sendBuffer[i] == NULL)
+ continue;
+ if (be->sendBuffer[i]->knapsackSolution == YES)
+ ret[j++] = be->sendBuffer[i];
+ }
+ for (j = 0; j < stotal; j++)
+ {
+ rnd = weak_randomi (stotal);
+ tmp = ret[j];
+ ret[j] = ret[rnd];
+ ret[rnd] = tmp;
+ }
tailpos = stotal - 1;
headpos = 0;
- for (i = 0; i <= tailpos; i++) {
- if (i >= stotal)
- break; /* corner case: integer underflow on tailpos */
- switch (ret[i]->flags & SE_PLACEMENT_FLAG) {
- case SE_FLAG_NONE:
- break;
- case SE_FLAG_PLACE_HEAD:
- /* swap slot with whoever is head now */
- tmp = ret[headpos];
- ret[headpos++] = ret[i];
- ret[i] = tmp;
- break;
- case SE_FLAG_PLACE_TAIL:
- /* swap slot with whoever is tail now */
- tmp = ret[tailpos];
- ret[tailpos--] = ret[i];
- ret[i] = tmp;
+ for (i = 0; i <= tailpos; i++)
+ {
+ if (i >= stotal)
+ break; /* corner case: integer underflow on tailpos */
+ switch (ret[i]->flags & SE_PLACEMENT_FLAG)
+ {
+ case SE_FLAG_NONE:
+ break;
+ case SE_FLAG_PLACE_HEAD:
+ /* swap slot with whoever is head now */
+ tmp = ret[headpos];
+ ret[headpos++] = ret[i];
+ ret[i] = tmp;
+ break;
+ case SE_FLAG_PLACE_TAIL:
+ /* swap slot with whoever is tail now */
+ tmp = ret[tailpos];
+ ret[tailpos--] = ret[i];
+ ret[i] = tmp;
+ }
}
- }
return ret;
}
@@ -1357,24 +1412,29 @@
* selected as the knapsack solution or
* that are dead (callback and closure NULL).
*/
-static void freeSelectedEntries(BufferEntry * be) {
+static void
+freeSelectedEntries (BufferEntry * be)
+{
int i;
SendEntry *entry;
- for (i = 0; i < be->sendBufferSize; i++) {
- entry = be->sendBuffer[i];
- GE_ASSERT(ectx, entry != NULL);
- if (entry->knapsackSolution == YES) {
- GE_ASSERT(ectx, entry->callback == NULL);
- FREENONNULL(entry->closure);
- FREE(entry);
- be->sendBuffer[i] = NULL;
- } else if ( (entry->callback == NULL) &&
- (entry->closure == NULL) ) {
- FREE(entry);
- be->sendBuffer[i] = NULL;
+ for (i = 0; i < be->sendBufferSize; i++)
+ {
+ entry = be->sendBuffer[i];
+ GE_ASSERT (ectx, entry != NULL);
+ if (entry->knapsackSolution == YES)
+ {
+ GE_ASSERT (ectx, entry->callback == NULL);
+ FREENONNULL (entry->closure);
+ FREE (entry);
+ be->sendBuffer[i] = NULL;
+ }
+ else if ((entry->callback == NULL) && (entry->closure == NULL))
+ {
+ FREE (entry);
+ be->sendBuffer[i] = NULL;
+ }
}
- }
}
/**
@@ -1382,47 +1442,47 @@
* MTU in the buffer. Check if this is the case, and if so,
* fragment those messages.
*/
-static void fragmentIfNecessary(BufferEntry * be) {
- SendEntry ** entries;
- SendEntry * entry;
+static void
+fragmentIfNecessary (BufferEntry * be)
+{
+ SendEntry **entries;
+ SendEntry *entry;
unsigned int i;
unsigned int ret;
unsigned int j;
int changed;
if (be->session.mtu == 0)
- return; /* clearly not necessary */
+ return; /* clearly not necessary */
/* MTU change may require new fragmentation! */
changed = YES;
- while (changed) {
- changed = NO;
- entries = be->sendBuffer;
- ret = be->sendBufferSize;
- for (i=0;i<ret;i++) {
- entry = entries[i];
- if (entry->len <= be->session.mtu - sizeof(P2P_PACKET_HEADER))
- continue;
- ret--;
- for (j = i; j < ret; j++)
- entries[j] = entries[j + 1]; /* preserve ordering */
- GROW(be->sendBuffer,
- be->sendBufferSize,
- ret);
- /* calling fragment will change be->sendBuffer;
- thus we need to restart from the beginning afterwards... */
- fragmentation->fragment(&be->session.sender,
- be->session.mtu - sizeof(P2P_PACKET_HEADER),
- entry->pri,
- entry->transmissionTime,
- entry->len,
- entry->callback,
- entry->closure);
- FREE(entry);
- changed = YES;
- break; /* "entries" changed as side-effect of fragment call */
- }
- } /* while changed */
+ while (changed)
+ {
+ changed = NO;
+ entries = be->sendBuffer;
+ ret = be->sendBufferSize;
+ for (i = 0; i < ret; i++)
+ {
+ entry = entries[i];
+ if (entry->len <= be->session.mtu - sizeof (P2P_PACKET_HEADER))
+ continue;
+ ret--;
+ for (j = i; j < ret; j++)
+ entries[j] = entries[j + 1]; /* preserve ordering */
+ GROW (be->sendBuffer, be->sendBufferSize, ret);
+ /* calling fragment will change be->sendBuffer;
+ thus we need to restart from the beginning afterwards... */
+ fragmentation->fragment (&be->session.sender,
+ be->session.mtu -
+ sizeof (P2P_PACKET_HEADER), entry->pri,
+ entry->transmissionTime, entry->len,
+ entry->callback, entry->closure);
+ FREE (entry);
+ changed = YES;
+ break; /* "entries" changed as side-effect of
fragment call */
+ }
+ } /* while changed */
}
/**
@@ -1433,14 +1493,16 @@
*
* @return OK on success, NO on error
*/
-static int ensureTransportConnected(BufferEntry * be) {
+static int
+ensureTransportConnected (BufferEntry * be)
+{
if (be->session.tsession != NULL)
return OK;
- be->session.tsession = transport->connectFreely(&be->session.sender, YES);
+ be->session.tsession = transport->connectFreely (&be->session.sender, YES);
if (be->session.tsession == NULL)
return NO;
- be->session.mtu = transport->getMTU(be->session.tsession->ttype);
- fragmentIfNecessary(be);
+ be->session.mtu = transport->getMTU (be->session.tsession->ttype);
+ fragmentIfNecessary (be);
return OK;
}
@@ -1454,7 +1516,9 @@
* @param be connection of the buffer that is to be transmitted
* @return YES if we might want to be re-run
*/
-static int sendBuffer(BufferEntry * be) {
+static int
+sendBuffer (BufferEntry * be)
+{
unsigned int i;
unsigned int j;
unsigned int p;
@@ -1466,232 +1530,230 @@
void *encryptedMsg;
unsigned int totalMessageSize;
int ret;
- SendEntry ** entries;
+ SendEntry **entries;
unsigned int stotal;
- ENTRY();
+ ENTRY ();
/* fast ways out */
- if (be == NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- if ( (be->status != STAT_UP) ||
- (be->sendBufferSize == 0) ||
- (be->inSendBuffer == YES) ) {
- return NO; /* must not run */
- }
+ if (be == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ if ((be->status != STAT_UP) ||
+ (be->sendBufferSize == 0) || (be->inSendBuffer == YES))
+ {
+ return NO; /* must not run */
+ }
be->inSendBuffer = YES;
- if ( (OK != ensureTransportConnected(be)) ||
- (OK != checkSendFrequency(be)) ){
- be->inSendBuffer = NO;
- return NO;
- }
+ if ((OK != ensureTransportConnected (be)) ||
+ (OK != checkSendFrequency (be)))
+ {
+ be->inSendBuffer = NO;
+ return NO;
+ }
/* test if receiver has enough bandwidth available! */
- updateCurBPS(be);
- totalMessageSize = selectMessagesToSend(be, &priority);
- if (totalMessageSize == 0) {
- expireSendBufferEntries(be);
- be->inSendBuffer = NO;
- return NO; /* deferr further */
- }
- GE_ASSERT(ectx,
- totalMessageSize > sizeof(P2P_PACKET_HEADER));
- if ( (be->session.mtu != 0) &&
- (totalMessageSize > be->session.mtu) ) {
- GE_BREAK(ectx, 0);
- be->inSendBuffer = NO;
- return NO;
- }
- ret = transport->testWouldTry(be->session.tsession,
- totalMessageSize,
- (priority >= EXTREME_PRIORITY) ? YES : NO);
+ updateCurBPS (be);
+ totalMessageSize = selectMessagesToSend (be, &priority);
+ if (totalMessageSize == 0)
+ {
+ expireSendBufferEntries (be);
+ be->inSendBuffer = NO;
+ return NO; /* deferr further */
+ }
+ GE_ASSERT (ectx, totalMessageSize > sizeof (P2P_PACKET_HEADER));
+ if ((be->session.mtu != 0) && (totalMessageSize > be->session.mtu))
+ {
+ GE_BREAK (ectx, 0);
+ be->inSendBuffer = NO;
+ return NO;
+ }
+ ret = transport->testWouldTry (be->session.tsession,
+ totalMessageSize,
+ (priority >= EXTREME_PRIORITY) ? YES : NO);
/* ret: YES: ok to send, NO: not ready yet, SYSERR: session down
- or serious internal error */
- if (ret == SYSERR) {
- /* transport session is gone! re-establish! */
- transport->disconnect(be->session.tsession);
- be->session.tsession = NULL;
- ensureTransportConnected(be);
- /* This may have changed the MTU => need to re-do
- everything. Since we don't want to possibly
- loop forever, give it another shot later;
- so even if "ensureTransportConnected" succeded,
- abort for now! */
- }
- if (YES != ret) {
- /* transport's buffer full -- no point in
- creating the actual message! */
- expireSendBufferEntries(be);
- be->inSendBuffer = NO;
- return NO;
- }
+ or serious internal error */
+ if (ret == SYSERR)
+ {
+ /* transport session is gone! re-establish! */
+ transport->disconnect (be->session.tsession);
+ be->session.tsession = NULL;
+ ensureTransportConnected (be);
+ /* This may have changed the MTU => need to re-do
+ everything. Since we don't want to possibly
+ loop forever, give it another shot later;
+ so even if "ensureTransportConnected" succeded,
+ abort for now! */
+ }
+ if (YES != ret)
+ {
+ /* transport's buffer full -- no point in
+ creating the actual message! */
+ expireSendBufferEntries (be);
+ be->inSendBuffer = NO;
+ return NO;
+ }
/* check if we (sender) have enough bandwidth available
if so, trigger callbacks on selected entries; if either
fails, return (but clean up garbage) */
- if ( (SYSERR == outgoingCheck(priority,
- totalMessageSize / sizeof(P2P_PACKET_HEADER))) ||
- (0 == prepareSelectedMessages(be)) ) {
- expireSendBufferEntries(be);
- be->inSendBuffer = NO;
- return NO; /* deferr further */
- }
+ if ((SYSERR == outgoingCheck (priority,
+ totalMessageSize /
+ sizeof (P2P_PACKET_HEADER)))
+ || (0 == prepareSelectedMessages (be)))
+ {
+ expireSendBufferEntries (be);
+ be->inSendBuffer = NO;
+ return NO; /* deferr further */
+ }
/* get permutation of SendBuffer Entries
such that SE_FLAGS are obeyed */
- entries = permuteSendBuffer(be, &stotal);
- if ( (stotal == 0) || (entries == NULL) ) {
- /* no messages selected!? */
- GE_BREAK(ectx, 0);
- be->inSendBuffer = NO;
- FREE(entries);
- return NO;
- }
+ entries = permuteSendBuffer (be, &stotal);
+ if ((stotal == 0) || (entries == NULL))
+ {
+ /* no messages selected!? */
+ GE_BREAK (ectx, 0);
+ be->inSendBuffer = NO;
+ FREE (entries);
+ return NO;
+ }
/* build message */
- plaintextMsg = MALLOC(totalMessageSize);
+ plaintextMsg = MALLOC (totalMessageSize);
p2pHdr = (P2P_PACKET_HEADER *) plaintextMsg;
- p2pHdr->timeStamp = htonl(TIME(NULL));
- p2pHdr->sequenceNumber = htonl(be->lastSequenceNumberSend);
- p2pHdr->bandwidth = htonl(be->idealized_limit);
- p = sizeof(P2P_PACKET_HEADER);
- for (i = 0; i < stotal; i++) {
- SendEntry * entry = entries[i];
+ p2pHdr->timeStamp = htonl (TIME (NULL));
+ p2pHdr->sequenceNumber = htonl (be->lastSequenceNumberSend);
+ p2pHdr->bandwidth = htonl (be->idealized_limit);
+ p = sizeof (P2P_PACKET_HEADER);
+ for (i = 0; i < stotal; i++)
+ {
+ SendEntry *entry = entries[i];
- GE_ASSERT(ectx,
- (entry != NULL) &&
- (entry->knapsackSolution == YES) &&
- (entry->callback == NULL) &&
- (p + entry->len <= totalMessageSize));
- memcpy(&plaintextMsg[p],
- entry->closure,
- entry->len);
- p += entry->len;
- }
- FREE(entries);
+ GE_ASSERT (ectx,
+ (entry != NULL) &&
+ (entry->knapsackSolution == YES) &&
+ (entry->callback == NULL) &&
+ (p + entry->len <= totalMessageSize));
+ memcpy (&plaintextMsg[p], entry->closure, entry->len);
+ p += entry->len;
+ }
+ FREE (entries);
entries = NULL;
- if (p > totalMessageSize) {
- GE_BREAK(ectx, 0);
- FREE(plaintextMsg);
- be->inSendBuffer = NO;
- return NO;
- }
+ if (p > totalMessageSize)
+ {
+ GE_BREAK (ectx, 0);
+ FREE (plaintextMsg);
+ be->inSendBuffer = NO;
+ return NO;
+ }
/* still room left? try callbacks! */
pos = scl_nextHead;
- while ( (pos != NULL) &&
- (p < totalMessageSize) ) {
- if ( (pos->minimumPadding + p >= p) &&
- (pos->minimumPadding + p <= totalMessageSize) ) {
- rsi = pos->callback(&be->session.sender,
- &plaintextMsg[p],
- totalMessageSize - p);
- GE_BREAK(ectx,
- rsi + p <= totalMessageSize);
- if ( (rsi + p < p) ||
- (rsi + p > totalMessageSize) ) {
- GE_BREAK(ectx, 0);
- FREE(plaintextMsg);
- be->inSendBuffer = NO;
- return NO;
- }
- p += rsi;
+ while ((pos != NULL) && (p < totalMessageSize))
+ {
+ if ((pos->minimumPadding + p >= p) &&
+ (pos->minimumPadding + p <= totalMessageSize))
+ {
+ rsi = pos->callback (&be->session.sender,
+ &plaintextMsg[p], totalMessageSize - p);
+ GE_BREAK (ectx, rsi + p <= totalMessageSize);
+ if ((rsi + p < p) || (rsi + p > totalMessageSize))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (plaintextMsg);
+ be->inSendBuffer = NO;
+ return NO;
+ }
+ p += rsi;
+ }
+ pos = pos->next;
}
- pos = pos->next;
- }
- if ( ( (be->session.mtu != 0) &&
- (p > be->session.mtu) )
- || (p > totalMessageSize) ) {
- GE_BREAK(ectx, 0);
- FREE(plaintextMsg);
- be->inSendBuffer = NO;
- return NO;
- }
+ if (((be->session.mtu != 0) &&
+ (p > be->session.mtu)) || (p > totalMessageSize))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (plaintextMsg);
+ be->inSendBuffer = NO;
+ return NO;
+ }
/* finally padd with noise */
- if ( (p + sizeof(MESSAGE_HEADER) <= totalMessageSize) &&
- (p < totalMessageSize) &&
- (p + sizeof(MESSAGE_HEADER) > p) &&
- (disable_random_padding == NO) ) {
- MESSAGE_HEADER part;
- unsigned short noiseLen = totalMessageSize - p;
+ if ((p + sizeof (MESSAGE_HEADER) <= totalMessageSize) &&
+ (p < totalMessageSize) &&
+ (p + sizeof (MESSAGE_HEADER) > p) && (disable_random_padding == NO))
+ {
+ MESSAGE_HEADER part;
+ unsigned short noiseLen = totalMessageSize - p;
- part.size = htons(noiseLen);
- part.type = htons(P2P_PROTO_noise);
- memcpy(&plaintextMsg[p],
- &part,
- sizeof(MESSAGE_HEADER));
- for (i = p + sizeof(MESSAGE_HEADER); i < totalMessageSize; i++)
- plaintextMsg[i] = (char) rand();
- p = totalMessageSize;
- if (stats != NULL)
- stats->change(stat_noise_sent, noiseLen);
- }
- if ( ( (be->session.mtu != 0) &&
- (p > be->session.mtu) )
- || (p > totalMessageSize) ) {
- GE_BREAK(ectx, 0);
- FREE(plaintextMsg);
- be->inSendBuffer = NO;
- return NO;
- }
+ part.size = htons (noiseLen);
+ part.type = htons (P2P_PROTO_noise);
+ memcpy (&plaintextMsg[p], &part, sizeof (MESSAGE_HEADER));
+ for (i = p + sizeof (MESSAGE_HEADER); i < totalMessageSize; i++)
+ plaintextMsg[i] = (char) rand ();
+ p = totalMessageSize;
+ if (stats != NULL)
+ stats->change (stat_noise_sent, noiseLen);
+ }
+ if (((be->session.mtu != 0) &&
+ (p > be->session.mtu)) || (p > totalMessageSize))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (plaintextMsg);
+ be->inSendBuffer = NO;
+ return NO;
+ }
- encryptedMsg = MALLOC(p);
- hash(&p2pHdr->sequenceNumber,
- p - sizeof(HashCode512),
- (HashCode512 *) encryptedMsg);
- ret = encryptBlock(&p2pHdr->sequenceNumber,
- p - sizeof(HashCode512),
- &be->skey_local,
- (const INITVECTOR *) encryptedMsg, /* IV */
- &((P2P_PACKET_HEADER *) encryptedMsg)->sequenceNumber);
- if(stats != NULL)
- stats->change(stat_encrypted,
- p - sizeof(HashCode512));
- GE_ASSERT(ectx, be->session.tsession != NULL);
- ret = transport->send(be->session.tsession,
- encryptedMsg,
- p,
- NO);
- if ( (ret == NO) &&
- (priority >= EXTREME_PRIORITY) ) {
- ret = transport->send(be->session.tsession,
- encryptedMsg,
- p,
- YES);
- }
- if (ret == YES) {
- if(stats != NULL)
- stats->change(stat_transmitted, p);
- be->available_send_window -= p;
- be->lastSequenceNumberSend++;
- if (be->idealized_limit > be->max_transmitted_limit)
- be->max_transmitted_limit = be->idealized_limit;
- else /* age */
- be->max_transmitted_limit
- = (be->idealized_limit + be->max_transmitted_limit * 3) / 4;
+ encryptedMsg = MALLOC (p);
+ hash (&p2pHdr->sequenceNumber,
+ p - sizeof (HashCode512), (HashCode512 *) encryptedMsg);
+ ret = encryptBlock (&p2pHdr->sequenceNumber, p - sizeof (HashCode512),
&be->skey_local, (const INITVECTOR *) encryptedMsg, /* IV */
+ &((P2P_PACKET_HEADER *) encryptedMsg)->sequenceNumber);
+ if (stats != NULL)
+ stats->change (stat_encrypted, p - sizeof (HashCode512));
+ GE_ASSERT (ectx, be->session.tsession != NULL);
+ ret = transport->send (be->session.tsession, encryptedMsg, p, NO);
+ if ((ret == NO) && (priority >= EXTREME_PRIORITY))
+ {
+ ret = transport->send (be->session.tsession, encryptedMsg, p, YES);
+ }
+ if (ret == YES)
+ {
+ if (stats != NULL)
+ stats->change (stat_transmitted, p);
+ be->available_send_window -= p;
+ be->lastSequenceNumberSend++;
+ if (be->idealized_limit > be->max_transmitted_limit)
+ be->max_transmitted_limit = be->idealized_limit;
+ else /* age */
+ be->max_transmitted_limit
+ = (be->idealized_limit + be->max_transmitted_limit * 3) / 4;
- if (rsnSize > 0) {
- j = sizeof(P2P_PACKET_HEADER);
- while (j < p) {
- MESSAGE_HEADER * part = (MESSAGE_HEADER *) &plaintextMsg[j];
- unsigned short plen = ntohs(MAKE_UNALIGNED(part->size));
- if (plen < sizeof(MESSAGE_HEADER)) {
- GE_BREAK(ectx, 0);
- break;
+ if (rsnSize > 0)
+ {
+ j = sizeof (P2P_PACKET_HEADER);
+ while (j < p)
+ {
+ MESSAGE_HEADER *part = (MESSAGE_HEADER *) & plaintextMsg[j];
+ unsigned short plen = ntohs (MAKE_UNALIGNED (part->size));
+ if (plen < sizeof (MESSAGE_HEADER))
+ {
+ GE_BREAK (ectx, 0);
+ break;
+ }
+ for (rsi = 0; rsi < rsnSize; rsi++)
+ rsns[rsi] (&be->session.sender, part);
+ j += plen;
+ }
}
- for (rsi = 0; rsi < rsnSize; rsi++)
- rsns[rsi](&be->session.sender, part);
- j += plen;
- }
+ freeSelectedEntries (be);
}
- freeSelectedEntries(be);
- }
- if ((ret == SYSERR) && (be->session.tsession != NULL)) {
- transport->disconnect(be->session.tsession);
- be->session.tsession = NULL;
- }
+ if ((ret == SYSERR) && (be->session.tsession != NULL))
+ {
+ transport->disconnect (be->session.tsession);
+ be->session.tsession = NULL;
+ }
- FREE(encryptedMsg);
- FREE(plaintextMsg);
- expireSendBufferEntries(be);
+ FREE (encryptedMsg);
+ FREE (plaintextMsg);
+ expireSendBufferEntries (be);
be->inSendBuffer = NO;
return NO;
}
@@ -1703,8 +1765,9 @@
* @param be on which connection to transmit
* @param se what to transmit (with meta-data)
*/
-static void appendToBuffer(BufferEntry * be,
- SendEntry * se) {
+static void
+appendToBuffer (BufferEntry * be, SendEntry * se)
+{
#if DEBUG_CONNECTION
EncName enc;
#endif
@@ -1713,86 +1776,87 @@
SendEntry **ne;
unsigned long long queueSize;
- ENTRY();
- if ( (se == NULL) ||
- (se->len == 0) ) {
- GE_BREAK(ectx, 0);
- FREENONNULL(se);
- return;
- }
- if ( (be->session.mtu != 0) &&
- (se->len > be->session.mtu - sizeof(P2P_PACKET_HEADER)) ) {
- /* this message is so big that it must be fragmented! */
- fragmentation->fragment(&be->session.sender,
- be->session.mtu - sizeof(P2P_PACKET_HEADER),
- se->pri,
- se->transmissionTime,
- se->len,
- se->callback,
- se->closure);
- FREE(se);
- return;
- }
+ ENTRY ();
+ if ((se == NULL) || (se->len == 0))
+ {
+ GE_BREAK (ectx, 0);
+ FREENONNULL (se);
+ return;
+ }
+ if ((be->session.mtu != 0) &&
+ (se->len > be->session.mtu - sizeof (P2P_PACKET_HEADER)))
+ {
+ /* this message is so big that it must be fragmented! */
+ fragmentation->fragment (&be->session.sender,
+ be->session.mtu - sizeof (P2P_PACKET_HEADER),
+ se->pri,
+ se->transmissionTime,
+ se->len, se->callback, se->closure);
+ FREE (se);
+ return;
+ }
- if ( (be->sendBufferSize > 0) &&
- (be->status != STAT_UP) ) {
- /* as long as we do not have a confirmed
- connection, do NOT queue messages! */
+ if ((be->sendBufferSize > 0) && (be->status != STAT_UP))
+ {
+ /* as long as we do not have a confirmed
+ connection, do NOT queue messages! */
#if DEBUG_CONNECTION
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&be->session.sender.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "not connected to `%s', message dropped\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&be->session.sender.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "not connected to `%s', message dropped\n", &enc);
#endif
- FREE(se->closure);
- FREE(se);
- return;
- }
+ FREE (se->closure);
+ FREE (se);
+ return;
+ }
queueSize = 0;
for (i = 0; i < be->sendBufferSize; i++)
queueSize += be->sendBuffer[i]->len;
- if (queueSize >= MAX_SEND_BUFFER_SIZE) {
- /* first, try to remedy! */
- sendBuffer(be);
- /* did it work? */
+ if (queueSize >= MAX_SEND_BUFFER_SIZE)
+ {
+ /* first, try to remedy! */
+ sendBuffer (be);
+ /* did it work? */
- queueSize = 0;
- for (i = 0; i < be->sendBufferSize; i++)
- queueSize += be->sendBuffer[i]->len;
+ queueSize = 0;
+ for (i = 0; i < be->sendBufferSize; i++)
+ queueSize += be->sendBuffer[i]->len;
- if (queueSize >= MAX_SEND_BUFFER_SIZE) {
- /* we need to enforce some hard limit here, otherwise we may take
- FAR too much memory (200 MB easily) */
- FREE(se->closure);
- FREE(se);
- return;
+ if (queueSize >= MAX_SEND_BUFFER_SIZE)
+ {
+ /* we need to enforce some hard limit here, otherwise we may take
+ FAR too much memory (200 MB easily) */
+ FREE (se->closure);
+ FREE (se);
+ return;
+ }
}
- }
/* grow send buffer, insertion sort! */
- ne = MALLOC((be->sendBufferSize + 1) * sizeof(SendEntry *));
- GE_ASSERT(ectx, se->len != 0);
+ ne = MALLOC ((be->sendBufferSize + 1) * sizeof (SendEntry *));
+ GE_ASSERT (ectx, se->len != 0);
apri = (float) se->pri / (float) se->len;
i = 0;
- while((i < be->sendBufferSize) &&
- (((float) be->sendBuffer[i]->pri /
- (float) be->sendBuffer[i]->len) >= apri)) {
- ne[i] = be->sendBuffer[i];
- i++;
- }
+ while ((i < be->sendBufferSize) &&
+ (((float) be->sendBuffer[i]->pri /
+ (float) be->sendBuffer[i]->len) >= apri))
+ {
+ ne[i] = be->sendBuffer[i];
+ i++;
+ }
ne[i++] = se;
- while(i < be->sendBufferSize + 1) {
- ne[i] = be->sendBuffer[i - 1];
- i++;
- }
- FREENONNULL(be->sendBuffer);
+ while (i < be->sendBufferSize + 1)
+ {
+ ne[i] = be->sendBuffer[i - 1];
+ i++;
+ }
+ FREENONNULL (be->sendBuffer);
be->sendBuffer = ne;
be->sendBufferSize++;
- sendBuffer(be);
+ sendBuffer (be);
}
/**
@@ -1802,16 +1866,19 @@
* @param hostId the ID of the peer for which the connection is returned
* @return the connection of the host in the table, NULL if not connected
*/
-static BufferEntry *lookForHost(const PeerIdentity * hostId) {
+static BufferEntry *
+lookForHost (const PeerIdentity * hostId)
+{
BufferEntry *root;
- root = CONNECTION_buffer_[computeIndex(hostId)];
- while(root != NULL) {
- if(equalsHashCode512(&hostId->hashPubKey,
- &root->session.sender.hashPubKey))
- return root;
- root = root->overflowChain;
- }
+ root = CONNECTION_buffer_[computeIndex (hostId)];
+ while (root != NULL)
+ {
+ if (equalsHashCode512 (&hostId->hashPubKey,
+ &root->session.sender.hashPubKey))
+ return root;
+ root = root->overflowChain;
+ }
return NULL;
}
@@ -1827,41 +1894,44 @@
* @return the table entry for the host
*/
static BufferEntry *
-addHost(const PeerIdentity * hostId,
- int establishSession) {
+addHost (const PeerIdentity * hostId, int establishSession)
+{
BufferEntry *root;
BufferEntry *prev;
unsigned int index;
- ENTRY();
- root = lookForHost(hostId);
- index = computeIndex(hostId);
- if (root == NULL) {
- root = CONNECTION_buffer_[index];
- prev = NULL;
- while (NULL != root) {
- /* settle for entry in the linked list that is down */
- if ( (root->status == STAT_DOWN) ||
- (equalsHashCode512(&hostId->hashPubKey,
- &root->session.sender.hashPubKey)))
- break;
- prev = root;
- root = root->overflowChain;
+ ENTRY ();
+ root = lookForHost (hostId);
+ index = computeIndex (hostId);
+ if (root == NULL)
+ {
+ root = CONNECTION_buffer_[index];
+ prev = NULL;
+ while (NULL != root)
+ {
+ /* settle for entry in the linked list that is down */
+ if ((root->status == STAT_DOWN) ||
+ (equalsHashCode512 (&hostId->hashPubKey,
+ &root->session.sender.hashPubKey)))
+ break;
+ prev = root;
+ root = root->overflowChain;
+ }
+ if (root == NULL)
+ {
+ root = initBufferEntry ();
+ if (prev == NULL)
+ CONNECTION_buffer_[index] = root;
+ else
+ prev->overflowChain = root;
+ }
+ root->session.sender = *hostId;
}
- if(root == NULL) {
- root = initBufferEntry();
- if(prev == NULL)
- CONNECTION_buffer_[index] = root;
- else
- prev->overflowChain = root;
+ if ((root->status == STAT_DOWN) && (establishSession == YES))
+ {
+ root->lastSequenceNumberReceived = 0;
+ session->tryConnect (hostId);
}
- root->session.sender = *hostId;
- }
- if ( (root->status == STAT_DOWN) &&
- (establishSession == YES) ) {
- root->lastSequenceNumberReceived = 0;
- session->tryConnect(hostId);
- }
return root;
}
@@ -1874,23 +1944,27 @@
* @param arg the second argument to the method
* @return the number of connected hosts
*/
-static int forAllConnectedHosts(BufferEntryCallback method,
- void *arg) {
+static int
+forAllConnectedHosts (BufferEntryCallback method, void *arg)
+{
unsigned int i;
int count = 0;
- BufferEntry * be;
+ BufferEntry *be;
- for(i=0;i<CONNECTION_MAX_HOSTS_;i++) {
- be = CONNECTION_buffer_[i];
- while (be != NULL) {
- if (be->status == STAT_UP) {
- if (method != NULL)
- method(be, arg);
- count++;
- }
- be = be->overflowChain;
+ for (i = 0; i < CONNECTION_MAX_HOSTS_; i++)
+ {
+ be = CONNECTION_buffer_[i];
+ while (be != NULL)
+ {
+ if (be->status == STAT_UP)
+ {
+ if (method != NULL)
+ method (be, arg);
+ count++;
+ }
+ be = be->overflowChain;
+ }
}
- }
return count;
}
@@ -1901,13 +1975,14 @@
* @param arg closure of type fENHWrap giving the function
* to call
*/
-static void fENHCallback(BufferEntry * be,
- void *arg) {
+static void
+fENHCallback (BufferEntry * be, void *arg)
+{
fENHWrap *wrap;
wrap = (fENHWrap *) arg;
- if(wrap->method != NULL)
- wrap->method(&be->session.sender, wrap->arg);
+ if (wrap->method != NULL)
+ wrap->method (&be->session.sender, wrap->arg);
}
/**
@@ -1917,79 +1992,81 @@
*
* @param be the connection to shutdown
*/
-static void shutdownConnection(BufferEntry * be) {
+static void
+shutdownConnection (BufferEntry * be)
+{
P2P_hangup_MESSAGE hangup;
unsigned int i;
#if DEBUG_CONNECTION
EncName enc;
#endif
- ENTRY();
+ ENTRY ();
#if DEBUG_CONNECTION
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- hash2enc(&be->session.sender.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Shutting down connection with `%s'\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ hash2enc (&be->session.sender.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Shutting down connection with `%s'\n", &enc);
#endif
- if(be->status == STAT_DOWN)
+ if (be->status == STAT_DOWN)
return; /* nothing to do */
- if(be->status == STAT_UP) {
- SendEntry * se;
+ if (be->status == STAT_UP)
+ {
+ SendEntry *se;
- hangup.header.type = htons(P2P_PROTO_hangup);
- hangup.header.size = htons(sizeof(P2P_hangup_MESSAGE));
- identity->getPeerIdentity(identity->getPublicPrivateKey(),
- &hangup.sender);
- se = MALLOC(sizeof(SendEntry));
- se->len = sizeof(P2P_hangup_MESSAGE);
- se->flags = SE_FLAG_PLACE_TAIL;
- se->pri = EXTREME_PRIORITY;
- se->transmissionTime = get_time(); /* now */
- se->callback = NULL;
- se->closure = MALLOC(sizeof(P2P_hangup_MESSAGE));
- se->knapsackSolution = NO;
- memcpy(se->closure,
- &hangup,
- sizeof(P2P_hangup_MESSAGE));
- appendToBuffer(be, se);
- if(stats != NULL)
- stats->change(stat_hangupSent, 1);
- /* override send frequency and
- really try hard to get the HANGUP
- out! */
- be->lastSendAttempt = 0;
- sendBuffer(be);
- }
+ hangup.header.type = htons (P2P_PROTO_hangup);
+ hangup.header.size = htons (sizeof (P2P_hangup_MESSAGE));
+ identity->getPeerIdentity (identity->getPublicPrivateKey (),
+ &hangup.sender);
+ se = MALLOC (sizeof (SendEntry));
+ se->len = sizeof (P2P_hangup_MESSAGE);
+ se->flags = SE_FLAG_PLACE_TAIL;
+ se->pri = EXTREME_PRIORITY;
+ se->transmissionTime = get_time (); /* now */
+ se->callback = NULL;
+ se->closure = MALLOC (sizeof (P2P_hangup_MESSAGE));
+ se->knapsackSolution = NO;
+ memcpy (se->closure, &hangup, sizeof (P2P_hangup_MESSAGE));
+ appendToBuffer (be, se);
+ if (stats != NULL)
+ stats->change (stat_hangupSent, 1);
+ /* override send frequency and
+ really try hard to get the HANGUP
+ out! */
+ be->lastSendAttempt = 0;
+ sendBuffer (be);
+ }
be->skey_remote_created = 0;
be->status = STAT_DOWN;
be->idealized_limit = MIN_BPM_PER_PEER;
be->max_transmitted_limit = MIN_BPM_PER_PEER;
- if (be->session.tsession != NULL) {
- transport->disconnect(be->session.tsession);
- be->session.tsession = NULL;
- }
- for (i=0; i<be->sendBufferSize; i++) {
- FREENONNULL(be->sendBuffer[i]->closure);
- FREE(be->sendBuffer[i]);
- }
- GROW(be->sendBuffer,
- be->sendBufferSize,
- 0);
+ if (be->session.tsession != NULL)
+ {
+ transport->disconnect (be->session.tsession);
+ be->session.tsession = NULL;
+ }
+ for (i = 0; i < be->sendBufferSize; i++)
+ {
+ FREENONNULL (be->sendBuffer[i]->closure);
+ FREE (be->sendBuffer[i]);
+ }
+ GROW (be->sendBuffer, be->sendBufferSize, 0);
}
/* ******** inbound bandwidth scheduling ************* */
-static void gatherEntries(BufferEntry * be,
- void * cls) {
- UTL_Closure * utl = cls;
+static void
+gatherEntries (BufferEntry * be, void *cls)
+{
+ UTL_Closure *utl = cls;
utl->e[utl->pos++] = be;
}
-static void resetRecentlyReceived(BufferEntry * be, void *unused) {
+static void
+resetRecentlyReceived (BufferEntry * be, void *unused)
+{
be->recently_received = 0;
}
@@ -2014,7 +2091,9 @@
* two, we specify to maintain at least 50% of the maximum
* number of connections).
*/
-static unsigned int minConnect() {
+static unsigned int
+minConnect ()
+{
return CONNECTION_MAX_HOSTS_ / 2;
}
@@ -2023,7 +2102,9 @@
* that this function is called A LOT (dozens of times per minute), so
* it should execute reasonably fast.
*/
-static void scheduleInboundTraffic() {
+static void
+scheduleInboundTraffic ()
+{
unsigned int activePeerCount;
static cron_t lastRoundStart = 0;
UTL_Closure utl;
@@ -2041,27 +2122,29 @@
int firstRound;
int earlyRun;
int load;
- int * perm;
+ int *perm;
#if DEBUG_CONNECTION
EncName enc;
#endif
- MUTEX_LOCK(lock);
- now = get_time();
+ MUTEX_LOCK (lock);
+ now = get_time ();
/* if this is the first round, don't bother... */
- if (lastRoundStart == 0) {
- /* no allocation the first time this function is called! */
- lastRoundStart = now;
- forAllConnectedHosts(&resetRecentlyReceived, NULL);
- MUTEX_UNLOCK(lock);
- return;
- }
- activePeerCount = forAllConnectedHosts(NULL, NULL);
- if (activePeerCount == 0) {
- MUTEX_UNLOCK(lock);
- return; /* nothing to be done here. */
- }
+ if (lastRoundStart == 0)
+ {
+ /* no allocation the first time this function is called! */
+ lastRoundStart = now;
+ forAllConnectedHosts (&resetRecentlyReceived, NULL);
+ MUTEX_UNLOCK (lock);
+ return;
+ }
+ activePeerCount = forAllConnectedHosts (NULL, NULL);
+ if (activePeerCount == 0)
+ {
+ MUTEX_UNLOCK (lock);
+ return; /* nothing to be done here. */
+ }
/* if time difference is too small, we don't have enough
sample data and should NOT update the limits;
@@ -2070,133 +2153,143 @@
to the limits anyway) */
timeDifference = now - lastRoundStart;
earlyRun = 0;
- if (timeDifference < MIN_SAMPLE_TIME) {
- earlyRun = 1;
- if (activePeerCount > CONNECTION_MAX_HOSTS_ / 16) {
- MUTEX_UNLOCK(lock);
- return; /* don't update too frequently, we need at
least some
+ if (timeDifference < MIN_SAMPLE_TIME)
+ {
+ earlyRun = 1;
+ if (activePeerCount > CONNECTION_MAX_HOSTS_ / 16)
+ {
+ MUTEX_UNLOCK (lock);
+ return; /* don't update too frequently, we need at
least some
semi-representative sampling! */
+ }
}
- }
if (timeDifference == 0)
timeDifference = 1;
/* build an array containing all BEs */
- entries = MALLOC(sizeof(BufferEntry *) * activePeerCount);
+ entries = MALLOC (sizeof (BufferEntry *) * activePeerCount);
utl.pos = 0;
utl.e = entries;
- forAllConnectedHosts(&gatherEntries,
- &utl);
+ forAllConnectedHosts (&gatherEntries, &utl);
/* compute latest shares based on traffic preferences */
- shares = MALLOC(sizeof(double) * activePeerCount);
+ shares = MALLOC (sizeof (double) * activePeerCount);
shareSum = 0.0;
- for (u = 0; u < activePeerCount; u++) {
- shares[u] = SHARE_DISTRIBUTION_FUNCTION(entries[u]);
- if (shares[u] < 0.0)
- shares[u] = 0.0;
- shareSum += shares[u];
- }
+ for (u = 0; u < activePeerCount; u++)
+ {
+ shares[u] = SHARE_DISTRIBUTION_FUNCTION (entries[u]);
+ if (shares[u] < 0.0)
+ shares[u] = 0.0;
+ shareSum += shares[u];
+ }
/* normalize distribution */
- if (shareSum >= 0.00001) { /* avoid numeric glitches... */
- for(u = 0; u < activePeerCount; u++)
- shares[u] = shares[u] / shareSum;
- } else {
- /* proportional shareing */
- for(u = 0; u < activePeerCount; u++)
- shares[u] = 1 / activePeerCount;
- }
+ if (shareSum >= 0.00001)
+ { /* avoid numeric glitches... */
+ for (u = 0; u < activePeerCount; u++)
+ shares[u] = shares[u] / shareSum;
+ }
+ else
+ {
+ /* proportional shareing */
+ for (u = 0; u < activePeerCount; u++)
+ shares[u] = 1 / activePeerCount;
+ }
/* compute how much bandwidth we can bargain with */
- minCon = minConnect();
+ minCon = minConnect ();
if (minCon > activePeerCount)
minCon = activePeerCount;
- if (max_bpm > minCon * MIN_BPM_PER_PEER) {
- schedulableBandwidth = max_bpm - minCon * MIN_BPM_PER_PEER;
- } else {
- schedulableBandwidth = 0;
- minCon = max_bpm / MIN_BPM_PER_PEER;
- }
- load = os_network_monitor_get_load(load_monitor,
- Download);
- if (load > 100) /* take counter measure */
+ if (max_bpm > minCon * MIN_BPM_PER_PEER)
+ {
+ schedulableBandwidth = max_bpm - minCon * MIN_BPM_PER_PEER;
+ }
+ else
+ {
+ schedulableBandwidth = 0;
+ minCon = max_bpm / MIN_BPM_PER_PEER;
+ }
+ load = os_network_monitor_get_load (load_monitor, Download);
+ if (load > 100) /* take counter measure */
schedulableBandwidth = schedulableBandwidth * 100 / load;
/* compute recent activity profile of the peer */
- adjustedRR = MALLOC(sizeof(long long) * activePeerCount);
- GE_ASSERT(ectx,
- timeDifference != 0);
- for (u=0;u<activePeerCount;u++) {
- adjustedRR[u]
- = entries[u]->recently_received * cronMINUTES / timeDifference / 2;
+ adjustedRR = MALLOC (sizeof (long long) * activePeerCount);
+ GE_ASSERT (ectx, timeDifference != 0);
+ for (u = 0; u < activePeerCount; u++)
+ {
+ adjustedRR[u]
+ = entries[u]->recently_received * cronMINUTES / timeDifference / 2;
#if DEBUG_CONNECTION
- if (adjustedRR[u] > entries[u]->idealized_limit) {
- IF_GELOG(ectx,
- GE_INFO | GE_BULK | GE_USER,
- hash2enc(&entries[u]->session.sender.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_INFO | GE_BULK | GE_USER,
- "peer `%s' transmitted above limit: %llu bpm > %u bpm\n",
- &enc,
- adjustedRR[u],
- entries[u]->idealized_limit);
- }
+ if (adjustedRR[u] > entries[u]->idealized_limit)
+ {
+ IF_GELOG (ectx,
+ GE_INFO | GE_BULK | GE_USER,
+ hash2enc (&entries[u]->session.sender.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_INFO | GE_BULK | GE_USER,
+ "peer `%s' transmitted above limit: %llu bpm > %u bpm\n",
+ &enc, adjustedRR[u], entries[u]->idealized_limit);
+ }
#endif
- /* Check for peers grossly exceeding send limits. Be a bit
- * reasonable and make the check against the max value we have
- * sent to this peer (assume announcements may have got lost).
- */
- if ( (earlyRun == 0) &&
- (adjustedRR[u] > 2 * MAX_BUF_FACT *
- entries[u]->max_transmitted_limit) &&
- (adjustedRR[u] > 2 * MAX_BUF_FACT * entries[u]->idealized_limit)) {
- entries[u]->violations++;
- entries[u]->recently_received = 0; /* "clear" slate */
- if (entries[u]->violations > 10) {
+ /* Check for peers grossly exceeding send limits. Be a bit
+ * reasonable and make the check against the max value we have
+ * sent to this peer (assume announcements may have got lost).
+ */
+ if ((earlyRun == 0) &&
+ (adjustedRR[u] > 2 * MAX_BUF_FACT *
+ entries[u]->max_transmitted_limit) &&
+ (adjustedRR[u] > 2 * MAX_BUF_FACT * entries[u]->idealized_limit))
+ {
+ entries[u]->violations++;
+ entries[u]->recently_received = 0; /* "clear" slate */
+ if (entries[u]->violations > 10)
+ {
#if DEBUG_CONNECTION
- IF_GELOG(ectx,
- GE_INFO | GE_BULK | GE_DEVELOPER,
- hash2enc(&entries[u]->session.sender.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_INFO | GE_BULK | GE_DEVELOPER,
- "blacklisting `%s': sent repeatedly %llu bpm "
- "(limit %u bpm, target %u bpm)\n",
- &enc,
- adjustedRR[u],
- entries[u]->max_transmitted_limit, entries[u]->idealized_limit);
+ IF_GELOG (ectx,
+ GE_INFO | GE_BULK | GE_DEVELOPER,
+ hash2enc (&entries[u]->session.sender.hashPubKey,
+ &enc));
+ GE_LOG (ectx,
+ GE_INFO | GE_BULK | GE_DEVELOPER,
+ "blacklisting `%s': sent repeatedly %llu bpm "
+ "(limit %u bpm, target %u bpm)\n",
+ &enc,
+ adjustedRR[u],
+ entries[u]->max_transmitted_limit,
+ entries[u]->idealized_limit);
#endif
- identity->blacklistHost(&entries[u]->session.sender,
- 24 * 60 * 60, /* 1 day */
- YES);
- shutdownConnection(entries[u]);
- activePeerCount--;
- entries[u] = entries[activePeerCount];
- shares[u] = shares[activePeerCount];
- adjustedRR[u] = adjustedRR[activePeerCount];
- u--;
- continue;
- }
- } else {
- if ( (earlyRun == 0) &&
- (adjustedRR[u] < entries[u]->max_transmitted_limit / 2) &&
- (entries[u]->violations > 0)) {
- /* allow very low traffic volume to
- balance out (rare) times of high
- volume */
- entries[u]->violations--;
- }
+ identity->blacklistHost (&entries[u]->session.sender, 24 * 60 *
60, /* 1 day */
+ YES);
+ shutdownConnection (entries[u]);
+ activePeerCount--;
+ entries[u] = entries[activePeerCount];
+ shares[u] = shares[activePeerCount];
+ adjustedRR[u] = adjustedRR[activePeerCount];
+ u--;
+ continue;
+ }
+ }
+ else
+ {
+ if ((earlyRun == 0) &&
+ (adjustedRR[u] < entries[u]->max_transmitted_limit / 2) &&
+ (entries[u]->violations > 0))
+ {
+ /* allow very low traffic volume to
+ balance out (rare) times of high
+ volume */
+ entries[u]->violations--;
+ }
+ }
+ /* even if we received NO traffic, allow
+ at least MIN_BPM_PER_PEER */
+ if (adjustedRR[u] < MIN_BPM_PER_PEER)
+ adjustedRR[u] = MIN_BPM_PER_PEER;
+ /* initial adjustedRR's should reflect aged value
+ from previous idealized_limit / iteration */
+ adjustedRR[u] = (entries[u]->idealized_limit * 3 + adjustedRR[u]) / 4;
}
- /* even if we received NO traffic, allow
- at least MIN_BPM_PER_PEER */
- if (adjustedRR[u] < MIN_BPM_PER_PEER)
- adjustedRR[u] = MIN_BPM_PER_PEER;
- /* initial adjustedRR's should reflect aged value
- from previous idealized_limit / iteration */
- adjustedRR[u] = (entries[u]->idealized_limit * 3 + adjustedRR[u]) / 4;
- }
/* now distribute the schedulableBandwidth according
to the shares. Note that since we cap peers at twice
@@ -2215,176 +2308,187 @@
firstRound = YES;
for (u = 0; u < activePeerCount; u++)
entries[u]->idealized_limit = 0;
- while ( (schedulableBandwidth > activePeerCount * 100) &&
- (activePeerCount > 0) &&
- (didAssign == YES) ) {
- didAssign = NO;
- decrementSB = 0;
- for (u = 0; u < activePeerCount; u++) {
- if ( (firstRound == NO) ||
- (entries[u]->idealized_limit < adjustedRR[u] * 2) ) {
- unsigned int share;
+ while ((schedulableBandwidth > activePeerCount * 100) &&
+ (activePeerCount > 0) && (didAssign == YES))
+ {
+ didAssign = NO;
+ decrementSB = 0;
+ for (u = 0; u < activePeerCount; u++)
+ {
+ if ((firstRound == NO) ||
+ (entries[u]->idealized_limit < adjustedRR[u] * 2))
+ {
+ unsigned int share;
- share =
- entries[u]->idealized_limit +
- (unsigned int) (shares[u] * schedulableBandwidth);
- if (share < entries[u]->idealized_limit)
- share = 0xFFFFFFFF; /* int overflow */
- if ( (share > adjustedRR[u] * 2) && (firstRound == YES) )
- share = adjustedRR[u] * 2;
- /* always allow allocating MIN_BPM_PER_PEER */
- if ( (share < MIN_BPM_PER_PEER) &&
- (minCon > 0) ) {
- /* use one of the minCon's to keep the connection! */
- share += MIN_BPM_PER_PEER;
- decrementSB -= MIN_BPM_PER_PEER; /* do not count */
- minCon--;
+ share =
+ entries[u]->idealized_limit +
+ (unsigned int) (shares[u] * schedulableBandwidth);
+ if (share < entries[u]->idealized_limit)
+ share = 0xFFFFFFFF; /* int overflow */
+ if ((share > adjustedRR[u] * 2) && (firstRound == YES))
+ share = adjustedRR[u] * 2;
+ /* always allow allocating MIN_BPM_PER_PEER */
+ if ((share < MIN_BPM_PER_PEER) && (minCon > 0))
+ {
+ /* use one of the minCon's to keep the connection! */
+ share += MIN_BPM_PER_PEER;
+ decrementSB -= MIN_BPM_PER_PEER; /* do not count */
+ minCon--;
+ }
+ if (share > entries[u]->idealized_limit)
+ {
+ decrementSB += share - entries[u]->idealized_limit;
+ didAssign = YES;
+ entries[u]->idealized_limit = share;
+ }
+ }
+ } /* end for all peers */
+
+ if (decrementSB < schedulableBandwidth)
+ {
+ schedulableBandwidth -= decrementSB;
}
- if (share > entries[u]->idealized_limit) {
- decrementSB += share - entries[u]->idealized_limit;
- didAssign = YES;
- entries[u]->idealized_limit = share;
- }
- }
- } /* end for all peers */
+ else
+ {
+ schedulableBandwidth = 0;
+ break;
+ }
+ if ((activePeerCount > 0) && (didAssign == NO))
+ {
+ perm = permute (WEAK, activePeerCount);
+ /* assign also to random "worthless" (zero-share) peers */
+ for (u = 0; u < activePeerCount; u++)
+ {
+ unsigned int v = perm[u]; /* use perm to avoid preference to
low-numbered slots */
+ if ((firstRound == NO) ||
+ (entries[v]->idealized_limit < adjustedRR[v] * 2))
+ {
+ unsigned int share;
- if (decrementSB < schedulableBandwidth) {
- schedulableBandwidth -= decrementSB;
- } else {
- schedulableBandwidth = 0;
- break;
- }
- if ( (activePeerCount > 0) &&
- (didAssign == NO) ) {
- perm = permute(WEAK, activePeerCount);
- /* assign also to random "worthless" (zero-share) peers */
- for (u = 0; u < activePeerCount; u++) {
- unsigned int v = perm[u]; /* use perm to avoid preference to
low-numbered slots */
- if ( (firstRound == NO) ||
- (entries[v]->idealized_limit < adjustedRR[v] * 2)) {
+ share =
+ entries[v]->idealized_limit +
+ (unsigned int) (schedulableBandwidth);
+ if (share < entries[v]->idealized_limit)
+ share = 0xFFFFFFFF; /* int overflow */
+ if ((firstRound == YES) && (share > adjustedRR[v] * 2))
+ share = adjustedRR[v] * 2;
+ if (share > entries[v]->idealized_limit)
+ {
+ schedulableBandwidth -=
+ share - entries[v]->idealized_limit;
+ entries[v]->idealized_limit = share;
+ }
+ }
+ }
+ FREE (perm);
+ perm = NULL;
+ } /* didAssign == NO? */
+ if (firstRound == YES)
+ {
+ /* keep some bandwidth off the market
+ for new connections */
+ schedulableBandwidth = (schedulableBandwidth * 7) / 8;
+ }
+ firstRound = NO;
+ } /* while bandwidth to distribute */
+
+ if ((schedulableBandwidth > 0) && (activePeerCount > 0))
+ {
+ /* assign rest disregarding traffic limits */
+ perm = permute (WEAK, activePeerCount);
+ for (u = 0; u < activePeerCount; u++)
+ {
unsigned int share;
+ unsigned int v = perm[u]; /* use perm to avoid preference to
low-numbered slots */
share =
entries[v]->idealized_limit +
- (unsigned int) (schedulableBandwidth);
- if (share < entries[v]->idealized_limit)
- share = 0xFFFFFFFF; /* int overflow */
- if ( (firstRound == YES) && (share > adjustedRR[v] * 2) )
- share = adjustedRR[v] * 2;
- if (share > entries[v]->idealized_limit) {
- schedulableBandwidth -= share - entries[v]->idealized_limit;
- entries[v]->idealized_limit = share;
- }
+ (unsigned int) (schedulableBandwidth / activePeerCount);
+ if (share >= entries[v]->idealized_limit)
+ { /* no int-overflow? */
+ entries[v]->idealized_limit = share;
+ }
+ else
+ {
+ entries[v]->idealized_limit = 0xFFFF0000;
+ }
}
- }
- FREE(perm);
+ schedulableBandwidth = 0;
+ FREE (perm);
perm = NULL;
- } /* didAssign == NO? */
- if (firstRound == YES) {
- /* keep some bandwidth off the market
- for new connections */
- schedulableBandwidth = (schedulableBandwidth * 7) / 8;
}
- firstRound = NO;
- } /* while bandwidth to distribute */
- if ( (schedulableBandwidth > 0) &&
- (activePeerCount > 0) ) {
- /* assign rest disregarding traffic limits */
- perm = permute(WEAK, activePeerCount);
- for (u = 0; u < activePeerCount; u++) {
- unsigned int share;
- unsigned int v = perm[u]; /* use perm to avoid preference to
low-numbered slots */
-
- share =
- entries[v]->idealized_limit +
- (unsigned int) (schedulableBandwidth / activePeerCount);
- if (share >= entries[v]->idealized_limit) { /* no int-overflow? */
- entries[v]->idealized_limit = share;
- } else {
- entries[v]->idealized_limit = 0xFFFF0000;
- }
- }
- schedulableBandwidth = 0;
- FREE(perm);
- perm = NULL;
- }
-
/* randomly add the remaining MIN_BPM_PER_PEER to minCon peers; yes, this
will
yield some fluctuation, but some amount of fluctuation should be
good since it creates opportunities. */
if (activePeerCount > 0)
- for (u=0;u<minCon;u++)
- entries[weak_randomi(activePeerCount)]->idealized_limit
+ for (u = 0; u < minCon; u++)
+ entries[weak_randomi (activePeerCount)]->idealized_limit
+= MIN_BPM_PER_PEER;
/* prepare for next round */
lastRoundStart = now;
- for (u=0;u<activePeerCount;u++) {
+ for (u = 0; u < activePeerCount; u++)
+ {
#if DEBUG_CONNECTION
- IF_GELOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- hash2enc(&entries[u]->session.sender.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- "inbound limit for peer %u: %s set to %u bpm\n",
- u,
- &enc,
- entries[u]->idealized_limit);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_BULK | GE_USER,
+ hash2enc (&entries[u]->session.sender.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_BULK | GE_USER,
+ "inbound limit for peer %u: %s set to %u bpm\n",
+ u, &enc, entries[u]->idealized_limit);
#endif
- if ( (timeDifference > 50) &&
- (weak_randomi(timeDifference + 1) > 50) )
- entries[u]->current_connection_value *= 0.9; /* age */
- decrementSB = entries[u]->idealized_limit * timeDifference / cronMINUTES /
2;
- if ( (decrementSB == 0) &&
- (weak_randomi(timeDifference + 1) != 0) )
- decrementSB = 1;
- if (entries[u]->recently_received >= decrementSB)
- entries[u]->recently_received -= decrementSB;
- else
- entries[u]->recently_received = 0;
- }
+ if ((timeDifference > 50) && (weak_randomi (timeDifference + 1) > 50))
+ entries[u]->current_connection_value *= 0.9; /* age */
+ decrementSB =
+ entries[u]->idealized_limit * timeDifference / cronMINUTES / 2;
+ if ((decrementSB == 0) && (weak_randomi (timeDifference + 1) != 0))
+ decrementSB = 1;
+ if (entries[u]->recently_received >= decrementSB)
+ entries[u]->recently_received -= decrementSB;
+ else
+ entries[u]->recently_received = 0;
+ }
/* free memory */
- FREE(adjustedRR);
- FREE(shares);
+ FREE (adjustedRR);
+ FREE (shares);
- for (u=0;u<activePeerCount;u++) {
- BufferEntry * be = entries[u];
+ for (u = 0; u < activePeerCount; u++)
+ {
+ BufferEntry *be = entries[u];
- if (be->idealized_limit < MIN_BPM_PER_PEER) {
+ if (be->idealized_limit < MIN_BPM_PER_PEER)
+ {
#if DEBUG_CONNECTION
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- hash2enc(&be->session.sender.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Number of connections too high, shutting down low-traffic connection
to `%s' (had only %u bpm)\n",
- &enc,
- be->idealized_limit);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ hash2enc (&be->session.sender.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Number of connections too high, shutting down low-traffic
connection to `%s' (had only %u bpm)\n",
+ &enc, be->idealized_limit);
#endif
- /* We need to avoid giving a too low limit (especially 0, which
- would indicate a plaintext msg). So we set the limit to the
- minimum value AND try to shutdown the connection. */
- be->idealized_limit = MIN_BPM_PER_PEER;
- /* do not try to reconnect any time soon! */
- identity->blacklistHost(&be->session.sender,
- SECONDS_BLACKLIST_AFTER_DISCONNECT,
- YES);
- shutdownConnection(be);
- } else {
+ /* We need to avoid giving a too low limit (especially 0, which
+ would indicate a plaintext msg). So we set the limit to the
+ minimum value AND try to shutdown the connection. */
+ be->idealized_limit = MIN_BPM_PER_PEER;
+ /* do not try to reconnect any time soon! */
+ identity->blacklistHost (&be->session.sender,
+ SECONDS_BLACKLIST_AFTER_DISCONNECT, YES);
+ shutdownConnection (be);
+ }
+ else
+ {
#if 0
- printf("Assigned %u bytes to peer %u\n",
- be->idealized_limit,
- u);
+ printf ("Assigned %u bytes to peer %u\n", be->idealized_limit, u);
#endif
+ }
}
- }
- FREE(entries);
- MUTEX_UNLOCK(lock);
+ FREE (entries);
+ MUTEX_UNLOCK (lock);
}
/* ******** end of inbound bandwidth scheduling ************* */
@@ -2404,10 +2508,12 @@
*
* @param unused not used, just to make signature type nicely
*/
-static void cronDecreaseLiveness(void *unused) {
- BufferEntry * root;
- BufferEntry * prev;
- BufferEntry * tmp;
+static void
+cronDecreaseLiveness (void *unused)
+{
+ BufferEntry *root;
+ BufferEntry *prev;
+ BufferEntry *tmp;
cron_t now;
int i;
unsigned long long total_allowed_sent;
@@ -2417,145 +2523,151 @@
int load_nup;
int load_cpu;
- load_cpu = os_cpu_get_load(ectx, cfg);
- load_nup = os_network_monitor_get_load(load_monitor,
- Upload);
- scheduleInboundTraffic();
- now = get_time();
+ load_cpu = os_cpu_get_load (ectx, cfg);
+ load_nup = os_network_monitor_get_load (load_monitor, Upload);
+ scheduleInboundTraffic ();
+ now = get_time ();
total_allowed_sent = 0;
total_allowed_recv = 0;
total_allowed_now = 0;
total_send_buffer_size = 0;
- MUTEX_LOCK(lock);
- for (i = 0; i < CONNECTION_MAX_HOSTS_; i++) {
- root = CONNECTION_buffer_[i];
- prev = NULL;
- while (NULL != root) {
- total_send_buffer_size += root->sendBufferSize;
- switch (root->status) {
- case STAT_DOWN:
- /* just compact linked list */
- if (prev == NULL)
- CONNECTION_buffer_[i] = root->overflowChain;
- else
- prev->overflowChain = root->overflowChain;
- tmp = root;
- root = root->overflowChain;
- FREE(tmp);
- continue; /* no need to call 'send buffer' */
- case STAT_UP:
- updateCurBPS(root);
- total_allowed_sent += root->max_bpm;
- total_allowed_recv += root->idealized_limit;
- total_allowed_now += root->available_send_window;
- if ( (now > root->isAlive) && /* concurrency might make this false...
*/
- (now - root->isAlive > SECONDS_INACTIVE_DROP * cronSECONDS) ) {
+ MUTEX_LOCK (lock);
+ for (i = 0; i < CONNECTION_MAX_HOSTS_; i++)
+ {
+ root = CONNECTION_buffer_[i];
+ prev = NULL;
+ while (NULL != root)
+ {
+ total_send_buffer_size += root->sendBufferSize;
+ switch (root->status)
+ {
+ case STAT_DOWN:
+ /* just compact linked list */
+ if (prev == NULL)
+ CONNECTION_buffer_[i] = root->overflowChain;
+ else
+ prev->overflowChain = root->overflowChain;
+ tmp = root;
+ root = root->overflowChain;
+ FREE (tmp);
+ continue; /* no need to call 'send buffer' */
+ case STAT_UP:
+ updateCurBPS (root);
+ total_allowed_sent += root->max_bpm;
+ total_allowed_recv += root->idealized_limit;
+ total_allowed_now += root->available_send_window;
+ if ((now > root->isAlive) && /* concurrency might make this
false... */
+ (now - root->isAlive > SECONDS_INACTIVE_DROP * cronSECONDS))
+ {
#if DEBUG_CONNECTION
- EncName enc;
+ EncName enc;
- /* switch state form UP to DOWN: too much inactivity */
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- hash2enc(&root->session.sender.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Closing connection with `%s': "
- "too much inactivity (%llu ms)\n",
- &enc,
- now - root->isAlive);
+ /* switch state form UP to DOWN: too much inactivity */
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ hash2enc (&root->session.sender.hashPubKey,
+ &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Closing connection with `%s': "
+ "too much inactivity (%llu ms)\n",
+ &enc, now - root->isAlive);
#endif
- /* peer timed out -- shutdown connection */
- identity->blacklistHost(&root->session.sender,
- SECONDS_BLACKLIST_AFTER_DISCONNECT,
- YES);
- shutdownConnection(root);
- }
- if ( (root->available_send_window > 35 * 1024) &&
- (root->sendBufferSize < 4) &&
- (scl_nextHead != NULL) &&
- (load_nup < IDLE_LOAD_THRESHOLD) &&
- (load_cpu < IDLE_LOAD_THRESHOLD) ) {
- /* create some traffic by force! */
- char * msgBuf;
- unsigned int mSize;
- SendCallbackList *pos;
- unsigned int hSize;
+ /* peer timed out -- shutdown connection */
+ identity->blacklistHost (&root->session.sender,
+ SECONDS_BLACKLIST_AFTER_DISCONNECT,
+ YES);
+ shutdownConnection (root);
+ }
+ if ((root->available_send_window > 35 * 1024) &&
+ (root->sendBufferSize < 4) &&
+ (scl_nextHead != NULL) &&
+ (load_nup < IDLE_LOAD_THRESHOLD) &&
+ (load_cpu < IDLE_LOAD_THRESHOLD))
+ {
+ /* create some traffic by force! */
+ char *msgBuf;
+ unsigned int mSize;
+ SendCallbackList *pos;
+ unsigned int hSize;
- hSize = root->available_send_window;
- if (hSize > 63 * 1024)
- hSize = 63 * 1024;
- msgBuf = MALLOC(hSize);
- pos = scl_nextHead;
- while ( (pos != NULL) &&
- (hSize > 0) ) {
- if (pos->minimumPadding <= hSize) {
- mSize = pos->callback(&root->session.sender,
- msgBuf,
- hSize);
- if (mSize > 0) {
- unicast(&root->session.sender,
- (MESSAGE_HEADER *) msgBuf,
- 0,
- 5 * cronMINUTES);
- if (mSize > hSize) {
- GE_BREAK(ectx, 0);
- hSize = 0;
- } else {
- hSize -= mSize;
- }
- }
- }
- pos = pos->next;
- }
- FREE(msgBuf);
- }
- break;
- default: /* not up, not down - partial SETKEY exchange */
- if ( (now > root->isAlive) &&
- (now - root->isAlive > SECONDS_NOPINGPONG_DROP * cronSECONDS)) {
+ hSize = root->available_send_window;
+ if (hSize > 63 * 1024)
+ hSize = 63 * 1024;
+ msgBuf = MALLOC (hSize);
+ pos = scl_nextHead;
+ while ((pos != NULL) && (hSize > 0))
+ {
+ if (pos->minimumPadding <= hSize)
+ {
+ mSize = pos->callback (&root->session.sender,
+ msgBuf, hSize);
+ if (mSize > 0)
+ {
+ unicast (&root->session.sender,
+ (MESSAGE_HEADER *) msgBuf,
+ 0, 5 * cronMINUTES);
+ if (mSize > hSize)
+ {
+ GE_BREAK (ectx, 0);
+ hSize = 0;
+ }
+ else
+ {
+ hSize -= mSize;
+ }
+ }
+ }
+ pos = pos->next;
+ }
+ FREE (msgBuf);
+ }
+ break;
+ default: /* not up, not down - partial SETKEY exchange */
+ if ((now > root->isAlive) &&
+ (now - root->isAlive >
+ SECONDS_NOPINGPONG_DROP * cronSECONDS))
+ {
#if DEBUG_CONNECTION
- EncName enc;
+ EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- hash2enc(&root->session.sender.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "closing connection to %s: %s not answered.\n",
- &enc,
- (root->status == STAT_SETKEY_SENT) ? "SETKEY" : "PING");
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ hash2enc (&root->session.sender.hashPubKey,
+ &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "closing connection to %s: %s not answered.\n",
+ &enc,
+ (root->status ==
+ STAT_SETKEY_SENT) ? "SETKEY" : "PING");
#endif
- /* do not try to reconnect any time soon,
- but allow the other peer to connect to
- us -- after all, we merely failed to
- establish a session in the first place! */
- identity->blacklistHost(&root->session.sender,
- SECONDS_BLACKLIST_AFTER_FAILED_CONNECT,
- NO);
- shutdownConnection(root);
- }
- break;
- } /* end of switch */
- sendBuffer(root);
- prev = root;
- root = root->overflowChain;
- } /* end of while */
- } /* for all buckets */
- MUTEX_UNLOCK(lock);
- if (stats != NULL) {
- if (total_allowed_sent > max_bpm_up)
- total_allowed_sent = max_bpm_up;
- stats->set(stat_total_allowed_sent,
- total_allowed_sent / 60); /* bpm to bps */
- stats->set(stat_total_allowed_recv,
- total_allowed_recv / 60); /* bpm to bps */
- stats->set(stat_total_allowed_now,
- total_allowed_now);
- stats->set(stat_total_send_buffer_size,
- total_send_buffer_size);
- }
+ /* do not try to reconnect any time soon,
+ but allow the other peer to connect to
+ us -- after all, we merely failed to
+ establish a session in the first place! */
+ identity->blacklistHost (&root->session.sender,
+
SECONDS_BLACKLIST_AFTER_FAILED_CONNECT,
+ NO);
+ shutdownConnection (root);
+ }
+ break;
+ } /* end of switch */
+ sendBuffer (root);
+ prev = root;
+ root = root->overflowChain;
+ } /* end of while */
+ } /* for all buckets */
+ MUTEX_UNLOCK (lock);
+ if (stats != NULL)
+ {
+ if (total_allowed_sent > max_bpm_up)
+ total_allowed_sent = max_bpm_up;
+ stats->set (stat_total_allowed_sent, total_allowed_sent / 60); /* bpm
to bps */
+ stats->set (stat_total_allowed_recv, total_allowed_recv / 60); /* bpm
to bps */
+ stats->set (stat_total_allowed_now, total_allowed_now);
+ stats->set (stat_total_send_buffer_size, total_send_buffer_size);
+ }
}
/**
@@ -2570,9 +2682,10 @@
* NO if it was in plaintext,
* SYSERR if it was malformed
*/
-int checkHeader(const PeerIdentity * sender,
- P2P_PACKET_HEADER * msg,
- unsigned short size) {
+int
+checkHeader (const PeerIdentity * sender,
+ P2P_PACKET_HEADER * msg, unsigned short size)
+{
BufferEntry *be;
int res;
unsigned int sequenceNumber;
@@ -2581,137 +2694,134 @@
HashCode512 hc;
EncName enc;
- ENTRY();
- GE_ASSERT(ectx, msg != NULL);
- GE_ASSERT(ectx, sender != NULL);
- if (size < sizeof(P2P_PACKET_HEADER)) {
- IF_GELOG(ectx,
- GE_WARNING | GE_BULK | GE_DEVELOPER,
- hash2enc(&sender->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_DEVELOPER,
- _("Message from `%s' discarded: invalid format.\n"),
- &enc);
- return SYSERR;
- }
+ ENTRY ();
+ GE_ASSERT (ectx, msg != NULL);
+ GE_ASSERT (ectx, sender != NULL);
+ if (size < sizeof (P2P_PACKET_HEADER))
+ {
+ IF_GELOG (ectx,
+ GE_WARNING | GE_BULK | GE_DEVELOPER,
+ hash2enc (&sender->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_DEVELOPER,
+ _("Message from `%s' discarded: invalid format.\n"), &enc);
+ return SYSERR;
+ }
if (stats != NULL)
- stats->change(stat_received, size);
- hash2enc(&sender->hashPubKey,
- &enc);
- hash(&msg->sequenceNumber,
- size - sizeof(HashCode512),
- &hc);
- if (equalsHashCode512(&hc,
- &msg->hash) &&
+ stats->change (stat_received, size);
+ hash2enc (&sender->hashPubKey, &enc);
+ hash (&msg->sequenceNumber, size - sizeof (HashCode512), &hc);
+ if (equalsHashCode512 (&hc,
+ &msg->hash) &&
(msg->sequenceNumber == 0) &&
- (msg->bandwidth == 0) &&
- (msg->timeStamp == 0) )
+ (msg->bandwidth == 0) && (msg->timeStamp == 0))
return NO; /* plaintext */
- MUTEX_LOCK(lock);
- be = lookForHost(sender);
- if ( (be == NULL) ||
- (be->status == STAT_DOWN) ||
- (be->status == STAT_SETKEY_SENT) ) {
+ MUTEX_LOCK (lock);
+ be = lookForHost (sender);
+ if ((be == NULL) ||
+ (be->status == STAT_DOWN) || (be->status == STAT_SETKEY_SENT))
+ {
#if DEBUG_CONNECTION
- IF_GELOG(ectx,
- GE_INFO | GE_BULK | GE_DEVELOPER,
- hash2enc(&sender->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_INFO | GE_BULK | GE_DEVELOPER,
- "Decrypting message from host `%s' failed, no sessionkey (yet)!\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_INFO | GE_BULK | GE_DEVELOPER,
+ hash2enc (&sender->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_INFO | GE_BULK | GE_DEVELOPER,
+ "Decrypting message from host `%s' failed, no sessionkey
(yet)!\n",
+ &enc);
#endif
- /* try to establish a connection, that way, we don't keep
- getting bogus messages until the other one times out. */
- if((be == NULL) || (be->status == STAT_DOWN))
- addHost(sender, YES);
- MUTEX_UNLOCK(lock);
- return SYSERR; /* could not decrypt */
- }
- tmp = MALLOC(size - sizeof(HashCode512));
- res = decryptBlock(&be->skey_remote,
- &msg->sequenceNumber,
- size - sizeof(HashCode512),
- (const INITVECTOR *) &msg->hash, /* IV */
- tmp);
- hash(tmp, size - sizeof(HashCode512), &hc);
- if (! ( (res != OK) &&
- equalsHashCode512(&hc, &msg->hash) ) ) {
+ /* try to establish a connection, that way, we don't keep
+ getting bogus messages until the other one times out. */
+ if ((be == NULL) || (be->status == STAT_DOWN))
+ addHost (sender, YES);
+ MUTEX_UNLOCK (lock);
+ return SYSERR; /* could not decrypt */
+ }
+ tmp = MALLOC (size - sizeof (HashCode512));
+ res = decryptBlock (&be->skey_remote, &msg->sequenceNumber, size - sizeof
(HashCode512), (const INITVECTOR *) &msg->hash, /* IV */
+ tmp);
+ hash (tmp, size - sizeof (HashCode512), &hc);
+ if (!((res != OK) && equalsHashCode512 (&hc, &msg->hash)))
+ {
#if DEBUG_CONNECTION
- IF_GELOG(ectx,
- GE_INFO | GE_BULK | GE_DEVELOPER,
- hash2enc(&sender->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_INFO | GE_BULK | GE_DEVELOPER,
- "Decrypting message from host `%s' failed, wrong sessionkey!\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_INFO | GE_BULK | GE_DEVELOPER,
+ hash2enc (&sender->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_INFO | GE_BULK | GE_DEVELOPER,
+ "Decrypting message from host `%s' failed, wrong sessionkey!\n",
+ &enc);
#endif
- addHost(sender, YES);
- MUTEX_UNLOCK(lock);
- FREE(tmp);
- return SYSERR;
- }
+ addHost (sender, YES);
+ MUTEX_UNLOCK (lock);
+ FREE (tmp);
+ return SYSERR;
+ }
if (stats != NULL)
- stats->change(stat_decrypted, size - sizeof(HashCode512));
- memcpy(&msg->sequenceNumber, tmp, size - sizeof(HashCode512));
- FREE(tmp);
+ stats->change (stat_decrypted, size - sizeof (HashCode512));
+ memcpy (&msg->sequenceNumber, tmp, size - sizeof (HashCode512));
+ FREE (tmp);
res = YES;
- sequenceNumber = ntohl(msg->sequenceNumber);
- if (be->lastSequenceNumberReceived >= sequenceNumber) {
- res = SYSERR;
- if ( (be->lastSequenceNumberReceived - sequenceNumber <= 32) &&
- (be->lastSequenceNumberReceived != sequenceNumber) ) {
- unsigned int rotbit =
- 1 << (be->lastSequenceNumberReceived - sequenceNumber - 1);
- if ((be->lastPacketsBitmap & rotbit) == 0) {
- be->lastPacketsBitmap |= rotbit;
- res = OK;
- }
+ sequenceNumber = ntohl (msg->sequenceNumber);
+ if (be->lastSequenceNumberReceived >= sequenceNumber)
+ {
+ res = SYSERR;
+ if ((be->lastSequenceNumberReceived - sequenceNumber <= 32) &&
+ (be->lastSequenceNumberReceived != sequenceNumber))
+ {
+ unsigned int rotbit =
+ 1 << (be->lastSequenceNumberReceived - sequenceNumber - 1);
+ if ((be->lastPacketsBitmap & rotbit) == 0)
+ {
+ be->lastPacketsBitmap |= rotbit;
+ res = OK;
+ }
+ }
+ if (res == SYSERR)
+ {
+#if DEBUG_CONNECTION
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ _("Invalid sequence number"
+ " %u <= %u, dropping message.\n"),
+ sequenceNumber, be->lastSequenceNumberReceived);
+#endif
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
}
- if (res == SYSERR) {
+ else
+ {
+ be->lastPacketsBitmap =
+ be->lastPacketsBitmap
+ << (sequenceNumber - be->lastSequenceNumberReceived);
+ be->lastSequenceNumberReceived = sequenceNumber;
+ }
+ stamp = ntohl (msg->timeStamp);
+ if (stamp + 1 * cronDAYS < TIME (NULL))
+ {
#if DEBUG_CONNECTION
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- _("Invalid sequence number"
- " %u <= %u, dropping message.\n"),
- sequenceNumber,
- be->lastSequenceNumberReceived);
+ GE_LOG (ectx,
+ GE_INFO | GE_BULK | GE_USER,
+ _("Message received more than one day old. Dropped.\n"));
#endif
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return SYSERR;
}
- } else {
- be->lastPacketsBitmap =
- be->lastPacketsBitmap
- << (sequenceNumber - be->lastSequenceNumberReceived);
- be->lastSequenceNumberReceived = sequenceNumber;
- }
- stamp = ntohl(msg->timeStamp);
- if (stamp + 1 * cronDAYS < TIME(NULL)) {
-#if DEBUG_CONNECTION
- GE_LOG(ectx,
- GE_INFO | GE_BULK | GE_USER,
- _("Message received more than one day old. Dropped.\n"));
-#endif
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- be->max_bpm = ntohl(msg->bandwidth);
- if (be->available_send_window > (long long) be->max_bpm * MAX_BUF_FACT) {
- if (stats != NULL)
- stats->change(stat_total_lost_sent,
- be->available_send_window
- - (long long) be->max_bpm * MAX_BUF_FACT);
- be->available_send_window = (long long) be->max_bpm * MAX_BUF_FACT;
- be->last_bps_update = get_time();
- }
+ be->max_bpm = ntohl (msg->bandwidth);
+ if (be->available_send_window > (long long) be->max_bpm * MAX_BUF_FACT)
+ {
+ if (stats != NULL)
+ stats->change (stat_total_lost_sent,
+ be->available_send_window
+ - (long long) be->max_bpm * MAX_BUF_FACT);
+ be->available_send_window = (long long) be->max_bpm * MAX_BUF_FACT;
+ be->last_bps_update = get_time ();
+ }
be->recently_received += size;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return YES;
}
@@ -2723,42 +2833,41 @@
* @param msg the HANGUP message
* @return OK on success, SYSERR on error
*/
-static int handleHANGUP(const PeerIdentity * sender,
- const MESSAGE_HEADER * msg) {
+static int
+handleHANGUP (const PeerIdentity * sender, const MESSAGE_HEADER * msg)
+{
BufferEntry *be;
#if DEBUG_CONNECTION
EncName enc;
#endif
- ENTRY();
- if (ntohs(msg->size) != sizeof(P2P_hangup_MESSAGE))
+ ENTRY ();
+ if (ntohs (msg->size) != sizeof (P2P_hangup_MESSAGE))
return SYSERR;
- if(0 != memcmp(sender,
- &((P2P_hangup_MESSAGE *) msg)->sender,
- sizeof(PeerIdentity)))
+ if (0 != memcmp (sender,
+ &((P2P_hangup_MESSAGE *) msg)->sender,
+ sizeof (PeerIdentity)))
return SYSERR;
#if DEBUG_CONNECTION
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- hash2enc(&sender->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "received HANGUP from `%s'\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ hash2enc (&sender->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "received HANGUP from `%s'\n", &enc);
#endif
- MUTEX_LOCK(lock);
- be = lookForHost(sender);
- if(be == NULL) {
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
+ MUTEX_LOCK (lock);
+ be = lookForHost (sender);
+ if (be == NULL)
+ {
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
/* do not try to reconnect any time soon! */
- identity->blacklistHost(&be->session.sender,
- SECONDS_BLACKLIST_AFTER_DISCONNECT,
- YES);
- shutdownConnection(be);
- MUTEX_UNLOCK(lock);
+ identity->blacklistHost (&be->session.sender,
+ SECONDS_BLACKLIST_AFTER_DISCONNECT, YES);
+ shutdownConnection (be);
+ MUTEX_UNLOCK (lock);
return OK;
}
@@ -2773,37 +2882,41 @@
* @param forSending NO if it is the key for receiving,
* YES if it is the key for sending
*/
-void assignSessionKey(const SESSIONKEY * key,
- const PeerIdentity * peer,
- TIME_T age,
- int forSending) {
+void
+assignSessionKey (const SESSIONKEY * key,
+ const PeerIdentity * peer, TIME_T age, int forSending)
+{
BufferEntry *be;
- MUTEX_LOCK(lock);
- be = lookForHost(peer);
+ MUTEX_LOCK (lock);
+ be = lookForHost (peer);
if (be == NULL)
- be = addHost(peer, NO);
- if (be != NULL) {
- be->isAlive = get_time();
- if (forSending == YES) {
- be->skey_local = *key;
- be->skey_local_created = age;
- be->status = STAT_SETKEY_SENT | (be->status & STAT_SETKEY_RECEIVED);
- } else { /* for receiving */
- if ( ((be->status & STAT_SETKEY_RECEIVED) == 0) ||
- (be->skey_remote_created < age) ) {
- if (0 != memcmp(key,
- &be->skey_remote,
- sizeof(SESSIONKEY))) {
- be->skey_remote = *key;
- be->lastSequenceNumberReceived = 0;
+ be = addHost (peer, NO);
+ if (be != NULL)
+ {
+ be->isAlive = get_time ();
+ if (forSending == YES)
+ {
+ be->skey_local = *key;
+ be->skey_local_created = age;
+ be->status = STAT_SETKEY_SENT | (be->status & STAT_SETKEY_RECEIVED);
}
- be->skey_remote_created = age;
- be->status |= STAT_SETKEY_RECEIVED;
- }
+ else
+ { /* for receiving */
+ if (((be->status & STAT_SETKEY_RECEIVED) == 0) ||
+ (be->skey_remote_created < age))
+ {
+ if (0 != memcmp (key, &be->skey_remote, sizeof (SESSIONKEY)))
+ {
+ be->skey_remote = *key;
+ be->lastSequenceNumberReceived = 0;
+ }
+ be->skey_remote_created = age;
+ be->status |= STAT_SETKEY_RECEIVED;
+ }
+ }
}
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
/**
@@ -2811,35 +2924,37 @@
*
* @param peer the other peer,
*/
-void confirmSessionUp(const PeerIdentity * peer) {
+void
+confirmSessionUp (const PeerIdentity * peer)
+{
BufferEntry *be;
- MUTEX_LOCK(lock);
- be = lookForHost(peer);
- if(be != NULL) {
- be->isAlive = get_time();
- identity->whitelistHost(peer);
- if( ((be->status & STAT_SETKEY_SENT) > 0) &&
- ((be->status & STAT_SETKEY_RECEIVED) > 0) &&
- (OK == ensureTransportConnected(be)) &&
- (be->status != STAT_UP) ) {
+ MUTEX_LOCK (lock);
+ be = lookForHost (peer);
+ if (be != NULL)
+ {
+ be->isAlive = get_time ();
+ identity->whitelistHost (peer);
+ if (((be->status & STAT_SETKEY_SENT) > 0) &&
+ ((be->status & STAT_SETKEY_RECEIVED) > 0) &&
+ (OK == ensureTransportConnected (be)) && (be->status != STAT_UP))
+ {
#if DEBUG_CONNECTION
- EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- hash2enc(&peer->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Received confirmation that session is UP for `%s'\n",
- &enc);
+ EncName enc;
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ hash2enc (&peer->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Received confirmation that session is UP for `%s'\n",
+ &enc);
#endif
- be->status = STAT_UP;
- be->lastSequenceNumberReceived = 0;
- be->lastSequenceNumberSend = 1;
+ be->status = STAT_UP;
+ be->lastSequenceNumberReceived = 0;
+ be->lastSequenceNumberSend = 1;
+ }
}
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
@@ -2847,7 +2962,9 @@
* Get the current number of slots in the connection table (as computed
* from the available bandwidth).
*/
-int getSlotCount() {
+int
+getSlotCount ()
+{
return CONNECTION_MAX_HOSTS_;
}
@@ -2856,20 +2973,24 @@
* @return 0 if not, otherwise number of peers in
* the slot
*/
-int isSlotUsed(int slot) {
+int
+isSlotUsed (int slot)
+{
BufferEntry *be;
int ret;
ret = 0;
- MUTEX_LOCK(lock);
- if((slot >= 0) && (slot < CONNECTION_MAX_HOSTS_)) {
- be = CONNECTION_buffer_[slot];
- while(be != NULL) {
- if(be->status == STAT_UP)
- ret++;
- be = be->overflowChain;
+ MUTEX_LOCK (lock);
+ if ((slot >= 0) && (slot < CONNECTION_MAX_HOSTS_))
+ {
+ be = CONNECTION_buffer_[slot];
+ while (be != NULL)
+ {
+ if (be->status == STAT_UP)
+ ret++;
+ be = be->overflowChain;
+ }
}
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return ret;
}
@@ -2879,22 +3000,26 @@
* @param time updated with the time
* @return SYSERR if we are not connected to the peer at the moment
*/
-int getLastActivityOf(const PeerIdentity * peer,
- cron_t * time) {
+int
+getLastActivityOf (const PeerIdentity * peer, cron_t * time)
+{
int ret;
BufferEntry *be;
ret = 0;
- MUTEX_LOCK(lock);
- be = lookForHost(peer);
- if((be != NULL) && (be->status == STAT_UP)) {
- *time = be->isAlive;
- ret = OK;
- } else {
- *time = 0;
- ret = SYSERR;
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_LOCK (lock);
+ be = lookForHost (peer);
+ if ((be != NULL) && (be->status == STAT_UP))
+ {
+ *time = be->isAlive;
+ ret = OK;
+ }
+ else
+ {
+ *time = 0;
+ ret = SYSERR;
+ }
+ MUTEX_UNLOCK (lock);
return ret;
}
@@ -2909,32 +3034,38 @@
* @return SYSERR if no sessionkey is known to the core,
* OK if the sessionkey was set.
*/
-int getCurrentSessionKey(const PeerIdentity * peer,
- SESSIONKEY * key,
- TIME_T * age,
- int forSending) {
+int
+getCurrentSessionKey (const PeerIdentity * peer,
+ SESSIONKEY * key, TIME_T * age, int forSending)
+{
int ret;
BufferEntry *be;
ret = SYSERR;
- MUTEX_LOCK(lock);
- be = lookForHost(peer);
- if(be != NULL) {
- if (forSending == YES) {
- if ((be->status & STAT_SETKEY_SENT) > 0) {
- *key = be->skey_local;
- *age = be->skey_local_created;
- ret = OK;
- }
- } else { /* for receiving */
- if((be->status & STAT_SETKEY_RECEIVED) > 0) {
- *key = be->skey_remote;
- *age = be->skey_remote_created;
- ret = OK;
- }
+ MUTEX_LOCK (lock);
+ be = lookForHost (peer);
+ if (be != NULL)
+ {
+ if (forSending == YES)
+ {
+ if ((be->status & STAT_SETKEY_SENT) > 0)
+ {
+ *key = be->skey_local;
+ *age = be->skey_local_created;
+ ret = OK;
+ }
+ }
+ else
+ { /* for receiving */
+ if ((be->status & STAT_SETKEY_RECEIVED) > 0)
+ {
+ *key = be->skey_remote;
+ *age = be->skey_remote_created;
+ ret = OK;
+ }
+ }
}
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return ret;
}
@@ -2953,30 +3084,31 @@
* @param tsession the transport session that is for grabs
* @param sender the identity of the other node
*/
-void considerTakeover(const PeerIdentity * sender,
- TSession * tsession) {
- BufferEntry * be;
+void
+considerTakeover (const PeerIdentity * sender, TSession * tsession)
+{
+ BufferEntry *be;
unsigned int cost;
- ENTRY();
+ ENTRY ();
if (tsession == NULL)
return;
- if (0 != memcmp(sender,
- &tsession->peer,
- sizeof(PeerIdentity))) {
- GE_BREAK(NULL, 0);
- return;
- }
- MUTEX_LOCK(lock);
- be = addHost(sender, NO);
- if (be == NULL) {
- MUTEX_UNLOCK(lock);
- transport->disconnect(tsession);
- return;
- }
+ if (0 != memcmp (sender, &tsession->peer, sizeof (PeerIdentity)))
+ {
+ GE_BREAK (NULL, 0);
+ return;
+ }
+ MUTEX_LOCK (lock);
+ be = addHost (sender, NO);
+ if (be == NULL)
+ {
+ MUTEX_UNLOCK (lock);
+ transport->disconnect (tsession);
+ return;
+ }
cost = -1;
if (be->session.tsession != NULL)
- cost = transport->getCost(be->session.tsession->ttype);
+ cost = transport->getCost (be->session.tsession->ttype);
/* Question: doesn't this always do takeover in tcp/udp
case, which have the same costs? Should it? -IW
@@ -2987,17 +3119,18 @@
sending very few messages (e.g. attempting an initial exchange
to get to know each other). See also transport paper and the
data on throughput. - CG
- */
- if ( (transport->getCost(tsession->ttype) < cost) &&
- (transport->associate(tsession) == OK) ) {
- if (be->session.tsession != NULL)
- transport->disconnect(be->session.tsession);
- be->session.tsession = tsession;
- be->session.mtu = transport->getMTU(tsession->ttype);
- fragmentIfNecessary(be);
- }
- transport->disconnect(tsession);
- MUTEX_UNLOCK(lock);
+ */
+ if ((transport->getCost (tsession->ttype) < cost) &&
+ (transport->associate (tsession) == OK))
+ {
+ if (be->session.tsession != NULL)
+ transport->disconnect (be->session.tsession);
+ be->session.tsession = tsession;
+ be->session.mtu = transport->getMTU (tsession->ttype);
+ fragmentIfNecessary (be);
+ }
+ transport->disconnect (tsession);
+ MUTEX_UNLOCK (lock);
}
@@ -3006,251 +3139,243 @@
* limits may now be different. Adjust the connection table
* accordingly.
*/
-static int connectionConfigChangeCallback(void * ctx,
- struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option) {
+static int
+connectionConfigChangeCallback (void *ctx,
+ struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section, const char *option)
+{
unsigned long long new_max_bpm;
unsigned int i;
- if (0 != strcmp(section, "LOAD"))
- return 0; /* fast path */
- if (-1 == GC_get_configuration_value_number(cfg,
- "LOAD",
- "MAXNETDOWNBPSTOTAL",
- 0,
- ((unsigned long long)-1)/60,
- 50000, /* default: 50 kbps */
- &new_max_bpm))
+ if (0 != strcmp (section, "LOAD"))
+ return 0; /* fast path */
+ if (-1 == GC_get_configuration_value_number (cfg, "LOAD",
"MAXNETDOWNBPSTOTAL", 0, ((unsigned long long) -1) / 60, 50000, /* default:
50 kbps */
+ &new_max_bpm))
return SYSERR;
- GC_get_configuration_value_number(cfg,
- "LOAD",
- "MAXNETUPBPSTOTAL",
- 0,
- ((unsigned long long)-1)/60,
- 50000, /* default: 50 kbps */
- &max_bpm_up);
- max_bpm_up *= 60; /* bps -> bpm */
- MUTEX_LOCK(lock);
+ GC_get_configuration_value_number (cfg, "LOAD", "MAXNETUPBPSTOTAL", 0,
((unsigned long long) -1) / 60, 50000, /* default: 50 kbps */
+ &max_bpm_up);
+ max_bpm_up *= 60; /* bps -> bpm */
+ MUTEX_LOCK (lock);
new_max_bpm = 60 * new_max_bpm;
- if(max_bpm != new_max_bpm) {
- unsigned int newMAXHOSTS = 0;
+ if (max_bpm != new_max_bpm)
+ {
+ unsigned int newMAXHOSTS = 0;
- max_bpm = new_max_bpm;
- newMAXHOSTS = max_bpm / (MIN_BPM_PER_PEER * 4);
- /* => for 1000 bps, we get 12 (rounded DOWN to 8) connections! */
- if (newMAXHOSTS < 4)
- newMAXHOSTS = 4; /* strict minimum is 4 (must match bootstrap.c!) */
- if (newMAXHOSTS > 256)
- newMAXHOSTS = 256; /* limit, otherwise we run out of sockets! */
+ max_bpm = new_max_bpm;
+ newMAXHOSTS = max_bpm / (MIN_BPM_PER_PEER * 4);
+ /* => for 1000 bps, we get 12 (rounded DOWN to 8) connections! */
+ if (newMAXHOSTS < 4)
+ newMAXHOSTS = 4; /* strict minimum is 4 (must match
bootstrap.c!) */
+ if (newMAXHOSTS > 256)
+ newMAXHOSTS = 256; /* limit, otherwise we run out of sockets! */
- if (newMAXHOSTS != CONNECTION_MAX_HOSTS_) {
- /* change size of connection buffer!!! */
- unsigned int olen;
- BufferEntry **newBuffer;
+ if (newMAXHOSTS != CONNECTION_MAX_HOSTS_)
+ {
+ /* change size of connection buffer!!! */
+ unsigned int olen;
+ BufferEntry **newBuffer;
- olen = CONNECTION_MAX_HOSTS_;
- CONNECTION_MAX_HOSTS_ = newMAXHOSTS;
- GE_BREAK(ectx,
- 0 == GC_set_configuration_value_number(cfg,
- ectx,
- "gnunetd",
- "connection-max-hosts",
- CONNECTION_MAX_HOSTS_));
- newBuffer =
- (BufferEntry **) MALLOC(sizeof(BufferEntry *) * newMAXHOSTS);
- for(i = 0; i < CONNECTION_MAX_HOSTS_; i++)
- newBuffer[i] = NULL;
+ olen = CONNECTION_MAX_HOSTS_;
+ CONNECTION_MAX_HOSTS_ = newMAXHOSTS;
+ GE_BREAK (ectx,
+ 0 == GC_set_configuration_value_number (cfg,
+ ectx,
+ "gnunetd",
+
"connection-max-hosts",
+
CONNECTION_MAX_HOSTS_));
+ newBuffer =
+ (BufferEntry **) MALLOC (sizeof (BufferEntry *) * newMAXHOSTS);
+ for (i = 0; i < CONNECTION_MAX_HOSTS_; i++)
+ newBuffer[i] = NULL;
- /* rehash! */
- for(i = 0; i < olen; i++) {
- BufferEntry *be;
+ /* rehash! */
+ for (i = 0; i < olen; i++)
+ {
+ BufferEntry *be;
- be = CONNECTION_buffer_[i];
- while(be != NULL) {
- BufferEntry *next;
- unsigned int j;
+ be = CONNECTION_buffer_[i];
+ while (be != NULL)
+ {
+ BufferEntry *next;
+ unsigned int j;
- next = be->overflowChain;
- j = computeIndex(&be->session.sender);
- be->overflowChain = newBuffer[j];
- newBuffer[j] = be;
- be = next;
- }
- }
- FREENONNULL(CONNECTION_buffer_);
- CONNECTION_buffer_ = newBuffer;
+ next = be->overflowChain;
+ j = computeIndex (&be->session.sender);
+ be->overflowChain = newBuffer[j];
+ newBuffer[j] = be;
+ be = next;
+ }
+ }
+ FREENONNULL (CONNECTION_buffer_);
+ CONNECTION_buffer_ = newBuffer;
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "connection goal is %s%d peers (%llu BPM bandwidth downstream)\n",
- (olen == 0) ? "" : "now ",
- CONNECTION_MAX_HOSTS_,
- max_bpm);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "connection goal is %s%d peers (%llu BPM bandwidth
downstream)\n",
+ (olen == 0) ? "" : "now ", CONNECTION_MAX_HOSTS_, max_bpm);
+ }
}
- }
- disable_random_padding = GC_get_configuration_value_yesno(cfg,
- "GNUNETD-EXPERIMENTAL",
- "PADDING",
- NO);
- MUTEX_UNLOCK(lock);
+ disable_random_padding = GC_get_configuration_value_yesno (cfg,
+
"GNUNETD-EXPERIMENTAL",
+ "PADDING", NO);
+ MUTEX_UNLOCK (lock);
return 0;
}
/**
* Initialize this module.
*/
-void initConnection(struct GE_Context * e,
- struct GC_Configuration * c,
- struct LoadMonitor * m,
- struct CronManager * cm) {
+void
+initConnection (struct GE_Context *e,
+ struct GC_Configuration *c,
+ struct LoadMonitor *m, struct CronManager *cm)
+{
ectx = e;
cfg = c;
load_monitor = m;
cron = cm;
- GE_ASSERT(ectx, P2P_MESSAGE_OVERHEAD == sizeof(P2P_PACKET_HEADER));
- GE_ASSERT(ectx, sizeof(P2P_hangup_MESSAGE) == 68);
- ENTRY();
+ GE_ASSERT (ectx, P2P_MESSAGE_OVERHEAD == sizeof (P2P_PACKET_HEADER));
+ GE_ASSERT (ectx, sizeof (P2P_hangup_MESSAGE) == 68);
+ ENTRY ();
scl_nextHead = NULL;
scl_nextTail = NULL;
- connectionConfigChangeCallback(NULL,
- cfg,
- ectx,
- "LOAD",
- "NOTHING");
- GE_ASSERT(ectx,
- 0 == GC_attach_change_listener(cfg,
- &connectionConfigChangeCallback,
- NULL));
- GE_ASSERT(ectx,
- CONNECTION_MAX_HOSTS_ != 0);
- registerp2pHandler(P2P_PROTO_hangup, &handleHANGUP);
- cron_add_job(cron,
- &cronDecreaseLiveness,
- CDL_FREQUENCY,
- CDL_FREQUENCY,
- NULL);
+ connectionConfigChangeCallback (NULL, cfg, ectx, "LOAD", "NOTHING");
+ GE_ASSERT (ectx,
+ 0 == GC_attach_change_listener (cfg,
+ &connectionConfigChangeCallback,
+ NULL));
+ GE_ASSERT (ectx, CONNECTION_MAX_HOSTS_ != 0);
+ registerp2pHandler (P2P_PROTO_hangup, &handleHANGUP);
+ cron_add_job (cron,
+ &cronDecreaseLiveness, CDL_FREQUENCY, CDL_FREQUENCY, NULL);
#if DEBUG_COLLECT_PRIO
- prioFile = FOPEN("/tmp/knapsack_prio.txt", "w");
+ prioFile = FOPEN ("/tmp/knapsack_prio.txt", "w");
#endif
- transport = requestService("transport");
- GE_ASSERT(ectx, transport != NULL);
- identity = requestService("identity");
- GE_ASSERT(ectx, identity != NULL);
- session = requestService("session");
- GE_ASSERT(ectx, session != NULL);
- fragmentation = requestService("fragmentation");
- GE_ASSERT(ectx, fragmentation != NULL);
- topology = requestService("topology");
- GE_ASSERT(ectx, topology != NULL);
- stats = requestService("stats");
- if(stats != NULL) {
- stat_messagesDropped
- = stats->create(gettext_noop(/* number of messages dropped by GNUnet core
- due to resource constraints */
- "# outgoing messages dropped"));
- stat_sizeMessagesDropped
- = stats->create(gettext_noop(/* bytes of messages dropped by GNUnet core
- due to resource constraints */
- "# bytes of outgoing messages dropped"));
- stat_hangupSent
- = stats->create(gettext_noop("# connections closed (HANGUP sent)"));
- stat_encrypted = stats->create(gettext_noop(/* includes encrypted but then
- not transmitted data */
- "# bytes encrypted"));
- stat_transmitted = stats->create(gettext_noop(/* encrypted data, confirmed
by
- transport, without transport
- headers */
- "# bytes transmitted"));
- stat_received = stats->create(gettext_noop(/* encrypted data received
- (incl. invalid/undecryptable data)
- without transport headers */
- "# bytes received"));
- stat_decrypted
- = stats->create(gettext_noop(/* bytes successfully decrypted */
- "# bytes decrypted"));
- stat_noise_sent
- = stats->create(gettext_noop("# bytes noise sent"));
- stat_total_allowed_sent
- = stats->create(gettext_noop("# total bytes per second send limit"));
- stat_total_allowed_recv
- = stats->create(gettext_noop("# total bytes per second receive limit"));
- stat_total_send_buffer_size
- = stats->create(gettext_noop("# total number of messages in send
buffers"));
- stat_total_lost_sent
- = stats->create(gettext_noop("# total number of bytes we were allowed to
sent but did not"));
- stat_total_allowed_inc
- = stats->create(gettext_noop("# total number of bytes we were allowed to
sent"));
- stat_total_allowed_now
- = stats->create(gettext_noop("# total number of bytes we are currently
allowed to send"));
- }
- transport->start(&core_receive);
+ transport = requestService ("transport");
+ GE_ASSERT (ectx, transport != NULL);
+ identity = requestService ("identity");
+ GE_ASSERT (ectx, identity != NULL);
+ session = requestService ("session");
+ GE_ASSERT (ectx, session != NULL);
+ fragmentation = requestService ("fragmentation");
+ GE_ASSERT (ectx, fragmentation != NULL);
+ topology = requestService ("topology");
+ GE_ASSERT (ectx, topology != NULL);
+ stats = requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_messagesDropped = stats->create (gettext_noop ( /* number of
messages dropped by GNUnet core
+ due to
resource constraints */
+ "# outgoing
messages dropped"));
+ stat_sizeMessagesDropped = stats->create (gettext_noop ( /* bytes of
messages dropped by GNUnet core
+ due to
resource constraints */
+ "# bytes of
outgoing messages dropped"));
+ stat_hangupSent
+ = stats->create (gettext_noop ("# connections closed (HANGUP sent)"));
+ stat_encrypted = stats->create (gettext_noop ( /* includes encrypted
but then
+ not transmitted
data */
+ "# bytes encrypted"));
+ stat_transmitted = stats->create (gettext_noop ( /* encrypted data,
confirmed by
+ transport, without
transport
+ headers */
+ "# bytes transmitted"));
+ stat_received = stats->create (gettext_noop ( /* encrypted data
received
+ (incl.
invalid/undecryptable data)
+ without transport
headers */
+ "# bytes received"));
+ stat_decrypted = stats->create (gettext_noop ( /* bytes successfully
decrypted */
+ "# bytes decrypted"));
+ stat_noise_sent = stats->create (gettext_noop ("# bytes noise sent"));
+ stat_total_allowed_sent
+ =
+ stats->create (gettext_noop ("# total bytes per second send limit"));
+ stat_total_allowed_recv =
+ stats->
+ create (gettext_noop ("# total bytes per second receive limit"));
+ stat_total_send_buffer_size =
+ stats->
+ create (gettext_noop ("# total number of messages in send buffers"));
+ stat_total_lost_sent =
+ stats->
+ create (gettext_noop
+ ("# total number of bytes we were allowed to sent but did
not"));
+ stat_total_allowed_inc =
+ stats->
+ create (gettext_noop
+ ("# total number of bytes we were allowed to sent"));
+ stat_total_allowed_now =
+ stats->
+ create (gettext_noop
+ ("# total number of bytes we are currently allowed to send"));
+ }
+ transport->start (&core_receive);
}
/**
* Shutdown the connection module.
*/
-void doneConnection() {
+void
+doneConnection ()
+{
unsigned int i;
BufferEntry *be;
SendCallbackList *scl;
- ENTRY();
- GC_detach_change_listener(cfg,
- &connectionConfigChangeCallback,
- NULL);
- cron_del_job(cron,
- &cronDecreaseLiveness,
- CDL_FREQUENCY,
- NULL);
- for(i = 0; i < CONNECTION_MAX_HOSTS_; i++) {
- BufferEntry *prev;
+ ENTRY ();
+ GC_detach_change_listener (cfg, &connectionConfigChangeCallback, NULL);
+ cron_del_job (cron, &cronDecreaseLiveness, CDL_FREQUENCY, NULL);
+ for (i = 0; i < CONNECTION_MAX_HOSTS_; i++)
+ {
+ BufferEntry *prev;
- prev = NULL;
- be = CONNECTION_buffer_[i];
- while(be != NULL) {
+ prev = NULL;
+ be = CONNECTION_buffer_[i];
+ while (be != NULL)
+ {
#if DEBUG_CONNECTION
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Closing connection: shutdown\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Closing connection: shutdown\n");
#endif
- shutdownConnection(be);
- prev = be;
- be = be->overflowChain;
- FREE(prev);
+ shutdownConnection (be);
+ prev = be;
+ be = be->overflowChain;
+ FREE (prev);
+ }
}
- }
- FREENONNULL(CONNECTION_buffer_);
+ FREENONNULL (CONNECTION_buffer_);
CONNECTION_buffer_ = NULL;
CONNECTION_MAX_HOSTS_ = 0;
- while(scl_nextHead != NULL) {
- scl = scl_nextHead;
- scl_nextHead = scl_nextHead->next;
- FREE(scl);
- }
+ while (scl_nextHead != NULL)
+ {
+ scl = scl_nextHead;
+ scl_nextHead = scl_nextHead->next;
+ FREE (scl);
+ }
scl_nextTail = NULL;
- transport->stop();
- releaseService(transport);
+ transport->stop ();
+ releaseService (transport);
transport = NULL;
- releaseService(identity);
+ releaseService (identity);
identity = NULL;
- releaseService(session);
+ releaseService (session);
session = NULL;
- releaseService(fragmentation);
+ releaseService (fragmentation);
fragmentation = NULL;
- releaseService(topology);
+ releaseService (topology);
topology = NULL;
- releaseService(stats);
+ releaseService (stats);
stats = NULL;
#if DEBUG_COLLECT_PRIO == YES
- if (prioFile != NULL) {
- fclose(prioFile);
- prioFile = NULL;
- }
+ if (prioFile != NULL)
+ {
+ fclose (prioFile);
+ prioFile = NULL;
+ }
#endif
ectx = NULL;
cfg = NULL;
@@ -3266,22 +3391,26 @@
* @param arg second argument to method
* @return number of connected nodes
*/
-int forEachConnectedNode(PerNodeCallback method, void *arg) {
+int
+forEachConnectedNode (PerNodeCallback method, void *arg)
+{
fENHWrap wrap;
int ret;
wrap.method = method;
wrap.arg = arg;
- MUTEX_LOCK(lock);
- ret = forAllConnectedHosts(&fENHCallback, &wrap);
- MUTEX_UNLOCK(lock);
+ MUTEX_LOCK (lock);
+ ret = forAllConnectedHosts (&fENHCallback, &wrap);
+ MUTEX_UNLOCK (lock);
return ret;
}
/**
* Print the contents of the connection buffer (for debugging).
*/
-void printConnectionBuffer() {
+void
+printConnectionBuffer ()
+{
unsigned int i;
BufferEntry *tmp;
EncName hostName;
@@ -3289,43 +3418,42 @@
EncName skey_remote;
unsigned int ttype;
- MUTEX_LOCK(lock);
- ENTRY();
- for(i = 0; i < CONNECTION_MAX_HOSTS_; i++) {
- tmp = CONNECTION_buffer_[i];
- while(tmp != NULL) {
- if(tmp->status != STAT_DOWN) {
- hash2enc(&tmp->session.sender.hashPubKey,
- &hostName);
- hash2enc((HashCode512 *) & tmp->skey_local,
- &skey_local);
- hash2enc((HashCode512 *) & tmp->skey_remote, &skey_remote);
- hostName.encoding[4] = '\0';
- skey_local.encoding[4] = '\0';
- skey_remote.encoding[4] = '\0';
- ttype = 0;
- if(tmp->session.tsession != NULL)
- ttype = tmp->session.tsession->ttype;
- GE_LOG(ectx,
- GE_INFO | GE_REQUEST | GE_USER,
- "CONNECTION-TABLE: %3d-%1d-%2d-%4ds"
- " (of %ds) BPM %4llu %8ut-%3u: %s-%s-%s\n",
- i,
- tmp->status,
- ttype,
- (int) ((get_time() - tmp->isAlive) / cronSECONDS),
- SECONDS_INACTIVE_DROP,
- tmp->recently_received,
- tmp->idealized_limit,
- tmp->sendBufferSize,
- &hostName,
- &skey_local,
- &skey_remote);
- }
- tmp = tmp->overflowChain;
+ MUTEX_LOCK (lock);
+ ENTRY ();
+ for (i = 0; i < CONNECTION_MAX_HOSTS_; i++)
+ {
+ tmp = CONNECTION_buffer_[i];
+ while (tmp != NULL)
+ {
+ if (tmp->status != STAT_DOWN)
+ {
+ hash2enc (&tmp->session.sender.hashPubKey, &hostName);
+ hash2enc ((HashCode512 *) & tmp->skey_local, &skey_local);
+ hash2enc ((HashCode512 *) & tmp->skey_remote, &skey_remote);
+ hostName.encoding[4] = '\0';
+ skey_local.encoding[4] = '\0';
+ skey_remote.encoding[4] = '\0';
+ ttype = 0;
+ if (tmp->session.tsession != NULL)
+ ttype = tmp->session.tsession->ttype;
+ GE_LOG (ectx,
+ GE_INFO | GE_REQUEST | GE_USER,
+ "CONNECTION-TABLE: %3d-%1d-%2d-%4ds"
+ " (of %ds) BPM %4llu %8ut-%3u: %s-%s-%s\n",
+ i,
+ tmp->status,
+ ttype,
+ (int) ((get_time () - tmp->isAlive) / cronSECONDS),
+ SECONDS_INACTIVE_DROP,
+ tmp->recently_received,
+ tmp->idealized_limit,
+ tmp->sendBufferSize,
+ &hostName, &skey_local, &skey_remote);
+ }
+ tmp = tmp->overflowChain;
+ }
}
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
/**
@@ -3348,25 +3476,29 @@
* that buffer (must be a positive number).
* @return OK if the handler was registered, SYSERR on error
*/
-int registerSendCallback(const unsigned int minimumPadding,
- BufferFillCallback callback) {
+int
+registerSendCallback (const unsigned int minimumPadding,
+ BufferFillCallback callback)
+{
SendCallbackList *scl;
- ENTRY();
- scl = MALLOC(sizeof(SendCallbackList));
+ ENTRY ();
+ scl = MALLOC (sizeof (SendCallbackList));
scl->minimumPadding = minimumPadding;
scl->callback = callback;
scl->next = NULL;
- MUTEX_LOCK(lock);
- if(scl_nextTail == NULL) {
- scl_nextHead = scl;
- scl_nextTail = scl;
- }
- else {
- scl_nextTail->next = scl;
- scl_nextTail = scl;
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_LOCK (lock);
+ if (scl_nextTail == NULL)
+ {
+ scl_nextHead = scl;
+ scl_nextTail = scl;
+ }
+ else
+ {
+ scl_nextTail->next = scl;
+ scl_nextTail = scl;
+ }
+ MUTEX_UNLOCK (lock);
return OK;
}
@@ -3383,31 +3515,35 @@
* that buffer (must be a positive number).
* @return OK if the handler was removed, SYSERR on error
*/
-int unregisterSendCallback(const unsigned int minimumPadding,
- BufferFillCallback callback) {
+int
+unregisterSendCallback (const unsigned int minimumPadding,
+ BufferFillCallback callback)
+{
SendCallbackList *pos;
SendCallbackList *prev;
prev = NULL;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
pos = scl_nextHead;
- while(pos != NULL) {
- if ( (pos->callback == callback) &&
- (pos->minimumPadding == minimumPadding) ) {
- if(prev == NULL)
- scl_nextHead = pos->next;
- else
- prev->next = pos->next;
- if(scl_nextTail == pos)
- scl_nextTail = prev;
- FREE(pos);
- MUTEX_UNLOCK(lock);
- return OK;
+ while (pos != NULL)
+ {
+ if ((pos->callback == callback) &&
+ (pos->minimumPadding == minimumPadding))
+ {
+ if (prev == NULL)
+ scl_nextHead = pos->next;
+ else
+ prev->next = pos->next;
+ if (scl_nextTail == pos)
+ scl_nextTail = prev;
+ FREE (pos);
+ MUTEX_UNLOCK (lock);
+ return OK;
+ }
+ prev = pos;
+ pos = pos->next;
}
- prev = pos;
- pos = pos->next;
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return SYSERR;
}
@@ -3423,33 +3559,32 @@
* @param msg the message to transmit, should contain MESSAGE_HEADERs
* @return OK on success, SYSERR on failure, NO on temporary failure
*/
-int sendPlaintext(TSession * tsession,
- const char *msg,
- unsigned int size) {
+int
+sendPlaintext (TSession * tsession, const char *msg, unsigned int size)
+{
char *buf;
int ret;
P2P_PACKET_HEADER *hdr;
- GE_ASSERT(ectx, tsession != NULL);
- if ( (transport->getMTU(tsession->ttype) > 0) &&
- (transport->getMTU(tsession->ttype) <
- size + sizeof(P2P_PACKET_HEADER)) ) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- buf = MALLOC(size + sizeof(P2P_PACKET_HEADER));
+ GE_ASSERT (ectx, tsession != NULL);
+ if ((transport->getMTU (tsession->ttype) > 0) &&
+ (transport->getMTU (tsession->ttype) <
+ size + sizeof (P2P_PACKET_HEADER)))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ buf = MALLOC (size + sizeof (P2P_PACKET_HEADER));
hdr = (P2P_PACKET_HEADER *) buf;
hdr->sequenceNumber = 0;
hdr->timeStamp = 0;
hdr->bandwidth = 0;
- memcpy(&buf[sizeof(P2P_PACKET_HEADER)], msg, size);
- hash(&hdr->sequenceNumber,
- size + sizeof(P2P_PACKET_HEADER) - sizeof(HashCode512), &hdr->hash);
- ret = transport->send(tsession,
- buf,
- size + sizeof(P2P_PACKET_HEADER),
- NO);
- FREE(buf);
+ memcpy (&buf[sizeof (P2P_PACKET_HEADER)], msg, size);
+ hash (&hdr->sequenceNumber,
+ size + sizeof (P2P_PACKET_HEADER) - sizeof (HashCode512), &hdr->hash);
+ ret = transport->send (tsession,
+ buf, size + sizeof (P2P_PACKET_HEADER), NO);
+ FREE (buf);
return ret;
}
@@ -3464,34 +3599,37 @@
* @param importance how important is the message?
* @param maxdelay how long can the message wait?
*/
-void unicastCallback(const PeerIdentity * hostId,
- BuildMessageCallback callback,
- void * closure,
- unsigned short len,
- unsigned int importance,
- unsigned int maxdelay) {
+void
+unicastCallback (const PeerIdentity * hostId,
+ BuildMessageCallback callback,
+ void *closure,
+ unsigned short len,
+ unsigned int importance, unsigned int maxdelay)
+{
BufferEntry *be;
- ENTRY();
- MUTEX_LOCK(lock);
- be = addHost(hostId, YES);
- if ((be != NULL) &&
- (be->status != STAT_DOWN)) {
- SendEntry *entry;
+ ENTRY ();
+ MUTEX_LOCK (lock);
+ be = addHost (hostId, YES);
+ if ((be != NULL) && (be->status != STAT_DOWN))
+ {
+ SendEntry *entry;
- entry = MALLOC(sizeof(SendEntry));
- entry->len = len;
- entry->flags = SE_FLAG_NONE;
- entry->pri = importance;
- entry->transmissionTime = get_time() + maxdelay;
- entry->callback = callback;
- entry->closure = closure;
- entry->knapsackSolution = NO;
- appendToBuffer(be, entry);
- } else {
- FREENONNULL(closure);
- }
- MUTEX_UNLOCK(lock);
+ entry = MALLOC (sizeof (SendEntry));
+ entry->len = len;
+ entry->flags = SE_FLAG_NONE;
+ entry->pri = importance;
+ entry->transmissionTime = get_time () + maxdelay;
+ entry->callback = callback;
+ entry->closure = closure;
+ entry->knapsackSolution = NO;
+ appendToBuffer (be, entry);
+ }
+ else
+ {
+ FREENONNULL (closure);
+ }
+ MUTEX_UNLOCK (lock);
}
/**
@@ -3503,33 +3641,30 @@
* @param importance how important is the message?
* @param maxdelay how long can the message be delayed?
*/
-void unicast(const PeerIdentity * receiver,
- const MESSAGE_HEADER * msg,
- unsigned int importance,
- unsigned int maxdelay) {
+void
+unicast (const PeerIdentity * receiver,
+ const MESSAGE_HEADER * msg,
+ unsigned int importance, unsigned int maxdelay)
+{
char *closure;
unsigned short len;
- if ( (getBandwidthAssignedTo(receiver, NULL, NULL) != OK) &&
- (identity->isBlacklistedStrict(receiver) == NO) )
- session->tryConnect(receiver);
+ if ((getBandwidthAssignedTo (receiver, NULL, NULL) != OK) &&
+ (identity->isBlacklistedStrict (receiver) == NO))
+ session->tryConnect (receiver);
if (msg == NULL)
return;
- len = ntohs(msg->size);
- if (len == 0) {
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_DEVELOPER,
- "Empty message send (hopefully used to initiate connection attempt)\n");
- return;
- }
- closure = MALLOC(len);
- memcpy(closure, msg, len);
- unicastCallback(receiver,
- NULL,
- closure,
- len,
- importance,
- maxdelay);
+ len = ntohs (msg->size);
+ if (len == 0)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_BULK | GE_DEVELOPER,
+ "Empty message send (hopefully used to initiate connection
attempt)\n");
+ return;
+ }
+ closure = MALLOC (len);
+ memcpy (closure, msg, len);
+ unicastCallback (receiver, NULL, closure, len, importance, maxdelay);
}
/**
@@ -3538,11 +3673,12 @@
* @param hostId the ID of a peer
* @return the index for this peer in the connection table
*/
-unsigned int computeIndex(const PeerIdentity * hostId) {
+unsigned int
+computeIndex (const PeerIdentity * hostId)
+{
unsigned int res = (((unsigned int) hostId->hashPubKey.bits[0]) &
((unsigned int) (CONNECTION_MAX_HOSTS_ - 1)));
- GE_ASSERT(ectx,
- res < CONNECTION_MAX_HOSTS_);
+ GE_ASSERT (ectx, res < CONNECTION_MAX_HOSTS_);
return res;
}
@@ -3551,31 +3687,36 @@
*
* @return the lock
*/
-struct MUTEX * getConnectionModuleLock() {
- GE_ASSERT(NULL, lock != NULL);
+struct MUTEX *
+getConnectionModuleLock ()
+{
+ GE_ASSERT (NULL, lock != NULL);
return lock;
}
-int getBandwidthAssignedTo(const PeerIdentity * node,
- unsigned int * bpm,
- cron_t * last_seen) {
+int
+getBandwidthAssignedTo (const PeerIdentity * node,
+ unsigned int *bpm, cron_t * last_seen)
+{
BufferEntry *be;
unsigned int ret;
- ENTRY();
- MUTEX_LOCK(lock);
- be = lookForHost(node);
- if ( (be != NULL) &&
- (be->status == STAT_UP) ) {
- if (bpm != NULL)
- *bpm = be->idealized_limit;
- if (last_seen != NULL)
- *last_seen = be->isAlive;
- ret = OK;
- } else {
- ret = SYSERR;
- }
- MUTEX_UNLOCK(lock);
+ ENTRY ();
+ MUTEX_LOCK (lock);
+ be = lookForHost (node);
+ if ((be != NULL) && (be->status == STAT_UP))
+ {
+ if (bpm != NULL)
+ *bpm = be->idealized_limit;
+ if (last_seen != NULL)
+ *last_seen = be->isAlive;
+ ret = OK;
+ }
+ else
+ {
+ ret = SYSERR;
+ }
+ MUTEX_UNLOCK (lock);
return ret;
}
@@ -3584,16 +3725,17 @@
* @param node the identity of the other peer
* @param preference how much should the traffic preference be increased?
*/
-void updateTrafficPreference(const PeerIdentity * node,
- double preference) {
+void
+updateTrafficPreference (const PeerIdentity * node, double preference)
+{
BufferEntry *be;
- ENTRY();
- MUTEX_LOCK(lock);
- be = lookForHost(node);
+ ENTRY ();
+ MUTEX_LOCK (lock);
+ be = lookForHost (node);
if (be != NULL)
be->current_connection_value += preference;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
/**
@@ -3602,32 +3744,33 @@
*
* @param peer the peer to disconnect
*/
-void disconnectFromPeer(const PeerIdentity * node) {
+void
+disconnectFromPeer (const PeerIdentity * node)
+{
BufferEntry *be;
- ENTRY();
- MUTEX_LOCK(lock);
- be = lookForHost(node);
- if (be != NULL) {
+ ENTRY ();
+ MUTEX_LOCK (lock);
+ be = lookForHost (node);
+ if (be != NULL)
+ {
#if DEBUG_CONNECTION
- EncName enc;
+ EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- hash2enc(&node->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
- "Closing connection to `%s' as requested by application.\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ hash2enc (&node->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_DEVELOPER,
+ "Closing connection to `%s' as requested by application.\n",
+ &enc);
#endif
- /* do not try to reconnect any time soon! */
- identity->blacklistHost(&be->session.sender,
- SECONDS_BLACKLIST_AFTER_DISCONNECT,
- YES);
- shutdownConnection(be);
- }
- MUTEX_UNLOCK(lock);
+ /* do not try to reconnect any time soon! */
+ identity->blacklistHost (&be->session.sender,
+ SECONDS_BLACKLIST_AFTER_DISCONNECT, YES);
+ shutdownConnection (be);
+ }
+ MUTEX_UNLOCK (lock);
}
/**
@@ -3638,13 +3781,15 @@
* P2P message part that is transmitted
* @return OK on success, SYSERR if there is a problem
*/
-int registerSendNotify(MessagePartHandler callback) {
- if(callback == NULL)
+int
+registerSendNotify (MessagePartHandler callback)
+{
+ if (callback == NULL)
return SYSERR;
- MUTEX_LOCK(lock);
- GROW(rsns, rsnSize, rsnSize + 1);
+ MUTEX_LOCK (lock);
+ GROW (rsns, rsnSize, rsnSize + 1);
rsns[rsnSize - 1] = callback;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return OK;
}
@@ -3656,30 +3801,36 @@
* P2P message part that is transmitted
* @return OK on success, SYSERR if there is a problem
*/
-int unregisterSendNotify(MessagePartHandler callback) {
+int
+unregisterSendNotify (MessagePartHandler callback)
+{
int i;
- MUTEX_LOCK(lock);
- for(i = 0; i < rsnSize; i++) {
- if(rsns[i] == callback) {
- rsns[i] = rsns[rsnSize - 1];
- GROW(rsns, rsnSize, rsnSize - 1);
- MUTEX_UNLOCK(lock);
- return OK;
+ MUTEX_LOCK (lock);
+ for (i = 0; i < rsnSize; i++)
+ {
+ if (rsns[i] == callback)
+ {
+ rsns[i] = rsns[rsnSize - 1];
+ GROW (rsns, rsnSize, rsnSize - 1);
+ MUTEX_UNLOCK (lock);
+ return OK;
+ }
}
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return SYSERR;
}
-void __attribute__ ((constructor)) gnunet_connection_ltdl_init() {
- lock = MUTEX_CREATE(YES);
+void __attribute__ ((constructor)) gnunet_connection_ltdl_init ()
+{
+ lock = MUTEX_CREATE (YES);
}
-void __attribute__ ((destructor)) gnunet_connection_ltdl_fini() {
- MUTEX_DESTROY(lock);
+void __attribute__ ((destructor)) gnunet_connection_ltdl_fini ()
+{
+ MUTEX_DESTROY (lock);
}
Modified: GNUnet/src/server/connection.h
===================================================================
--- GNUnet/src/server/connection.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/connection.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -39,7 +39,8 @@
* by the 'data' which contains a sequence of GNUnet p2p messages,
* each with its own MESSAGE_HEADER.
*/
-typedef struct {
+typedef struct
+{
/* hash of the plaintext, used to verify message integrity;
ALSO used as the IV for the symmetric cipher! */
HashCode512 hash;
@@ -49,27 +50,26 @@
TIME_T timeStamp;
/* desired bandwidth, 0 for plaintext messages! */
unsigned int bandwidth;
-} P2P_PACKET_HEADER; /* 76 bytes */
+} P2P_PACKET_HEADER; /* 76 bytes */
/* ***************** GNUnet core internals ************ */
/**
* Initialize this module.
*/
-void initConnection(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct LoadMonitor * mon,
- struct CronManager * cron);
+void initConnection (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct LoadMonitor *mon, struct CronManager *cron);
/**
* Shutdown the connection module.
*/
-void doneConnection(void);
+void doneConnection (void);
/**
* For debugging.
*/
-void printConnectionBuffer(void);
+void printConnectionBuffer (void);
/**
* Check the sequence number and timestamp. Decrypts the
@@ -83,9 +83,8 @@
* NO if it was in plaintext,
* SYSERR if it was malformed
*/
-int checkHeader(const PeerIdentity * sender,
- P2P_PACKET_HEADER * msg,
- unsigned short size);
+int checkHeader (const PeerIdentity * sender,
+ P2P_PACKET_HEADER * msg, unsigned short size);
/**
* Consider switching the transport mechanism used for contacting the
@@ -98,16 +97,14 @@
* @param tsession the transport session that is for grabs
* @param sender the identity of the other node
*/
-void considerTakeover(const PeerIdentity * sender,
- TSession * tsession);
+void considerTakeover (const PeerIdentity * sender, TSession * tsession);
/* ***************** CORE API methods ************* */
/**
* Call method for every connected node.
*/
-int forEachConnectedNode(PerNodeCallback method,
- void * arg);
+int forEachConnectedNode (PerNodeCallback method, void *arg);
/**
@@ -122,14 +119,12 @@
* @param msg the message to transmit, should contain MESSAGE_HEADERs
* @return OK on success, SYSERR on failure
*/
-int sendPlaintext(TSession * tsession,
- const char * msg,
- unsigned int size);
+int sendPlaintext (TSession * tsession, const char *msg, unsigned int size);
/**
* Compute the hashtable index of a host id.
*/
-unsigned int computeIndex(const PeerIdentity * hostId);
+unsigned int computeIndex (const PeerIdentity * hostId);
/**
* Register a callback method that should be invoked whenever a
@@ -151,15 +146,15 @@
* that buffer (must be a positive number).
* @return OK if the handler was registered, SYSERR on error
*/
-int registerSendCallback(const unsigned int minimumPadding,
- BufferFillCallback callback);
+int registerSendCallback (const unsigned int minimumPadding,
+ BufferFillCallback callback);
/**
* Unregister a handler that was registered with registerSendCallback.
* @return OK if the handler was removed, SYSERR on error
*/
-int unregisterSendCallback(const unsigned int minimumPadding,
- BufferFillCallback callback);
+int unregisterSendCallback (const unsigned int minimumPadding,
+ BufferFillCallback callback);
/**
* Send an encrypted, on-demand build message to another node.
@@ -171,12 +166,11 @@
* @param importance how important is the message?
* @param maxdelay how long can the message wait?
*/
-void unicastCallback(const PeerIdentity * hostId,
- BuildMessageCallback callback,
- void * closure,
- unsigned short len,
- unsigned int importance,
- unsigned int maxdelay);
+void unicastCallback (const PeerIdentity * hostId,
+ BuildMessageCallback callback,
+ void *closure,
+ unsigned short len,
+ unsigned int importance, unsigned int maxdelay);
/**
* Send an encrypted message to another node.
@@ -186,15 +180,14 @@
* @param importance how important is the message?
* @param maxdelay how long can the message be delayed?
*/
-void unicast(const PeerIdentity * receiver,
- const MESSAGE_HEADER * msg,
- unsigned int importance,
- unsigned int maxdelay);
+void unicast (const PeerIdentity * receiver,
+ const MESSAGE_HEADER * msg,
+ unsigned int importance, unsigned int maxdelay);
/**
* Return a pointer to the lock of the connection module.
*/
-struct MUTEX * getConnectionModuleLock(void);
+struct MUTEX *getConnectionModuleLock (void);
/* ******************** traffic management ********** */
@@ -203,17 +196,15 @@
* How many bpm did we assign this peer (how much traffic
* may the given peer send to us per minute?)
*/
-int getBandwidthAssignedTo(const PeerIdentity * hostId,
- unsigned int * bpm,
- cron_t * last_seen);
+int getBandwidthAssignedTo (const PeerIdentity * hostId,
+ unsigned int *bpm, cron_t * last_seen);
/**
* Increase the preference for traffic from some other peer.
* @param node the identity of the other peer
* @param preference how much should the traffic preference be increased?
*/
-void updateTrafficPreference(const PeerIdentity * node,
- double preference);
+void updateTrafficPreference (const PeerIdentity * node, double preference);
/**
@@ -222,7 +213,7 @@
*
* @param peer the peer to disconnect
*/
-void disconnectFromPeer(const PeerIdentity *node);
+void disconnectFromPeer (const PeerIdentity * node);
/**
@@ -234,8 +225,7 @@
* use it after this call. If the core does not want/need
* the session, it will also be disconnected.
*/
-void offerTSessionFor(const PeerIdentity * peer,
- TSession * session);
+void offerTSessionFor (const PeerIdentity * peer, TSession * session);
/**
@@ -248,10 +238,8 @@
* @param forSending NO if it is the key for receiving,
* YES if it is the key for sending
*/
-void assignSessionKey(const SESSIONKEY * key,
- const PeerIdentity * peer,
- TIME_T age,
- int forSending);
+void assignSessionKey (const SESSIONKEY * key,
+ const PeerIdentity * peer, TIME_T age, int forSending);
/**
* Obtain the session key used for traffic from or to a given peer.
@@ -264,24 +252,22 @@
* @return SYSERR if no sessionkey is known to the core,
* OK if the sessionkey was set.
*/
-int getCurrentSessionKey(const PeerIdentity * peer,
- SESSIONKEY * key,
- TIME_T * age,
- int forSending);
+int getCurrentSessionKey (const PeerIdentity * peer,
+ SESSIONKEY * key, TIME_T * age, int forSending);
/**
* Get the current number of slots in the connection table (as computed
* from the available bandwidth).
*/
-int getSlotCount();
+int getSlotCount ();
/**
* Is the given slot used?
* @return 0 if not, otherwise number of peers in
* the slot
*/
-int isSlotUsed(int slot);
+int isSlotUsed (int slot);
/**
* Get the time of the last encrypted message that was received
@@ -289,8 +275,7 @@
* @param time updated with the time
* @return SYSERR if we are not connected to the peer at the moment
*/
-int getLastActivityOf(const PeerIdentity * peer,
- cron_t * time);
+int getLastActivityOf (const PeerIdentity * peer, cron_t * time);
/**
@@ -298,7 +283,7 @@
*
* @param peer the other peer,
*/
-void confirmSessionUp(const PeerIdentity * peer);
+void confirmSessionUp (const PeerIdentity * peer);
/**
@@ -309,7 +294,7 @@
* P2P message part that is transmitted
* @return OK on success, SYSERR if there is a problem
*/
-int registerSendNotify(MessagePartHandler callback);
+int registerSendNotify (MessagePartHandler callback);
/**
* Unregister a handler that is to be called for each
@@ -319,7 +304,7 @@
* P2P message part that is transmitted
* @return OK on success, SYSERR if there is a problem
*/
-int unregisterSendNotify(MessagePartHandler callback);
+int unregisterSendNotify (MessagePartHandler callback);
Modified: GNUnet/src/server/core.c
===================================================================
--- GNUnet/src/server/core.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/core.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -37,16 +37,17 @@
/**
* Linked list of loaded protocols (for clean shutdown).
*/
-typedef struct ShutdownList {
+typedef struct ShutdownList
+{
/**
* Pointer to the library (as returned by dlopen).
*/
- struct PluginHandle * library;
+ struct PluginHandle *library;
/**
* Textual name of the library ("libgnunet_afs_protocol").
*/
- char * dsoName;
+ char *dsoName;
/**
* YES or NO: is the application initialized at this point?
@@ -61,12 +62,12 @@
/**
* Pointer to the service API (or NULL if service not in use).
*/
- void * servicePTR;
+ void *servicePTR;
/**
* This is a linked list.
*/
- struct ShutdownList * next;
+ struct ShutdownList *next;
} ShutdownList;
/**
@@ -77,7 +78,7 @@
/**
* List of loaded modules and their status.
*/
-static ShutdownList * shutdownList = NULL;
+static ShutdownList *shutdownList = NULL;
#define DSO_PREFIX "libgnunet"
@@ -86,79 +87,80 @@
*/
static PeerIdentity myIdentity;
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
/**
* Load the application module named "pos".
* @return OK on success, SYSERR on error
*/
-static int loadApplicationModule(const char * rpos) {
+static int
+loadApplicationModule (const char *rpos)
+{
int ok;
- ShutdownList * nxt;
- ShutdownList * spos;
+ ShutdownList *nxt;
+ ShutdownList *spos;
ApplicationInitMethod mptr;
- struct PluginHandle * library;
- char * name;
- char * pos;
+ struct PluginHandle *library;
+ char *name;
+ char *pos;
pos = NULL;
- if (-1 == GC_get_configuration_value_string(applicationCore.cfg,
- "MODULES",
- rpos,
- rpos,
- &pos))
+ if (-1 == GC_get_configuration_value_string (applicationCore.cfg,
+ "MODULES", rpos, rpos, &pos))
return SYSERR;
- GE_ASSERT(applicationCore.ectx, pos != NULL);
- name = MALLOC(strlen(pos) + strlen("module_") + 1);
- strcpy(name, "module_");
- strcat(name, pos);
- FREE(pos);
+ GE_ASSERT (applicationCore.ectx, pos != NULL);
+ name = MALLOC (strlen (pos) + strlen ("module_") + 1);
+ strcpy (name, "module_");
+ strcat (name, pos);
+ FREE (pos);
nxt = shutdownList;
- while (nxt != NULL) {
- if (0 == strcmp(name,
- nxt->dsoName)) {
- if (nxt->applicationInitialized == YES) {
- GE_LOG(applicationCore.ectx,
- GE_WARNING | GE_DEVELOPER | GE_BULK,
- _("Application module `%s' already initialized!\n"),
- name);
- FREE(name);
- return SYSERR;
- } else {
- mptr = os_plugin_resolve_function(nxt->library,
- "initialize_",
- YES);
- if (mptr == NULL) {
- FREE(name);
- return SYSERR;
- }
- ok = mptr(&applicationCore);
- if (ok == OK)
- nxt->applicationInitialized = YES;
- FREE(name);
- return ok;
- }
+ while (nxt != NULL)
+ {
+ if (0 == strcmp (name, nxt->dsoName))
+ {
+ if (nxt->applicationInitialized == YES)
+ {
+ GE_LOG (applicationCore.ectx,
+ GE_WARNING | GE_DEVELOPER | GE_BULK,
+ _("Application module `%s' already initialized!\n"),
+ name);
+ FREE (name);
+ return SYSERR;
+ }
+ else
+ {
+ mptr = os_plugin_resolve_function (nxt->library,
+ "initialize_", YES);
+ if (mptr == NULL)
+ {
+ FREE (name);
+ return SYSERR;
+ }
+ ok = mptr (&applicationCore);
+ if (ok == OK)
+ nxt->applicationInitialized = YES;
+ FREE (name);
+ return ok;
+ }
+ }
+ nxt = nxt->next;
}
- nxt = nxt->next;
- }
- library = os_plugin_load(applicationCore.ectx,
- DSO_PREFIX,
- name);
- if (library == NULL) {
- FREE(name);
- return SYSERR;
- }
- mptr = os_plugin_resolve_function(library,
- "initialize_",
- YES);
- if (mptr == NULL) {
- os_plugin_unload(library);
- FREE(name);
- return SYSERR;
- }
- nxt = MALLOC(sizeof(ShutdownList));
+ library = os_plugin_load (applicationCore.ectx, DSO_PREFIX, name);
+ if (library == NULL)
+ {
+ FREE (name);
+ return SYSERR;
+ }
+ mptr = os_plugin_resolve_function (library, "initialize_", YES);
+ if (mptr == NULL)
+ {
+ os_plugin_unload (library);
+ FREE (name);
+ return SYSERR;
+ }
+ nxt = MALLOC (sizeof (ShutdownList));
nxt->next = shutdownList;
nxt->dsoName = name;
nxt->library = library;
@@ -166,170 +168,178 @@
nxt->serviceCount = 0;
nxt->servicePTR = NULL;
shutdownList = nxt;
- ok = mptr(&applicationCore);
- if (OK != ok) {
- /* undo loading */
- GE_LOG(applicationCore.ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- _("Failed to load plugin `%s' at %s:%d. Unloading plugin.\n"),
- name, __FILE__, __LINE__);
- /* Note: we cannot assert that shutdownList == nxt here,
- so we have to traverse the list again! */
- nxt->applicationInitialized = NO;
- if (shutdownList == nxt) {
- spos = NULL;
- } else {
- spos = shutdownList;
- while (spos->next != nxt) {
- spos = spos->next;
- if (spos == NULL) {
- GE_BREAK(applicationCore.ectx, 0); /* should never happen! */
- return ok;
- }
- }
+ ok = mptr (&applicationCore);
+ if (OK != ok)
+ {
+ /* undo loading */
+ GE_LOG (applicationCore.ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
+ _("Failed to load plugin `%s' at %s:%d. Unloading plugin.\n"),
+ name, __FILE__, __LINE__);
+ /* Note: we cannot assert that shutdownList == nxt here,
+ so we have to traverse the list again! */
+ nxt->applicationInitialized = NO;
+ if (shutdownList == nxt)
+ {
+ spos = NULL;
+ }
+ else
+ {
+ spos = shutdownList;
+ while (spos->next != nxt)
+ {
+ spos = spos->next;
+ if (spos == NULL)
+ {
+ GE_BREAK (applicationCore.ectx, 0); /* should never
happen! */
+ return ok;
+ }
+ }
+ }
+ if (spos == NULL)
+ shutdownList = nxt->next;
+ else
+ spos->next = nxt->next;
+ os_plugin_unload (library);
+ FREE (name);
+ FREE (nxt);
}
- if (spos == NULL)
- shutdownList = nxt->next;
- else
- spos->next = nxt->next;
- os_plugin_unload(library);
- FREE(name);
- FREE(nxt);
- }
return ok;
}
-static int unloadApplicationModule(const char * name) {
- ShutdownList * pos;
- ShutdownList * prev;
+static int
+unloadApplicationModule (const char *name)
+{
+ ShutdownList *pos;
+ ShutdownList *prev;
ApplicationDoneMethod mptr;
prev = NULL;
pos = shutdownList;
- while ( (pos != NULL) &&
- (0 != strcmp(name,
- pos->dsoName) ) )
+ while ((pos != NULL) && (0 != strcmp (name, pos->dsoName)))
pos = pos->next;
- if (pos == NULL) {
- GE_LOG(applicationCore.ectx,
- GE_ERROR | GE_USER | GE_BULK | GE_DEVELOPER,
- _("Could not shutdown `%s': application not loaded\n"),
- name);
- return SYSERR;
- }
+ if (pos == NULL)
+ {
+ GE_LOG (applicationCore.ectx,
+ GE_ERROR | GE_USER | GE_BULK | GE_DEVELOPER,
+ _("Could not shutdown `%s': application not loaded\n"), name);
+ return SYSERR;
+ }
- if (pos->applicationInitialized != YES) {
- GE_LOG(applicationCore.ectx,
- GE_WARNING | GE_USER | GE_BULK | GE_DEVELOPER,
- _("Could not shutdown application `%s': not initialized\n"),
- name);
- return SYSERR;
- }
- mptr = os_plugin_resolve_function(pos->library,
- "done_",
- YES);
- if (mptr == NULL) {
- GE_LOG(applicationCore.ectx,
- GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
- _("Could not find '%s%s' method in library `%s'.\n"),
- "done_",
- pos->dsoName,
- pos->dsoName);
- return SYSERR;
- }
- mptr();
+ if (pos->applicationInitialized != YES)
+ {
+ GE_LOG (applicationCore.ectx,
+ GE_WARNING | GE_USER | GE_BULK | GE_DEVELOPER,
+ _("Could not shutdown application `%s': not initialized\n"),
+ name);
+ return SYSERR;
+ }
+ mptr = os_plugin_resolve_function (pos->library, "done_", YES);
+ if (mptr == NULL)
+ {
+ GE_LOG (applicationCore.ectx,
+ GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
+ _("Could not find '%s%s' method in library `%s'.\n"),
+ "done_", pos->dsoName, pos->dsoName);
+ return SYSERR;
+ }
+ mptr ();
pos->applicationInitialized = NO;
if (pos->serviceCount > 0)
return OK;
/* compute prev! */
- if (pos == shutdownList) {
- prev = NULL;
- } else {
- prev = shutdownList;
- while (prev->next != pos)
- prev = prev->next;
- }
- os_plugin_unload(pos->library);
+ if (pos == shutdownList)
+ {
+ prev = NULL;
+ }
+ else
+ {
+ prev = shutdownList;
+ while (prev->next != pos)
+ prev = prev->next;
+ }
+ os_plugin_unload (pos->library);
if (prev == NULL)
shutdownList = pos->next;
else
prev->next = pos->next;
- FREE(pos->dsoName);
- FREE(pos);
+ FREE (pos->dsoName);
+ FREE (pos);
return OK;
}
-void * requestService(const char * rpos) {
- ShutdownList * nxt;
+void *
+requestService (const char *rpos)
+{
+ ShutdownList *nxt;
ServiceInitMethod mptr;
- void * library;
- char * name;
- void * api;
- char * pos;
+ void *library;
+ char *name;
+ void *api;
+ char *pos;
/* subtyping, GNUnet style */
pos = NULL;
- if (-1 == GC_get_configuration_value_string(applicationCore.cfg,
- "MODULES",
- rpos,
- rpos,
- &pos))
+ if (-1 == GC_get_configuration_value_string (applicationCore.cfg,
+ "MODULES", rpos, rpos, &pos))
return NULL;
- GE_ASSERT(applicationCore.ectx, pos != NULL);
- name = MALLOC(strlen(pos) + strlen("module_") + 1);
- strcpy(name, "module_");
- strcat(name, pos);
+ GE_ASSERT (applicationCore.ectx, pos != NULL);
+ name = MALLOC (strlen (pos) + strlen ("module_") + 1);
+ strcpy (name, "module_");
+ strcat (name, pos);
nxt = shutdownList;
- while (nxt != NULL) {
- if (0 == strcmp(name,
- nxt->dsoName)) {
- if (nxt->serviceCount > 0) {
- if (nxt->servicePTR != NULL)
- nxt->serviceCount++;
- FREE(name);
- FREE(pos);
- return nxt->servicePTR;
- } else {
- mptr = os_plugin_resolve_function(nxt->library,
- "provide_",
- YES);
- if (mptr == NULL) {
- FREE(name);
- FREE(pos);
- return NULL;
- }
- nxt->servicePTR = mptr(&applicationCore);
- if (nxt->servicePTR != NULL)
- nxt->serviceCount++;
- FREE(name);
- FREE(pos);
- return nxt->servicePTR;
- }
+ while (nxt != NULL)
+ {
+ if (0 == strcmp (name, nxt->dsoName))
+ {
+ if (nxt->serviceCount > 0)
+ {
+ if (nxt->servicePTR != NULL)
+ nxt->serviceCount++;
+ FREE (name);
+ FREE (pos);
+ return nxt->servicePTR;
+ }
+ else
+ {
+ mptr = os_plugin_resolve_function (nxt->library,
+ "provide_", YES);
+ if (mptr == NULL)
+ {
+ FREE (name);
+ FREE (pos);
+ return NULL;
+ }
+ nxt->servicePTR = mptr (&applicationCore);
+ if (nxt->servicePTR != NULL)
+ nxt->serviceCount++;
+ FREE (name);
+ FREE (pos);
+ return nxt->servicePTR;
+ }
+ }
+ nxt = nxt->next;
}
- nxt = nxt->next;
- }
- library = os_plugin_load(applicationCore.ectx,
- DSO_PREFIX,
- name);
- if (library == NULL) {
- FREE(name);
- FREE(pos);
- return NULL;
- }
- mptr = os_plugin_resolve_function(library,
- "provide_",
- YES);
- if (mptr == NULL) {
- os_plugin_unload(library);
- FREE(name);
- FREE(pos);
- return NULL;
- }
- nxt = MALLOC(sizeof(ShutdownList));
+ library = os_plugin_load (applicationCore.ectx, DSO_PREFIX, name);
+ if (library == NULL)
+ {
+ FREE (name);
+ FREE (pos);
+ return NULL;
+ }
+ mptr = os_plugin_resolve_function (library, "provide_", YES);
+ if (mptr == NULL)
+ {
+ os_plugin_unload (library);
+ FREE (name);
+ FREE (pos);
+ return NULL;
+ }
+ nxt = MALLOC (sizeof (ShutdownList));
nxt->next = shutdownList;
nxt->dsoName = name;
nxt->library = library;
@@ -337,230 +347,244 @@
nxt->serviceCount = 1;
nxt->servicePTR = NULL;
shutdownList = nxt;
- GE_LOG(applicationCore.ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- "Loading service `%s'\n",
- pos);
- api = mptr(&applicationCore);
- if (api != NULL) {
- nxt->servicePTR = api;
- } else {
- GE_LOG(applicationCore.ectx,
- GE_WARNING | GE_ADMIN | GE_USER | GE_IMMEDIATE,
- "Failed to load service `%s'\n",
- pos);
- nxt->serviceCount = 0;
- }
- FREE(pos);
+ GE_LOG (applicationCore.ectx,
+ GE_INFO | GE_USER | GE_REQUEST, "Loading service `%s'\n", pos);
+ api = mptr (&applicationCore);
+ if (api != NULL)
+ {
+ nxt->servicePTR = api;
+ }
+ else
+ {
+ GE_LOG (applicationCore.ectx,
+ GE_WARNING | GE_ADMIN | GE_USER | GE_IMMEDIATE,
+ "Failed to load service `%s'\n", pos);
+ nxt->serviceCount = 0;
+ }
+ FREE (pos);
return api;
}
-int releaseService(void * service) {
- ShutdownList * pos;
- ShutdownList * prev;
+int
+releaseService (void *service)
+{
+ ShutdownList *pos;
+ ShutdownList *prev;
ApplicationDoneMethod mptr;
if (service == NULL)
return OK;
prev = NULL;
pos = shutdownList;
- while ( (pos != NULL) &&
- (pos->servicePTR != service) )
+ while ((pos != NULL) && (pos->servicePTR != service))
pos = pos->next;
- if (pos == NULL) {
- GE_LOG(applicationCore.ectx,
- GE_BULK | GE_DEVELOPER | GE_ERROR,
- _("Could not release %p: service not loaded\n"),
- service);
- return SYSERR;
- }
- if (pos->serviceCount > 1) {
- pos->serviceCount--;
- return OK; /* service still in use elsewhere! */
- }
- GE_LOG(applicationCore.ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- "Unloading service `%s'.\n",
- pos->dsoName);
- mptr = os_plugin_resolve_function(pos->library,
- "release_",
- YES);
+ if (pos == NULL)
+ {
+ GE_LOG (applicationCore.ectx,
+ GE_BULK | GE_DEVELOPER | GE_ERROR,
+ _("Could not release %p: service not loaded\n"), service);
+ return SYSERR;
+ }
+ if (pos->serviceCount > 1)
+ {
+ pos->serviceCount--;
+ return OK; /* service still in use elsewhere! */
+ }
+ GE_LOG (applicationCore.ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ "Unloading service `%s'.\n", pos->dsoName);
+ mptr = os_plugin_resolve_function (pos->library, "release_", YES);
if (mptr == NULL)
return SYSERR;
- mptr();
+ mptr ();
pos->serviceCount--;
pos->servicePTR = NULL;
if (pos->applicationInitialized == YES)
- return OK; /* protocol still in use! */
+ return OK; /* protocol still in use! */
/* compute prev */
- if (pos == shutdownList) {
- prev = NULL;
- } else {
- prev = shutdownList;
- while (prev->next != pos)
- prev = prev->next;
- }
+ if (pos == shutdownList)
+ {
+ prev = NULL;
+ }
+ else
+ {
+ prev = shutdownList;
+ while (prev->next != pos)
+ prev = prev->next;
+ }
if (prev == NULL)
shutdownList = pos->next;
else
prev->next = pos->next;
- os_plugin_unload(pos->library);
- FREE(pos->dsoName);
- FREE(pos);
+ os_plugin_unload (pos->library);
+ FREE (pos->dsoName);
+ FREE (pos);
return OK;
}
-int loadApplicationModules() {
- char * dso;
- char * next;
- char * pos;
+int
+loadApplicationModules ()
+{
+ char *dso;
+ char *next;
+ char *pos;
int ok;
ok = OK;
dso = NULL;
- if (-1 == GC_get_configuration_value_string(applicationCore.cfg,
- "GNUNETD",
- "APPLICATIONS",
- "advertising fs getoption stats traffic",
- &dso))
+ if (-1 == GC_get_configuration_value_string (applicationCore.cfg,
+ "GNUNETD",
+ "APPLICATIONS",
+ "advertising fs getoption stats
traffic",
+ &dso))
return SYSERR;
- GE_ASSERT(applicationCore.ectx, dso != NULL);
+ GE_ASSERT (applicationCore.ectx, dso != NULL);
next = dso;
- do {
- while (*next == ' ')
- next++;
- pos = next;
- while ( (*next != '\0') &&
- (*next != ' ') )
- next++;
- if (*next == '\0') {
- next = NULL; /* terminate! */
- } else {
- *next = '\0'; /* add 0-termination for pos */
- next++;
+ do
+ {
+ while (*next == ' ')
+ next++;
+ pos = next;
+ while ((*next != '\0') && (*next != ' '))
+ next++;
+ if (*next == '\0')
+ {
+ next = NULL; /* terminate! */
+ }
+ else
+ {
+ *next = '\0'; /* add 0-termination for pos */
+ next++;
+ }
+ if (strlen (pos) > 0)
+ {
+ GE_LOG (applicationCore.ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ "Loading application `%s'\n", pos);
+ if (OK != loadApplicationModule (pos))
+ ok = SYSERR;
+ }
}
- if (strlen(pos) > 0) {
- GE_LOG(applicationCore.ectx,
- GE_INFO | GE_USER | GE_BULK,
- "Loading application `%s'\n",
- pos);
- if (OK != loadApplicationModule(pos))
- ok = SYSERR;
- }
- } while (next != NULL);
- FREE(dso);
+ while (next != NULL);
+ FREE (dso);
return ok;
}
-int unloadApplicationModules() {
- ShutdownList * pos;
- ShutdownList * nxt;
+int
+unloadApplicationModules ()
+{
+ ShutdownList *pos;
+ ShutdownList *nxt;
int ok;
ok = OK;
pos = shutdownList;
- while (pos != NULL) {
- nxt = pos->next;
- if ( (pos->applicationInitialized == YES) &&
- (OK != unloadApplicationModule(pos->dsoName)) ) {
- GE_LOG(applicationCore.ectx,
- GE_ERROR | GE_DEVELOPER | GE_BULK,
- _("Could not properly shutdown application `%s'.\n"),
- pos->dsoName);
- ok = SYSERR;
+ while (pos != NULL)
+ {
+ nxt = pos->next;
+ if ((pos->applicationInitialized == YES) &&
+ (OK != unloadApplicationModule (pos->dsoName)))
+ {
+ GE_LOG (applicationCore.ectx,
+ GE_ERROR | GE_DEVELOPER | GE_BULK,
+ _("Could not properly shutdown application `%s'.\n"),
+ pos->dsoName);
+ ok = SYSERR;
+ }
+ pos = nxt;
}
- pos = nxt;
- }
return OK;
}
/**
* Initialize the CORE's globals.
*/
-int initCore(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct CronManager * cron,
- struct LoadMonitor * monitor) {
+int
+initCore (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct CronManager *cron, struct LoadMonitor *monitor)
+{
applicationCore.ectx = ectx;
applicationCore.cfg = cfg;
applicationCore.load_monitor = monitor;
applicationCore.cron = cron;
applicationCore.version = 0;
- applicationCore.myIdentity = NULL; /* for now */
- applicationCore.loadApplicationModule = &loadApplicationModule; /* core.c */
- applicationCore.unloadApplicationModule = &unloadApplicationModule; /*
core.c */
- applicationCore.requestService = &requestService; /* core.c */
- applicationCore.releaseService = &releaseService; /* core.c */
+ applicationCore.myIdentity = NULL; /* for now */
+ applicationCore.loadApplicationModule = &loadApplicationModule; /*
core.c */
+ applicationCore.unloadApplicationModule = &unloadApplicationModule; /*
core.c */
+ applicationCore.requestService = &requestService; /* core.c */
+ applicationCore.releaseService = &releaseService; /* core.c */
- applicationCore.sendPlaintext = &sendPlaintext; /* connection.c */
- applicationCore.unicast = &unicast; /* connection.c */
- applicationCore.unicastCallback = &unicastCallback; /* connection.c */
+ applicationCore.sendPlaintext = &sendPlaintext; /* connection.c */
+ applicationCore.unicast = &unicast; /* connection.c */
+ applicationCore.unicastCallback = &unicastCallback; /* connection.c */
applicationCore.forAllConnectedNodes = &forEachConnectedNode; /*
connection.c */
applicationCore.registerSendCallback = ®isterSendCallback; /*
connection.c */
- applicationCore.unregisterSendCallback = &unregisterSendCallback; /*
connection.c */
+ applicationCore.unregisterSendCallback = &unregisterSendCallback; /*
connection.c */
applicationCore.registerSendNotify = ®isterSendNotify;
applicationCore.unregisterSendNotify = &unregisterSendNotify;
- applicationCore.registerHandler = ®isterp2pHandler; /* handler.c */
- applicationCore.unregisterHandler = &unregisterp2pHandler; /* handler.c*/
+ applicationCore.registerHandler = ®isterp2pHandler; /* handler.c */
+ applicationCore.unregisterHandler = &unregisterp2pHandler; /* handler.c */
applicationCore.registerPlaintextHandler = ®isterPlaintextHandler; /*
handler.c */
- applicationCore.unregisterPlaintextHandler = &unregisterPlaintextHandler; /*
handler.c*/
- applicationCore.isHandlerRegistered = &isHandlerRegistered; /* handler.c*/
+ applicationCore.unregisterPlaintextHandler = &unregisterPlaintextHandler;
/* handler.c */
+ applicationCore.isHandlerRegistered = &isHandlerRegistered; /* handler.c */
applicationCore.offerTSessionFor = &considerTakeover; /* connection.c */
applicationCore.assignSessionKey = &assignSessionKey; /* connection.c */
applicationCore.getCurrentSessionKey = &getCurrentSessionKey; /*
connection.c */
applicationCore.confirmSessionUp = &confirmSessionUp; /* connection.c */
applicationCore.preferTrafficFrom = &updateTrafficPreference; /*
connection.c */
- applicationCore.queryPeerStatus = &getBandwidthAssignedTo; /* connection.c */
- applicationCore.disconnectFromPeer = &disconnectFromPeer; /* connection.c */
+ applicationCore.queryPeerStatus = &getBandwidthAssignedTo; /*
connection.c */
+ applicationCore.disconnectFromPeer = &disconnectFromPeer; /*
connection.c */
- applicationCore.sendValueToClient = &sendTCPResultToClient; /* tcpserver.c */
+ applicationCore.sendValueToClient = &sendTCPResultToClient; /* tcpserver.c
*/
applicationCore.sendToClient = &sendToClient; /* tcpserver.c */
- applicationCore.registerClientHandler = ®isterCSHandler; /* tcpserver.c */
- applicationCore.unregisterClientHandler = &unregisterCSHandler; /*
tcpserver.c */
- applicationCore.registerClientExitHandler = ®isterClientExitHandler; /*
tcpserver.c */
- applicationCore.unregisterClientExitHandler = &unregisterClientExitHandler;
/* tcpserver.c */
- applicationCore.terminateClientConnection = &terminateClientConnection; /*
tcpserver.c */
+ applicationCore.registerClientHandler = ®isterCSHandler; /* tcpserver.c
*/
+ applicationCore.unregisterClientHandler = &unregisterCSHandler; /*
tcpserver.c */
+ applicationCore.registerClientExitHandler = ®isterClientExitHandler;
/* tcpserver.c */
+ applicationCore.unregisterClientExitHandler = &unregisterClientExitHandler;
/* tcpserver.c */
+ applicationCore.terminateClientConnection = &terminateClientConnection;
/* tcpserver.c */
- applicationCore.injectMessage = &injectMessage; /* handler.c */
+ applicationCore.injectMessage = &injectMessage; /* handler.c */
applicationCore.computeIndex = &computeIndex; /* connection.c */
- applicationCore.getConnectionModuleLock = &getConnectionModuleLock; /*
connection.c */
+ applicationCore.getConnectionModuleLock = &getConnectionModuleLock; /*
connection.c */
applicationCore.getSlotCount = &getSlotCount; /* connection.c */
- applicationCore.isSlotUsed = &isSlotUsed; /* connection.c */
- applicationCore.getLastActivityOf = &getLastActivityOf; /* connection.c */
+ applicationCore.isSlotUsed = &isSlotUsed; /* connection.c */
+ applicationCore.getLastActivityOf = &getLastActivityOf; /*
connection.c */
- applicationCore.sendErrorMessageToClient = &sendTCPErrorToClient; /*
tcpserver.c */
- applicationCore.createClientLogContext = &createClientLogContext; /*
tcpserver.c */
+ applicationCore.sendErrorMessageToClient = &sendTCPErrorToClient; /*
tcpserver.c */
+ applicationCore.createClientLogContext = &createClientLogContext; /*
tcpserver.c */
- identity = requestService("identity");
+ identity = requestService ("identity");
if (identity == NULL)
return SYSERR;
- identity->getPeerIdentity(identity->getPublicPrivateKey(),
- &myIdentity);
- applicationCore.myIdentity = &myIdentity; /* core.c */
- if (initTCPServer(ectx,
- cfg) != OK) {
- releaseService(identity);
- return SYSERR;
- }
- initHandler(ectx);
+ identity->getPeerIdentity (identity->getPublicPrivateKey (), &myIdentity);
+ applicationCore.myIdentity = &myIdentity; /* core.c */
+ if (initTCPServer (ectx, cfg) != OK)
+ {
+ releaseService (identity);
+ return SYSERR;
+ }
+ initHandler (ectx);
return OK;
}
/**
* Shutdown the CORE modules (shuts down all application modules).
*/
-void doneCore() {
- ShutdownList * pos;
- ShutdownList * prev;
- ShutdownList * nxt;
+void
+doneCore ()
+{
+ ShutdownList *pos;
+ ShutdownList *prev;
+ ShutdownList *nxt;
int change;
- doneHandler();
- releaseService(identity);
+ doneHandler ();
+ releaseService (identity);
identity = NULL;
/* unload all modules;
@@ -569,37 +593,41 @@
pos = shutdownList;
prev = NULL;
change = 1;
- while (change) {
- pos = shutdownList;
- change = 0;
- while (pos != NULL) {
- if ( (pos->applicationInitialized == NO) &&
- (pos->serviceCount == 0) ) {
- change = 1;
- os_plugin_unload(pos->library);
- nxt = pos->next;
- if (prev == NULL)
- shutdownList = nxt;
- else
- prev->next = nxt;
- FREE(pos->dsoName);
- FREE(pos);
- pos = nxt;
- } else {
- prev = pos;
- pos = pos->next;
- }
+ while (change)
+ {
+ pos = shutdownList;
+ change = 0;
+ while (pos != NULL)
+ {
+ if ((pos->applicationInitialized == NO) && (pos->serviceCount == 0))
+ {
+ change = 1;
+ os_plugin_unload (pos->library);
+ nxt = pos->next;
+ if (prev == NULL)
+ shutdownList = nxt;
+ else
+ prev->next = nxt;
+ FREE (pos->dsoName);
+ FREE (pos);
+ pos = nxt;
+ }
+ else
+ {
+ prev = pos;
+ pos = pos->next;
+ }
+ }
}
- }
pos = shutdownList;
- while (pos != NULL) {
- GE_LOG(applicationCore.ectx,
- GE_ERROR | GE_DEVELOPER | GE_BULK,
- _("Could not properly unload service `%s'!\n"),
- pos->dsoName);
- pos = pos->next;
- }
- doneTCPServer();
+ while (pos != NULL)
+ {
+ GE_LOG (applicationCore.ectx,
+ GE_ERROR | GE_DEVELOPER | GE_BULK,
+ _("Could not properly unload service `%s'!\n"), pos->dsoName);
+ pos = pos->next;
+ }
+ doneTCPServer ();
}
/* end of core.c */
Modified: GNUnet/src/server/gnunet-peer-info.c
===================================================================
--- GNUnet/src/server/gnunet-peer-info.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/server/gnunet-peer-info.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,13 +35,13 @@
#include "gnunet_util_cron.h"
#include "core.h"
-static Transport_ServiceAPI * transport;
+static Transport_ServiceAPI *transport;
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static char * cfgFilename = DEFAULT_DAEMON_CONFIG_FILE;
+static char *cfgFilename = DEFAULT_DAEMON_CONFIG_FILE;
static int no_resolve = NO;
@@ -49,14 +49,14 @@
* All gnunet-peer-info command line options
*/
static struct CommandLineOption gnunetpeerinfoOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- COMMAND_LINE_OPTION_HELP(gettext_noop("Print information about GNUnet
peers.")), /* -h */
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Print information about GNUnet
peers.")), /* -h */
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'n', "numeric", NULL,
- gettext_noop("don't resolve host names"),
- 0, &gnunet_getopt_configure_set_one, &no_resolve },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'n', "numeric", NULL,
+ gettext_noop ("don't resolve host names"),
+ 0, &gnunet_getopt_configure_set_one, &no_resolve},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_END,
};
@@ -64,37 +64,32 @@
/**
* Prepass just to resolve DNS entries.
*/
-static int resolveHostInfo(const PeerIdentity * id,
- const unsigned short proto,
- int verified,
- void * data) {
- P2P_hello_MESSAGE * hello;
- void * addr;
+static int
+resolveHostInfo (const PeerIdentity * id,
+ const unsigned short proto, int verified, void *data)
+{
+ P2P_hello_MESSAGE *hello;
+ void *addr;
unsigned int addr_len;
- char * info;
+ char *info;
int have_addr;
- if (GNUNET_SHUTDOWN_TEST()==YES)
+ if (GNUNET_SHUTDOWN_TEST () == YES)
return SYSERR;
- hello = identity->identity2Hello(id,
- proto,
- NO);
+ hello = identity->identity2Hello (id, proto, NO);
if (NULL == hello)
return OK;
addr = NULL;
addr_len = 0;
- have_addr = transport->helloToAddress(hello,
- &addr,
- &addr_len);
- FREE(hello);
- if (have_addr == OK) {
- info = network_get_ip_as_string(addr,
- addr_len,
- ! no_resolve);
- FREE(addr);
- addr = NULL;
- FREENONNULL(info);
- }
+ have_addr = transport->helloToAddress (hello, &addr, &addr_len);
+ FREE (hello);
+ if (have_addr == OK)
+ {
+ info = network_get_ip_as_string (addr, addr_len, !no_resolve);
+ FREE (addr);
+ addr = NULL;
+ FREENONNULL (info);
+ }
return OK;
}
@@ -105,116 +100,108 @@
* Currently prints the PeerIdentity, trust and the IP.
* Could of course do more (e.g. resolve via DNS).
*/
-static int printHostInfo(const PeerIdentity * id,
- const unsigned short proto,
- int verified,
- void * data) {
- P2P_hello_MESSAGE * hello;
- void * addr;
+static int
+printHostInfo (const PeerIdentity * id,
+ const unsigned short proto, int verified, void *data)
+{
+ P2P_hello_MESSAGE *hello;
+ void *addr;
unsigned int addr_len;
- char * info;
+ char *info;
int have_addr;
EncName enc;
- if (GNUNET_SHUTDOWN_TEST()==YES)
+ if (GNUNET_SHUTDOWN_TEST () == YES)
return SYSERR;
- hash2enc(&id->hashPubKey,
- &enc);
- hello = identity->identity2Hello(id,
- proto,
- NO);
- if (NULL == hello) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Could not get address of peer `%s'.\n"),
- &enc);
- return OK;
- }
- if (SYSERR == verifySig(&hello->senderIdentity,
- P2P_hello_MESSAGE_size(hello) - sizeof(Signature) -
sizeof(PublicKey) - sizeof(MESSAGE_HEADER),
- &hello->signature,
- &hello->publicKey)) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("hello message invalid (signature invalid).\n"));
- }
+ hash2enc (&id->hashPubKey, &enc);
+ hello = identity->identity2Hello (id, proto, NO);
+ if (NULL == hello)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Could not get address of peer `%s'.\n"), &enc);
+ return OK;
+ }
+ if (SYSERR == verifySig (&hello->senderIdentity,
+ P2P_hello_MESSAGE_size (hello) -
+ sizeof (Signature) - sizeof (PublicKey) -
+ sizeof (MESSAGE_HEADER), &hello->signature,
+ &hello->publicKey))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("hello message invalid (signature invalid).\n"));
+ }
addr = NULL;
addr_len = 0;
- have_addr = transport->helloToAddress(hello,
- &addr,
- &addr_len);
- FREE(hello);
- if (have_addr != OK) {
- info = STRDUP("NAT"); /* most likely */
- } else {
- info = network_get_ip_as_string(addr,
- addr_len,
- ! no_resolve);
- FREE(addr);
- addr = NULL;
- }
- if (info == NULL) {
- GE_LOG(ectx,
- GE_DEBUG | GE_BULK | GE_USER,
- _("Could not get address of peer `%s'.\n"),
- &enc);
- printf(_("Peer `%s' with trust %8u\n"),
- (char*)&enc,
- identity->getHostTrust(id));
- return OK;
- }
- printf(_("Peer `%s' with trust %8u and address `%s'\n"),
- (char*)&enc,
- identity->getHostTrust(id),
- info);
- FREE(info);
+ have_addr = transport->helloToAddress (hello, &addr, &addr_len);
+ FREE (hello);
+ if (have_addr != OK)
+ {
+ info = STRDUP ("NAT"); /* most likely */
+ }
+ else
+ {
+ info = network_get_ip_as_string (addr, addr_len, !no_resolve);
+ FREE (addr);
+ addr = NULL;
+ }
+ if (info == NULL)
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_BULK | GE_USER,
+ _("Could not get address of peer `%s'.\n"), &enc);
+ printf (_("Peer `%s' with trust %8u\n"),
+ (char *) &enc, identity->getHostTrust (id));
+ return OK;
+ }
+ printf (_("Peer `%s' with trust %8u and address `%s'\n"),
+ (char *) &enc, identity->getHostTrust (id), info);
+ FREE (info);
return OK;
}
-int main(int argc,
- char * const * argv) {
- struct GC_Configuration * cfg;
- struct CronManager * cron;
+int
+main (int argc, char *const *argv)
+{
+ struct GC_Configuration *cfg;
+ struct CronManager *cron;
int ret;
- ret = GNUNET_init(argc,
- argv,
- "gnunet-peer-info",
- &cfgFilename,
- gnunetpeerinfoOptions,
- &ectx,
- &cfg);
- if (ret == -1) {
- GNUNET_fini(ectx, cfg);
- return -1;
- }
- GE_ASSERT(ectx,
- 0 == GC_set_configuration_value_string(cfg,
- ectx,
- "TCPSERVER",
- "DISABLE",
- "YES"));
- cron = cron_create(ectx);
- initCore(ectx, cfg, cron, NULL);
- identity = requestService("identity");
- transport = requestService("transport");
- if (no_resolve != YES) {
+ ret = GNUNET_init (argc,
+ argv,
+ "gnunet-peer-info",
+ &cfgFilename, gnunetpeerinfoOptions, &ectx, &cfg);
+ if (ret == -1)
+ {
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
+ GE_ASSERT (ectx,
+ 0 == GC_set_configuration_value_string (cfg,
+ ectx,
+ "TCPSERVER",
+ "DISABLE", "YES"));
+ cron = cron_create (ectx);
+ initCore (ectx, cfg, cron, NULL);
+ identity = requestService ("identity");
+ transport = requestService ("transport");
+ if (no_resolve != YES)
+ {
#if HAVE_ADNS
- identity->forEachHost(0, /* no timeout */
- &resolveHostInfo,
- NULL);
- /* give GNU ADNS time to resolve... */
- PTHREAD_SLEEP(2 * cronSECONDS);
+ identity->forEachHost (0, /* no timeout */
+ &resolveHostInfo, NULL);
+ /* give GNU ADNS time to resolve... */
+ PTHREAD_SLEEP (2 * cronSECONDS);
#endif
- }
- identity->forEachHost(0, /* no timeout */
- &printHostInfo,
- NULL);
- releaseService(identity);
- releaseService(transport);
- doneCore();
- cron_destroy(cron);
- GNUNET_fini(ectx, cfg);
+ }
+ identity->forEachHost (0, /* no timeout */
+ &printHostInfo, NULL);
+ releaseService (identity);
+ releaseService (transport);
+ doneCore ();
+ cron_destroy (cron);
+ GNUNET_fini (ectx, cfg);
return 0;
}
Modified: GNUnet/src/server/gnunet-transport-check.c
===================================================================
--- GNUnet/src/server/gnunet-transport-check.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/server/gnunet-transport-check.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -43,333 +43,297 @@
#define DEBUG_TRANSPORT_CHECK NO
-static struct SEMAPHORE * sem;
+static struct SEMAPHORE *sem;
static int terminate;
static unsigned long long timeout;
-static Transport_ServiceAPI * transport;
+static Transport_ServiceAPI *transport;
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
-static Pingpong_ServiceAPI * pingpong;
+static Pingpong_ServiceAPI *pingpong;
-static Bootstrap_ServiceAPI * bootstrap;
+static Bootstrap_ServiceAPI *bootstrap;
static int ok;
static int ping;
-static char * expectedValue;
+static char *expectedValue;
static unsigned long long expectedSize;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct CronManager * cron;
+static struct CronManager *cron;
-static char * cfgFilename = DEFAULT_DAEMON_CONFIG_FILE;
+static char *cfgFilename = DEFAULT_DAEMON_CONFIG_FILE;
-static void semUp(void * arg) {
- struct SEMAPHORE * sem = arg;
+static void
+semUp (void *arg)
+{
+ struct SEMAPHORE *sem = arg;
terminate = YES;
- SEMAPHORE_UP(sem);
+ SEMAPHORE_UP (sem);
}
-static int noiseHandler(const PeerIdentity *peer,
- const MESSAGE_HEADER * msg,
- TSession * s) {
- if ( (ntohs(msg->size) ==
- sizeof(MESSAGE_HEADER) + expectedSize) &&
- (0 == memcmp(expectedValue,
- &msg[1],
- expectedSize)) )
+static int
+noiseHandler (const PeerIdentity * peer,
+ const MESSAGE_HEADER * msg, TSession * s)
+{
+ if ((ntohs (msg->size) ==
+ sizeof (MESSAGE_HEADER) + expectedSize) &&
+ (0 == memcmp (expectedValue, &msg[1], expectedSize)))
ok = YES;
- SEMAPHORE_UP(sem);
+ SEMAPHORE_UP (sem);
return OK;
}
/**
* Test the given transport API.
*/
-static void testTAPI(TransportAPI * tapi,
- void * ctx) {
- int * res = ctx;
- P2P_hello_MESSAGE * helo;
- TSession * tsession;
+static void
+testTAPI (TransportAPI * tapi, void *ctx)
+{
+ int *res = ctx;
+ P2P_hello_MESSAGE *helo;
+ TSession *tsession;
unsigned long long repeat;
unsigned long long total;
cron_t start;
cron_t end;
- MESSAGE_HEADER * noise;
+ MESSAGE_HEADER *noise;
- GE_ASSERT(ectx, tapi != NULL);
- if (tapi->protocolNumber == NAT_PROTOCOL_NUMBER) {
- *res = OK;
- return; /* NAT cannot be tested */
- }
- helo = tapi->createhello();
- if (helo == NULL) {
- fprintf(stderr,
- _("`%s': Could not create hello.\n"),
- tapi->transName);
- *res = SYSERR;
- return;
- }
+ GE_ASSERT (ectx, tapi != NULL);
+ if (tapi->protocolNumber == NAT_PROTOCOL_NUMBER)
+ {
+ *res = OK;
+ return; /* NAT cannot be tested */
+ }
+ helo = tapi->createhello ();
+ if (helo == NULL)
+ {
+ fprintf (stderr, _("`%s': Could not create hello.\n"), tapi->transName);
+ *res = SYSERR;
+ return;
+ }
tsession = NULL;
- if (OK != tapi->connect(helo,
- &tsession)) {
- fprintf(stderr,
- _("`%s': Could not connect.\n"),
- tapi->transName);
- *res = SYSERR;
- FREE(helo);
- return;
- }
- FREE(helo);
- if (-1 == GC_get_configuration_value_number(cfg,
- "TRANSPORT-CHECK",
- "REPEAT",
- 1,
- (unsigned long) -1,
- 1,
- &repeat)) {
- *res = SYSERR;
- return;
- }
- total = repeat;
- sem = SEMAPHORE_CREATE(0);
- start = get_time();
- noise = MALLOC(expectedSize + sizeof(MESSAGE_HEADER));
- noise->type = htons(P2P_PROTO_noise);
- noise->size = htons(expectedSize + sizeof(MESSAGE_HEADER));
- memcpy(&noise[1],
- expectedValue,
- expectedSize);
- while ( (repeat > 0) &&
- (GNUNET_SHUTDOWN_TEST() == NO) ) {
- repeat--;
- ok = NO;
- if (OK != sendPlaintext(tsession,
- (char*)noise,
- ntohs(noise->size))) {
- fprintf(stderr,
- _("`%s': Could not send.\n"),
- tapi->transName);
+ if (OK != tapi->connect (helo, &tsession))
+ {
+ fprintf (stderr, _("`%s': Could not connect.\n"), tapi->transName);
*res = SYSERR;
- tapi->disconnect(tsession);
- SEMAPHORE_DESTROY(sem);
- FREE(noise);
+ FREE (helo);
return;
}
- cron_add_job(cron,
- &semUp,
- timeout,
- 0,
- sem);
- SEMAPHORE_DOWN(sem, YES);
- cron_suspend(cron, NO);
- cron_del_job(cron,
- &semUp,
- 0,
- sem);
- cron_resume_jobs(cron, NO);
- if (ok != YES) {
- FPRINTF(stderr,
- _("`%s': Did not receive message within %llu ms.\n"),
- tapi->transName,
- timeout);
+ FREE (helo);
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "TRANSPORT-CHECK",
+ "REPEAT",
+ 1,
+ (unsigned long) -1,
+ 1, &repeat))
+ {
*res = SYSERR;
- tapi->disconnect(tsession);
- SEMAPHORE_DESTROY(sem);
- FREE(noise);
return;
}
- }
- FREE(noise);
- end = get_time();
- if (OK != tapi->disconnect(tsession)) {
- fprintf(stderr,
- _("`%s': Could not disconnect.\n"),
- tapi->transName);
- *res = SYSERR;
- SEMAPHORE_DESTROY(sem);
- return;
- }
- SEMAPHORE_DESTROY(sem);
- printf(_("`%s' transport OK. It took %ums to transmit %llu messages of %llu
bytes each.\n"),
- tapi->transName,
- (unsigned int) ((end - start)/cronMILLIS),
- total,
- expectedSize);
+ total = repeat;
+ sem = SEMAPHORE_CREATE (0);
+ start = get_time ();
+ noise = MALLOC (expectedSize + sizeof (MESSAGE_HEADER));
+ noise->type = htons (P2P_PROTO_noise);
+ noise->size = htons (expectedSize + sizeof (MESSAGE_HEADER));
+ memcpy (&noise[1], expectedValue, expectedSize);
+ while ((repeat > 0) && (GNUNET_SHUTDOWN_TEST () == NO))
+ {
+ repeat--;
+ ok = NO;
+ if (OK != sendPlaintext (tsession, (char *) noise, ntohs (noise->size)))
+ {
+ fprintf (stderr, _("`%s': Could not send.\n"), tapi->transName);
+ *res = SYSERR;
+ tapi->disconnect (tsession);
+ SEMAPHORE_DESTROY (sem);
+ FREE (noise);
+ return;
+ }
+ cron_add_job (cron, &semUp, timeout, 0, sem);
+ SEMAPHORE_DOWN (sem, YES);
+ cron_suspend (cron, NO);
+ cron_del_job (cron, &semUp, 0, sem);
+ cron_resume_jobs (cron, NO);
+ if (ok != YES)
+ {
+ FPRINTF (stderr,
+ _("`%s': Did not receive message within %llu ms.\n"),
+ tapi->transName, timeout);
+ *res = SYSERR;
+ tapi->disconnect (tsession);
+ SEMAPHORE_DESTROY (sem);
+ FREE (noise);
+ return;
+ }
+ }
+ FREE (noise);
+ end = get_time ();
+ if (OK != tapi->disconnect (tsession))
+ {
+ fprintf (stderr, _("`%s': Could not disconnect.\n"), tapi->transName);
+ *res = SYSERR;
+ SEMAPHORE_DESTROY (sem);
+ return;
+ }
+ SEMAPHORE_DESTROY (sem);
+ printf (_
+ ("`%s' transport OK. It took %ums to transmit %llu messages of %llu
bytes each.\n"),
+ tapi->transName, (unsigned int) ((end - start) / cronMILLIS), total,
+ expectedSize);
}
-static void pingCallback(void * unused) {
+static void
+pingCallback (void *unused)
+{
ok = YES;
- SEMAPHORE_UP(sem);
+ SEMAPHORE_UP (sem);
}
-static void testPING(const P2P_hello_MESSAGE * xhello,
- void * arg) {
- int * stats = arg;
- TSession * tsession;
- P2P_hello_MESSAGE * hello;
- P2P_hello_MESSAGE * myHello;
- MESSAGE_HEADER * ping;
- char * msg;
+static void
+testPING (const P2P_hello_MESSAGE * xhello, void *arg)
+{
+ int *stats = arg;
+ TSession *tsession;
+ P2P_hello_MESSAGE *hello;
+ P2P_hello_MESSAGE *myHello;
+ MESSAGE_HEADER *ping;
+ char *msg;
int len;
PeerIdentity peer;
unsigned long long verbose;
- stats[0]++; /* one more seen */
- if (NO == transport->isAvailable(ntohs(xhello->protocol))) {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- _(" Transport %d is not being tested\n"),
- ntohs(xhello->protocol));
- return;
- }
- if (ntohs(xhello->protocol) == NAT_PROTOCOL_NUMBER)
- return; /* NAT cannot be tested */
+ stats[0]++; /* one more seen */
+ if (NO == transport->isAvailable (ntohs (xhello->protocol)))
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ _(" Transport %d is not being tested\n"),
+ ntohs (xhello->protocol));
+ return;
+ }
+ if (ntohs (xhello->protocol) == NAT_PROTOCOL_NUMBER)
+ return; /* NAT cannot be tested */
- stats[1]++; /* one more with transport 'available' */
- GC_get_configuration_value_number(cfg,
- "GNUNET",
- "VERBOSE",
- 0,
- (unsigned long long) -1,
- 0,
- &verbose);
- if (verbose > 0) {
- char * str;
- void * addr;
- unsigned int addr_len;
- int have_addr;
+ stats[1]++; /* one more with transport 'available' */
+ GC_get_configuration_value_number (cfg,
+ "GNUNET",
+ "VERBOSE",
+ 0, (unsigned long long) -1, 0, &verbose);
+ if (verbose > 0)
+ {
+ char *str;
+ void *addr;
+ unsigned int addr_len;
+ int have_addr;
- have_addr = transport->helloToAddress(xhello,
- &addr,
- &addr_len);
- if (have_addr == NO) {
- str = STRDUP("NAT"); /* most likely */
- } else {
- str = network_get_ip_as_string(addr,
- addr_len,
- YES);
- FREE(addr);
+ have_addr = transport->helloToAddress (xhello, &addr, &addr_len);
+ if (have_addr == NO)
+ {
+ str = STRDUP ("NAT"); /* most likely */
+ }
+ else
+ {
+ str = network_get_ip_as_string (addr, addr_len, YES);
+ FREE (addr);
+ }
+ fprintf (stderr, _("\nContacting `%s'."), str);
+ FREE (str);
}
- fprintf(stderr,
- _("\nContacting `%s'."),
- str);
- FREE(str);
- } else
- fprintf(stderr, ".");
- hello = MALLOC(ntohs(xhello->header.size));
- memcpy(hello,
- xhello,
- ntohs(xhello->header.size));
+ else
+ fprintf (stderr, ".");
+ hello = MALLOC (ntohs (xhello->header.size));
+ memcpy (hello, xhello, ntohs (xhello->header.size));
- myHello = transport->createhello(ntohs(xhello->protocol));
+ myHello = transport->createhello (ntohs (xhello->protocol));
if (myHello == NULL)
/* try NAT */
- myHello = transport->createhello(NAT_PROTOCOL_NUMBER);
- if (myHello == NULL) {
- FREE(hello);
- return;
- }
+ myHello = transport->createhello (NAT_PROTOCOL_NUMBER);
+ if (myHello == NULL)
+ {
+ FREE (hello);
+ return;
+ }
if (verbose > 0)
- fprintf(stderr, ".");
+ fprintf (stderr, ".");
tsession = NULL;
peer = hello->senderIdentity;
- tsession = transport->connect(hello);
- FREE(hello);
- if (tsession == NULL) {
- fprintf(stderr,
- _(" Connection failed\n"));
- return;
- }
- if (tsession == NULL) {
- GE_BREAK(ectx, 0);
- fprintf(stderr,
- _(" Connection failed (bug?)\n"));
- return;
- }
+ tsession = transport->connect (hello);
+ FREE (hello);
+ if (tsession == NULL)
+ {
+ fprintf (stderr, _(" Connection failed\n"));
+ return;
+ }
+ if (tsession == NULL)
+ {
+ GE_BREAK (ectx, 0);
+ fprintf (stderr, _(" Connection failed (bug?)\n"));
+ return;
+ }
if (verbose > 0)
- fprintf(stderr, ".");
+ fprintf (stderr, ".");
- sem = SEMAPHORE_CREATE(0);
- ping = pingpong->pingUser(&peer,
- &pingCallback,
- NULL,
- YES,
- rand());
- len = ntohs(ping->size) + ntohs(myHello->header.size);
- msg = MALLOC(len);
- memcpy(msg,
- myHello,
- ntohs(myHello->header.size));
- memcpy(&msg[ntohs(myHello->header.size)],
- ping,
- ntohs(ping->size));
- FREE(myHello);
- FREE(ping);
+ sem = SEMAPHORE_CREATE (0);
+ ping = pingpong->pingUser (&peer, &pingCallback, NULL, YES, rand ());
+ len = ntohs (ping->size) + ntohs (myHello->header.size);
+ msg = MALLOC (len);
+ memcpy (msg, myHello, ntohs (myHello->header.size));
+ memcpy (&msg[ntohs (myHello->header.size)], ping, ntohs (ping->size));
+ FREE (myHello);
+ FREE (ping);
/* send ping */
ok = NO;
- if (OK != sendPlaintext(tsession,
- msg,
- len)) {
- fprintf(stderr,
- "Send failed.\n");
- FREE(msg);
- transport->disconnect(tsession);
- return;
- }
- FREE(msg);
+ if (OK != sendPlaintext (tsession, msg, len))
+ {
+ fprintf (stderr, "Send failed.\n");
+ FREE (msg);
+ transport->disconnect (tsession);
+ return;
+ }
+ FREE (msg);
if (verbose > 0)
- fprintf(stderr, ".");
+ fprintf (stderr, ".");
/* check: received pong? */
#if DEBUG_TRANSPORT_CHECK
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Waiting for PONG\n");
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER, "Waiting for PONG\n");
#endif
terminate = NO;
- cron_add_job(cron,
- &semUp,
- timeout,
- 5 * cronSECONDS,
- sem);
- SEMAPHORE_DOWN(sem, YES);
+ cron_add_job (cron, &semUp, timeout, 5 * cronSECONDS, sem);
+ SEMAPHORE_DOWN (sem, YES);
- if (verbose > 0) {
- if (ok != YES)
- FPRINTF(stderr,
- _("Timeout after %llums.\n"),
- timeout);
- else
- fprintf(stderr,
- _("OK!\n"));
- }
- cron_suspend(cron,
- NO);
- cron_del_job(cron,
- &semUp,
- 5 * cronSECONDS,
- sem);
- cron_resume_jobs(cron,
- NO);
- SEMAPHORE_DESTROY(sem);
+ if (verbose > 0)
+ {
+ if (ok != YES)
+ FPRINTF (stderr, _("Timeout after %llums.\n"), timeout);
+ else
+ fprintf (stderr, _("OK!\n"));
+ }
+ cron_suspend (cron, NO);
+ cron_del_job (cron, &semUp, 5 * cronSECONDS, sem);
+ cron_resume_jobs (cron, NO);
+ SEMAPHORE_DESTROY (sem);
sem = NULL;
- transport->disconnect(tsession);
+ transport->disconnect (tsession);
if (ok == YES)
stats[2]++;
}
-static int testTerminate(void * arg) {
- if (GNUNET_SHUTDOWN_TEST() == NO)
+static int
+testTerminate (void *arg)
+{
+ if (GNUNET_SHUTDOWN_TEST () == NO)
return YES;
return NO;
}
@@ -378,187 +342,155 @@
* All gnunet-transport-check command line options
*/
static struct CommandLineOption gnunettransportcheckOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- COMMAND_LINE_OPTION_HELP(gettext_noop("Tool to test if GNUnet transport
services are operational.")), /* -h */
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Tool to test if GNUnet transport
services are operational.")), /* -h */
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'p', "ping", NULL,
- gettext_noop("ping peers from HOSTLISTURL that match transports"),
- 0, &gnunet_getopt_configure_set_one, &ping },
- { 'r', "repeat", "COUNT",
- gettext_noop("send COUNT messages"),
- 1, &gnunet_getopt_configure_set_option, "TRANSPORT-CHECK:REPEAT" },
- { 's', "size", "SIZE",
- gettext_noop("send messages with SIZE bytes payload"),
- 1, &gnunet_getopt_configure_set_option, "TRANSPORT-CHECK:SIZE" },
- { 't', "transport", "TRANSPORT",
- gettext_noop("specifies which TRANSPORT should be tested"),
- 1, &gnunet_getopt_configure_set_option, "GNUNETD:TRANSPORTS" },
- { 'T', "timeout", "MS",
- gettext_noop("specifies after how many MS to time-out"),
- 1, &gnunet_getopt_configure_set_option, "TRANSPORT-CHECK:TIMEOUT" },
- { 'u', "user", "LOGIN",
- gettext_noop("run as user LOGIN"),
- 1, &gnunet_getopt_configure_set_option, "GNUNETD:USER" },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'p', "ping", NULL,
+ gettext_noop ("ping peers from HOSTLISTURL that match transports"),
+ 0, &gnunet_getopt_configure_set_one, &ping},
+ {'r', "repeat", "COUNT",
+ gettext_noop ("send COUNT messages"),
+ 1, &gnunet_getopt_configure_set_option, "TRANSPORT-CHECK:REPEAT"},
+ {'s', "size", "SIZE",
+ gettext_noop ("send messages with SIZE bytes payload"),
+ 1, &gnunet_getopt_configure_set_option, "TRANSPORT-CHECK:SIZE"},
+ {'t', "transport", "TRANSPORT",
+ gettext_noop ("specifies which TRANSPORT should be tested"),
+ 1, &gnunet_getopt_configure_set_option, "GNUNETD:TRANSPORTS"},
+ {'T', "timeout", "MS",
+ gettext_noop ("specifies after how many MS to time-out"),
+ 1, &gnunet_getopt_configure_set_option, "TRANSPORT-CHECK:TIMEOUT"},
+ {'u', "user", "LOGIN",
+ gettext_noop ("run as user LOGIN"),
+ 1, &gnunet_getopt_configure_set_option, "GNUNETD:USER"},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_VERBOSE,
- { 'X', "Xrepeat", "X",
- gettext_noop("repeat each test X times"),
- 1, &gnunet_getopt_configure_set_option, "TRANSPORT-CHECK:X-REPEAT" },
+ {'X', "Xrepeat", "X",
+ gettext_noop ("repeat each test X times"),
+ 1, &gnunet_getopt_configure_set_option, "TRANSPORT-CHECK:X-REPEAT"},
COMMAND_LINE_OPTION_END,
};
-int main(int argc,
- char * const * argv) {
+int
+main (int argc, char *const *argv)
+{
int res;
unsigned long long Xrepeat;
- char * trans;
+ char *trans;
int stats[3];
int pos;
- res = GNUNET_init(argc,
- argv,
- "gnunet-transport-check",
- &cfgFilename,
- gnunettransportcheckOptions,
- &ectx,
- &cfg);
- if ( (res == -1) ||
- (OK != changeUser(ectx, cfg)) ) {
- GNUNET_fini(ectx, cfg);
- return -1;
- }
+ res = GNUNET_init (argc,
+ argv,
+ "gnunet-transport-check",
+ &cfgFilename, gnunettransportcheckOptions, &ectx, &cfg);
+ if ((res == -1) || (OK != changeUser (ectx, cfg)))
+ {
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
- if (-1 == GC_get_configuration_value_number(cfg,
- "TRANSPORT-CHECK",
- "SIZE",
- 1,
- 60000,
- 12,
- &expectedSize)) {
- GNUNET_fini(ectx, cfg);
- return 1;
- }
- if (-1 == GC_get_configuration_value_number(cfg,
- "TRANSPORT-CHECK",
- "TIMEOUT",
- 1,
- 60 * cronSECONDS,
- 3 * cronSECONDS,
- &timeout)) {
- GNUNET_fini(ectx, cfg);
- return 1;
- }
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "TRANSPORT-CHECK",
+ "SIZE",
+ 1, 60000, 12, &expectedSize))
+ {
+ GNUNET_fini (ectx, cfg);
+ return 1;
+ }
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "TRANSPORT-CHECK",
+ "TIMEOUT",
+ 1,
+ 60 * cronSECONDS,
+ 3 * cronSECONDS, &timeout))
+ {
+ GNUNET_fini (ectx, cfg);
+ return 1;
+ }
- expectedValue = MALLOC(expectedSize);
+ expectedValue = MALLOC (expectedSize);
pos = expectedSize;
expectedValue[--pos] = '\0';
while (pos-- > 0)
expectedValue[pos] = 'A' + (pos % 26);
trans = NULL;
- if (-1 == GC_get_configuration_value_string(cfg,
- "GNUNETD",
- "TRANSPORTS",
- "udp tcp http",
- &trans)) {
- FREE(expectedValue);
- GNUNET_fini(ectx, cfg);
- return 1;
- }
- GE_ASSERT(ectx, trans != NULL);
+ if (-1 == GC_get_configuration_value_string (cfg,
+ "GNUNETD",
+ "TRANSPORTS",
+ "udp tcp http", &trans))
+ {
+ FREE (expectedValue);
+ GNUNET_fini (ectx, cfg);
+ return 1;
+ }
+ GE_ASSERT (ectx, trans != NULL);
if (ping)
- printf(_("Testing transport(s) %s\n"),
- trans);
+ printf (_("Testing transport(s) %s\n"), trans);
else
- printf(_("Available transport(s): %s\n"),
- trans);
- FREE(trans);
- if (! ping) {
- /* disable blacklists (loopback is often blacklisted)... */
- GC_set_configuration_value_string(cfg,
- ectx,
- "TCP",
- "BLACKLIST",
- "");
- GC_set_configuration_value_string(cfg,
- ectx,
- "TCP6",
- "BLACKLIST",
- "");
- GC_set_configuration_value_string(cfg,
- ectx,
- "UDP",
- "BLACKLIST",
- "");
- GC_set_configuration_value_string(cfg,
- ectx,
- "UDP6",
- "BLACKLIST",
- "");
- GC_set_configuration_value_string(cfg,
- ectx,
- "HTTP",
- "BLACKLIST",
- "");
- }
- cron = cron_create(ectx);
- if (OK != initCore(ectx, cfg, cron, NULL)) {
- FREE(expectedValue);
- cron_destroy(cron);
- GNUNET_fini(ectx, cfg);
- return 1;
- }
- initConnection(ectx, cfg, NULL, cron);
- registerPlaintextHandler(P2P_PROTO_noise,
- &noiseHandler);
- enableCoreProcessing();
- identity = requestService("identity");
- transport = requestService("transport");
- pingpong = requestService("pingpong");
- cron_start(cron);
+ printf (_("Available transport(s): %s\n"), trans);
+ FREE (trans);
+ if (!ping)
+ {
+ /* disable blacklists (loopback is often blacklisted)... */
+ GC_set_configuration_value_string (cfg, ectx, "TCP", "BLACKLIST", "");
+ GC_set_configuration_value_string (cfg, ectx, "TCP6", "BLACKLIST", "");
+ GC_set_configuration_value_string (cfg, ectx, "UDP", "BLACKLIST", "");
+ GC_set_configuration_value_string (cfg, ectx, "UDP6", "BLACKLIST", "");
+ GC_set_configuration_value_string (cfg, ectx, "HTTP", "BLACKLIST", "");
+ }
+ cron = cron_create (ectx);
+ if (OK != initCore (ectx, cfg, cron, NULL))
+ {
+ FREE (expectedValue);
+ cron_destroy (cron);
+ GNUNET_fini (ectx, cfg);
+ return 1;
+ }
+ initConnection (ectx, cfg, NULL, cron);
+ registerPlaintextHandler (P2P_PROTO_noise, &noiseHandler);
+ enableCoreProcessing ();
+ identity = requestService ("identity");
+ transport = requestService ("transport");
+ pingpong = requestService ("pingpong");
+ cron_start (cron);
- GC_get_configuration_value_number(cfg,
- "TRANSPORT-CHECK",
- "X-REPEAT",
- 1,
- (unsigned long long) -1,
- 1,
- &Xrepeat);
+ GC_get_configuration_value_number (cfg,
+ "TRANSPORT-CHECK",
+ "X-REPEAT",
+ 1, (unsigned long long) -1, 1, &Xrepeat);
res = OK;
- if (ping) {
- bootstrap = requestService("bootstrap");
+ if (ping)
+ {
+ bootstrap = requestService ("bootstrap");
- stats[0] = 0;
- stats[1] = 0;
- stats[2] = 0;
- bootstrap->bootstrap(&testPING,
- &stats[0],
- &testTerminate,
- NULL);
- printf(_("\n%d out of %d peers contacted successfully (%d times transport
unavailable).\n"),
- stats[2],
- stats[1],
- stats[0] - stats[1]);
- releaseService(bootstrap);
- } else {
- while ( (Xrepeat-- > 0) &&
- (GNUNET_SHUTDOWN_TEST() == NO) )
- transport->forEach(&testTAPI,
- &res);
- }
- cron_stop(cron);
- releaseService(identity);
- releaseService(transport);
- releaseService(pingpong);
- disableCoreProcessing();
- unregisterPlaintextHandler(P2P_PROTO_noise,
- &noiseHandler);
- doneConnection();
- doneCore();
- FREE(expectedValue);
- cron_destroy(cron);
- GNUNET_fini(ectx, cfg);
+ stats[0] = 0;
+ stats[1] = 0;
+ stats[2] = 0;
+ bootstrap->bootstrap (&testPING, &stats[0], &testTerminate, NULL);
+ printf (_
+ ("\n%d out of %d peers contacted successfully (%d times
transport unavailable).\n"),
+ stats[2], stats[1], stats[0] - stats[1]);
+ releaseService (bootstrap);
+ }
+ else
+ {
+ while ((Xrepeat-- > 0) && (GNUNET_SHUTDOWN_TEST () == NO))
+ transport->forEach (&testTAPI, &res);
+ }
+ cron_stop (cron);
+ releaseService (identity);
+ releaseService (transport);
+ releaseService (pingpong);
+ disableCoreProcessing ();
+ unregisterPlaintextHandler (P2P_PROTO_noise, &noiseHandler);
+ doneConnection ();
+ doneCore ();
+ FREE (expectedValue);
+ cron_destroy (cron);
+ GNUNET_fini (ectx, cfg);
if (res != OK)
return -1;
Modified: GNUnet/src/server/gnunet-update.c
===================================================================
--- GNUnet/src/server/gnunet-update.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/gnunet-update.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -43,68 +43,66 @@
*/
#define DSO_PREFIX "libgnunet"
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static char ** processed;
+static char **processed;
static unsigned int processedCount;
static UpdateAPI uapi;
-static char * cfgFilename = DEFAULT_DAEMON_CONFIG_FILE;
+static char *cfgFilename = DEFAULT_DAEMON_CONFIG_FILE;
/**
* Allow the module named "pos" to update.
* @return OK on success, SYSERR on error
*/
-static int updateModule(const char * rpos) {
+static int
+updateModule (const char *rpos)
+{
UpdateMethod mptr;
- struct PluginHandle * library;
- char * name;
+ struct PluginHandle *library;
+ char *name;
int i;
- char * pos;
+ char *pos;
- for (i=0;i<processedCount;i++)
- if (0 == strcmp(rpos, processed[i])) {
- return OK; /* already done */
- }
- GROW(processed, processedCount, processedCount+1);
- processed[processedCount-1] = STRDUP(rpos);
+ for (i = 0; i < processedCount; i++)
+ if (0 == strcmp (rpos, processed[i]))
+ {
+ return OK; /* already done */
+ }
+ GROW (processed, processedCount, processedCount + 1);
+ processed[processedCount - 1] = STRDUP (rpos);
pos = NULL;
- if (-1 == GC_get_configuration_value_string(cfg,
- "MODULES",
- rpos,
- rpos,
- &pos))
+ if (-1 == GC_get_configuration_value_string (cfg,
+ "MODULES", rpos, rpos, &pos))
return SYSERR;
- GE_ASSERT(ectx, pos != NULL);
+ GE_ASSERT (ectx, pos != NULL);
- name = MALLOC(strlen(pos) + strlen("module_") + 1);
- strcpy(name, "module_");
- strcat(name, pos);
- FREE(pos);
- library = os_plugin_load(ectx,
- DSO_PREFIX,
- name);
- if (library == NULL) {
- FREE(name);
- return SYSERR;
- }
- mptr = os_plugin_resolve_function(library,
- "update_",
- NO);
- if (mptr == NULL) {
- os_plugin_unload(library);
- FREE(name);
- return OK; /* module needs no updates! */
- }
- mptr(&uapi);
- os_plugin_unload(library);
- FREE(name);
+ name = MALLOC (strlen (pos) + strlen ("module_") + 1);
+ strcpy (name, "module_");
+ strcat (name, pos);
+ FREE (pos);
+ library = os_plugin_load (ectx, DSO_PREFIX, name);
+ if (library == NULL)
+ {
+ FREE (name);
+ return SYSERR;
+ }
+ mptr = os_plugin_resolve_function (library, "update_", NO);
+ if (mptr == NULL)
+ {
+ os_plugin_unload (library);
+ FREE (name);
+ return OK; /* module needs no updates! */
+ }
+ mptr (&uapi);
+ os_plugin_unload (library);
+ FREE (name);
return OK;
}
@@ -112,117 +110,121 @@
* Call the update module for each of the applications
* in the current configuration.
*/
-static void updateApplicationModules() {
- char * dso;
- char * next;
- char * pos;
+static void
+updateApplicationModules ()
+{
+ char *dso;
+ char *next;
+ char *pos;
dso = NULL;
- if (-1 == GC_get_configuration_value_string(cfg,
- "GNUNETD",
- "APPLICATIONS",
- "advertising fs getoption stats traffic",
- &dso))
+ if (-1 == GC_get_configuration_value_string (cfg,
+ "GNUNETD",
+ "APPLICATIONS",
+ "advertising fs getoption stats
traffic",
+ &dso))
return;
- GE_ASSERT(ectx, dso != NULL);
+ GE_ASSERT (ectx, dso != NULL);
next = dso;
- do {
- pos = next;
- while ( (*next != '\0') &&
- (*next != ' ') )
- next++;
- if (*next == '\0') {
- next = NULL; /* terminate! */
- } else {
- *next = '\0'; /* add 0-termination for pos */
- next++;
+ do
+ {
+ pos = next;
+ while ((*next != '\0') && (*next != ' '))
+ next++;
+ if (*next == '\0')
+ {
+ next = NULL; /* terminate! */
+ }
+ else
+ {
+ *next = '\0'; /* add 0-termination for pos */
+ next++;
+ }
+ if (strlen (pos) > 0)
+ {
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ _("Updating data for module `%s'\n"), pos);
+ if (OK != updateModule (pos))
+ GE_LOG (ectx,
+ GE_ERROR | GE_DEVELOPER | GE_BULK | GE_USER,
+ _("Failed to update data for module `%s'\n"), pos);
+ }
}
- if (strlen(pos) > 0) {
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- _("Updating data for module `%s'\n"),
- pos);
- if (OK != updateModule(pos))
- GE_LOG(ectx,
- GE_ERROR | GE_DEVELOPER | GE_BULK | GE_USER,
- _("Failed to update data for module `%s'\n"),
- pos);
- }
- } while (next != NULL);
- FREE(dso);
+ while (next != NULL);
+ FREE (dso);
}
-static void doGet(char * get) {
- char * sec;
- char * ent;
- char * val;
+static void
+doGet (char *get)
+{
+ char *sec;
+ char *ent;
+ char *val;
sec = get;
ent = get;
- while ( ( (*ent) != ':') &&
- ( (*ent) != '\0') )
+ while (((*ent) != ':') && ((*ent) != '\0'))
ent++;
- if (*ent == ':') {
- *ent = '\0';
- ent++;
- }
- if (YES == GC_have_configuration_value(cfg,
- sec,
- ent)) {
- GC_get_configuration_value_string(cfg,
- sec,
- ent,
- NULL,
- &val);
- printf("%s\n",
- val);
- FREE(val);
- }
+ if (*ent == ':')
+ {
+ *ent = '\0';
+ ent++;
+ }
+ if (YES == GC_have_configuration_value (cfg, sec, ent))
+ {
+ GC_get_configuration_value_string (cfg, sec, ent, NULL, &val);
+ printf ("%s\n", val);
+ FREE (val);
+ }
}
-static void work() {
+static void
+work ()
+{
int i;
- struct CronManager * cron;
+ struct CronManager *cron;
- uapi.updateModule = &updateModule;
+ uapi.updateModule = &updateModule;
uapi.requestService = &requestService;
uapi.releaseService = &releaseService;
uapi.ectx = ectx;
uapi.cfg = cfg;
- cron = cron_create(ectx);
- if (initCore(ectx, cfg, cron, NULL) != OK) {
- GE_LOG(ectx, GE_FATAL | GE_USER | GE_IMMEDIATE,
- _("Core initialization failed.\n"));
-
- return;
- }
+ cron = cron_create (ectx);
+ if (initCore (ectx, cfg, cron, NULL) != OK)
+ {
+ GE_LOG (ectx, GE_FATAL | GE_USER | GE_IMMEDIATE,
+ _("Core initialization failed.\n"));
+ return;
+ }
+
/* enforce filesystem limits */
- capFSQuotaSize(ectx, cfg);
+ capFSQuotaSize (ectx, cfg);
/* force update of common modules (used by core) */
- updateModule("transport");
- updateModule("identity");
- updateModule("session");
- updateModule("fragmentation");
- updateModule("topology");
+ updateModule ("transport");
+ updateModule ("identity");
+ updateModule ("session");
+ updateModule ("fragmentation");
+ updateModule ("topology");
/* then update active application modules */
- updateApplicationModules();
+ updateApplicationModules ();
/* store information about update */
- upToDate(ectx, cfg);
+ upToDate (ectx, cfg);
- for (i=0;i<processedCount;i++)
- FREE(processed[i]);
- GROW(processed, processedCount, 0);
- doneCore();
- cron_destroy(cron);
+ for (i = 0; i < processedCount; i++)
+ FREE (processed[i]);
+ GROW (processed, processedCount, 0);
+ doneCore ();
+ cron_destroy (cron);
}
-static int set_client_config(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value) {
+static int
+set_client_config (CommandLineProcessorContext * ctx,
+ void *scls, const char *option, const char *value)
+{
cfgFilename = DEFAULT_CLIENT_CONFIG_FILE;
return OK;
}
@@ -232,54 +234,49 @@
* All gnunet-update command line options
*/
static struct CommandLineOption gnunetupdateOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- { 'g', "get", "SECTION:ENTRY",
- gettext_noop("print a value from the configuration file to stdout"),
- 1, &gnunet_getopt_configure_set_option, "GNUNET-UPDATE:GET" },
- COMMAND_LINE_OPTION_HELP(gettext_noop("Updates GNUnet datastructures after
version change.")), /* -h */
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ {'g', "get", "SECTION:ENTRY",
+ gettext_noop ("print a value from the configuration file to stdout"),
+ 1, &gnunet_getopt_configure_set_option, "GNUNET-UPDATE:GET"},
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Updates GNUnet datastructures after
version change.")), /* -h */
COMMAND_LINE_OPTION_HOSTNAME, /* -H */
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'u', "user", "LOGIN",
- gettext_noop("run as user LOGIN"),
- 1, &gnunet_getopt_configure_set_option, "GNUNETD:USER" },
- { 'U', "client", NULL,
- gettext_noop("run in client mode (for getting client configuration
values)"),
- 0, &set_client_config, NULL },
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'u', "user", "LOGIN",
+ gettext_noop ("run as user LOGIN"),
+ 1, &gnunet_getopt_configure_set_option, "GNUNETD:USER"},
+ {'U', "client", NULL,
+ gettext_noop
+ ("run in client mode (for getting client configuration values)"),
+ 0, &set_client_config, NULL},
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_VERBOSE,
COMMAND_LINE_OPTION_END,
};
-int main(int argc,
- char * const * argv) {
- char * get;
+int
+main (int argc, char *const *argv)
+{
+ char *get;
int ret;
- ret = GNUNET_init(argc,
- argv,
- "gnunet-update",
- &cfgFilename,
- gnunetupdateOptions,
- &ectx,
- &cfg);
- if ( (ret == -1) ||
- (OK != changeUser(ectx, cfg)) ) {
- GNUNET_fini(ectx, cfg);
- return -1;
- }
+ ret = GNUNET_init (argc,
+ argv,
+ "gnunet-update",
+ &cfgFilename, gnunetupdateOptions, &ectx, &cfg);
+ if ((ret == -1) || (OK != changeUser (ectx, cfg)))
+ {
+ GNUNET_fini (ectx, cfg);
+ return -1;
+ }
get = NULL;
- GC_get_configuration_value_string(cfg,
- "GNUNET-UPDATE",
- "GET",
- "",
- &get);
- if (strlen(get) > 0)
- doGet(get);
+ GC_get_configuration_value_string (cfg, "GNUNET-UPDATE", "GET", "", &get);
+ if (strlen (get) > 0)
+ doGet (get);
else
- work();
- FREE(get);
- GNUNET_fini(ectx, cfg);
+ work ();
+ FREE (get);
+ GNUNET_fini (ectx, cfg);
return 0;
}
Modified: GNUnet/src/server/gnunetd.c
===================================================================
--- GNUnet/src/server/gnunetd.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/gnunetd.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -40,13 +40,13 @@
#include "startup.h"
#include "version.h"
-static struct GC_Configuration * cfg;
-static struct GE_Context * ectx = NULL;
+static struct GC_Configuration *cfg;
+static struct GE_Context *ectx = NULL;
-static struct CronManager * cron;
-static struct LoadMonitor * mon;
+static struct CronManager *cron;
+static struct LoadMonitor *mon;
-static char * cfgFilename = DEFAULT_DAEMON_CONFIG_FILE;
+static char *cfgFilename = DEFAULT_DAEMON_CONFIG_FILE;
static int debug_flag;
@@ -56,48 +56,48 @@
/**
* Cron job that triggers re-reading of the configuration.
*/
-static void reread_config_helper(void * unused) {
- GE_ASSERT(NULL, cfgFilename != NULL);
- GC_parse_configuration(cfg,
- cfgFilename);
+static void
+reread_config_helper (void *unused)
+{
+ GE_ASSERT (NULL, cfgFilename != NULL);
+ GC_parse_configuration (cfg, cfgFilename);
}
/**
* Signal handler for SIGHUP.
* Re-reads the configuration file.
*/
-static void reread_config() {
- cron_add_job(cron,
- &reread_config_helper,
- 1 * cronSECONDS,
- 0,
- NULL);
+static void
+reread_config ()
+{
+ cron_add_job (cron, &reread_config_helper, 1 * cronSECONDS, 0, NULL);
}
#endif
/**
* Park main thread until shutdown has been signaled.
*/
-static void waitForSignalHandler(struct GE_Context * ectx) {
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- _("`%s' startup complete.\n"),
- "gnunetd");
- GNUNET_SHUTDOWN_WAITFOR();
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_REQUEST,
- _("`%s' is shutting down.\n"),
- "gnunetd");
+static void
+waitForSignalHandler (struct GE_Context *ectx)
+{
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ _("`%s' startup complete.\n"), "gnunetd");
+ GNUNET_SHUTDOWN_WAITFOR ();
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_REQUEST,
+ _("`%s' is shutting down.\n"), "gnunetd");
}
-static int post_detach() {
- if (OK != changeUser(ectx, cfg))
+static int
+post_detach ()
+{
+ if (OK != changeUser (ectx, cfg))
return SYSERR;
- if (OK != checkPermissions(ectx, cfg))
+ if (OK != checkPermissions (ectx, cfg))
return SYSERR;
- mon = os_network_monitor_create(ectx,
- cfg);
+ mon = os_network_monitor_create (ectx, cfg);
if (mon == NULL)
return SYSERR;
return OK;
@@ -106,83 +106,67 @@
/**
* The main method of gnunetd.
*/
-int gnunet_main() {
- struct SignalHandlerContext * shc_hup;
- int filedes[2]; /* pipe between client and parent */
+int
+gnunet_main ()
+{
+ struct SignalHandlerContext *shc_hup;
+ int filedes[2]; /* pipe between client and parent */
- if ( (NO == debug_flag) &&
- (OK != os_terminal_detach(ectx,
- cfg,
- filedes)) )
+ if ((NO == debug_flag) && (OK != os_terminal_detach (ectx, cfg, filedes)))
return SYSERR;
if (NO != debug_flag)
- os_write_pid_file(ectx,
- cfg,
- (unsigned int)getpid());
- if (OK != post_detach()) {
- if (NO == debug_flag)
- os_terminal_detach_complete(ectx,
- filedes,
- NO);
- else
- os_delete_pid_file(ectx, cfg);
- return SYSERR;
- }
- cron = cron_create(ectx);
- GE_ASSERT(ectx,
- cron != NULL);
+ os_write_pid_file (ectx, cfg, (unsigned int) getpid ());
+ if (OK != post_detach ())
+ {
+ if (NO == debug_flag)
+ os_terminal_detach_complete (ectx, filedes, NO);
+ else
+ os_delete_pid_file (ectx, cfg);
+ return SYSERR;
+ }
+ cron = cron_create (ectx);
+ GE_ASSERT (ectx, cron != NULL);
#ifndef WINDOWS
- shc_hup = signal_handler_install(SIGHUP,
- &reread_config);
+ shc_hup = signal_handler_install (SIGHUP, &reread_config);
#endif
- if (OK != initCore(ectx,
- cfg,
- cron,
- mon)) {
- GE_LOG(ectx,
- GE_FATAL | GE_USER | GE_IMMEDIATE,
- _("Core initialization failed.\n"));
-
- cron_destroy(cron);
- os_network_monitor_destroy(mon);
+ if (OK != initCore (ectx, cfg, cron, mon))
+ {
+ GE_LOG (ectx,
+ GE_FATAL | GE_USER | GE_IMMEDIATE,
+ _("Core initialization failed.\n"));
+
+ cron_destroy (cron);
+ os_network_monitor_destroy (mon);
#ifndef WINDOWS
- signal_handler_uninstall(SIGHUP,
- &reread_config,
- shc_hup);
+ signal_handler_uninstall (SIGHUP, &reread_config, shc_hup);
#endif
- if (NO == debug_flag)
- os_terminal_detach_complete(ectx,
- filedes,
- NO);
- return SYSERR;
- }
+ if (NO == debug_flag)
+ os_terminal_detach_complete (ectx, filedes, NO);
+ return SYSERR;
+ }
/* enforce filesystem limits */
- capFSQuotaSize(ectx, cfg);
+ capFSQuotaSize (ectx, cfg);
- initConnection(ectx, cfg, mon, cron);
- loadApplicationModules();
+ initConnection (ectx, cfg, mon, cron);
+ loadApplicationModules ();
if (NO == debug_flag)
- os_terminal_detach_complete(ectx,
- filedes,
- YES);
- cron_start(cron);
- enableCoreProcessing();
- waitForSignalHandler(ectx);
- disableCoreProcessing();
- cron_stop(cron);
- os_delete_pid_file(ectx, cfg);
- stopTCPServer();
- unloadApplicationModules();
- doneConnection();
- doneCore();
- os_network_monitor_destroy(mon);
+ os_terminal_detach_complete (ectx, filedes, YES);
+ cron_start (cron);
+ enableCoreProcessing ();
+ waitForSignalHandler (ectx);
+ disableCoreProcessing ();
+ cron_stop (cron);
+ os_delete_pid_file (ectx, cfg);
+ stopTCPServer ();
+ unloadApplicationModules ();
+ doneConnection ();
+ doneCore ();
+ os_network_monitor_destroy (mon);
#ifndef WINDOWS
- signal_handler_uninstall(SIGHUP,
- &reread_config,
- shc_hup);
+ signal_handler_uninstall (SIGHUP, &reread_config, shc_hup);
#endif
- cron_destroy(cron);
+ cron_destroy (cron);
return OK;
}
@@ -190,8 +174,10 @@
/**
* Main method of the windows service
*/
-void WINAPI ServiceMain(DWORD argc, LPSTR *argv) {
- win_service_main(gnunet_main);
+void WINAPI
+ServiceMain (DWORD argc, LPSTR * argv)
+{
+ win_service_main (gnunet_main);
}
#endif
@@ -199,28 +185,29 @@
* All gnunetd command line options
*/
static struct CommandLineOption gnunetdOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- { '@', "win-service", NULL, "", 0,
- &gnunet_getopt_configure_set_option, "GNUNETD:WINSERVICE" },
- { 'd', "debug", NULL,
- gettext_noop("run in debug mode; gnunetd will "
- "not daemonize and error messages will "
- "be written to stderr instead of a logfile"),
- 0, &gnunet_getopt_configure_set_one, &debug_flag },
- COMMAND_LINE_OPTION_HELP(gettext_noop("Starts the gnunetd daemon.")), /* -h
*/
- COMMAND_LINE_OPTION_LOGGING, /* -L */
- { 'p', "padding-disable", "YES/NO",
- gettext_noop("disable padding with random data (experimental)"), 0,
- &gnunet_getopt_configure_set_option, "GNUNETD-EXPERIMENTAL:PADDING" },
- { 'l', "loud", NULL,
- gettext_noop("print all log messages to the console (only works together
with -d)"),
- 0, &gnunet_getopt_configure_set_one, &loud_flag },
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ {'@', "win-service", NULL, "", 0,
+ &gnunet_getopt_configure_set_option, "GNUNETD:WINSERVICE"},
+ {'d', "debug", NULL,
+ gettext_noop ("run in debug mode; gnunetd will "
+ "not daemonize and error messages will "
+ "be written to stderr instead of a logfile"),
+ 0, &gnunet_getopt_configure_set_one, &debug_flag},
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Starts the gnunetd daemon.")),
/* -h */
+ COMMAND_LINE_OPTION_LOGGING, /* -L */
+ {'p', "padding-disable", "YES/NO",
+ gettext_noop ("disable padding with random data (experimental)"), 0,
+ &gnunet_getopt_configure_set_option, "GNUNETD-EXPERIMENTAL:PADDING"},
+ {'l', "loud", NULL,
+ gettext_noop
+ ("print all log messages to the console (only works together with -d)"),
+ 0, &gnunet_getopt_configure_set_one, &loud_flag},
#ifndef MINGW
- { 'u', "user", "USERNAME",
- gettext_noop("specify username as which gnunetd should run"), 1,
- &gnunet_getopt_configure_set_option, "GNUNETD:USERNAME" },
+ {'u', "user", "USERNAME",
+ gettext_noop ("specify username as which gnunetd should run"), 1,
+ &gnunet_getopt_configure_set_option, "GNUNETD:USERNAME"},
#endif
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_END,
};
@@ -228,81 +215,78 @@
* Initialize util (parse command line, options) and
* call the main routine.
*/
-int main(int argc,
- char * const * argv) {
+int
+main (int argc, char *const *argv)
+{
int ret;
- if ( (4 != sizeof(MESSAGE_HEADER)) ||
- (600 != sizeof(P2P_hello_MESSAGE)) ) {
- fprintf(stderr,
- "Sorry, your C compiler did not properly align the C structs.
Aborting.\n");
- return -1;
- }
- ret = GNUNET_init(argc,
- argv,
- "gnunetd [OPTIONS]",
- &cfgFilename,
- gnunetdOptions,
- &ectx,
- &cfg);
- if (ret == -1) {
- GNUNET_fini(ectx, cfg);
- return 1;
- }
- if (YES == debug_flag) {
- int dev;
- char * user_log_level;
- GE_KIND ull;
+ if ((4 != sizeof (MESSAGE_HEADER)) || (600 != sizeof (P2P_hello_MESSAGE)))
+ {
+ fprintf (stderr,
+ "Sorry, your C compiler did not properly align the C structs.
Aborting.\n");
+ return -1;
+ }
+ ret = GNUNET_init (argc,
+ argv,
+ "gnunetd [OPTIONS]",
+ &cfgFilename, gnunetdOptions, &ectx, &cfg);
+ if (ret == -1)
+ {
+ GNUNET_fini (ectx, cfg);
+ return 1;
+ }
+ if (YES == debug_flag)
+ {
+ int dev;
+ char *user_log_level;
+ GE_KIND ull;
- GE_setDefaultContext(NULL);
- GE_free_context(ectx);
- GC_get_configuration_value_string(cfg,
- "LOGGING",
- "USER-LEVEL",
- "WARNING",
- &user_log_level);
- dev = GC_get_configuration_value_yesno(cfg,
- "LOGGING",
- "DEVELOPER",
- NO);
- ull = GE_getKIND(user_log_level);
- ull |= (ull - 1); /* set bits for all lower log-levels */
- if (dev == YES)
- ull |= GE_DEVELOPER | GE_REQUEST;
- if (loud_flag == 1)
- ectx = GE_create_context_stderr(YES,
- GE_ALL);
- else
- ectx = GE_create_context_stderr(YES,
- GE_USER | GE_ADMIN
- | ull
- | GE_BULK | GE_IMMEDIATE);
- GE_setDefaultContext(ectx);
- FREE(user_log_level);
- }
- setFdLimit(ectx, cfg);
- if (OK != checkUpToDate(ectx,
- cfg)) {
- GE_LOG(ectx,
- GE_USER | GE_FATAL | GE_IMMEDIATE,
- _("Configuration or GNUnet version changed. You need to run `%s'!\n"),
- "gnunet-update");
- GNUNET_fini(ectx, cfg);
- return 1;
- }
+ GE_setDefaultContext (NULL);
+ GE_free_context (ectx);
+ GC_get_configuration_value_string (cfg,
+ "LOGGING",
+ "USER-LEVEL",
+ "WARNING", &user_log_level);
+ dev = GC_get_configuration_value_yesno (cfg,
+ "LOGGING", "DEVELOPER", NO);
+ ull = GE_getKIND (user_log_level);
+ ull |= (ull - 1); /* set bits for all lower log-levels */
+ if (dev == YES)
+ ull |= GE_DEVELOPER | GE_REQUEST;
+ if (loud_flag == 1)
+ ectx = GE_create_context_stderr (YES, GE_ALL);
+ else
+ ectx = GE_create_context_stderr (YES,
+ GE_USER | GE_ADMIN
+ | ull | GE_BULK | GE_IMMEDIATE);
+ GE_setDefaultContext (ectx);
+ FREE (user_log_level);
+ }
+ setFdLimit (ectx, cfg);
+ if (OK != checkUpToDate (ectx, cfg))
+ {
+ GE_LOG (ectx,
+ GE_USER | GE_FATAL | GE_IMMEDIATE,
+ _
+ ("Configuration or GNUnet version changed. You need to run
`%s'!\n"),
+ "gnunet-update");
+ GNUNET_fini (ectx, cfg);
+ return 1;
+ }
#ifdef MINGW
- if (GC_get_configuration_value_yesno(cfg,
- "GNUNETD",
- "WINSERVICE",
- NO) == YES) {
- SERVICE_TABLE_ENTRY DispatchTable[] =
- {{"GNUnet", ServiceMain}, {NULL, NULL}};
- ret = (GNStartServiceCtrlDispatcher(DispatchTable) != 0);
- } else
+ if (GC_get_configuration_value_yesno (cfg,
+ "GNUNETD", "WINSERVICE", NO) == YES)
+ {
+ SERVICE_TABLE_ENTRY DispatchTable[] = { {"GNUnet", ServiceMain}
+ , {NULL, NULL}
+ };
+ ret = (GNStartServiceCtrlDispatcher (DispatchTable) != 0);
+ }
+ else
#endif
- ret = gnunet_main();
- GNUNET_fini(ectx, cfg);
+ ret = gnunet_main ();
+ GNUNET_fini (ectx, cfg);
if (ret != OK)
return 1;
return 0;
Modified: GNUnet/src/server/handler.c
===================================================================
--- GNUnet/src/server/handler.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/handler.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -62,15 +62,15 @@
/**
* Transport service
*/
-static Transport_ServiceAPI * transport;
+static Transport_ServiceAPI *transport;
/**
* Identity service
*/
-static Identity_ServiceAPI * identity;
+static Identity_ServiceAPI *identity;
-static P2P_PACKET * bufferQueue_[QUEUE_LENGTH];
+static P2P_PACKET *bufferQueue_[QUEUE_LENGTH];
static int bq_firstFree_;
@@ -78,15 +78,15 @@
static int threads_running = NO;
-static struct SEMAPHORE * bufferQueueRead_;
+static struct SEMAPHORE *bufferQueueRead_;
-static struct SEMAPHORE * bufferQueueWrite_;
+static struct SEMAPHORE *bufferQueueWrite_;
-static struct MUTEX * globalLock_;
+static struct MUTEX *globalLock_;
-static struct SEMAPHORE * mainShutdownSignal;
+static struct SEMAPHORE *mainShutdownSignal;
-static struct PTHREAD * threads_[THREAD_COUNT];
+static struct PTHREAD *threads_[THREAD_COUNT];
#if TRACK_DISCARD
static unsigned int discarded;
@@ -97,7 +97,7 @@
/**
* Array of arrays of message handlers.
*/
-static MessagePartHandler ** handlers = NULL;
+static MessagePartHandler **handlers = NULL;
/**
* Number of handlers in the array (max, there
@@ -108,7 +108,7 @@
/**
* Array of arrays of the message handlers for plaintext messages.
*/
-static PlaintextMessagePartHandler ** plaintextHandlers = NULL;
+static PlaintextMessagePartHandler **plaintextHandlers = NULL;
/**
* Number of handlers in the plaintextHandlers array (max, there
@@ -119,9 +119,9 @@
/**
* Mutex to guard access to the handler array.
*/
-static struct MUTEX * handlerLock;
+static struct MUTEX *handlerLock;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
#if MEASURE_TIME
static cron_t time_by_type[P2P_PROTO_MAX_USED];
@@ -142,34 +142,35 @@
* @return OK on success, SYSERR if core threads are running
* and updates to the handler list are illegal!
*/
-int registerp2pHandler(unsigned short type,
- MessagePartHandler callback) {
+int
+registerp2pHandler (unsigned short type, MessagePartHandler callback)
+{
unsigned int last;
- if (threads_running == YES) {
- GE_BREAK(ectx, NULL);
- return SYSERR;
- }
- MUTEX_LOCK(handlerLock);
- if (type >= max_registeredType) {
- unsigned int ort = max_registeredType;
- GROW(handlers,
- max_registeredType,
- type + 32);
- while (ort < max_registeredType) {
- unsigned int zero = 0;
- GROW(handlers[ort],
- zero,
- 1);
- ort++;
+ if (threads_running == YES)
+ {
+ GE_BREAK (ectx, NULL);
+ return SYSERR;
}
- }
+ MUTEX_LOCK (handlerLock);
+ if (type >= max_registeredType)
+ {
+ unsigned int ort = max_registeredType;
+ GROW (handlers, max_registeredType, type + 32);
+ while (ort < max_registeredType)
+ {
+ unsigned int zero = 0;
+ GROW (handlers[ort], zero, 1);
+ ort++;
+ }
+ }
last = 0;
- while (handlers[type][last] != NULL) last++;
+ while (handlers[type][last] != NULL)
+ last++;
last++;
- GROW(handlers[type], last, last+1);
- handlers[type][last-2] = callback;
- MUTEX_UNLOCK(handlerLock);
+ GROW (handlers[type], last, last + 1);
+ handlers[type][last - 2] = callback;
+ MUTEX_UNLOCK (handlerLock);
return OK;
}
@@ -184,37 +185,43 @@
* handler for that type or if core threads are running
* and updates to the handler list are illegal!
*/
-int unregisterp2pHandler(unsigned short type,
- MessagePartHandler callback) {
+int
+unregisterp2pHandler (unsigned short type, MessagePartHandler callback)
+{
unsigned int pos;
unsigned int last;
- if (threads_running == YES) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- MUTEX_LOCK(handlerLock);
- if (type < max_registeredType) {
- pos = 0;
- while ( (handlers[type][pos] != NULL) &&
- (handlers[type][pos] != callback) )
- pos++;
- last = pos;
- while (handlers[type][last] != NULL)
- last++;
- if (last == pos) {
- MUTEX_UNLOCK(handlerLock);
+ if (threads_running == YES)
+ {
+ GE_BREAK (ectx, 0);
return SYSERR;
- } else {
- handlers[type][pos] = handlers[type][last-1];
- handlers[type][last-1] = NULL;
- last++;
- GROW(handlers[type], last, last-1);
- MUTEX_UNLOCK(handlerLock);
- return OK;
}
- }
- MUTEX_UNLOCK(handlerLock);
+ MUTEX_LOCK (handlerLock);
+ if (type < max_registeredType)
+ {
+ pos = 0;
+ while ((handlers[type][pos] != NULL) &&
+ (handlers[type][pos] != callback))
+ pos++;
+ last = pos;
+ while (handlers[type][last] != NULL)
+ last++;
+ if (last == pos)
+ {
+ MUTEX_UNLOCK (handlerLock);
+ return SYSERR;
+ }
+ else
+ {
+ handlers[type][pos] = handlers[type][last - 1];
+ handlers[type][last - 1] = NULL;
+ last++;
+ GROW (handlers[type], last, last - 1);
+ MUTEX_UNLOCK (handlerLock);
+ return OK;
+ }
+ }
+ MUTEX_UNLOCK (handlerLock);
return SYSERR;
}
@@ -231,34 +238,36 @@
* @return OK on success, SYSERR if core threads are running
* and updates to the handler list are illegal!
*/
-int registerPlaintextHandler(unsigned short type,
- PlaintextMessagePartHandler callback) {
+int
+registerPlaintextHandler (unsigned short type,
+ PlaintextMessagePartHandler callback)
+{
unsigned int last;
- if (threads_running == YES) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- MUTEX_LOCK(handlerLock);
- if (type >= plaintextmax_registeredType) {
- unsigned int ort = plaintextmax_registeredType;
- GROW(plaintextHandlers,
- plaintextmax_registeredType,
- type + 32);
- while (ort < plaintextmax_registeredType) {
- unsigned int zero = 0;
- GROW(plaintextHandlers[ort],
- zero,
- 1);
- ort++;
+ if (threads_running == YES)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
}
- }
+ MUTEX_LOCK (handlerLock);
+ if (type >= plaintextmax_registeredType)
+ {
+ unsigned int ort = plaintextmax_registeredType;
+ GROW (plaintextHandlers, plaintextmax_registeredType, type + 32);
+ while (ort < plaintextmax_registeredType)
+ {
+ unsigned int zero = 0;
+ GROW (plaintextHandlers[ort], zero, 1);
+ ort++;
+ }
+ }
last = 0;
- while (plaintextHandlers[type][last] != NULL) last++;
+ while (plaintextHandlers[type][last] != NULL)
+ last++;
last++;
- GROW(plaintextHandlers[type], last, last+1);
- plaintextHandlers[type][last-2] = callback;
- MUTEX_UNLOCK(handlerLock);
+ GROW (plaintextHandlers[type], last, last + 1);
+ plaintextHandlers[type][last - 2] = callback;
+ MUTEX_UNLOCK (handlerLock);
return OK;
}
@@ -273,37 +282,44 @@
* handler for that type or if core threads are running
* and updates to the handler list are illegal!
*/
-int unregisterPlaintextHandler(unsigned short type,
- PlaintextMessagePartHandler callback) {
+int
+unregisterPlaintextHandler (unsigned short type,
+ PlaintextMessagePartHandler callback)
+{
unsigned int pos;
unsigned int last;
- if (threads_running == YES) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- MUTEX_LOCK(handlerLock);
- if (type < plaintextmax_registeredType) {
- pos = 0;
- while ( (plaintextHandlers[type][pos] != NULL) &&
- (plaintextHandlers[type][pos] != callback) )
- pos++;
- last = pos;
- while (plaintextHandlers[type][last] != NULL)
- last++;
- if (last == pos) {
- MUTEX_UNLOCK(handlerLock);
+ if (threads_running == YES)
+ {
+ GE_BREAK (ectx, 0);
return SYSERR;
- } else {
- plaintextHandlers[type][pos] = plaintextHandlers[type][last-1];
- plaintextHandlers[type][last-1] = NULL;
- last++;
- GROW(plaintextHandlers[type], last, last-1);
- MUTEX_UNLOCK(handlerLock);
- return OK;
}
- }
- MUTEX_UNLOCK(handlerLock);
+ MUTEX_LOCK (handlerLock);
+ if (type < plaintextmax_registeredType)
+ {
+ pos = 0;
+ while ((plaintextHandlers[type][pos] != NULL) &&
+ (plaintextHandlers[type][pos] != callback))
+ pos++;
+ last = pos;
+ while (plaintextHandlers[type][last] != NULL)
+ last++;
+ if (last == pos)
+ {
+ MUTEX_UNLOCK (handlerLock);
+ return SYSERR;
+ }
+ else
+ {
+ plaintextHandlers[type][pos] = plaintextHandlers[type][last - 1];
+ plaintextHandlers[type][last - 1] = NULL;
+ last++;
+ GROW (plaintextHandlers[type], last, last - 1);
+ MUTEX_UNLOCK (handlerLock);
+ return OK;
+ }
+ }
+ MUTEX_UNLOCK (handlerLock);
return SYSERR;
}
@@ -320,36 +336,38 @@
* handler for that type or if core threads are running
* and updates to the handler list are illegal!
*/
-int isHandlerRegistered(unsigned short type,
- unsigned short handlerType) {
+int
+isHandlerRegistered (unsigned short type, unsigned short handlerType)
+{
int pos;
int ret;
if (handlerType == 3)
- return isCSHandlerRegistered(type);
- if (handlerType > 3) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ return isCSHandlerRegistered (type);
+ if (handlerType > 3)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
ret = 0;
- MUTEX_LOCK(handlerLock);
- if (type < plaintextmax_registeredType) {
- pos = 0;
- while (plaintextHandlers[type][pos] != NULL)
- pos++;
- if ( (handlerType == 0) ||
- (handlerType == 2) )
- ret += pos;
- }
- if (type < max_registeredType) {
- pos = 0;
- while (handlers[type][pos] != NULL)
- pos++;
- if ( (handlerType == 1) ||
- (handlerType == 2) )
- ret += pos;
- }
- MUTEX_UNLOCK(handlerLock);
+ MUTEX_LOCK (handlerLock);
+ if (type < plaintextmax_registeredType)
+ {
+ pos = 0;
+ while (plaintextHandlers[type][pos] != NULL)
+ pos++;
+ if ((handlerType == 0) || (handlerType == 2))
+ ret += pos;
+ }
+ if (type < max_registeredType)
+ {
+ pos = 0;
+ while (handlers[type][pos] != NULL)
+ pos++;
+ if ((handlerType == 1) || (handlerType == 2))
+ ret += pos;
+ }
+ MUTEX_UNLOCK (handlerLock);
return ret;
}
@@ -363,15 +381,15 @@
* NO if plaintext,
* @param session NULL if not available
*/
-void injectMessage(const PeerIdentity * sender,
- const char * msg,
- unsigned int size,
- int wasEncrypted,
- TSession * session) {
+void
+injectMessage (const PeerIdentity * sender,
+ const char *msg,
+ unsigned int size, int wasEncrypted, TSession * session)
+{
unsigned int pos;
- const MESSAGE_HEADER * part;
+ const MESSAGE_HEADER *part;
MESSAGE_HEADER cpart;
- MESSAGE_HEADER * copy;
+ MESSAGE_HEADER *copy;
int last;
EncName enc;
#if MEASURE_TIME
@@ -380,141 +398,146 @@
pos = 0;
copy = NULL;
- while (pos < size) {
- unsigned short plen;
- unsigned short ptyp;
+ while (pos < size)
+ {
+ unsigned short plen;
+ unsigned short ptyp;
- FREENONNULL(copy);
- copy = NULL;
- memcpy(&cpart,
- &msg[pos],
- sizeof(MESSAGE_HEADER));
- plen = htons(cpart.size);
- if (pos + plen > size) {
- if (sender != NULL) {
- IF_GELOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- hash2enc(&sender->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Received corrupt message from peer `%s'in %s:%d.\n"),
- &enc,
- __FILE__, __LINE__);
- } else {
- GE_BREAK(ectx, 0);
- }
- return;
- }
- if ( (pos % sizeof(int)) != 0) {
- /* correct misalignment; we allow messages to _not_ be a
- multiple of 4 bytes (if absolutely necessary; it should be
- avoided where the cost for doing so is not prohibitive);
- however we also (need to) guaranteed word-alignment for the
- handlers; so we must re-align the message if it is
- misaligned. */
- copy = MALLOC(plen);
- memcpy(copy,
- &msg[pos],
- plen);
- part = copy;
- } else {
- part = (const MESSAGE_HEADER*) &msg[pos];
- }
- pos += plen;
+ FREENONNULL (copy);
+ copy = NULL;
+ memcpy (&cpart, &msg[pos], sizeof (MESSAGE_HEADER));
+ plen = htons (cpart.size);
+ if (pos + plen > size)
+ {
+ if (sender != NULL)
+ {
+ IF_GELOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ hash2enc (&sender->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Received corrupt message from peer `%s'in %s:%d.\n"),
+ &enc, __FILE__, __LINE__);
+ }
+ else
+ {
+ GE_BREAK (ectx, 0);
+ }
+ return;
+ }
+ if ((pos % sizeof (int)) != 0)
+ {
+ /* correct misalignment; we allow messages to _not_ be a
+ multiple of 4 bytes (if absolutely necessary; it should be
+ avoided where the cost for doing so is not prohibitive);
+ however we also (need to) guaranteed word-alignment for the
+ handlers; so we must re-align the message if it is
+ misaligned. */
+ copy = MALLOC (plen);
+ memcpy (copy, &msg[pos], plen);
+ part = copy;
+ }
+ else
+ {
+ part = (const MESSAGE_HEADER *) &msg[pos];
+ }
+ pos += plen;
- ptyp = htons(part->type);
+ ptyp = htons (part->type);
#if DEBUG_HANDLER
- if (sender != NULL) {
- IF_GELOG(ectx,
- GE_DEBUG,
- hash2enc(&sender->hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG,
- "Received %s message of type %u from peer `%s'\n",
- wasEncrypted ? "encrypted" : "plaintext",
- ptyp,
- &enc);
- }
+ if (sender != NULL)
+ {
+ IF_GELOG (ectx, GE_DEBUG, hash2enc (&sender->hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG,
+ "Received %s message of type %u from peer `%s'\n",
+ wasEncrypted ? "encrypted" : "plaintext", ptyp, &enc);
+ }
#endif
- if (YES == wasEncrypted) {
- MessagePartHandler callback;
+ if (YES == wasEncrypted)
+ {
+ MessagePartHandler callback;
- if ( (ptyp >= max_registeredType) ||
- (NULL == handlers[ptyp][0]) ) {
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "Encrypted message of type '%d' not understood (no handler
registered).\n",
- ptyp);
- continue; /* no handler registered, go to next part */
- }
+ if ((ptyp >= max_registeredType) || (NULL == handlers[ptyp][0]))
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST,
+ "Encrypted message of type '%d' not understood (no
handler registered).\n",
+ ptyp);
+ continue; /* no handler registered, go to next part */
+ }
#if MEASURE_TIME
- now = get_time();
+ now = get_time ();
#endif
- last = 0;
- while (NULL != (callback = handlers[ptyp][last])) {
- if (SYSERR == callback(sender,
- part)) {
+ last = 0;
+ while (NULL != (callback = handlers[ptyp][last]))
+ {
+ if (SYSERR == callback (sender, part))
+ {
#if DEBUG_HANDLER
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Handler aborted message processing after receiving message of type
'%d'.\n",
- ptyp);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "Handler aborted message processing after receiving
message of type '%d'.\n",
+ ptyp);
#endif
- FREENONNULL(copy);
- copy = NULL;
- return; /* handler says: do not process the rest of the message */
- }
- last++;
- }
+ FREENONNULL (copy);
+ copy = NULL;
+ return; /* handler says: do not process the rest of
the message */
+ }
+ last++;
+ }
#if MEASURE_TIME
- if (ptyp < P2P_PROTO_MAX_USED) {
- time_by_type[ptyp] += get_time() - now;
- count_by_type[ptyp]++;
- }
+ if (ptyp < P2P_PROTO_MAX_USED)
+ {
+ time_by_type[ptyp] += get_time () - now;
+ count_by_type[ptyp]++;
+ }
#endif
- } else { /* isEncrypted == NO */
- PlaintextMessagePartHandler callback;
+ }
+ else
+ { /* isEncrypted == NO */
+ PlaintextMessagePartHandler callback;
- if ( (ptyp >= plaintextmax_registeredType) ||
- (NULL == plaintextHandlers[ptyp][0]) ) {
- GE_LOG(ectx,
- GE_REQUEST | GE_DEBUG | GE_USER,
- "Plaintext message of type '%d' not understood (no handler
registered).\n",
- ptyp);
- continue; /* no handler registered, go to next part */
- }
+ if ((ptyp >= plaintextmax_registeredType) ||
+ (NULL == plaintextHandlers[ptyp][0]))
+ {
+ GE_LOG (ectx,
+ GE_REQUEST | GE_DEBUG | GE_USER,
+ "Plaintext message of type '%d' not understood (no
handler registered).\n",
+ ptyp);
+ continue; /* no handler registered, go to next part */
+ }
#if MEASURE_TIME
- now = get_time();
+ now = get_time ();
#endif
- last = 0;
- while (NULL != (callback = plaintextHandlers[ptyp][last])) {
- if (SYSERR == callback(sender,
- part,
- session)) {
+ last = 0;
+ while (NULL != (callback = plaintextHandlers[ptyp][last]))
+ {
+ if (SYSERR == callback (sender, part, session))
+ {
#if DEBUG_HANDLER
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Handler aborted message processing after receiving message of type
'%d'.\n",
- ptyp);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "Handler aborted message processing after receiving
message of type '%d'.\n",
+ ptyp);
#endif
- FREENONNULL(copy);
- copy = NULL;
- return; /* handler says: do not process the rest of the message */
- }
- last++;
- }
+ FREENONNULL (copy);
+ copy = NULL;
+ return; /* handler says: do not process the rest of
the message */
+ }
+ last++;
+ }
#if MEASURE_TIME
- if (ptyp < P2P_PROTO_MAX_USED) {
- time_by_type[ptyp] += get_time() - now;
- count_by_type[ptyp]++;
- }
+ if (ptyp < P2P_PROTO_MAX_USED)
+ {
+ time_by_type[ptyp] += get_time () - now;
+ count_by_type[ptyp]++;
+ }
#endif
- } /* if plaintext */
- } /* while loop */
- FREENONNULL(copy);
+ } /* if plaintext */
+ } /* while loop */
+ FREENONNULL (copy);
copy = NULL;
}
@@ -526,35 +549,30 @@
* @param msg the message that was received. caller frees it on return
* @param size the size of the message
*/
-static void handleMessage(TSession * tsession,
- const PeerIdentity * sender,
- const char * msg,
- unsigned int size) {
+static void
+handleMessage (TSession * tsession,
+ const PeerIdentity * sender,
+ const char *msg, unsigned int size)
+{
int ret;
- if ( (tsession != NULL) &&
- (sender != NULL) &&
- (0 != memcmp(sender,
- &tsession->peer,
- sizeof(PeerIdentity))) ) {
- GE_BREAK(NULL, 0);
- return;
- }
- ret = checkHeader(sender,
- (P2P_PACKET_HEADER*) msg,
- size);
+ if ((tsession != NULL) &&
+ (sender != NULL) &&
+ (0 != memcmp (sender, &tsession->peer, sizeof (PeerIdentity))))
+ {
+ GE_BREAK (NULL, 0);
+ return;
+ }
+ ret = checkHeader (sender, (P2P_PACKET_HEADER *) msg, size);
if (ret == SYSERR)
- return; /* message malformed */
- if ( (ret == YES) &&
- (tsession != NULL) &&
- (sender != NULL) &&
- (OK == transport->associate(tsession)) )
- considerTakeover(sender, tsession);
- injectMessage(sender,
- &msg[sizeof(P2P_PACKET_HEADER)],
- size - sizeof(P2P_PACKET_HEADER),
- ret,
- tsession);
+ return; /* message malformed */
+ if ((ret == YES) &&
+ (tsession != NULL) &&
+ (sender != NULL) && (OK == transport->associate (tsession)))
+ considerTakeover (sender, tsession);
+ injectMessage (sender,
+ &msg[sizeof (P2P_PACKET_HEADER)],
+ size - sizeof (P2P_PACKET_HEADER), ret, tsession);
}
/**
@@ -562,274 +580,272 @@
* for incomming packets in the packet queue. Then it calls "handle"
* (defined in handler.c) on the packet.
*/
-static void * threadMain(void * cls) {
- P2P_PACKET * mp;
+static void *
+threadMain (void *cls)
+{
+ P2P_PACKET *mp;
- while (mainShutdownSignal == NULL) {
- SEMAPHORE_DOWN(bufferQueueRead_, YES);
- /* handle buffer entry */
- /* sync with other handlers to get buffer */
- if (mainShutdownSignal != NULL)
- break;
- MUTEX_LOCK(globalLock_);
- mp = bufferQueue_[bq_firstFull_];
- bufferQueue_[bq_firstFull_++] = NULL;
- if (bq_firstFull_ == QUEUE_LENGTH)
- bq_firstFull_ = 0;
- MUTEX_UNLOCK(globalLock_);
- /* end of sync */
- SEMAPHORE_UP(bufferQueueWrite_);
- /* handle buffer - now out of sync */
- handleMessage(mp->tsession,
- &mp->sender,
- mp->msg,
- mp->size);
- if (mp->tsession != NULL)
- transport->disconnect(mp->tsession);
- FREE(mp->msg);
- FREE(mp);
- }
- SEMAPHORE_UP(mainShutdownSignal);
+ while (mainShutdownSignal == NULL)
+ {
+ SEMAPHORE_DOWN (bufferQueueRead_, YES);
+ /* handle buffer entry */
+ /* sync with other handlers to get buffer */
+ if (mainShutdownSignal != NULL)
+ break;
+ MUTEX_LOCK (globalLock_);
+ mp = bufferQueue_[bq_firstFull_];
+ bufferQueue_[bq_firstFull_++] = NULL;
+ if (bq_firstFull_ == QUEUE_LENGTH)
+ bq_firstFull_ = 0;
+ MUTEX_UNLOCK (globalLock_);
+ /* end of sync */
+ SEMAPHORE_UP (bufferQueueWrite_);
+ /* handle buffer - now out of sync */
+ handleMessage (mp->tsession, &mp->sender, mp->msg, mp->size);
+ if (mp->tsession != NULL)
+ transport->disconnect (mp->tsession);
+ FREE (mp->msg);
+ FREE (mp);
+ }
+ SEMAPHORE_UP (mainShutdownSignal);
return NULL;
-} /* end of threadMain */
+} /* end of threadMain */
/**
* Processing of a message from the transport layer
* (receive implementation).
*/
-void core_receive(P2P_PACKET * mp) {
- if ( (mp->tsession != NULL) &&
- (0 != memcmp(&mp->sender,
- &mp->tsession->peer,
- sizeof(PeerIdentity))) ) {
- GE_BREAK(NULL, 0);
- FREE(mp->msg);
- FREE(mp);
- return;
- }
- if ( (threads_running == NO) ||
- (mainShutdownSignal != NULL) ) {
+void
+core_receive (P2P_PACKET * mp)
+{
+ if ((mp->tsession != NULL) &&
+ (0 != memcmp (&mp->sender, &mp->tsession->peer, sizeof (PeerIdentity))))
+ {
+ GE_BREAK (NULL, 0);
+ FREE (mp->msg);
+ FREE (mp);
+ return;
+ }
+ if ((threads_running == NO) || (mainShutdownSignal != NULL))
+ {
#if TRACK_DISCARD
- if (globalLock_ != NULL)
- MUTEX_LOCK(globalLock_);
- discarded++;
- if (0 == discarded % 64)
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
- "Accepted: %u discarded: %u blacklisted: %u, ratio: %f\n",
- accepted,
- discarded,
- blacklisted,
- 1.0 * accepted / (blacklisted + discarded + 1));
- if (globalLock_ != NULL)
- MUTEX_UNLOCK(globalLock_);
+ if (globalLock_ != NULL)
+ MUTEX_LOCK (globalLock_);
+ discarded++;
+ if (0 == discarded % 64)
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ "Accepted: %u discarded: %u blacklisted: %u, ratio: %f\n",
+ accepted,
+ discarded,
+ blacklisted, 1.0 * accepted / (blacklisted + discarded + 1));
+ if (globalLock_ != NULL)
+ MUTEX_UNLOCK (globalLock_);
#endif
- }
+ }
/* check for blacklisting */
- if (YES == identity->isBlacklistedStrict(&mp->sender)) {
+ if (YES == identity->isBlacklistedStrict (&mp->sender))
+ {
#if DEBUG_HANDLER
- EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
- hash2enc(&mp->sender.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
- "Strictly blacklisted peer `%s' sent message, dropping for now.\n",
- (char*)&enc);
+ EncName enc;
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ hash2enc (&mp->sender.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ "Strictly blacklisted peer `%s' sent message, dropping for
now.\n",
+ (char *) &enc);
#endif
#if TRACK_DISCARD
- MUTEX_LOCK(globalLock_);
- blacklisted++;
- if (0 == blacklisted % 64)
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
- "Accepted: %u discarded: %u blacklisted: %u, ratio: %f\n",
- accepted,
- discarded,
- blacklisted,
- 1.0 * accepted / (blacklisted + discarded + 1));
- MUTEX_UNLOCK(globalLock_);
+ MUTEX_LOCK (globalLock_);
+ blacklisted++;
+ if (0 == blacklisted % 64)
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ "Accepted: %u discarded: %u blacklisted: %u, ratio: %f\n",
+ accepted,
+ discarded,
+ blacklisted, 1.0 * accepted / (blacklisted + discarded + 1));
+ MUTEX_UNLOCK (globalLock_);
#endif
- FREE(mp->msg);
- FREE(mp);
- return;
- }
- if ( (threads_running == NO) ||
- (mainShutdownSignal != NULL) ||
- (SYSERR == SEMAPHORE_DOWN(bufferQueueWrite_, NO)) ) {
- /* discard message, buffer is full or
- we're shut down! */
+ FREE (mp->msg);
+ FREE (mp);
+ return;
+ }
+ if ((threads_running == NO) ||
+ (mainShutdownSignal != NULL) ||
+ (SYSERR == SEMAPHORE_DOWN (bufferQueueWrite_, NO)))
+ {
+ /* discard message, buffer is full or
+ we're shut down! */
#if 0
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
- "Discarding message of size %u -- buffer full!\n",
- mp->size);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ "Discarding message of size %u -- buffer full!\n", mp->size);
#endif
- FREE(mp->msg);
- FREE(mp);
+ FREE (mp->msg);
+ FREE (mp);
#if TRACK_DISCARD
- if (globalLock_ != NULL)
- MUTEX_LOCK(globalLock_);
- discarded++;
- if (0 == discarded % 64)
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
- "Accepted: %u discarded: %u blacklisted: %u, ratio: %f\n",
- accepted,
- discarded,
- blacklisted,
- 1.0 * accepted / (blacklisted + discarded + 1));
- if (globalLock_ != NULL)
- MUTEX_UNLOCK(globalLock_);
+ if (globalLock_ != NULL)
+ MUTEX_LOCK (globalLock_);
+ discarded++;
+ if (0 == discarded % 64)
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ "Accepted: %u discarded: %u blacklisted: %u, ratio: %f\n",
+ accepted,
+ discarded,
+ blacklisted, 1.0 * accepted / (blacklisted + discarded + 1));
+ if (globalLock_ != NULL)
+ MUTEX_UNLOCK (globalLock_);
#endif
- return;
- }
+ return;
+ }
/* try to increment session reference count */
- if (SYSERR == transport->associate(mp->tsession))
+ if (SYSERR == transport->associate (mp->tsession))
mp->tsession = NULL;
- MUTEX_LOCK(globalLock_);
+ MUTEX_LOCK (globalLock_);
if (bq_firstFree_ == QUEUE_LENGTH)
bq_firstFree_ = 0;
bufferQueue_[bq_firstFree_++] = mp;
#if TRACK_DISCARD
accepted++;
if (0 == accepted % 64)
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
- "Accepted: %u discarded: %u blacklisted: %u, ratio: %f\n",
- accepted,
- discarded,
- blacklisted,
- 1.0 * accepted / (blacklisted + discarded + 1));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ "Accepted: %u discarded: %u blacklisted: %u, ratio: %f\n",
+ accepted,
+ discarded,
+ blacklisted, 1.0 * accepted / (blacklisted + discarded + 1));
#endif
- MUTEX_UNLOCK(globalLock_);
- SEMAPHORE_UP(bufferQueueRead_);
+ MUTEX_UNLOCK (globalLock_);
+ SEMAPHORE_UP (bufferQueueRead_);
}
/**
* Start processing p2p messages.
*/
-void enableCoreProcessing() {
+void
+enableCoreProcessing ()
+{
int i;
- globalLock_ = MUTEX_CREATE(NO);
- for (i=0;i<QUEUE_LENGTH;i++)
+ globalLock_ = MUTEX_CREATE (NO);
+ for (i = 0; i < QUEUE_LENGTH; i++)
bufferQueue_[i] = NULL;
bq_firstFree_ = 0;
bq_firstFull_ = 0;
/* create message handling threads */
threads_running = YES;
- for (i=0;i<THREAD_COUNT;i++) {
- threads_[i] = PTHREAD_CREATE(&threadMain,
- &i,
- 128 * 1024);
- if (threads_[i] == NULL)
- GE_LOG_STRERROR(ectx,
- GE_ERROR,
- "pthread_create");
- }
+ for (i = 0; i < THREAD_COUNT; i++)
+ {
+ threads_[i] = PTHREAD_CREATE (&threadMain, &i, 128 * 1024);
+ if (threads_[i] == NULL)
+ GE_LOG_STRERROR (ectx, GE_ERROR, "pthread_create");
+ }
}
/**
* Stop processing (p2p) messages.
*/
-void disableCoreProcessing() {
+void
+disableCoreProcessing ()
+{
int i;
- void * unused;
+ void *unused;
/* shutdown processing of inbound messages... */
threads_running = NO;
- mainShutdownSignal = SEMAPHORE_CREATE(0);
- for (i=0;i<THREAD_COUNT;i++) {
- SEMAPHORE_UP(bufferQueueRead_);
- SEMAPHORE_DOWN(mainShutdownSignal, YES);
- }
- for (i=0;i<THREAD_COUNT;i++) {
- PTHREAD_JOIN(threads_[i], &unused);
- threads_[i] = NULL;
- }
- SEMAPHORE_DESTROY(mainShutdownSignal);
+ mainShutdownSignal = SEMAPHORE_CREATE (0);
+ for (i = 0; i < THREAD_COUNT; i++)
+ {
+ SEMAPHORE_UP (bufferQueueRead_);
+ SEMAPHORE_DOWN (mainShutdownSignal, YES);
+ }
+ for (i = 0; i < THREAD_COUNT; i++)
+ {
+ PTHREAD_JOIN (threads_[i], &unused);
+ threads_[i] = NULL;
+ }
+ SEMAPHORE_DESTROY (mainShutdownSignal);
mainShutdownSignal = NULL;
- MUTEX_DESTROY(globalLock_);
+ MUTEX_DESTROY (globalLock_);
globalLock_ = NULL;
}
/**
* Initialize message handling module.
*/
-void initHandler(struct GE_Context * e) {
+void
+initHandler (struct GE_Context *e)
+{
ectx = e;
- handlerLock = MUTEX_CREATE(NO);
- transport = requestService("transport");
- GE_ASSERT(ectx, transport != NULL);
- identity = requestService("identity");
- GE_ASSERT(ectx, identity != NULL);
+ handlerLock = MUTEX_CREATE (NO);
+ transport = requestService ("transport");
+ GE_ASSERT (ectx, transport != NULL);
+ identity = requestService ("identity");
+ GE_ASSERT (ectx, identity != NULL);
/* initialize sync mechanisms for message handling threads */
- bufferQueueRead_ = SEMAPHORE_CREATE(0);
- bufferQueueWrite_ = SEMAPHORE_CREATE(QUEUE_LENGTH);
+ bufferQueueRead_ = SEMAPHORE_CREATE (0);
+ bufferQueueWrite_ = SEMAPHORE_CREATE (QUEUE_LENGTH);
}
/**
* Shutdown message handling module.
*/
-void doneHandler() {
+void
+doneHandler ()
+{
unsigned int i;
/* free datastructures */
- SEMAPHORE_DESTROY(bufferQueueRead_);
+ SEMAPHORE_DESTROY (bufferQueueRead_);
bufferQueueRead_ = NULL;
- SEMAPHORE_DESTROY(bufferQueueWrite_);
+ SEMAPHORE_DESTROY (bufferQueueWrite_);
bufferQueueWrite_ = NULL;
- for (i=0;i<QUEUE_LENGTH;i++) {
- if (bufferQueue_[i] != NULL)
- FREENONNULL(bufferQueue_[i]->msg);
- FREENONNULL(bufferQueue_[i]);
- }
+ for (i = 0; i < QUEUE_LENGTH; i++)
+ {
+ if (bufferQueue_[i] != NULL)
+ FREENONNULL (bufferQueue_[i]->msg);
+ FREENONNULL (bufferQueue_[i]);
+ }
- MUTEX_DESTROY(handlerLock);
+ MUTEX_DESTROY (handlerLock);
handlerLock = NULL;
- for (i=0;i<max_registeredType;i++) {
- unsigned int last = 0;
- while (handlers[i][last] != NULL)
+ for (i = 0; i < max_registeredType; i++)
+ {
+ unsigned int last = 0;
+ while (handlers[i][last] != NULL)
+ last++;
last++;
- last++;
- GROW(handlers[i],
- last,
- 0);
- }
- GROW(handlers,
- max_registeredType,
- 0);
- for (i=0;i<plaintextmax_registeredType;i++) {
- unsigned int last = 0;
- while (plaintextHandlers[i][last] != NULL)
- last++;
- GROW(plaintextHandlers[i],
- last,
- 0);
- }
- GROW(plaintextHandlers,
- plaintextmax_registeredType,
- 0);
- releaseService(transport);
+ GROW (handlers[i], last, 0);
+ }
+ GROW (handlers, max_registeredType, 0);
+ for (i = 0; i < plaintextmax_registeredType; i++)
+ {
+ unsigned int last = 0;
+ while (plaintextHandlers[i][last] != NULL)
+ last++;
+ GROW (plaintextHandlers[i], last, 0);
+ }
+ GROW (plaintextHandlers, plaintextmax_registeredType, 0);
+ releaseService (transport);
transport = NULL;
- releaseService(identity);
+ releaseService (identity);
identity = NULL;
#if MEASURE_TIME
- for (i=0;i<P2P_PROTO_MAX_USED;i++) {
- if (count_by_type[i] == 0)
- continue;
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
- "%10u msgs of type %2u took %16llu ms (%llu on average)\n",
- count_by_type[i],
- i,
- time_by_type[i],
- time_by_type[i] / count_by_type[i]);
- }
+ for (i = 0; i < P2P_PROTO_MAX_USED; i++)
+ {
+ if (count_by_type[i] == 0)
+ continue;
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ "%10u msgs of type %2u took %16llu ms (%llu on average)\n",
+ count_by_type[i],
+ i, time_by_type[i], time_by_type[i] / count_by_type[i]);
+ }
#endif
}
Modified: GNUnet/src/server/handler.h
===================================================================
--- GNUnet/src/server/handler.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/handler.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,22 +33,22 @@
* Initialize message handling module (make ready to register
* handlers).
*/
-void initHandler(struct GE_Context * e);
+void initHandler (struct GE_Context *e);
/**
* Shutdown message handling module.
*/
-void doneHandler();
+void doneHandler ();
/**
* Start processing messages from the transports.
*/
-void enableCoreProcessing();
+void enableCoreProcessing ();
/**
* Stop processing messages from the transports.
*/
-void disableCoreProcessing();
+void disableCoreProcessing ();
/**
* Handle a message (that was decrypted if needed). Processes the
@@ -57,18 +57,16 @@
* @param wasEncrypted YES if it was encrypted,
* NO if plaintext,
*/
-void injectMessage(const PeerIdentity * sender,
- const char * msg,
- unsigned int size,
- int wasEncrypted,
- TSession * session);
+void injectMessage (const PeerIdentity * sender,
+ const char *msg,
+ unsigned int size, int wasEncrypted, TSession * session);
/**
* Processing of a message from the transport layer (receive
* implementation). Detects if the message is encrypted, possibly
* decrypts and calls injectMessage.
*/
-void core_receive(P2P_PACKET * mp);
+void core_receive (P2P_PACKET * mp);
/**
* Register a method as a handler for specific message
@@ -81,8 +79,8 @@
* @return OK on success, SYSERR if there is already a
* handler for that type
*/
-int registerp2pHandler(const unsigned short type,
- MessagePartHandler callback);
+int registerp2pHandler (const unsigned short type,
+ MessagePartHandler callback);
/**
@@ -94,8 +92,8 @@
* @return OK on success, SYSERR if there is a different
* handler for that type
*/
-int unregisterp2pHandler(const unsigned short type,
- MessagePartHandler callback);
+int unregisterp2pHandler (const unsigned short type,
+ MessagePartHandler callback);
/**
@@ -111,8 +109,8 @@
* @return OK on success, SYSERR if core threads are running
* and updates to the handler list are illegal!
*/
-int registerPlaintextHandler(const unsigned short type,
- PlaintextMessagePartHandler callback);
+int registerPlaintextHandler (const unsigned short type,
+ PlaintextMessagePartHandler callback);
/**
@@ -126,8 +124,8 @@
* handler for that type or if core threads are running
* and updates to the handler list are illegal!
*/
-int unregisterPlaintextHandler(const unsigned short type,
- PlaintextMessagePartHandler callback);
+int unregisterPlaintextHandler (const unsigned short type,
+ PlaintextMessagePartHandler callback);
/**
* Is a handler registered for messages of the given type?
@@ -140,8 +138,7 @@
* @return number of handlers registered, 0 for none,
* SYSERR for invalid value of handlerType
*/
-int isHandlerRegistered(unsigned short type,
- unsigned short handlerType);
+int isHandlerRegistered (unsigned short type, unsigned short handlerType);
#endif
Modified: GNUnet/src/server/startup.c
===================================================================
--- GNUnet/src/server/startup.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/startup.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -50,42 +50,43 @@
* @param cfg configuration, may be NULL if in service mode
* @param sig signal code that causes shutdown, optional
*/
-void shutdown_gnunetd(struct GC_Configuration * cfg,
- int sig) {
+void
+shutdown_gnunetd (struct GC_Configuration *cfg, int sig)
+{
#ifdef MINGW
- if (!cfg || GC_get_configuration_value_yesno(cfg,
- "GNUNETD",
- "WINSERVICE",
- NO) == YES) {
- /* If GNUnet runs as service, only the
- Service Control Manager is allowed
- to kill us. */
- if (sig != SERVICE_CONTROL_STOP)
- {
- SERVICE_STATUS theStat;
-
- /* Init proper shutdown through the SCM */
- if (GNControlService(hService, SERVICE_CONTROL_STOP, &theStat))
+ if (!cfg || GC_get_configuration_value_yesno (cfg,
+ "GNUNETD",
+ "WINSERVICE", NO) == YES)
{
- /* Success */
+ /* If GNUnet runs as service, only the
+ Service Control Manager is allowed
+ to kill us. */
+ if (sig != SERVICE_CONTROL_STOP)
+ {
+ SERVICE_STATUS theStat;
- /* The Service Control Manager will call
- gnunetd.c::ServiceCtrlHandler(), which calls
- this function again. We then stop the gnunetd. */
- return;
- }
- /* We weren't able to tell the SCM to stop the service,
- but we don't care.
- Just shut the gnunetd process down. */
- }
+ /* Init proper shutdown through the SCM */
+ if (GNControlService (hService, SERVICE_CONTROL_STOP, &theStat))
+ {
+ /* Success */
- /* Acknowledge the shutdown request */
- theServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
- GNSetServiceStatus(hService, &theServiceStatus);
- }
+ /* The Service Control Manager will call
+ gnunetd.c::ServiceCtrlHandler(), which calls
+ this function again. We then stop the gnunetd. */
+ return;
+ }
+ /* We weren't able to tell the SCM to stop the service,
+ but we don't care.
+ Just shut the gnunetd process down. */
+ }
+
+ /* Acknowledge the shutdown request */
+ theServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
+ GNSetServiceStatus (hService, &theServiceStatus);
+ }
#endif
- GNUNET_SHUTDOWN_INITIATE();
+ GNUNET_SHUTDOWN_INITIATE ();
}
#ifdef MINGW
@@ -93,71 +94,75 @@
* This function is called from the Windows Service Control Manager
* when a service has to shutdown
*/
-static void WINAPI ServiceCtrlHandler(DWORD dwOpcode) {
+static void WINAPI
+ServiceCtrlHandler (DWORD dwOpcode)
+{
if (dwOpcode == SERVICE_CONTROL_STOP)
- shutdown_gnunetd(NULL, dwOpcode);
+ shutdown_gnunetd (NULL, dwOpcode);
}
/**
* called by gnunetd.c::ServiceMain()
*/
-void win_service_main(void (*gnunet_main)()) {
- memset(&theServiceStatus, 0, sizeof(theServiceStatus));
+void
+win_service_main (void (*gnunet_main) ())
+{
+ memset (&theServiceStatus, 0, sizeof (theServiceStatus));
theServiceStatus.dwServiceType = SERVICE_WIN32;
theServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
theServiceStatus.dwCurrentState = SERVICE_RUNNING;
- hService = GNRegisterServiceCtrlHandler("GNUnet", ServiceCtrlHandler);
- if (! hService)
+ hService = GNRegisterServiceCtrlHandler ("GNUnet", ServiceCtrlHandler);
+ if (!hService)
return;
- GNSetServiceStatus(hService, &theServiceStatus);
+ GNSetServiceStatus (hService, &theServiceStatus);
- gnunet_main();
+ gnunet_main ();
theServiceStatus.dwCurrentState = SERVICE_STOPPED;
- GNSetServiceStatus(hService, &theServiceStatus);
+ GNSetServiceStatus (hService, &theServiceStatus);
}
#endif
-int changeUser(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- char * user;
+int
+changeUser (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ char *user;
user = NULL;
- if (0 == GC_get_configuration_value_string(cfg,
- "GNUNETD",
- "USER",
- "",
- &user) && strlen(user)) {
- if (OK != os_change_user(ectx,
- user)) {
- FREE(user);
- return SYSERR;
+ if (0 == GC_get_configuration_value_string (cfg,
+ "GNUNETD",
+ "USER",
+ "", &user) && strlen (user))
+ {
+ if (OK != os_change_user (ectx, user))
+ {
+ FREE (user);
+ return SYSERR;
+ }
}
- }
- FREE(user);
+ FREE (user);
return OK;
}
-int setFdLimit(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
+int
+setFdLimit (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
unsigned long long limit;
limit = 0;
- if (0 == GC_get_configuration_value_number(cfg,
- "GNUNETD",
- "FDLIMIT",
- 0,
- 65536,
- 1024,
- &limit)) {
- if (OK != os_set_fd_limit(ectx,
- (int)limit)) {
- return SYSERR;
+ if (0 == GC_get_configuration_value_number (cfg,
+ "GNUNETD",
+ "FDLIMIT",
+ 0, 65536, 1024, &limit))
+ {
+ if (OK != os_set_fd_limit (ectx, (int) limit))
+ {
+ return SYSERR;
+ }
}
- }
return OK;
}
@@ -167,145 +172,121 @@
* @param ectx error handler
* @param cfg configuration manager
*/
-void capFSQuotaSize(struct GE_Context * ectx,
- struct GC_Configuration * cfg)
+void
+capFSQuotaSize (struct GE_Context *ectx, struct GC_Configuration *cfg)
{
#ifdef WINDOWS
unsigned long long quota, cap;
char *afsdir, fs[MAX_PATH + 1];
DWORD flags;
- if (-1 == GC_get_configuration_value_number(cfg,
- "FS",
- "QUOTA",
- 0,
- ((unsigned long long)-1)/1024/1024,
- 1024,
- "a))
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "FS",
+ "QUOTA",
+ 0,
+ ((unsigned long long) -1) /
+ 1024 / 1024, 1024, "a))
return;
- GC_get_configuration_value_filename(cfg,
- "FS",
- "DIR",
- VAR_DAEMON_DIRECTORY "/data/fs/",
- &afsdir);
- GE_ASSERT(ectx, strlen(afsdir) > 2);
+ GC_get_configuration_value_filename (cfg,
+ "FS",
+ "DIR",
+ VAR_DAEMON_DIRECTORY "/data/fs/",
+ &afsdir);
+ GE_ASSERT (ectx, strlen (afsdir) > 2);
/* get root directory */
afsdir[3] = '\0';
- if (!GetVolumeInformation(afsdir,
- NULL,
- 0,
- NULL,
- NULL,
- &flags,
- fs,
- _MAX_PATH + 1)) {
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_IMMEDIATE,
- _("Unable to obtain filesystem information for `%s': %u\n"),
- afsdir,
- GetLastError());
+ if (!GetVolumeInformation (afsdir,
+ NULL, 0, NULL, NULL, &flags, fs, _MAX_PATH + 1))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_IMMEDIATE,
+ _("Unable to obtain filesystem information for `%s': %u\n"),
+ afsdir, GetLastError ());
- return;
- }
+ return;
+ }
- if (strncasecmp(fs, "NTFS", 4) == 0)
+ if (strncasecmp (fs, "NTFS", 4) == 0)
cap = 0;
- else if (strcasecmp(fs, "FAT32") == 0)
+ else if (strcasecmp (fs, "FAT32") == 0)
cap = 3000;
- else if (strcasecmp(fs, "FAT16") == 0)
+ else if (strcasecmp (fs, "FAT16") == 0)
cap = 1500;
- else {
- /* unknown FS */
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_IMMEDIATE,
- _("Filesystem `%s' of partition `%s' is unknown. Please "
- "contact address@hidden"),
- fs,
- afsdir);
+ else
+ {
+ /* unknown FS */
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_IMMEDIATE,
+ _("Filesystem `%s' of partition `%s' is unknown. Please "
+ "contact address@hidden"), fs, afsdir);
- if (!(flags & FILE_PERSISTENT_ACLS))
- cap = 1500;
- else
- cap = 0;
- }
+ if (!(flags & FILE_PERSISTENT_ACLS))
+ cap = 1500;
+ else
+ cap = 0;
+ }
- if ((cap != 0) && (cap < quota)) {
- GE_LOG(ectx,
- GE_WARNING | GE_ADMIN | GE_USER | GE_IMMEDIATE,
- _("Limiting datastore size to %llu GB, because the `%s' filesystem does "
- "not support larger files. Please consider storing the database on "
- "a NTFS partition!\n"),
- cap / 1000,
- fs);
+ if ((cap != 0) && (cap < quota))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_ADMIN | GE_USER | GE_IMMEDIATE,
+ _
+ ("Limiting datastore size to %llu GB, because the `%s'
filesystem does "
+ "not support larger files. Please consider storing the database
on "
+ "a NTFS partition!\n"), cap / 1000, fs);
- GC_set_configuration_value_number(cfg,
- ectx,
- "FS",
- "QUOTA",
- cap);
- }
+ GC_set_configuration_value_number (cfg, ectx, "FS", "QUOTA", cap);
+ }
#endif
}
-int checkPermission(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char * def,
- int is_directory,
- int mode) {
- char * fn;
+int
+checkPermission (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ const char *def, int is_directory, int mode)
+{
+ char *fn;
int i;
- GC_get_configuration_value_filename(cfg,
- section,
- option,
- def,
- &fn);
+ GC_get_configuration_value_filename (cfg, section, option, def, &fn);
if (is_directory)
- disk_directory_create(ectx, fn);
+ disk_directory_create (ectx, fn);
else
- disk_directory_create_for_file(ectx, fn);
- if ( (0 != ACCESS(fn, F_OK)) &&
- (mode == W_OK) ) {
- /* adjust check to see if directory is writable */
- i = strlen(fn);
- while ( (i > 1) &&
- (fn[i] != DIR_SEPARATOR) )
- i--;
- fn[i] = '\0';
- mode = X_OK | W_OK;
- }
- if (0 != ACCESS(fn, mode)) {
- GE_LOG(ectx,
- GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- _("Insufficient access permissions for `%s': %s\n"),
- fn,
- STRERROR(errno));
- FREE(fn);
- return SYSERR;
- }
- FREE(fn);
+ disk_directory_create_for_file (ectx, fn);
+ if ((0 != ACCESS (fn, F_OK)) && (mode == W_OK))
+ {
+ /* adjust check to see if directory is writable */
+ i = strlen (fn);
+ while ((i > 1) && (fn[i] != DIR_SEPARATOR))
+ i--;
+ fn[i] = '\0';
+ mode = X_OK | W_OK;
+ }
+ if (0 != ACCESS (fn, mode))
+ {
+ GE_LOG (ectx,
+ GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ _("Insufficient access permissions for `%s': %s\n"),
+ fn, STRERROR (errno));
+ FREE (fn);
+ return SYSERR;
+ }
+ FREE (fn);
return OK;
}
#define CHECK(a,b,c,d,e) if (OK != checkPermission(ectx, cfg, a, b, c, d, e))
return SYSERR;
-int checkPermissions(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- CHECK("PATHS",
- "GNUNETD_HOME",
- "/var/lib/gnunet",
- YES,
- W_OK | X_OK);
- CHECK("GNUNETD",
- "LOGFILE",
- "$GNUNETD_HOME/daemon-logs",
- NO,
- W_OK);
+int
+checkPermissions (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ CHECK ("PATHS", "GNUNETD_HOME", "/var/lib/gnunet", YES, W_OK | X_OK);
+ CHECK ("GNUNETD", "LOGFILE", "$GNUNETD_HOME/daemon-logs", NO, W_OK);
/* these should only be checked if "fs" is actually
loaded; we clearly should not check everything here
that just might be used (MYSQL-CONFIG, F2F-FRIENDS),
@@ -313,16 +294,9 @@
not great. Would be nice if we could find a way to
keep things decentralized and still do a nice job
with reporting errors... */
- CHECK("FS",
- "DIR",
- "$GNUNETD_HOME/data/fs",
- YES,
- W_OK | X_OK);
- CHECK("FS",
- "INDEX-DIRECTORY",
- "$GNUNETD_HOME/data/shared",
- YES,
- W_OK | X_OK);
+ CHECK ("FS", "DIR", "$GNUNETD_HOME/data/fs", YES, W_OK | X_OK);
+ CHECK ("FS",
+ "INDEX-DIRECTORY", "$GNUNETD_HOME/data/shared", YES, W_OK | X_OK);
return OK;
}
Modified: GNUnet/src/server/startup.h
===================================================================
--- GNUnet/src/server/startup.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/startup.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -31,14 +31,11 @@
#include "gnunet_util.h"
#include "platform.h"
-int changeUser(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+int changeUser (struct GE_Context *ectx, struct GC_Configuration *cfg);
-int setFdLimit(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+int setFdLimit (struct GE_Context *ectx, struct GC_Configuration *cfg);
-int checkPermissions(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+int checkPermissions (struct GE_Context *ectx, struct GC_Configuration *cfg);
/**
* @brief Cap datastore limit to the filesystem's capabilities
@@ -46,19 +43,18 @@
* @param ectx error handler
* @param cfg configuration manager
*/
-void capFSQuotaSize(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+void capFSQuotaSize (struct GE_Context *ectx, struct GC_Configuration *cfg);
/**
* Shutdown gnunetd
* @param cfg configuration
* @param sig signal code that causes shutdown, optional
*/
-void shutdown_gnunetd(struct GC_Configuration * cfg, int sig);
+void shutdown_gnunetd (struct GC_Configuration *cfg, int sig);
#ifdef MINGW
-void win_service_main(void (*gnunet_main)());
+void win_service_main (void (*gnunet_main) ());
#endif
#endif
/* end of startup.h */
Modified: GNUnet/src/server/tcpserver.c
===================================================================
--- GNUnet/src/server/tcpserver.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/tcpserver.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -41,7 +41,7 @@
/**
* Array of the message handlers.
*/
-static CSHandler * handlers = NULL;
+static CSHandler *handlers = NULL;
/**
* Number of handlers in the array (max, there
@@ -52,7 +52,7 @@
/**
* Handlers to call if client exits.
*/
-static ClientExitHandler * exitHandlers;
+static ClientExitHandler *exitHandlers;
/**
* How many entries are in exitHandlers?
@@ -62,121 +62,126 @@
/**
* Mutex to guard access to the handler array.
*/
-static struct MUTEX * handlerlock;
+static struct MUTEX *handlerlock;
/**
* The thread that waits for new connections.
*/
-static struct SelectHandle * selector;
+static struct SelectHandle *selector;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
/**
* Per-client data structure.
*/
-typedef struct ClientHandle {
+typedef struct ClientHandle
+{
- struct SocketHandle * sock;
+ struct SocketHandle *sock;
} ClientHandle;
/**
* Configuration...
*/
-static struct CIDRNetwork * trustedNetworks_ = NULL;
+static struct CIDRNetwork *trustedNetworks_ = NULL;
/**
* Is this IP labeled as trusted for CS connections?
*/
-static int isWhitelisted(IPaddr ip) {
- return check_ipv4_listed(trustedNetworks_,
- ip);
+static int
+isWhitelisted (IPaddr ip)
+{
+ return check_ipv4_listed (trustedNetworks_, ip);
}
-static int shutdownHandler(struct ClientHandle * client,
- const MESSAGE_HEADER * msg) {
+static int
+shutdownHandler (struct ClientHandle *client, const MESSAGE_HEADER * msg)
+{
int ret;
- if (ntohs(msg->size) != sizeof(MESSAGE_HEADER)) {
- GE_LOG(NULL,
- GE_WARNING | GE_USER | GE_BULK,
- _("The `%s' request received from client is malformed.\n"),
- "shutdown");
- return SYSERR;
- }
- GE_LOG(NULL,
- GE_INFO | GE_USER | GE_REQUEST,
- "shutdown request accepted from client\n");
- ret = sendTCPResultToClient(client,
- OK);
- shutdown_gnunetd(cfg, 0);
+ if (ntohs (msg->size) != sizeof (MESSAGE_HEADER))
+ {
+ GE_LOG (NULL,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("The `%s' request received from client is malformed.\n"),
+ "shutdown");
+ return SYSERR;
+ }
+ GE_LOG (NULL,
+ GE_INFO | GE_USER | GE_REQUEST,
+ "shutdown request accepted from client\n");
+ ret = sendTCPResultToClient (client, OK);
+ shutdown_gnunetd (cfg, 0);
return ret;
}
-int registerClientExitHandler(ClientExitHandler callback) {
- MUTEX_LOCK(handlerlock);
- GROW(exitHandlers,
- exitHandlerCount,
- exitHandlerCount+1);
- exitHandlers[exitHandlerCount-1] = callback;
- MUTEX_UNLOCK(handlerlock);
+int
+registerClientExitHandler (ClientExitHandler callback)
+{
+ MUTEX_LOCK (handlerlock);
+ GROW (exitHandlers, exitHandlerCount, exitHandlerCount + 1);
+ exitHandlers[exitHandlerCount - 1] = callback;
+ MUTEX_UNLOCK (handlerlock);
return OK;
}
-int unregisterClientExitHandler(ClientExitHandler callback) {
+int
+unregisterClientExitHandler (ClientExitHandler callback)
+{
int i;
- MUTEX_LOCK(handlerlock);
- for (i=0;i<exitHandlerCount;i++) {
- if (exitHandlers[i] == callback) {
- exitHandlers[i] = exitHandlers[exitHandlerCount-1];
- GROW(exitHandlers,
- exitHandlerCount,
- exitHandlerCount-1);
- MUTEX_UNLOCK(handlerlock);
- return OK;
+ MUTEX_LOCK (handlerlock);
+ for (i = 0; i < exitHandlerCount; i++)
+ {
+ if (exitHandlers[i] == callback)
+ {
+ exitHandlers[i] = exitHandlers[exitHandlerCount - 1];
+ GROW (exitHandlers, exitHandlerCount, exitHandlerCount - 1);
+ MUTEX_UNLOCK (handlerlock);
+ return OK;
+ }
}
- }
- MUTEX_UNLOCK(handlerlock);
+ MUTEX_UNLOCK (handlerlock);
return SYSERR;
}
-static void * select_accept_handler(void * ah_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- const void * addr,
- unsigned int addr_len) {
- struct ClientHandle * session;
+static void *
+select_accept_handler (void *ah_cls,
+ struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ const void *addr, unsigned int addr_len)
+{
+ struct ClientHandle *session;
IPaddr ip;
- struct sockaddr_in * a;
+ struct sockaddr_in *a;
- if (addr_len != sizeof(struct sockaddr_in))
+ if (addr_len != sizeof (struct sockaddr_in))
return NULL;
a = (struct sockaddr_in *) addr;
- memcpy(&ip,
- &a->sin_addr,
- sizeof(IPaddr));
- if (! isWhitelisted(ip))
+ memcpy (&ip, &a->sin_addr, sizeof (IPaddr));
+ if (!isWhitelisted (ip))
return NULL;
- session = MALLOC(sizeof(ClientHandle));
+ session = MALLOC (sizeof (ClientHandle));
session->sock = sock;
return session;
}
-static void select_close_handler(void * ch_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * sock_ctx) {
- ClientHandle * session = sock_ctx;
+static void
+select_close_handler (void *ch_cls,
+ struct SelectHandle *sh,
+ struct SocketHandle *sock, void *sock_ctx)
+{
+ ClientHandle *session = sock_ctx;
int i;
- MUTEX_LOCK(handlerlock);
- for (i=0;i<exitHandlerCount;i++)
- exitHandlers[i](session);
- MUTEX_UNLOCK(handlerlock);
- FREE(session);
+ MUTEX_LOCK (handlerlock);
+ for (i = 0; i < exitHandlerCount; i++)
+ exitHandlers[i] (session);
+ MUTEX_UNLOCK (handlerlock);
+ FREE (session);
}
/**
@@ -186,261 +191,238 @@
* on the other hand does NOT confirm delivery since the actual
* transfer happens asynchronously.
*/
-int sendToClient(struct ClientHandle * handle,
- const MESSAGE_HEADER * message) {
+int
+sendToClient (struct ClientHandle *handle, const MESSAGE_HEADER * message)
+{
#if DEBUG_TCPHANDLER
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
- "%s: sending reply to client\n",
- __FUNCTION__);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_REQUEST,
+ "%s: sending reply to client\n", __FUNCTION__);
#endif
- return select_write(selector,
- handle->sock,
- message,
- NO,
- YES);
+ return select_write (selector, handle->sock, message, NO, YES);
}
-void terminateClientConnection(struct ClientHandle * sock) {
- select_disconnect(selector,
- sock->sock);
+void
+terminateClientConnection (struct ClientHandle *sock)
+{
+ select_disconnect (selector, sock->sock);
}
-static int select_message_handler(void * mh_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * sock_ctx,
- const MESSAGE_HEADER * msg) {
- struct ClientHandle * sender = sock_ctx;
+static int
+select_message_handler (void *mh_cls,
+ struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ void *sock_ctx, const MESSAGE_HEADER * msg)
+{
+ struct ClientHandle *sender = sock_ctx;
unsigned short ptyp;
CSHandler callback;
#if TIME_HANDLERS
cron_t start;
#endif
- ptyp = htons(msg->type);
- MUTEX_LOCK(handlerlock);
- if (ptyp >= max_registeredType) {
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- "%s: Message of type %d not understood: no handler registered\n",
- __FUNCTION__,
- ptyp,
- max_registeredType);
- MUTEX_UNLOCK(handlerlock);
- return SYSERR;
- }
+ ptyp = htons (msg->type);
+ MUTEX_LOCK (handlerlock);
+ if (ptyp >= max_registeredType)
+ {
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ "%s: Message of type %d not understood: no handler registered\n",
+ __FUNCTION__, ptyp, max_registeredType);
+ MUTEX_UNLOCK (handlerlock);
+ return SYSERR;
+ }
callback = handlers[ptyp];
- if (callback == NULL) {
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- "%s: Message of type %d not understood: no handler registered\n",
- __FUNCTION__,
- ptyp);
- MUTEX_UNLOCK(handlerlock);
- return SYSERR;
- } else {
+ if (callback == NULL)
+ {
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ "%s: Message of type %d not understood: no handler registered\n",
+ __FUNCTION__, ptyp);
+ MUTEX_UNLOCK (handlerlock);
+ return SYSERR;
+ }
+ else
+ {
#if TIME_HANDLERS
- start = get_time();
+ start = get_time ();
#endif
- if (OK != callback(sender,
- msg)) {
+ if (OK != callback (sender, msg))
+ {
#if 0
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_BULK,
- "%s: Message of type %d caused error in handler\n",
- __FUNCTION__,
- ptyp);
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_BULK,
+ "%s: Message of type %d caused error in handler\n",
+ __FUNCTION__, ptyp);
#endif
- MUTEX_UNLOCK(handlerlock);
- return SYSERR;
- }
+ MUTEX_UNLOCK (handlerlock);
+ return SYSERR;
+ }
#if TIME_HANDLERS
- if (get_time() - start > cronSECONDS)
- GE_LOG(ectx,
- GE_INFO | GE_DEVELOPER | GE_IMMEDIATE,
- "Handling message of type %u took %llu s\n",
- ptyp,
- (get_time()-start) / cronSECONDS);
+ if (get_time () - start > cronSECONDS)
+ GE_LOG (ectx,
+ GE_INFO | GE_DEVELOPER | GE_IMMEDIATE,
+ "Handling message of type %u took %llu s\n",
+ ptyp, (get_time () - start) / cronSECONDS);
#endif
- }
- MUTEX_UNLOCK(handlerlock);
+ }
+ MUTEX_UNLOCK (handlerlock);
return OK;
}
/**
* Get the GNUnet TCP port from the configuration.
*/
-static unsigned short getGNUnetPort() {
+static unsigned short
+getGNUnetPort ()
+{
unsigned long long port;
- if (-1 == GC_get_configuration_value_number(cfg,
- "NETWORK",
- "PORT",
- 1,
- 65535,
- 2087,
- &port))
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "NETWORK",
+ "PORT", 1, 65535, 2087, &port))
port = 0;
return (unsigned short) port;
}
-static int startTCPServer() {
+static int
+startTCPServer ()
+{
int listenerFD;
int listenerPort;
struct sockaddr_in serverAddr;
const int on = 1;
- listenerPort = getGNUnetPort();
+ listenerPort = getGNUnetPort ();
if (listenerPort == 0)
return SYSERR;
- listenerFD = SOCKET(PF_INET,
- SOCK_STREAM,
- 0);
- if (listenerFD < 0) {
- GE_LOG_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_USER | GE_IMMEDIATE,
- "socket");
- return SYSERR;
- }
+ listenerFD = SOCKET (PF_INET, SOCK_STREAM, 0);
+ if (listenerFD < 0)
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_FATAL | GE_ADMIN | GE_USER | GE_IMMEDIATE,
+ "socket");
+ return SYSERR;
+ }
/* fill in the inet address structure */
- memset(&serverAddr,
- 0,
- sizeof(serverAddr));
- serverAddr.sin_family
- = AF_INET;
- serverAddr.sin_addr.s_addr
- = htonl(INADDR_ANY);
- serverAddr.sin_port
- = htons(listenerPort);
- if ( SETSOCKOPT(listenerFD,
- SOL_SOCKET,
- SO_REUSEADDR,
- &on,
- sizeof(on)) < 0 )
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "setsockopt");
+ memset (&serverAddr, 0, sizeof (serverAddr));
+ serverAddr.sin_family = AF_INET;
+ serverAddr.sin_addr.s_addr = htonl (INADDR_ANY);
+ serverAddr.sin_port = htons (listenerPort);
+ if (SETSOCKOPT (listenerFD, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0)
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_ADMIN | GE_BULK, "setsockopt");
/* bind the socket */
- if (BIND(listenerFD,
- (struct sockaddr *) &serverAddr,
- sizeof(serverAddr)) < 0) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_IMMEDIATE,
- "bind");
- GE_LOG(ectx,
- GE_FATAL | GE_ADMIN | GE_USER | GE_IMMEDIATE,
- _("`%s' failed for port %d. Is gnunetd already running?\n"),
- "bind",
- listenerPort);
- CLOSE(listenerFD);
- return SYSERR;
- }
- selector = select_create("tcpserver",
- NO,
- ectx,
- NULL,
- listenerFD,
- sizeof(struct sockaddr_in),
- 0, /* no timeout */
- &select_message_handler,
- NULL,
- &select_accept_handler,
- NULL,
- &select_close_handler,
- NULL,
- 0 /* no memory quota */,
- 256 /* max sockets */);
- if (selector == NULL) {
- CLOSE(listenerFD); /* maybe closed already
- depending on how select_create
- failed... */
- return SYSERR;
- }
+ if (BIND (listenerFD,
+ (struct sockaddr *) &serverAddr, sizeof (serverAddr)) < 0)
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_ADMIN | GE_IMMEDIATE, "bind");
+ GE_LOG (ectx,
+ GE_FATAL | GE_ADMIN | GE_USER | GE_IMMEDIATE,
+ _("`%s' failed for port %d. Is gnunetd already running?\n"),
+ "bind", listenerPort);
+ CLOSE (listenerFD);
+ return SYSERR;
+ }
+ selector = select_create ("tcpserver", NO, ectx, NULL, listenerFD, sizeof
(struct sockaddr_in), 0, /* no timeout */
+ &select_message_handler,
+ NULL,
+ &select_accept_handler,
+ NULL,
+ &select_close_handler,
+ NULL, 0 /* no memory quota */ ,
+ 256 /* max sockets */ );
+ if (selector == NULL)
+ {
+ CLOSE (listenerFD); /* maybe closed already
+ depending on how select_create
+ failed... */
+ return SYSERR;
+ }
return OK;
}
-int doneTCPServer() {
+int
+doneTCPServer ()
+{
if (selector != NULL)
- stopTCPServer(); /* just to be sure; used mostly
- for the benefit of gnunet-update
- and other gnunet-tools that are
- not gnunetd */
- unregisterCSHandler(CS_PROTO_SHUTDOWN_REQUEST,
- &shutdownHandler);
- GROW(handlers,
- max_registeredType,
- 0);
- GROW(exitHandlers,
- exitHandlerCount,
- 0);
- FREE(trustedNetworks_);
+ stopTCPServer (); /* just to be sure; used mostly
+ for the benefit of gnunet-update
+ and other gnunet-tools that are
+ not gnunetd */
+ unregisterCSHandler (CS_PROTO_SHUTDOWN_REQUEST, &shutdownHandler);
+ GROW (handlers, max_registeredType, 0);
+ GROW (exitHandlers, exitHandlerCount, 0);
+ FREE (trustedNetworks_);
return OK;
}
-void __attribute__ ((constructor)) gnunet_tcpserver_ltdl_init() {
- handlerlock = MUTEX_CREATE(YES);
+void __attribute__ ((constructor)) gnunet_tcpserver_ltdl_init ()
+{
+ handlerlock = MUTEX_CREATE (YES);
}
-void __attribute__ ((destructor)) gnunet_tcpserver_ltdl_fini() {
- MUTEX_DESTROY(handlerlock);
+void __attribute__ ((destructor)) gnunet_tcpserver_ltdl_fini ()
+{
+ MUTEX_DESTROY (handlerlock);
handlerlock = NULL;
}
/**
* Initialize the TCP port and listen for incoming client connections.
*/
-int initTCPServer(struct GE_Context * e,
- struct GC_Configuration * c) {
- char * ch;
+int
+initTCPServer (struct GE_Context *e, struct GC_Configuration *c)
+{
+ char *ch;
cfg = c;
ectx = e;
/* move to reload-configuration method! */
ch = NULL;
- if (-1 == GC_get_configuration_value_string(cfg,
- "NETWORK",
- "TRUSTED",
- "127.0.0.0/8;",
- &ch))
+ if (-1 == GC_get_configuration_value_string (cfg,
+ "NETWORK",
+ "TRUSTED",
+ "127.0.0.0/8;", &ch))
return SYSERR;
- GE_ASSERT(ectx, ch != NULL);
- trustedNetworks_ = parse_ipv4_network_specification(ectx,
- ch);
- if (trustedNetworks_ == NULL) {
- GE_LOG(ectx,
- GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- _("Malformed network specification in the configuration in section `%s'
for entry `%s': %s\n"),
- "NETWORK",
- "TRUSTED",
- ch);
- FREE(ch);
- return SYSERR;
- }
- FREE(ch);
+ GE_ASSERT (ectx, ch != NULL);
+ trustedNetworks_ = parse_ipv4_network_specification (ectx, ch);
+ if (trustedNetworks_ == NULL)
+ {
+ GE_LOG (ectx,
+ GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ _
+ ("Malformed network specification in the configuration in
section `%s' for entry `%s': %s\n"),
+ "NETWORK", "TRUSTED", ch);
+ FREE (ch);
+ return SYSERR;
+ }
+ FREE (ch);
- registerCSHandler(CS_PROTO_SHUTDOWN_REQUEST,
- &shutdownHandler);
- if ( (NO == GC_get_configuration_value_yesno(cfg,
- "TCPSERVER",
- "DISABLE",
- NO)) &&
- (OK != startTCPServer()) ) {
- doneTCPServer();
- return SYSERR;
- }
+ registerCSHandler (CS_PROTO_SHUTDOWN_REQUEST, &shutdownHandler);
+ if ((NO == GC_get_configuration_value_yesno (cfg,
+ "TCPSERVER",
+ "DISABLE",
+ NO)) &&
+ (OK != startTCPServer ()))
+ {
+ doneTCPServer ();
+ return SYSERR;
+ }
return OK;
}
/**
* Shutdown the module.
*/
-int stopTCPServer() {
- if (selector != NULL) {
- select_destroy(selector);
- selector = NULL;
- }
+int
+stopTCPServer ()
+{
+ if (selector != NULL)
+ {
+ select_destroy (selector);
+ selector = NULL;
+ }
return OK;
}
@@ -455,25 +437,26 @@
* @return OK on success, SYSERR if there is already a
* handler for that type
*/
-int registerCSHandler(unsigned short type,
- CSHandler callback) {
- MUTEX_LOCK(handlerlock);
- if (type < max_registeredType) {
- if (handlers[type] != NULL) {
- MUTEX_UNLOCK(handlerlock);
- GE_LOG(ectx,
- GE_WARNING | GE_DEVELOPER | GE_BULK,
- _("%s failed, message type %d already in use.\n"),
- __FUNCTION__,
- type);
- return SYSERR;
+int
+registerCSHandler (unsigned short type, CSHandler callback)
+{
+ MUTEX_LOCK (handlerlock);
+ if (type < max_registeredType)
+ {
+ if (handlers[type] != NULL)
+ {
+ MUTEX_UNLOCK (handlerlock);
+ GE_LOG (ectx,
+ GE_WARNING | GE_DEVELOPER | GE_BULK,
+ _("%s failed, message type %d already in use.\n"),
+ __FUNCTION__, type);
+ return SYSERR;
+ }
}
- } else
- GROW(handlers,
- max_registeredType,
- type + 8);
+ else
+ GROW (handlers, max_registeredType, type + 8);
handlers[type] = callback;
- MUTEX_UNLOCK(handlerlock);
+ MUTEX_UNLOCK (handlerlock);
return OK;
}
@@ -489,22 +472,29 @@
* @return OK on success, SYSERR if there is no or another
* handler for that type
*/
-int unregisterCSHandler(unsigned short type,
- CSHandler callback) {
- MUTEX_LOCK(handlerlock);
- if (type < max_registeredType) {
- if (handlers[type] != callback) {
- MUTEX_UNLOCK(handlerlock);
- return SYSERR; /* another handler present */
- } else {
- handlers[type] = NULL;
- MUTEX_UNLOCK(handlerlock);
- return OK; /* success */
+int
+unregisterCSHandler (unsigned short type, CSHandler callback)
+{
+ MUTEX_LOCK (handlerlock);
+ if (type < max_registeredType)
+ {
+ if (handlers[type] != callback)
+ {
+ MUTEX_UNLOCK (handlerlock);
+ return SYSERR; /* another handler present */
+ }
+ else
+ {
+ handlers[type] = NULL;
+ MUTEX_UNLOCK (handlerlock);
+ return OK; /* success */
+ }
}
- } else { /* can't be there */
- MUTEX_UNLOCK(handlerlock);
- return SYSERR;
- }
+ else
+ { /* can't be there */
+ MUTEX_UNLOCK (handlerlock);
+ return SYSERR;
+ }
}
/**
@@ -515,18 +505,15 @@
* @return SYSERR on error, OK if the return value was
* send successfully
*/
-int sendTCPResultToClient(struct ClientHandle * sock,
- int ret) {
+int
+sendTCPResultToClient (struct ClientHandle *sock, int ret)
+{
RETURN_VALUE_MESSAGE rv;
- rv.header.size
- = htons(sizeof(RETURN_VALUE_MESSAGE));
- rv.header.type
- = htons(CS_PROTO_RETURN_VALUE);
- rv.return_value
- = htonl(ret);
- return sendToClient(sock,
- &rv.header);
+ rv.header.size = htons (sizeof (RETURN_VALUE_MESSAGE));
+ rv.header.type = htons (CS_PROTO_RETURN_VALUE);
+ rv.return_value = htonl (ret);
+ return sendToClient (sock, &rv.header);
}
/**
@@ -537,36 +524,29 @@
* @return SYSERR on error, OK if the return value was
* send successfully
*/
-int sendTCPErrorToClient(struct ClientHandle * sock,
- GE_KIND kind,
- const char * message) {
- RETURN_ERROR_MESSAGE * rv;
+int
+sendTCPErrorToClient (struct ClientHandle *sock,
+ GE_KIND kind, const char *message)
+{
+ RETURN_ERROR_MESSAGE *rv;
size_t msgLen;
int ret;
- msgLen = strlen(message);
+ msgLen = strlen (message);
msgLen = ((msgLen + 3) >> 2) << 2;
if (msgLen > 60000)
msgLen = 60000;
- rv = MALLOC(sizeof(RETURN_ERROR_MESSAGE) + msgLen);
- memset(rv,
- 0,
- sizeof(RETURN_ERROR_MESSAGE) + msgLen);
- rv->header.size
- = htons(sizeof(MESSAGE_HEADER) + msgLen);
- rv->header.type
- = htons(CS_PROTO_RETURN_ERROR);
- rv->kind
- = htonl(kind);
- memcpy(&rv[1],
- message,
- strlen(message));
- ret = sendToClient(sock,
- &rv->header);
- FREE(rv);
+ rv = MALLOC (sizeof (RETURN_ERROR_MESSAGE) + msgLen);
+ memset (rv, 0, sizeof (RETURN_ERROR_MESSAGE) + msgLen);
+ rv->header.size = htons (sizeof (MESSAGE_HEADER) + msgLen);
+ rv->header.type = htons (CS_PROTO_RETURN_ERROR);
+ rv->kind = htonl (kind);
+ memcpy (&rv[1], message, strlen (message));
+ ret = sendToClient (sock, &rv->header);
+ FREE (rv);
return ret;
}
-
+
/**
* Check if a handler is registered for a given
* message type.
@@ -574,39 +554,47 @@
* @param type the message type
* @return number of registered handlers (0 or 1)
*/
-unsigned int isCSHandlerRegistered(unsigned short type) {
- MUTEX_LOCK(handlerlock);
- if (type < max_registeredType) {
- if (handlers[type] != NULL) {
- MUTEX_UNLOCK(handlerlock);
- return 1;
+unsigned int
+isCSHandlerRegistered (unsigned short type)
+{
+ MUTEX_LOCK (handlerlock);
+ if (type < max_registeredType)
+ {
+ if (handlers[type] != NULL)
+ {
+ MUTEX_UNLOCK (handlerlock);
+ return 1;
+ }
}
- }
- MUTEX_UNLOCK(handlerlock);
+ MUTEX_UNLOCK (handlerlock);
return 0;
}
-static void freeClientLogContext(void * ctx) { }
+static void
+freeClientLogContext (void *ctx)
+{
+}
-static void confirmClientLogContext(void * ctx) { }
+static void
+confirmClientLogContext (void *ctx)
+{
+}
-static void logClientLogContext(void * ctx,
- GE_KIND kind,
- const char * date,
- const char * msg) {
- sendTCPErrorToClient(ctx,
- kind,
- msg);
+static void
+logClientLogContext (void *ctx,
+ GE_KIND kind, const char *date, const char *msg)
+{
+ sendTCPErrorToClient (ctx, kind, msg);
}
struct GE_Context *
-createClientLogContext(GE_KIND mask,
- struct ClientHandle * handle) {
- return GE_create_context_callback(mask,
- &logClientLogContext,
- handle,
- &freeClientLogContext,
- &confirmClientLogContext);
+createClientLogContext (GE_KIND mask, struct ClientHandle *handle)
+{
+ return GE_create_context_callback (mask,
+ &logClientLogContext,
+ handle,
+ &freeClientLogContext,
+ &confirmClientLogContext);
}
/* end of tcpserver.c */
Modified: GNUnet/src/server/tcpserver.h
===================================================================
--- GNUnet/src/server/tcpserver.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/tcpserver.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,19 +33,18 @@
* Initialize the TCP port and listen for incoming client connections.
* @return OK on success, SYSERR on error
*/
-int initTCPServer(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+int initTCPServer (struct GE_Context *ectx, struct GC_Configuration *cfg);
/**
* Stop the server (but do not yet destroy the data structures)
*/
-int stopTCPServer(void);
+int stopTCPServer (void);
/**
* Shutdown the module.
* @return OK on success, SYSERR on error
*/
-int doneTCPServer(void);
+int doneTCPServer (void);
/**
* Register a method as a handler for specific message
@@ -58,8 +57,7 @@
* @return OK on success, SYSERR if there is already a
* handler for that type
*/
-int registerCSHandler(unsigned short type,
- CSHandler callback);
+int registerCSHandler (unsigned short type, CSHandler callback);
/**
* Unregister a method as a handler for specific message
@@ -72,12 +70,11 @@
* @return OK on success, SYSERR if there is no or another
* handler for that type
*/
-int unregisterCSHandler(unsigned short type,
- CSHandler callback);
+int unregisterCSHandler (unsigned short type, CSHandler callback);
-int registerClientExitHandler(ClientExitHandler callback);
+int registerClientExitHandler (ClientExitHandler callback);
-int unregisterClientExitHandler(ClientExitHandler callback);
+int unregisterClientExitHandler (ClientExitHandler callback);
/**
* Send a message to the client identified by the handle. Note that
@@ -86,8 +83,8 @@
* on the other hand does NOT confirm delivery since the actual
* transfer happens asynchronously.
*/
-int sendToClient(struct ClientHandle * handle,
- const MESSAGE_HEADER * message);
+int sendToClient (struct ClientHandle *handle,
+ const MESSAGE_HEADER * message);
/**
@@ -98,8 +95,7 @@
* @return SYSERR on error, OK if the return value was
* send successfully
*/
-int sendTCPResultToClient(struct ClientHandle * sock,
- int ret);
+int sendTCPResultToClient (struct ClientHandle *sock, int ret);
/**
* Send an error message to the caller of a remote call via
@@ -109,11 +105,10 @@
* @return SYSERR on error, OK if the return value was
* send successfully
*/
-int sendTCPErrorToClient(struct ClientHandle * sock,
- GE_KIND kind,
- const char * message);
+int sendTCPErrorToClient (struct ClientHandle *sock,
+ GE_KIND kind, const char *message);
-void terminateClientConnection(struct ClientHandle * sock);
+void terminateClientConnection (struct ClientHandle *sock);
/**
* Check if a handler is registered for a given
@@ -122,11 +117,10 @@
* @param type the message type
* @return number of registered handlers (0 or 1)
*/
-unsigned int isCSHandlerRegistered(unsigned short type);
+unsigned int isCSHandlerRegistered (unsigned short type);
-struct GE_Context *
-createClientLogContext(GE_KIND mask,
- struct ClientHandle * handle);
+struct GE_Context *createClientLogContext (GE_KIND mask,
+ struct ClientHandle *handle);
#endif
/* end of tcpserver.h */
Modified: GNUnet/src/server/version.c
===================================================================
--- GNUnet/src/server/version.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/version.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -38,36 +38,32 @@
* val is the configuration value from the
* configuration file.
*/
-static void dyncat(struct GC_Configuration * cfg,
- char ** string,
- const char * section,
- const char * part) {
+static void
+dyncat (struct GC_Configuration *cfg,
+ char **string, const char *section, const char *part)
+{
int len;
- char * tmp;
- char * val;
+ char *tmp;
+ char *val;
- len = strlen(*string);
- len += strlen(section) + 1;
- len += strlen(part) + 1;
+ len = strlen (*string);
+ len += strlen (section) + 1;
+ len += strlen (part) + 1;
val = NULL;
- GC_get_configuration_value_string(cfg,
- section,
- part,
- "",
- &val);
+ GC_get_configuration_value_string (cfg, section, part, "", &val);
if (val == NULL)
- val = STRDUP("");
- len += strlen(val) + 2;
- tmp = MALLOC(len);
- strcpy(tmp, *string);
- strcat(tmp, section);
- strcat(tmp, ":");
- strcat(tmp, part);
- strcat(tmp, "=");
- strcat(tmp, val);
- strcat(tmp, ";");
- FREE(val);
- FREE(*string);
+ val = STRDUP ("");
+ len += strlen (val) + 2;
+ tmp = MALLOC (len);
+ strcpy (tmp, *string);
+ strcat (tmp, section);
+ strcat (tmp, ":");
+ strcat (tmp, part);
+ strcat (tmp, "=");
+ strcat (tmp, val);
+ strcat (tmp, ";");
+ FREE (val);
+ FREE (*string);
*string = tmp;
}
@@ -79,56 +75,46 @@
* since changes to certain values there will also
* require us to run gnunet-update!
*/
-static void getVersionHash(struct GC_Configuration * cfg,
- EncName * enc) {
+static void
+getVersionHash (struct GC_Configuration *cfg, EncName * enc)
+{
HashCode512 hc;
- char * string;
+ char *string;
- string = STRDUP("");
+ string = STRDUP ("");
/* yes, this is a bit ugly since we break the isolation between core
and apps, but adding code to query the apps which configuration
changes require gnunet-update feels like overkill for now; one
simple alternative would be to require gnunet-update for any
configuration change, but that again would be too strict. */
- dyncat(cfg,
- &string,
- "GNUNETD",
- "APPLICATIONS");
- dyncat(cfg,
- &string,
- "FS",
- "QUOTA");
- dyncat(cfg,
- &string,
- "MODULES",
- "sqstore");
- hash(string,
- strlen(string),
- &hc);
- hash2enc(&hc, enc);
- FREE(string);
+ dyncat (cfg, &string, "GNUNETD", "APPLICATIONS");
+ dyncat (cfg, &string, "FS", "QUOTA");
+ dyncat (cfg, &string, "MODULES", "sqstore");
+ hash (string, strlen (string), &hc);
+ hash2enc (&hc, enc);
+ FREE (string);
}
-static char * getVersionFileName(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- char * en;
- char * cn;
+static char *
+getVersionFileName (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ char *en;
+ char *cn;
en = NULL;
- if (-1 == GC_get_configuration_value_filename(cfg,
- "GNUNETD",
- "GNUNETD_HOME",
- VAR_DAEMON_DIRECTORY,
- &en))
+ if (-1 == GC_get_configuration_value_filename (cfg,
+ "GNUNETD",
+ "GNUNETD_HOME",
+ VAR_DAEMON_DIRECTORY, &en))
return NULL;
- GE_ASSERT(ectx, en != NULL);
- cn = MALLOC(strlen(en) + strlen(VERSIONFILE) + 1);
- strcpy(cn, en);
- strcat(cn, VERSIONDIR);
- disk_directory_create(ectx, cn);
- strcpy(cn, en);
- strcat(cn, VERSIONFILE);
- FREE(en);
+ GE_ASSERT (ectx, en != NULL);
+ cn = MALLOC (strlen (en) + strlen (VERSIONFILE) + 1);
+ strcpy (cn, en);
+ strcat (cn, VERSIONDIR);
+ disk_directory_create (ectx, cn);
+ strcpy (cn, en);
+ strcat (cn, VERSIONFILE);
+ FREE (en);
return cn;
}
@@ -138,47 +124,42 @@
* Check if we are up-to-date.
* @return OK if we are
*/
-int checkUpToDate(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
+int
+checkUpToDate (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
char version[MAX_VS];
int len;
EncName enc;
- char * fn;
+ char *fn;
- fn = getVersionFileName(ectx, cfg);
- if (fn == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- _("Failed to determine filename used to store GNUnet version
information!\n"));
- return OK; /* uh uh */
- }
- if (disk_file_test(ectx,
- fn) != YES) {
- FREE(fn);
- upToDate(ectx, cfg); /* first start */
- return OK;
- }
- len = disk_file_read(ectx,
- fn,
- MAX_VS,
- version);
- FREE(fn);
- if (len == -1) { /* should never happen -- file should exist */
- upToDate(ectx,
- cfg); /* first start */
- return OK;
- }
- if ( (len != strlen(VERSION) + 1 + sizeof(EncName)) ||
- (0 != memcmp(VERSION,
- version,
- strlen(VERSION)+1)) )
- return SYSERR; /* wrong version */
- getVersionHash(cfg,
- &enc);
- if (0 != memcmp(&enc,
- &version[strlen(VERSION)+1],
- sizeof(EncName)))
- return SYSERR; /* wrong hash */
+ fn = getVersionFileName (ectx, cfg);
+ if (fn == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ _
+ ("Failed to determine filename used to store GNUnet version
information!\n"));
+ return OK; /* uh uh */
+ }
+ if (disk_file_test (ectx, fn) != YES)
+ {
+ FREE (fn);
+ upToDate (ectx, cfg); /* first start */
+ return OK;
+ }
+ len = disk_file_read (ectx, fn, MAX_VS, version);
+ FREE (fn);
+ if (len == -1)
+ { /* should never happen -- file should exist */
+ upToDate (ectx, cfg); /* first start */
+ return OK;
+ }
+ if ((len != strlen (VERSION) + 1 + sizeof (EncName)) ||
+ (0 != memcmp (VERSION, version, strlen (VERSION) + 1)))
+ return SYSERR; /* wrong version */
+ getVersionHash (cfg, &enc);
+ if (0 != memcmp (&enc, &version[strlen (VERSION) + 1], sizeof (EncName)))
+ return SYSERR; /* wrong hash */
return OK;
}
@@ -186,29 +167,23 @@
* We are up-to-date.
* Writes the version tag
*/
-void upToDate(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
+void
+upToDate (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
char version[MAX_VS];
int len;
EncName enc;
- char * fn;
+ char *fn;
- fn = getVersionFileName(ectx, cfg);
- len = strlen(VERSION) + 1 + sizeof(EncName);
- GE_ASSERT(ectx, len < MAX_VS);
- memcpy(version, VERSION, strlen(VERSION)+1);
- getVersionHash(cfg,
- &enc);
- memcpy(&version[strlen(VERSION)+1],
- &enc,
- sizeof(EncName));
- UNLINK(fn);
- disk_file_write(ectx,
- fn,
- version,
- len,
- "600");
- FREE(fn);
+ fn = getVersionFileName (ectx, cfg);
+ len = strlen (VERSION) + 1 + sizeof (EncName);
+ GE_ASSERT (ectx, len < MAX_VS);
+ memcpy (version, VERSION, strlen (VERSION) + 1);
+ getVersionHash (cfg, &enc);
+ memcpy (&version[strlen (VERSION) + 1], &enc, sizeof (EncName));
+ UNLINK (fn);
+ disk_file_write (ectx, fn, version, len, "600");
+ FREE (fn);
}
-
+
/* end of version.c */
Modified: GNUnet/src/server/version.h
===================================================================
--- GNUnet/src/server/version.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/server/version.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,13 +33,11 @@
* Check if we are up-to-date.
* @return OK if we are
*/
-int checkUpToDate(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+int checkUpToDate (struct GE_Context *ectx, struct GC_Configuration *cfg);
/**
* We are up-to-date.
*/
-void upToDate(struct GE_Context * ectx,
- struct GC_Configuration * cfg);
+void upToDate (struct GE_Context *ectx, struct GC_Configuration *cfg);
#endif
Modified: GNUnet/src/setup/gnunet-setup.c
===================================================================
--- GNUnet/src/setup/gnunet-setup.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/gnunet-setup.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -32,105 +32,92 @@
#include "platform.h"
-typedef int (*ConfigurationPluginMain)(int argc,
- char * const * argv,
- struct PluginHandle * self,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon);
+typedef int (*ConfigurationPluginMain) (int argc,
+ char *const *argv,
+ struct PluginHandle * self,
+ struct GE_Context * ectx,
+ struct GC_Configuration * cfg,
+ struct GNS_Context * gns,
+ const char *filename, int is_daemon);
static int config_daemon;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static struct GNS_Context * gns;
+static struct GNS_Context *gns;
-static char * cfgFilename;
+static char *cfgFilename;
/**
* All gnunet-setup command line options
*/
static struct CommandLineOption gnunetsetupOptions[] = {
- COMMAND_LINE_OPTION_CFG_FILE(&cfgFilename), /* -c */
- { 'd', "daemon", NULL,
- gettext_noop("generate configuration for gnunetd, the GNUnet daemon"),
- 0, &gnunet_getopt_configure_set_one, &config_daemon },
- COMMAND_LINE_OPTION_HELP(gettext_noop("Tool to setup GNUnet.")), /* -h */
- COMMAND_LINE_OPTION_VERSION(PACKAGE_VERSION), /* -v */
+ COMMAND_LINE_OPTION_CFG_FILE (&cfgFilename), /* -c */
+ {'d', "daemon", NULL,
+ gettext_noop ("generate configuration for gnunetd, the GNUnet daemon"),
+ 0, &gnunet_getopt_configure_set_one, &config_daemon},
+ COMMAND_LINE_OPTION_HELP (gettext_noop ("Tool to setup GNUnet.")), /* -h
*/
+ COMMAND_LINE_OPTION_VERSION (PACKAGE_VERSION), /* -v */
COMMAND_LINE_OPTION_VERBOSE,
COMMAND_LINE_OPTION_END,
};
-static void gns2cfg(struct GNS_Tree * pos) {
+static void
+gns2cfg (struct GNS_Tree *pos)
+{
int i;
- char * val;
+ char *val;
if (pos == NULL)
return;
i = 0;
- while (pos->children[i] != NULL) {
- gns2cfg(pos->children[i]);
- i++;
- }
+ while (pos->children[i] != NULL)
+ {
+ gns2cfg (pos->children[i]);
+ i++;
+ }
if (i != 0)
return;
- if ( (pos->section == NULL) ||
- (pos->option == NULL) )
+ if ((pos->section == NULL) || (pos->option == NULL))
return;
- if (NO == GC_have_configuration_value(cfg,
- pos->section,
- pos->option)) {
- val = GNS_get_default_value_as_string(pos->type,
- &pos->value);
- if (val != NULL) {
- GC_set_configuration_value_string(cfg,
- ectx,
- pos->section,
- pos->option,
- val);
- FREE(val);
+ if (NO == GC_have_configuration_value (cfg, pos->section, pos->option))
+ {
+ val = GNS_get_default_value_as_string (pos->type, &pos->value);
+ if (val != NULL)
+ {
+ GC_set_configuration_value_string (cfg,
+ ectx,
+ pos->section, pos->option, val);
+ FREE (val);
+ }
}
- }
}
-static int dyn_config(const char * module,
- const char * mainfunc,
- int argc,
- char * const * argv,
- const char * filename) {
+static int
+dyn_config (const char *module,
+ const char *mainfunc,
+ int argc, char *const *argv, const char *filename)
+{
ConfigurationPluginMain mptr;
- struct PluginHandle * library;
+ struct PluginHandle *library;
- library = os_plugin_load(ectx,
- "libgnunet",
- module);
+ library = os_plugin_load (ectx, "libgnunet", module);
if (!library)
return SYSERR;
- mptr = os_plugin_resolve_function(library,
- mainfunc,
- YES);
- if (! mptr) {
- os_plugin_unload(library);
- return SYSERR;
- }
- mptr(argc,
- argv,
- library,
- ectx,
- cfg,
- gns,
- filename,
- config_daemon);
- os_plugin_unload(library);
+ mptr = os_plugin_resolve_function (library, mainfunc, YES);
+ if (!mptr)
+ {
+ os_plugin_unload (library);
+ return SYSERR;
+ }
+ mptr (argc, argv, library, ectx, cfg, gns, filename, config_daemon);
+ os_plugin_unload (library);
return YES;
}
-static const char * INFO =
- "gnunet-setup [OPTIONS] config|generate-defaults"
+static const char *INFO = "gnunet-setup [OPTIONS] config|generate-defaults"
#if HAVE_DIALOG
"|menuconfig|wizard-curses"
#endif
@@ -144,154 +131,153 @@
* of three strings: option name, plugin library
* name and main method name.
*/
-static const char * modules[] = {
- "gconfig", "setup_gtk", "gconf_main" ,
- "menuconfig", "setup_curses", "mconf_main" ,
- "config", "setup_text", "main_" ,
- "wizard-curses", "setup_curses", "wizard_curs_main",
- "wizard-gtk", "setup_gtk", "gtk_wizard_main",
- "generate-defaults", "setup_text", "dump_",
- NULL,
+static const char *modules[] = {
+ "gconfig", "setup_gtk", "gconf_main",
+ "menuconfig", "setup_curses", "mconf_main",
+ "config", "setup_text", "main_",
+ "wizard-curses", "setup_curses", "wizard_curs_main",
+ "wizard-gtk", "setup_gtk", "gtk_wizard_main",
+ "generate-defaults", "setup_text", "dump_",
+ NULL,
};
-int main(int argc,
- char * const * argv) {
- const char * operation;
+int
+main (int argc, char *const *argv)
+{
+ const char *operation;
int done;
- char * dirname;
- char * specname;
+ char *dirname;
+ char *specname;
int i;
- ectx = GE_create_context_stderr(NO,
- GE_WARNING | GE_ERROR | GE_FATAL |
- GE_USER | GE_ADMIN | GE_DEVELOPER |
- GE_IMMEDIATE | GE_BULK);
- GE_setDefaultContext(ectx);
- os_init(ectx);
- cfg = GC_create_C_impl();
- GE_ASSERT(ectx, cfg != NULL);
- i = gnunet_parse_options(INFO,
- ectx,
- cfg,
- gnunetsetupOptions,
- (unsigned int) argc,
- argv);
- if (i < 0) {
- GC_free(cfg);
- GE_free_context(ectx);
- return -1;
- }
- if (i != argc - 1) {
- if (i < argc - 1) {
- fprintf(stderr,
- _("Too many arguments.\n"));
+ ectx = GE_create_context_stderr (NO,
+ GE_WARNING | GE_ERROR | GE_FATAL |
+ GE_USER | GE_ADMIN | GE_DEVELOPER |
+ GE_IMMEDIATE | GE_BULK);
+ GE_setDefaultContext (ectx);
+ os_init (ectx);
+ cfg = GC_create_C_impl ();
+ GE_ASSERT (ectx, cfg != NULL);
+ i = gnunet_parse_options (INFO,
+ ectx,
+ cfg,
+ gnunetsetupOptions, (unsigned int) argc, argv);
+ if (i < 0)
+ {
+ GC_free (cfg);
+ GE_free_context (ectx);
return -1;
}
- GE_LOG(ectx,
- GE_WARNING | GE_REQUEST | GE_USER,
- _("No interface specified, using default\n"));
- operation = "config";
+ if (i != argc - 1)
+ {
+ if (i < argc - 1)
+ {
+ fprintf (stderr, _("Too many arguments.\n"));
+ return -1;
+ }
+ GE_LOG (ectx,
+ GE_WARNING | GE_REQUEST | GE_USER,
+ _("No interface specified, using default\n"));
+ operation = "config";
#if HAVE_DIALOG
- operation = "menuconfig";
+ operation = "menuconfig";
#endif
#if HAVE_GTK
- operation = "gconfig";
+ operation = "gconfig";
#endif
- } else {
- operation = argv[i];
- }
- if (NULL != strstr(operation, "wizard"))
- config_daemon = YES; /* wizard implies daemon! */
+ }
+ else
+ {
+ operation = argv[i];
+ }
+ if (NULL != strstr (operation, "wizard"))
+ config_daemon = YES; /* wizard implies daemon! */
if (cfgFilename == NULL)
cfgFilename = config_daemon
- ? STRDUP(DEFAULT_DAEMON_CONFIG_FILE)
- : STRDUP(DEFAULT_CLIENT_CONFIG_FILE);
- dirname = string_expandFileName(ectx, cfgFilename);
- FREE(cfgFilename);
- cfgFilename = STRDUP(dirname);
- i = strlen(dirname) - 1;
- while (i > -1) {
- char ch = dirname[i];
- if ( (ch == '/') || (ch == '\\')) {
- dirname[i + 1] = 0;
- break;
+ ? STRDUP (DEFAULT_DAEMON_CONFIG_FILE)
+ : STRDUP (DEFAULT_CLIENT_CONFIG_FILE);
+ dirname = string_expandFileName (ectx, cfgFilename);
+ FREE (cfgFilename);
+ cfgFilename = STRDUP (dirname);
+ i = strlen (dirname) - 1;
+ while (i > -1)
+ {
+ char ch = dirname[i];
+ if ((ch == '/') || (ch == '\\'))
+ {
+ dirname[i + 1] = 0;
+ break;
+ }
+ i--;
}
- i--;
- }
- disk_directory_create(ectx, dirname);
- if ( ( (0 != ACCESS(cfgFilename, W_OK)) &&
- ( (errno != ENOENT) ||
- (0 != ACCESS(dirname, W_OK))) ) )
- GE_DIE_STRERROR_FILE(ectx,
- GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "access",
- dirname);
- FREE(dirname);
+ disk_directory_create (ectx, dirname);
+ if (((0 != ACCESS (cfgFilename, W_OK)) &&
+ ((errno != ENOENT) || (0 != ACCESS (dirname, W_OK)))))
+ GE_DIE_STRERROR_FILE (ectx,
+ GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ "access", dirname);
+ FREE (dirname);
- if (0 == ACCESS(cfgFilename, F_OK))
- GC_parse_configuration(cfg,
- cfgFilename);
- dirname = os_get_installation_path(IPK_DATADIR);
- GE_ASSERT(ectx, dirname != NULL);
- specname = MALLOC(strlen(dirname) + strlen("config-daemon.scm") + 1);
- strcpy(specname, dirname);
- FREE(dirname);
+ if (0 == ACCESS (cfgFilename, F_OK))
+ GC_parse_configuration (cfg, cfgFilename);
+ dirname = os_get_installation_path (IPK_DATADIR);
+ GE_ASSERT (ectx, dirname != NULL);
+ specname = MALLOC (strlen (dirname) + strlen ("config-daemon.scm") + 1);
+ strcpy (specname, dirname);
+ FREE (dirname);
if (config_daemon)
- strcat(specname, "config-daemon.scm");
+ strcat (specname, "config-daemon.scm");
else
- strcat(specname, "config-client.scm");
- gns = GNS_load_specification(ectx,
- cfg,
- specname);
- FREE(specname);
- if (gns == NULL) {
- GC_free(cfg);
- GE_free_context(ectx);
- FREE(cfgFilename);
- return -1;
- }
- gns2cfg(GNS_get_tree(gns));
+ strcat (specname, "config-client.scm");
+ gns = GNS_load_specification (ectx, cfg, specname);
+ FREE (specname);
+ if (gns == NULL)
+ {
+ GC_free (cfg);
+ GE_free_context (ectx);
+ FREE (cfgFilename);
+ return -1;
+ }
+ gns2cfg (GNS_get_tree (gns));
done = NO;
i = 0;
- while ( (done == NO) &&
- (modules[i] != NULL) ) {
- if (strcmp(operation, modules[i]) == 0) {
- if (dyn_config(modules[i+1],
- modules[i+2],
- argc,
- argv,
- cfgFilename) != YES) {
- GE_LOG(ectx,
- GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- _("`%s' is not available."),
- operation);
- GNS_free_specification(gns);
- GC_free(cfg);
- GE_free_context(ectx);
- FREE(cfgFilename);
- return -1;
- } else {
- done = YES;
- }
+ while ((done == NO) && (modules[i] != NULL))
+ {
+ if (strcmp (operation, modules[i]) == 0)
+ {
+ if (dyn_config (modules[i + 1],
+ modules[i + 2], argc, argv, cfgFilename) != YES)
+ {
+ GE_LOG (ectx,
+ GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ _("`%s' is not available."), operation);
+ GNS_free_specification (gns);
+ GC_free (cfg);
+ GE_free_context (ectx);
+ FREE (cfgFilename);
+ return -1;
+ }
+ else
+ {
+ done = YES;
+ }
+ }
+ i += 3;
}
- i += 3;
- }
- FREE(cfgFilename);
- if (done == NO) {
- fprintf(stderr,
- _("Unknown operation `%s'\n"),
- operation);
- fprintf(stderr,
- _("Use --help to get a list of options.\n"));
- GNS_free_specification(gns);
- GC_free(cfg);
- GE_free_context(ectx);
- return 1;
- }
- GNS_free_specification(gns);
- GC_free(cfg);
- GE_free_context(ectx);
+ FREE (cfgFilename);
+ if (done == NO)
+ {
+ fprintf (stderr, _("Unknown operation `%s'\n"), operation);
+ fprintf (stderr, _("Use --help to get a list of options.\n"));
+ GNS_free_specification (gns);
+ GC_free (cfg);
+ GE_free_context (ectx);
+ return 1;
+ }
+ GNS_free_specification (gns);
+ GC_free (cfg);
+ GE_free_context (ectx);
return 0;
}
Modified: GNUnet/src/setup/gnunet-win-tool.c
===================================================================
--- GNUnet/src/setup/gnunet-win-tool.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/gnunet-win-tool.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,222 +33,231 @@
#define WINTOOL_VERSION "0.1.0"
-static char chunk1[] = {0x62, 0x13, 0x06, 0x00};
-static char chunk2[] = {0xFE, 0xFF, 0xFF, 0x00};
-static char chunk3[] = {0xBC, 0x28, 0x06, 0x00};
-static char chunk4[] = {0xCF, 0x47, 0x06, 0x00};
+static char chunk1[] = { 0x62, 0x13, 0x06, 0x00 };
+static char chunk2[] = { 0xFE, 0xFF, 0xFF, 0x00 };
+static char chunk3[] = { 0xBC, 0x28, 0x06, 0x00 };
+static char chunk4[] = { 0xCF, 0x47, 0x06, 0x00 };
/**
* configuration
*/
-static unsigned int bPrintAdapters = 0, bInstall = 0, bUninstall = 0, bConn =
0;
+static unsigned int bPrintAdapters = 0, bInstall = 0, bUninstall = 0, bConn =
+ 0;
static char *hashFile = NULL;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
/**
* All gnunet-win-tool command line options
*/
static struct CommandLineOption gnunetwinOptions[] = {
- { 'n', "netadapters", "network adapters",
- gettext_noop("list all network adapters"),
- 0, &gnunet_getopt_configure_set_uint, &bPrintAdapters },
- { 'i', "install", "install service",
- gettext_noop("install GNUnet as Windows service"),
- 0, &gnunet_getopt_configure_set_uint, &bInstall },
- { 'u', "uninstall", "uninstall service",
- gettext_noop("uninstall GNUnet service"),
- 0, &gnunet_getopt_configure_set_uint, &bUninstall },
- { 'C', "increase-connections", "increase connections",
- gettext_noop("increase the maximum number of TCP/IP connections"),
- 0, &gnunet_getopt_configure_set_uint, &bConn },
- { 'R', "filehash", "hash",
- gettext_noop("display a file's hash value"),
- 1, &gnunet_getopt_configure_set_string, &hashFile },
- COMMAND_LINE_OPTION_VERSION(WINTOOL_VERSION), /* -v */
- COMMAND_LINE_OPTION_END,
+ {'n', "netadapters", "network adapters",
+ gettext_noop ("list all network adapters"),
+ 0, &gnunet_getopt_configure_set_uint, &bPrintAdapters},
+ {'i', "install", "install service",
+ gettext_noop ("install GNUnet as Windows service"),
+ 0, &gnunet_getopt_configure_set_uint, &bInstall},
+ {'u', "uninstall", "uninstall service",
+ gettext_noop ("uninstall GNUnet service"),
+ 0, &gnunet_getopt_configure_set_uint, &bUninstall},
+ {'C', "increase-connections", "increase connections",
+ gettext_noop ("increase the maximum number of TCP/IP connections"),
+ 0, &gnunet_getopt_configure_set_uint, &bConn},
+ {'R', "filehash", "hash",
+ gettext_noop ("display a file's hash value"),
+ 1, &gnunet_getopt_configure_set_string, &hashFile},
+ COMMAND_LINE_OPTION_VERSION (WINTOOL_VERSION), /* -v */
+ COMMAND_LINE_OPTION_END,
};
/**
* Print all network adapters with their index number
*/
-void PrintAdapters()
+void
+PrintAdapters ()
{
PMIB_IFTABLE pTable;
PMIB_IPADDRTABLE pAddrTable;
DWORD dwIfIdx;
- EnumNICs(&pTable, &pAddrTable);
+ EnumNICs (&pTable, &pAddrTable);
if (pTable)
- {
- for(dwIfIdx=0; dwIfIdx <= pTable->dwNumEntries; dwIfIdx++)
{
- BYTE bPhysAddr[MAXLEN_PHYSADDR];
+ for (dwIfIdx = 0; dwIfIdx <= pTable->dwNumEntries; dwIfIdx++)
+ {
+ BYTE bPhysAddr[MAXLEN_PHYSADDR];
- memset(bPhysAddr, 0, MAXLEN_PHYSADDR);
- memcpy(bPhysAddr,
- pTable->table[dwIfIdx].bPhysAddr,
- pTable->table[dwIfIdx].dwPhysAddrLen);
+ memset (bPhysAddr, 0, MAXLEN_PHYSADDR);
+ memcpy (bPhysAddr,
+ pTable->table[dwIfIdx].bPhysAddr,
+ pTable->table[dwIfIdx].dwPhysAddrLen);
- printf("Index: %i\nAdapter name: %s\nID: %I64u\n",
- (int) pTable->table[dwIfIdx].dwIndex, pTable->table[dwIfIdx].bDescr,
- *((unsigned long long *) bPhysAddr));
+ printf ("Index: %i\nAdapter name: %s\nID: %I64u\n",
+ (int) pTable->table[dwIfIdx].dwIndex,
+ pTable->table[dwIfIdx].bDescr,
+ *((unsigned long long *) bPhysAddr));
- /* Get IP-Addresses */
- int i;
- for(i = 0; i < pAddrTable->dwNumEntries; i++)
- {
- if (pAddrTable->table[i].dwIndex == pTable->table[dwIfIdx].dwIndex)
- printf("Address: %u.%u.%u.%u\n",
- PRIP(ntohl(pAddrTable->table[i].dwAddr)));
- }
- printf("\n");
+ /* Get IP-Addresses */
+ int i;
+ for (i = 0; i < pAddrTable->dwNumEntries; i++)
+ {
+ if (pAddrTable->table[i].dwIndex ==
+ pTable->table[dwIfIdx].dwIndex)
+ printf ("Address: %u.%u.%u.%u\n",
+ PRIP (ntohl (pAddrTable->table[i].dwAddr)));
+ }
+ printf ("\n");
+ }
+ GlobalFree (pAddrTable);
+ GlobalFree (pTable);
}
- GlobalFree(pAddrTable);
- GlobalFree(pTable);
- }
}
/**
* Install GNUnet as Windows service
*/
-void Install()
+void
+Install ()
{
- switch(InstallAsService(NULL))
- {
- case 0:
- printf(_("GNUnet service installed successfully.\n"));
- break;
- case 1:
- printf(_("This version of Windows doesn't support
services.\n"));
- break;
- case 2:
- SetErrnoFromWinError(GetLastError());
- printf(_("Error: can't open Service Control Manager: %s\n"),
- _win_strerror(errno));
- break;
- case 3:
- SetErrnoFromWinError(GetLastError());
- printf(_("Error: can't create service: %s\n"), _win_strerror(errno));
- break;
- default:
- printf(_("Unknown error.\n"));
- }
+ switch (InstallAsService (NULL))
+ {
+ case 0:
+ printf (_("GNUnet service installed successfully.\n"));
+ break;
+ case 1:
+ printf (_("This version of Windows doesn't support services.\n"));
+ break;
+ case 2:
+ SetErrnoFromWinError (GetLastError ());
+ printf (_("Error: can't open Service Control Manager: %s\n"),
+ _win_strerror (errno));
+ break;
+ case 3:
+ SetErrnoFromWinError (GetLastError ());
+ printf (_("Error: can't create service: %s\n"), _win_strerror (errno));
+ break;
+ default:
+ printf (_("Unknown error.\n"));
+ }
}
/**
* Uninstall the service
*/
-void Uninstall()
+void
+Uninstall ()
{
- switch(UninstallService())
- {
- case 0:
- printf(_("Service deleted.\n"));
- break;
- case 1:
- printf(_("This version of Windows doesn't support
services.\n"));
- break;
- case 2:
- SetErrnoFromWinError(GetLastError());
- printf(_("Error: can't open Service Control Manager: %s\n"),
- _win_strerror(errno));
- break;
- case 3:
- SetErrnoFromWinError(GetLastError());
- printf(_("Error: can't access service: %s\n"), _win_strerror(errno));
- break;
- case 4:
- SetErrnoFromWinError(GetLastError());
- printf(_("Error: can't delete service: %s\n"), _win_strerror(errno));
- break;
- default:
- printf(_("Unknown error.\n"));
- }
+ switch (UninstallService ())
+ {
+ case 0:
+ printf (_("Service deleted.\n"));
+ break;
+ case 1:
+ printf (_("This version of Windows doesn't support services.\n"));
+ break;
+ case 2:
+ SetErrnoFromWinError (GetLastError ());
+ printf (_("Error: can't open Service Control Manager: %s\n"),
+ _win_strerror (errno));
+ break;
+ case 3:
+ SetErrnoFromWinError (GetLastError ());
+ printf (_("Error: can't access service: %s\n"), _win_strerror (errno));
+ break;
+ case 4:
+ SetErrnoFromWinError (GetLastError ());
+ printf (_("Error: can't delete service: %s\n"), _win_strerror (errno));
+ break;
+ default:
+ printf (_("Unknown error.\n"));
+ }
}
-void PatchSys(char *szFn)
+void
+PatchSys (char *szFn)
{
FILE *pFile;
unsigned long lMem;
char *pMem;
int iCrc;
- pFile = fopen(szFn, "r+b");
+ pFile = fopen (szFn, "r+b");
if (!pFile)
- {
- printf("failed.\n Cannot open %s\n", szFn);
- return;
- }
+ {
+ printf ("failed.\n Cannot open %s\n", szFn);
+ return;
+ }
- if (fseek(pFile, 0, SEEK_END))
- {
- printf("failed.\n Cannot seek.\n");
- return;
- }
+ if (fseek (pFile, 0, SEEK_END))
+ {
+ printf ("failed.\n Cannot seek.\n");
+ return;
+ }
- lMem = ftell(pFile);
- pMem = malloc(lMem);
- if (! pMem)
- {
- printf("failed.\n Not enough memory.\n");
- fclose(pFile);
- return;
- }
+ lMem = ftell (pFile);
+ pMem = malloc (lMem);
+ if (!pMem)
+ {
+ printf ("failed.\n Not enough memory.\n");
+ fclose (pFile);
+ return;
+ }
- fseek(pFile, 0, SEEK_SET);
- fread(pMem, 1, lMem, pFile);
+ fseek (pFile, 0, SEEK_SET);
+ fread (pMem, 1, lMem, pFile);
- switch(iCrc = crc32N(pMem, lMem))
- {
+ switch (iCrc = crc32N (pMem, lMem))
+ {
case 2151852539:
- memcpy(pMem + 0x130, chunk1, 4);
- memcpy(pMem + 0x4F322, chunk2, 4);
+ memcpy (pMem + 0x130, chunk1, 4);
+ memcpy (pMem + 0x4F322, chunk2, 4);
break;
case 3886810835:
- memcpy(pMem + 0x130, chunk3, 4);
- memcpy(pMem + 0x4f5a2, chunk2, 4);
+ memcpy (pMem + 0x130, chunk3, 4);
+ memcpy (pMem + 0x4f5a2, chunk2, 4);
break;
case 3246854107:
- memcpy(pMem + 0x130, chunk4, 4);
- memcpy(pMem + 0x4f5a2, chunk2, 4);
+ memcpy (pMem + 0x130, chunk4, 4);
+ memcpy (pMem + 0x4f5a2, chunk2, 4);
break;
case 2437296753:
case 2826512337:
case 1912882803:
- printf("already patched.\n");
- free(pMem);
- fclose(pFile);
+ printf ("already patched.\n");
+ free (pMem);
+ fclose (pFile);
return;
default:
- printf("Unknown DLL version. CRC: %u\n", iCrc);
- free(pMem);
- fclose(pFile);
+ printf ("Unknown DLL version. CRC: %u\n", iCrc);
+ free (pMem);
+ fclose (pFile);
return;
- }
+ }
- fseek(pFile, 0, SEEK_SET);
- fwrite(pMem, 1, lMem, pFile);
- fclose(pFile);
+ fseek (pFile, 0, SEEK_SET);
+ fwrite (pMem, 1, lMem, pFile);
+ fclose (pFile);
- free(pMem);
+ free (pMem);
- printf("OK.\n");
+ printf ("OK.\n");
}
/**
* Increase the maximum number of connections.
* This is especially important under Windows XP Service Pack 2
**/
-void IncreaseConnections()
+void
+IncreaseConnections ()
{
HKEY hKey;
char szSys[_MAX_PATH + 1];
- puts("Warning: This modifies your operating system. Use it at your own
risk.\nContinue?[Y/n]");
- switch(_getch())
- {
+ puts
+ ("Warning: This modifies your operating system. Use it at your own
risk.\nContinue?[Y/n]");
+ switch (_getch ())
+ {
case 'Y':
case 'y':
case 13:
@@ -257,71 +266,77 @@
break;
default:
return;
- }
- puts("Y\n");
+ }
+ puts ("Y\n");
/* Step 1: Registry setting,
see http://support.microsoft.com/default.aspx?scid=kb;EN-US;314053 */
- printf("Writing to registry... ");
- if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\"
- "Tcpip\\Parameters\\Winsock", 0,
- KEY_WRITE, &hKey) != ERROR_SUCCESS)
- {
- DWORD dwErr = GetLastError();
- SetErrnoFromWinError(dwErr);
- printf("failed.\n Error: %s (%i)\n", STRERROR(errno), (int) dwErr);
- }
+ printf ("Writing to registry... ");
+ if (RegOpenKeyEx
+ (HKEY_LOCAL_MACHINE,
+ "SYSTEM\\CurrentControlSet\\Services\\" "Tcpip\\Parameters\\Winsock",
+ 0, KEY_WRITE, &hKey) != ERROR_SUCCESS)
+ {
+ DWORD dwErr = GetLastError ();
+ SetErrnoFromWinError (dwErr);
+ printf ("failed.\n Error: %s (%i)\n", STRERROR (errno), (int) dwErr);
+ }
else
- {
- DWORD dwCon = 0xfffffe;
- if (RegSetValueEx(hKey, "TcpNumConnections", 0, REG_DWORD,
- (const BYTE *) &dwCon, sizeof(dwCon)) != ERROR_SUCCESS)
{
- DWORD dwErr = GetLastError();
- SetErrnoFromWinError(dwErr);
- printf("failed.\n Error: %s (%i)\n", STRERROR(errno), (int) dwErr);
+ DWORD dwCon = 0xfffffe;
+ if (RegSetValueEx (hKey, "TcpNumConnections", 0, REG_DWORD,
+ (const BYTE *) &dwCon,
+ sizeof (dwCon)) != ERROR_SUCCESS)
+ {
+ DWORD dwErr = GetLastError ();
+ SetErrnoFromWinError (dwErr);
+ printf ("failed.\n Error: %s (%i)\n", STRERROR (errno),
+ (int) dwErr);
+ }
+ else
+ printf ("OK.\n");
+ RegCloseKey (hKey);
}
- else
- printf("OK.\n");
- RegCloseKey(hKey);
- }
/* Step 2: Patch tcpip.sys */
- printf("Patching DLLCACHE\\tcpip.sys... ");
- snprintf(szSys, _MAX_PATH, "%s\\SYSTEM32\\DLLCACHE\\tcpip.sys",
getenv("windir"));
- PatchSys(szSys);
+ printf ("Patching DLLCACHE\\tcpip.sys... ");
+ snprintf (szSys, _MAX_PATH, "%s\\SYSTEM32\\DLLCACHE\\tcpip.sys",
+ getenv ("windir"));
+ PatchSys (szSys);
- printf("Patching DRIVERS\\tcpip.sys... ");
- snprintf(szSys, _MAX_PATH, "%s\\SYSTEM32\\DRIVERS\\tcpip.sys",
getenv("windir"));
- PatchSys(szSys);
+ printf ("Patching DRIVERS\\tcpip.sys... ");
+ snprintf (szSys, _MAX_PATH, "%s\\SYSTEM32\\DRIVERS\\tcpip.sys",
+ getenv ("windir"));
+ PatchSys (szSys);
- printf("OK.\n\nPress any key to continue...");
- getch();
+ printf ("OK.\n\nPress any key to continue...");
+ getch ();
}
/**
* Print the hash of a file
*/
-void doHash()
+void
+doHash ()
{
HashCode512 code;
EncName hex;
char *c;
- getFileHash(ectx, hashFile, &code);
- hash2enc(&code, &hex);
- printf("SHA512(%s)= ", hashFile);
+ getFileHash (ectx, hashFile, &code);
+ hash2enc (&code, &hex);
+ printf ("SHA512(%s)= ", hashFile);
/* Flip byte order */
c = (char *) hex.encoding;
- while(*c)
- {
- putchar(*(c + 1));
- putchar(*c);
- c += 2;
- }
- putchar('\n');
- FREE(hashFile);
+ while (*c)
+ {
+ putchar (*(c + 1));
+ putchar (*c);
+ c += 2;
+ }
+ putchar ('\n');
+ FREE (hashFile);
hashFile = NULL;
}
@@ -332,40 +347,40 @@
* @param argv command line arguments
* @return 0 ok, 1 on error
*/
-int main(int argc, char ** argv) {
+int
+main (int argc, char **argv)
+{
int res;
res = OK;
/* startup */
- ectx = GE_create_context_stderr(NO,
- GE_WARNING | GE_ERROR | GE_FATAL |
- GE_USER | GE_ADMIN | GE_DEVELOPER |
- GE_IMMEDIATE | GE_BULK);
- res = gnunet_parse_options("gnunet-win-tool [OPTIONS] [KEYWORDS]",
- ectx,
- NULL,
- gnunetwinOptions,
- (unsigned int) argc,
- argv);
+ ectx = GE_create_context_stderr (NO,
+ GE_WARNING | GE_ERROR | GE_FATAL |
+ GE_USER | GE_ADMIN | GE_DEVELOPER |
+ GE_IMMEDIATE | GE_BULK);
+ res = gnunet_parse_options ("gnunet-win-tool [OPTIONS] [KEYWORDS]",
+ ectx,
+ NULL,
+ gnunetwinOptions, (unsigned int) argc, argv);
if (res == SYSERR)
- {
- GE_free_context(ectx);
- return -1;
- }
+ {
+ GE_free_context (ectx);
+ return -1;
+ }
if (bPrintAdapters)
- PrintAdapters();
+ PrintAdapters ();
if (bUninstall)
- Uninstall();
+ Uninstall ();
else if (bInstall)
- Install();
+ Install ();
if (bConn)
- IncreaseConnections();
+ IncreaseConnections ();
if (hashFile)
- doHash();
+ doHash ();
- GE_free_context(ectx);
+ GE_free_context (ectx);
return (res == OK) ? 0 : 1;
}
Modified: GNUnet/src/setup/gtk/about.c
===================================================================
--- GNUnet/src/setup/gtk/about.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/gtk/about.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -32,18 +32,16 @@
/**
* This displays an about window
*/
-void on_aboutButton_activatesetup_gtk(GtkWidget * dummy,
- gpointer data) {
- GtkWidget * ad;
- GladeXML * axml;
+void
+on_aboutButton_activatesetup_gtk (GtkWidget * dummy, gpointer data)
+{
+ GtkWidget *ad;
+ GladeXML *axml;
- axml
- = load_xml("aboutdialog");
- ad
- = glade_xml_get_widget(axml,
- "aboutdialog");
- gtk_dialog_run(GTK_DIALOG(ad));
- g_object_unref(axml);
+ axml = load_xml ("aboutdialog");
+ ad = glade_xml_get_widget (axml, "aboutdialog");
+ gtk_dialog_run (GTK_DIALOG (ad));
+ g_object_unref (axml);
}
/* end of about.c */
Modified: GNUnet/src/setup/gtk/gconf.c
===================================================================
--- GNUnet/src/setup/gtk/gconf.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/gtk/gconf.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,7 +33,8 @@
* @brief definition of the entries in the main model for
* the setup tree
*/
-enum {
+enum
+{
SETUP_SECTION,
SETUP_OPTION,
SETUP_TREENODE,
@@ -54,492 +55,452 @@
SETUP_NUM,
};
-static GtkListStore * no_model;
+static GtkListStore *no_model;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static const char * cfg_filename;
+static const char *cfg_filename;
-static void addToTree(GtkTreeStore * model,
- GtkTreeIter * parent,
- struct GNS_Tree * pos) {
+static void
+addToTree (GtkTreeStore * model, GtkTreeIter * parent, struct GNS_Tree *pos)
+{
GtkTreeIter it;
GtkTreeIter it2;
int i;
int j;
int k;
- GtkListStore * cmodel;
+ GtkListStore *cmodel;
char defStr[128];
char valStr[128];
- char * tmp;
+ char *tmp;
size_t tmpl;
- if (! pos->visible)
+ if (!pos->visible)
return;
- gtk_tree_store_append(model,
- &it,
- parent);
- gtk_tree_store_set(model,
- &it,
- SETUP_SECTION, pos->section,
- SETUP_OPTION, pos->option,
- SETUP_TREENODE, pos,
- SETUP_ZERO, 0,
- SETUP_FALSE, FALSE,
- SETUP_TRUE, TRUE,
- SETUP_DWIDTH, 120,
- SETUP_HWIDTH, 400,
- SETUP_WRAP, PANGO_WRAP_WORD_CHAR,
- SETUP_EDIT_BGCOLOR, "yellow",
- SETUP_DEFAULT_VALUE, "",
- SETUP_TEXT_VALUE, "",
- SETUP_COMBO_MODEL, no_model,
- SETUP_TEXT_VIS, FALSE,
- SETUP_COMBO_VIS, FALSE,
- SETUP_DESCRIPTION, pos->description,
- SETUP_HELPTEXT, pos->help,
- -1);
- switch (pos->type & GNS_KindMask) {
- case GNS_Node:
- i = 0;
- while (pos->children[i] != NULL) {
- addToTree(model,
- &it,
- pos->children[i]);
- i++;
- }
- break;
- case GNS_Leaf:
- switch (pos->type & GNS_TypeMask) {
- case GNS_Boolean:
- cmodel = gtk_list_store_new(1,
- G_TYPE_STRING);
- gtk_list_store_insert_with_values(cmodel,
- &it2,
- -1,
- 0, "YES",
- -1);
- gtk_list_store_insert_with_values(cmodel,
- &it2,
- -1,
- 0, "NO",
- -1);
- gtk_tree_store_set(model,
- &it,
- SETUP_COMBO_MODEL, cmodel,
- SETUP_COMBO_VIS, TRUE,
- SETUP_DEFAULT_VALUE, pos->value.Boolean.def ? "YES" : "NO",
- SETUP_TEXT_VALUE, pos->value.Boolean.val ? "YES" : "NO",
- -1);
- break;
- case GNS_String:
- cmodel = gtk_list_store_new(1,
- G_TYPE_STRING);
- gtk_tree_store_set(model,
- &it,
- SETUP_DEFAULT_VALUE, pos->value.String.def,
- SETUP_TEXT_VALUE, pos->value.String.val,
- SETUP_COMBO_MODEL, cmodel,
- -1);
+ gtk_tree_store_append (model, &it, parent);
+ gtk_tree_store_set (model,
+ &it,
+ SETUP_SECTION, pos->section,
+ SETUP_OPTION, pos->option,
+ SETUP_TREENODE, pos,
+ SETUP_ZERO, 0,
+ SETUP_FALSE, FALSE,
+ SETUP_TRUE, TRUE,
+ SETUP_DWIDTH, 120,
+ SETUP_HWIDTH, 400,
+ SETUP_WRAP, PANGO_WRAP_WORD_CHAR,
+ SETUP_EDIT_BGCOLOR, "yellow",
+ SETUP_DEFAULT_VALUE, "",
+ SETUP_TEXT_VALUE, "",
+ SETUP_COMBO_MODEL, no_model,
+ SETUP_TEXT_VIS, FALSE,
+ SETUP_COMBO_VIS, FALSE,
+ SETUP_DESCRIPTION, pos->description,
+ SETUP_HELPTEXT, pos->help, -1);
+ switch (pos->type & GNS_KindMask)
+ {
+ case GNS_Node:
i = 0;
- while (pos->value.String.legalRange[i] != NULL) {
- gtk_list_store_insert_with_values(cmodel,
- &it2,
- -1,
- 0, pos->value.String.legalRange[i],
- -1);
- i++;
- }
- gtk_tree_store_set(model,
- &it,
- SETUP_TEXT_VIS, TRUE,
- SETUP_COMBO_VIS, TRUE,
- -1);
+ while (pos->children[i] != NULL)
+ {
+ addToTree (model, &it, pos->children[i]);
+ i++;
+ }
break;
- case GNS_MC:
- cmodel = gtk_list_store_new(1,
- G_TYPE_STRING);
- gtk_tree_store_set(model,
- &it,
- SETUP_DEFAULT_VALUE, pos->value.String.def,
- SETUP_TEXT_VALUE, pos->value.String.val,
- SETUP_COMBO_MODEL, cmodel,
- -1);
- i = 0;
- j = 1;
- tmpl = 2;
- while (pos->value.String.legalRange[i] != NULL) {
- tmpl += strlen(pos->value.String.legalRange[i]) + 1;
- i++;
- j *= 2;
- }
- tmp = MALLOC(tmpl);
- /* For now, only allow multiple choice for less than 12 entries...
- (10 are needed for applications!) */
- if (i < 12) {
- while (--j >= 0) {
- tmp[0] = '\0';
- for (k=0;k<i;k++) {
- if ((j & (1 << k)) == 0)
- continue;
- strcat(tmp, pos->value.String.legalRange[k]);
- strcat(tmp, " ");
- }
- if (strlen(tmp) > 0)
- tmp[strlen(tmp)-1] = '\0';
- gtk_list_store_insert_with_values(cmodel,
- &it2,
- -1,
- 0, tmp,
- -1);
- }
- } else {
- fprintf(stderr,
- "Too many choices in multiple choice for `%s': %d\n",
- pos->option,
- i);
- GE_BREAK(NULL, 0);
- }
- FREE(tmp);
- gtk_tree_store_set(model,
- &it,
- SETUP_TEXT_VIS, TRUE,
- SETUP_COMBO_VIS, TRUE,
- -1);
+ case GNS_Leaf:
+ switch (pos->type & GNS_TypeMask)
+ {
+ case GNS_Boolean:
+ cmodel = gtk_list_store_new (1, G_TYPE_STRING);
+ gtk_list_store_insert_with_values (cmodel, &it2, -1, 0, "YES", -1);
+ gtk_list_store_insert_with_values (cmodel, &it2, -1, 0, "NO", -1);
+ gtk_tree_store_set (model,
+ &it,
+ SETUP_COMBO_MODEL, cmodel,
+ SETUP_COMBO_VIS, TRUE,
+ SETUP_DEFAULT_VALUE,
+ pos->value.Boolean.def ? "YES" : "NO",
+ SETUP_TEXT_VALUE,
+ pos->value.Boolean.val ? "YES" : "NO", -1);
+ break;
+ case GNS_String:
+ cmodel = gtk_list_store_new (1, G_TYPE_STRING);
+ gtk_tree_store_set (model,
+ &it,
+ SETUP_DEFAULT_VALUE, pos->value.String.def,
+ SETUP_TEXT_VALUE, pos->value.String.val,
+ SETUP_COMBO_MODEL, cmodel, -1);
+ i = 0;
+ while (pos->value.String.legalRange[i] != NULL)
+ {
+ gtk_list_store_insert_with_values (cmodel,
+ &it2,
+ -1,
+ 0,
+ pos->value.String.
+ legalRange[i], -1);
+ i++;
+ }
+ gtk_tree_store_set (model,
+ &it,
+ SETUP_TEXT_VIS, TRUE,
+ SETUP_COMBO_VIS, TRUE, -1);
+ break;
+ case GNS_MC:
+ cmodel = gtk_list_store_new (1, G_TYPE_STRING);
+ gtk_tree_store_set (model,
+ &it,
+ SETUP_DEFAULT_VALUE, pos->value.String.def,
+ SETUP_TEXT_VALUE, pos->value.String.val,
+ SETUP_COMBO_MODEL, cmodel, -1);
+ i = 0;
+ j = 1;
+ tmpl = 2;
+ while (pos->value.String.legalRange[i] != NULL)
+ {
+ tmpl += strlen (pos->value.String.legalRange[i]) + 1;
+ i++;
+ j *= 2;
+ }
+ tmp = MALLOC (tmpl);
+ /* For now, only allow multiple choice for less than 12 entries...
+ (10 are needed for applications!) */
+ if (i < 12)
+ {
+ while (--j >= 0)
+ {
+ tmp[0] = '\0';
+ for (k = 0; k < i; k++)
+ {
+ if ((j & (1 << k)) == 0)
+ continue;
+ strcat (tmp, pos->value.String.legalRange[k]);
+ strcat (tmp, " ");
+ }
+ if (strlen (tmp) > 0)
+ tmp[strlen (tmp) - 1] = '\0';
+ gtk_list_store_insert_with_values (cmodel,
+ &it2, -1, 0, tmp, -1);
+ }
+ }
+ else
+ {
+ fprintf (stderr,
+ "Too many choices in multiple choice for `%s': %d\n",
+ pos->option, i);
+ GE_BREAK (NULL, 0);
+ }
+ FREE (tmp);
+ gtk_tree_store_set (model,
+ &it,
+ SETUP_TEXT_VIS, TRUE,
+ SETUP_COMBO_VIS, TRUE, -1);
+ break;
+ case GNS_SC:
+ cmodel = gtk_list_store_new (1, G_TYPE_STRING);
+ gtk_tree_store_set (model,
+ &it,
+ SETUP_DEFAULT_VALUE, pos->value.String.def,
+ SETUP_TEXT_VALUE, pos->value.String.val,
+ SETUP_COMBO_MODEL, cmodel, -1);
+ i = 0;
+ while (pos->value.String.legalRange[i] != NULL)
+ {
+ gtk_list_store_insert_with_values (cmodel,
+ &it2,
+ -1,
+ 0,
+ pos->value.String.
+ legalRange[i], -1);
+ i++;
+ }
+ gtk_tree_store_set (model, &it, SETUP_COMBO_VIS, TRUE, -1);
+ break;
+ case GNS_Double:
+ cmodel = gtk_list_store_new (1, G_TYPE_STRING);
+ SNPRINTF (defStr, 128, "%f", pos->value.Double.def);
+ SNPRINTF (valStr, 128, "%f", pos->value.Double.val);
+ gtk_list_store_insert_with_values (cmodel, &it2, -1, 0, valStr, -1);
+ if (0 != strcmp (valStr, defStr))
+ {
+ gtk_list_store_insert_with_values (cmodel,
+ &it2, -1, 0, valStr, -1);
+ }
+ gtk_tree_store_set (model,
+ &it,
+ SETUP_DEFAULT_VALUE, defStr,
+ SETUP_TEXT_VALUE, valStr,
+ SETUP_COMBO_VIS, TRUE,
+ SETUP_TEXT_VIS, TRUE,
+ SETUP_COMBO_MODEL, cmodel, -1);
+ break;
+ case GNS_UInt64:
+ cmodel = gtk_list_store_new (1, G_TYPE_STRING);
+ SNPRINTF (defStr, 128, "%llu", pos->value.UInt64.def);
+ SNPRINTF (valStr, 128, "%llu", pos->value.UInt64.val);
+ gtk_list_store_insert_with_values (cmodel, &it2, -1, 0, valStr, -1);
+ if (0 != strcmp (valStr, defStr))
+ {
+ gtk_list_store_insert_with_values (cmodel,
+ &it2, -1, 0, valStr, -1);
+ }
+ gtk_tree_store_set (model,
+ &it,
+ SETUP_DEFAULT_VALUE, defStr,
+ SETUP_COMBO_VIS, TRUE,
+ SETUP_TEXT_VALUE, valStr,
+ SETUP_TEXT_VIS, TRUE,
+ SETUP_COMBO_MODEL, cmodel, -1);
+ break;
+ default:
+ GE_ASSERT (NULL, 0);
+ gtk_tree_store_remove (model, &it);
+ return;
+ }
break;
- case GNS_SC:
- cmodel = gtk_list_store_new(1,
- G_TYPE_STRING);
- gtk_tree_store_set(model,
- &it,
- SETUP_DEFAULT_VALUE, pos->value.String.def,
- SETUP_TEXT_VALUE, pos->value.String.val,
- SETUP_COMBO_MODEL, cmodel,
- -1);
- i = 0;
- while (pos->value.String.legalRange[i] != NULL) {
- gtk_list_store_insert_with_values(cmodel,
- &it2,
- -1,
- 0, pos->value.String.legalRange[i],
- -1);
- i++;
- }
- gtk_tree_store_set(model,
- &it,
- SETUP_COMBO_VIS, TRUE,
- -1);
- break;
- case GNS_Double:
- cmodel = gtk_list_store_new(1,
- G_TYPE_STRING);
- SNPRINTF(defStr, 128, "%f", pos->value.Double.def);
- SNPRINTF(valStr, 128, "%f", pos->value.Double.val);
- gtk_list_store_insert_with_values(cmodel,
- &it2,
- -1,
- 0, valStr,
- -1);
- if (0 != strcmp(valStr, defStr)) {
- gtk_list_store_insert_with_values(cmodel,
- &it2,
- -1,
- 0, valStr,
- -1);
- }
- gtk_tree_store_set(model,
- &it,
- SETUP_DEFAULT_VALUE, defStr,
- SETUP_TEXT_VALUE, valStr,
- SETUP_COMBO_VIS, TRUE,
- SETUP_TEXT_VIS, TRUE,
- SETUP_COMBO_MODEL, cmodel,
- -1);
- break;
- case GNS_UInt64:
- cmodel = gtk_list_store_new(1,
- G_TYPE_STRING);
- SNPRINTF(defStr, 128, "%llu", pos->value.UInt64.def);
- SNPRINTF(valStr, 128, "%llu", pos->value.UInt64.val);
- gtk_list_store_insert_with_values(cmodel,
- &it2,
- -1,
- 0, valStr,
- -1);
- if (0 != strcmp(valStr, defStr)) {
- gtk_list_store_insert_with_values(cmodel,
- &it2,
- -1,
- 0, valStr,
- -1);
- }
- gtk_tree_store_set(model,
- &it,
- SETUP_DEFAULT_VALUE, defStr,
- SETUP_COMBO_VIS, TRUE,
- SETUP_TEXT_VALUE, valStr,
- SETUP_TEXT_VIS, TRUE,
- SETUP_COMBO_MODEL, cmodel,
- -1);
- break;
+ case GNS_Root:
default:
- GE_ASSERT(NULL, 0);
- gtk_tree_store_remove(model,
- &it);
+ GE_ASSERT (NULL, 0);
+ gtk_tree_store_remove (model, &it);
return;
}
- break;
- case GNS_Root:
- default:
- GE_ASSERT(NULL, 0);
- gtk_tree_store_remove(model,
- &it);
- return;
- }
}
-typedef struct {
+typedef struct
+{
unsigned int size;
- char ** paths;
+ char **paths;
} CR_Context;
-static void collectRows(GtkTreeView * tree_view,
- GtkTreePath * path,
- gpointer user_data) {
- CR_Context * ctx = user_data;
+static void
+collectRows (GtkTreeView * tree_view, GtkTreePath * path, gpointer user_data)
+{
+ CR_Context *ctx = user_data;
- GROW(ctx->paths,
- ctx->size,
- ctx->size+1);
- ctx->paths[ctx->size-1] = gtk_tree_path_to_string(path);
+ GROW (ctx->paths, ctx->size, ctx->size + 1);
+ ctx->paths[ctx->size - 1] = gtk_tree_path_to_string (path);
}
-static void updateTreeModel(struct GNS_Context * gns) {
- GtkWidget * treeView;
- GtkTreeStore * model;
- struct GNS_Tree * tree;
+static void
+updateTreeModel (struct GNS_Context *gns)
+{
+ GtkWidget *treeView;
+ GtkTreeStore *model;
+ struct GNS_Tree *tree;
CR_Context crCTX;
- GtkTreePath * path;
+ GtkTreePath *path;
int i;
/* create new model */
- model = gtk_tree_store_new(SETUP_NUM,
- G_TYPE_STRING, /* section */
- G_TYPE_STRING, /* option */
- G_TYPE_POINTER, /* node */
- G_TYPE_INT, /* always 0 */
- G_TYPE_BOOLEAN, /* always FALSE */
- G_TYPE_BOOLEAN, /* always TRUE */
- G_TYPE_INT, /* dwidth */
- G_TYPE_INT, /* hwidth */
- G_TYPE_INT, /* wrap */
- G_TYPE_STRING, /* edit bg color */
- G_TYPE_STRING, /* default value */
- G_TYPE_STRING, /* current text value */
- GTK_TYPE_LIST_STORE, /* combo model */
- G_TYPE_BOOLEAN, /* text visible? */
- G_TYPE_BOOLEAN, /* combo visible? */
- G_TYPE_STRING, /* description */
- G_TYPE_STRING); /* help text */
+ model = gtk_tree_store_new (SETUP_NUM, G_TYPE_STRING, /* section */
+ G_TYPE_STRING, /* option */
+ G_TYPE_POINTER, /* node */
+ G_TYPE_INT, /* always 0 */
+ G_TYPE_BOOLEAN, /* always FALSE */
+ G_TYPE_BOOLEAN, /* always TRUE */
+ G_TYPE_INT, /* dwidth */
+ G_TYPE_INT, /* hwidth */
+ G_TYPE_INT, /* wrap */
+ G_TYPE_STRING, /* edit bg color */
+ G_TYPE_STRING, /* default value */
+ G_TYPE_STRING, /* current text value */
+ GTK_TYPE_LIST_STORE, /* combo model */
+ G_TYPE_BOOLEAN, /* text visible? */
+ G_TYPE_BOOLEAN, /* combo visible? */
+ G_TYPE_STRING, /* description */
+ G_TYPE_STRING); /* help text */
- tree = GNS_get_tree(gns);
+ tree = GNS_get_tree (gns);
i = 0;
- while (tree->children[i] != NULL) {
- addToTree(model,
- NULL,
- tree->children[i]);
- i++;
- }
+ while (tree->children[i] != NULL)
+ {
+ addToTree (model, NULL, tree->children[i]);
+ i++;
+ }
/* capture paths that are currently expanded */
crCTX.size = 0;
crCTX.paths = NULL;
- treeView = lookup_widget("configTreeView");
- gtk_tree_view_map_expanded_rows(GTK_TREE_VIEW(treeView),
- &collectRows,
- &crCTX);
+ treeView = lookup_widget ("configTreeView");
+ gtk_tree_view_map_expanded_rows (GTK_TREE_VIEW (treeView),
+ &collectRows, &crCTX);
/* update model */
- gtk_tree_view_set_model(GTK_TREE_VIEW(treeView),
- GTK_TREE_MODEL(model));
- g_object_unref(model);
+ gtk_tree_view_set_model (GTK_TREE_VIEW (treeView), GTK_TREE_MODEL (model));
+ g_object_unref (model);
/* restore expanded paths */
- for (i=0;i<crCTX.size;i++) {
- path = gtk_tree_path_new_from_string(crCTX.paths[i]);
- gtk_tree_view_expand_row(GTK_TREE_VIEW(treeView),
- path,
- FALSE);
- gtk_tree_path_free(path);
- free(crCTX.paths[i]);
- }
- GROW(crCTX.paths,
- crCTX.size,
- 0);
+ for (i = 0; i < crCTX.size; i++)
+ {
+ path = gtk_tree_path_new_from_string (crCTX.paths[i]);
+ gtk_tree_view_expand_row (GTK_TREE_VIEW (treeView), path, FALSE);
+ gtk_tree_path_free (path);
+ free (crCTX.paths[i]);
+ }
+ GROW (crCTX.paths, crCTX.size, 0);
}
-static void editedTextHandler(GtkCellRendererToggle * rdner,
- gchar * path,
- gchar * new_value,
- gpointer user_data) {
- struct GNS_Context * gns = user_data;
- GtkTreePath * gtk_path;
+static void
+editedTextHandler (GtkCellRendererToggle * rdner,
+ gchar * path, gchar * new_value, gpointer user_data)
+{
+ struct GNS_Context *gns = user_data;
+ GtkTreePath *gtk_path;
GtkTreeIter iter;
- GtkWidget * treeView;
- GtkTreeModel * model;
- char * section;
- char * option;
+ GtkWidget *treeView;
+ GtkTreeModel *model;
+ char *section;
+ char *option;
- treeView = lookup_widget("configTreeView");
- model = gtk_tree_view_get_model(GTK_TREE_VIEW(treeView));
- gtk_path = gtk_tree_path_new_from_string(path);
- if (TRUE != gtk_tree_model_get_iter(model,
- &iter,
- gtk_path)) {
- GE_BREAK(ectx, 0);
- gtk_tree_path_free(gtk_path);
- return;
- }
- gtk_tree_path_free(gtk_path);
- gtk_tree_model_get(model,
- &iter,
- SETUP_SECTION, §ion,
- SETUP_OPTION, &option,
- -1);
- GC_set_configuration_value_string(cfg,
- ectx,
- section,
- option,
- new_value);
- updateTreeModel(gns);
- free(section);
- free(option);
+ treeView = lookup_widget ("configTreeView");
+ model = gtk_tree_view_get_model (GTK_TREE_VIEW (treeView));
+ gtk_path = gtk_tree_path_new_from_string (path);
+ if (TRUE != gtk_tree_model_get_iter (model, &iter, gtk_path))
+ {
+ GE_BREAK (ectx, 0);
+ gtk_tree_path_free (gtk_path);
+ return;
+ }
+ gtk_tree_path_free (gtk_path);
+ gtk_tree_model_get (model,
+ &iter,
+ SETUP_SECTION, §ion, SETUP_OPTION, &option, -1);
+ GC_set_configuration_value_string (cfg, ectx, section, option, new_value);
+ updateTreeModel (gns);
+ free (section);
+ free (option);
}
-static void initTreeView(struct GNS_Context * gns) {
- GtkWidget * treeView;
- GtkTreeViewColumn * column;
- GtkCellRenderer * renderer;
+static void
+initTreeView (struct GNS_Context *gns)
+{
+ GtkWidget *treeView;
+ GtkTreeViewColumn *column;
+ GtkCellRenderer *renderer;
int col;
- treeView = lookup_widget("configTreeView");
+ treeView = lookup_widget ("configTreeView");
- renderer = gtk_cell_renderer_text_new();
- col = gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(treeView),
- -1,
- _("Description"),
- renderer,
- "text", SETUP_DESCRIPTION,
- "wrap-width", SETUP_DWIDTH,
- "wrap-mode", SETUP_WRAP,
- NULL);
- column = gtk_tree_view_get_column(GTK_TREE_VIEW(treeView),
- col - 1);
- gtk_tree_view_column_set_resizable(column, TRUE);
+ renderer = gtk_cell_renderer_text_new ();
+ col = gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeView),
+ -1,
+ _("Description"),
+ renderer,
+ "text",
+ SETUP_DESCRIPTION,
+ "wrap-width",
+ SETUP_DWIDTH,
+ "wrap-mode", SETUP_WRAP,
+ NULL);
+ column = gtk_tree_view_get_column (GTK_TREE_VIEW (treeView), col - 1);
+ gtk_tree_view_column_set_resizable (column, TRUE);
- renderer = gtk_cell_renderer_combo_new();
- g_signal_connect(renderer,
- "edited",
- G_CALLBACK(&editedTextHandler),
- gns);
- col = gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(treeView),
- -1,
- _("Value"),
- renderer,
- "text", SETUP_TEXT_VALUE,
- "visible", SETUP_COMBO_VIS,
- "model", SETUP_COMBO_MODEL,
- "text-column", SETUP_ZERO,
- "has-entry", SETUP_TEXT_VIS,
- "background", SETUP_EDIT_BGCOLOR,
- "background-set", SETUP_TRUE,
- "editable", SETUP_TRUE,
- "wrap-width", SETUP_DWIDTH,
- "wrap-mode", SETUP_WRAP,
- NULL);
- column = gtk_tree_view_get_column(GTK_TREE_VIEW(treeView),
- col - 1);
- gtk_tree_view_column_set_resizable(column, TRUE);
+ renderer = gtk_cell_renderer_combo_new ();
+ g_signal_connect (renderer, "edited", G_CALLBACK (&editedTextHandler), gns);
+ col = gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeView),
+ -1,
+ _("Value"),
+ renderer,
+ "text", SETUP_TEXT_VALUE,
+ "visible",
+ SETUP_COMBO_VIS, "model",
+ SETUP_COMBO_MODEL,
+ "text-column",
+ SETUP_ZERO, "has-entry",
+ SETUP_TEXT_VIS,
+ "background",
+ SETUP_EDIT_BGCOLOR,
+ "background-set",
+ SETUP_TRUE, "editable",
+ SETUP_TRUE, "wrap-width",
+ SETUP_DWIDTH,
+ "wrap-mode", SETUP_WRAP,
+ NULL);
+ column = gtk_tree_view_get_column (GTK_TREE_VIEW (treeView), col - 1);
+ gtk_tree_view_column_set_resizable (column, TRUE);
- renderer = gtk_cell_renderer_text_new();
- col = gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(treeView),
- -1,
- _("Default"),
- renderer,
- "text", SETUP_DEFAULT_VALUE,
- "wrap-width", SETUP_DWIDTH,
- "wrap-mode", SETUP_WRAP,
- NULL);
- column = gtk_tree_view_get_column(GTK_TREE_VIEW(treeView),
- col - 1);
- gtk_tree_view_column_set_resizable(column, TRUE);
+ renderer = gtk_cell_renderer_text_new ();
+ col = gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeView),
+ -1,
+ _("Default"),
+ renderer,
+ "text",
+ SETUP_DEFAULT_VALUE,
+ "wrap-width",
+ SETUP_DWIDTH,
+ "wrap-mode", SETUP_WRAP,
+ NULL);
+ column = gtk_tree_view_get_column (GTK_TREE_VIEW (treeView), col - 1);
+ gtk_tree_view_column_set_resizable (column, TRUE);
- renderer = gtk_cell_renderer_text_new();
- col = gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(treeView),
- -1,
- _("Help"),
- renderer,
- "text", SETUP_HELPTEXT,
- "wrap-width", SETUP_HWIDTH,
- "wrap-mode", SETUP_WRAP,
- NULL);
- column = gtk_tree_view_get_column(GTK_TREE_VIEW(treeView),
- col - 1);
- gtk_tree_view_column_set_resizable(column, TRUE);
+ renderer = gtk_cell_renderer_text_new ();
+ col = gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeView),
+ -1,
+ _("Help"),
+ renderer,
+ "text", SETUP_HELPTEXT,
+ "wrap-width",
+ SETUP_HWIDTH,
+ "wrap-mode", SETUP_WRAP,
+ NULL);
+ column = gtk_tree_view_get_column (GTK_TREE_VIEW (treeView), col - 1);
+ gtk_tree_view_column_set_resizable (column, TRUE);
- renderer = gtk_cell_renderer_text_new();
- col = gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(treeView),
- -1,
- _("Section"),
- renderer,
- "text", SETUP_SECTION,
- NULL);
- column = gtk_tree_view_get_column(GTK_TREE_VIEW(treeView),
- col - 1);
- gtk_tree_view_column_set_resizable(column, TRUE);
+ renderer = gtk_cell_renderer_text_new ();
+ col = gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeView),
+ -1,
+ _("Section"),
+ renderer,
+ "text", SETUP_SECTION,
+ NULL);
+ column = gtk_tree_view_get_column (GTK_TREE_VIEW (treeView), col - 1);
+ gtk_tree_view_column_set_resizable (column, TRUE);
- renderer = gtk_cell_renderer_text_new();
- col = gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(treeView),
- -1,
- _("Option"),
- renderer,
- "text", SETUP_OPTION,
- NULL);
- column = gtk_tree_view_get_column(GTK_TREE_VIEW(treeView),
- col - 1);
- gtk_tree_view_column_set_resizable(column, TRUE);
+ renderer = gtk_cell_renderer_text_new ();
+ col = gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeView),
+ -1,
+ _("Option"),
+ renderer,
+ "text", SETUP_OPTION,
+ NULL);
+ column = gtk_tree_view_get_column (GTK_TREE_VIEW (treeView), col - 1);
+ gtk_tree_view_column_set_resizable (column, TRUE);
}
/**
* User requested save manually. Save configuration.
*/
-void on_saveButton_activatesetup_gtk() {
- GtkWidget * dialog;
+void
+on_saveButton_activatesetup_gtk ()
+{
+ GtkWidget *dialog;
- if (0 == GC_write_configuration(cfg,
- cfg_filename)) {
- dialog = gtk_message_dialog_new(NULL,
- GTK_DIALOG_MODAL,
- GTK_MESSAGE_INFO,
- GTK_BUTTONS_OK,
- _("Configuration saved."));
- gtk_dialog_run(GTK_DIALOG(dialog));
- gtk_widget_destroy(dialog);
- } else {
- dialog = gtk_message_dialog_new(NULL,
- GTK_DIALOG_MODAL,
- GTK_MESSAGE_ERROR,
- GTK_BUTTONS_OK,
- _("Failed to save configuration."));
- gtk_dialog_run(GTK_DIALOG(dialog));
- gtk_widget_destroy(dialog);
- }
+ if (0 == GC_write_configuration (cfg, cfg_filename))
+ {
+ dialog = gtk_message_dialog_new (NULL,
+ GTK_DIALOG_MODAL,
+ GTK_MESSAGE_INFO,
+ GTK_BUTTONS_OK,
+ _("Configuration saved."));
+ gtk_dialog_run (GTK_DIALOG (dialog));
+ gtk_widget_destroy (dialog);
+ }
+ else
+ {
+ dialog = gtk_message_dialog_new (NULL,
+ GTK_DIALOG_MODAL,
+ GTK_MESSAGE_ERROR,
+ GTK_BUTTONS_OK,
+ _("Failed to save configuration."));
+ gtk_dialog_run (GTK_DIALOG (dialog));
+ gtk_widget_destroy (dialog);
+ }
}
@@ -550,104 +511,107 @@
*
* @return TRUE to NOT exit (i.e. user hits cancel on save YES/NO/CANCEL).
*/
-gboolean on_main_window_delete_eventsetup_gtk() {
- GtkWidget * dialog;
+gboolean
+on_main_window_delete_eventsetup_gtk ()
+{
+ GtkWidget *dialog;
gint ret;
- if (GC_test_dirty(cfg)) {
- dialog = gtk_message_dialog_new(NULL,
- GTK_DIALOG_MODAL,
- GTK_MESSAGE_QUESTION,
- GTK_BUTTONS_YES_NO,
- _("Configuration changed. Save?"));
- ret = gtk_dialog_run(GTK_DIALOG(dialog));
- gtk_widget_destroy(dialog);
- switch (ret) {
- case GTK_RESPONSE_YES:
- if (0 != GC_write_configuration(cfg,
- cfg_filename)) {
- dialog = gtk_message_dialog_new(NULL,
- GTK_DIALOG_MODAL,
- GTK_MESSAGE_ERROR,
- GTK_BUTTONS_OK,
- _("Error saving configuration."));
- gtk_dialog_run(GTK_DIALOG(dialog));
- gtk_widget_destroy(dialog);
- }
- return FALSE;
- case GTK_RESPONSE_NO:
- return FALSE;
- case GTK_RESPONSE_CANCEL:
- default:
- return TRUE;
+ if (GC_test_dirty (cfg))
+ {
+ dialog = gtk_message_dialog_new (NULL,
+ GTK_DIALOG_MODAL,
+ GTK_MESSAGE_QUESTION,
+ GTK_BUTTONS_YES_NO,
+ _("Configuration changed. Save?"));
+ ret = gtk_dialog_run (GTK_DIALOG (dialog));
+ gtk_widget_destroy (dialog);
+ switch (ret)
+ {
+ case GTK_RESPONSE_YES:
+ if (0 != GC_write_configuration (cfg, cfg_filename))
+ {
+ dialog = gtk_message_dialog_new (NULL,
+ GTK_DIALOG_MODAL,
+ GTK_MESSAGE_ERROR,
+ GTK_BUTTONS_OK,
+ _
+ ("Error saving
configuration."));
+ gtk_dialog_run (GTK_DIALOG (dialog));
+ gtk_widget_destroy (dialog);
+ }
+ return FALSE;
+ case GTK_RESPONSE_NO:
+ return FALSE;
+ case GTK_RESPONSE_CANCEL:
+ default:
+ return TRUE;
+ }
}
- }
return FALSE;
}
/**
* We're really exiting. Final cleanup code (in GTK).
*/
-void gtk_main_quitsetup_gtk() {
- gtk_main_quit();
+void
+gtk_main_quitsetup_gtk ()
+{
+ gtk_main_quit ();
}
-int gconf_main_post_init(struct PluginHandle * self,
- struct GE_Context * e,
- struct GC_Configuration * c,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon) {
- GtkWidget * mainWindow;
+int
+gconf_main_post_init (struct PluginHandle *self,
+ struct GE_Context *e,
+ struct GC_Configuration *c,
+ struct GNS_Context *gns,
+ const char *filename, int is_daemon)
+{
+ GtkWidget *mainWindow;
cfg = c;
ectx = e;
cfg_filename = filename;
- no_model = gtk_list_store_new(1,
- G_TYPE_STRING);
- setLibrary(self);
- mainWindow = get_xml("setupWindow");
- updateTreeModel(gns);
- initTreeView(gns);
- gtk_window_maximize(GTK_WINDOW(mainWindow));
- gtk_widget_show(mainWindow);
- gdk_threads_enter();
+ no_model = gtk_list_store_new (1, G_TYPE_STRING);
+ setLibrary (self);
+ mainWindow = get_xml ("setupWindow");
+ updateTreeModel (gns);
+ initTreeView (gns);
+ gtk_window_maximize (GTK_WINDOW (mainWindow));
+ gtk_widget_show (mainWindow);
+ gdk_threads_enter ();
#ifdef WINDOWS
- SetCursor(LoadCursor(NULL, IDC_ARROW));
+ SetCursor (LoadCursor (NULL, IDC_ARROW));
#endif
- gtk_main();
- gdk_threads_leave();
- destroyMainXML();
- setLibrary(NULL);
- g_object_unref(G_OBJECT(no_model));
+ gtk_main ();
+ gdk_threads_leave ();
+ destroyMainXML ();
+ setLibrary (NULL);
+ g_object_unref (G_OBJECT (no_model));
no_model = NULL;
return 0;
}
/* Main */
-int gconf_mainsetup_gtk(int argc,
- const char ** argv,
- struct PluginHandle * self,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon) {
- g_thread_init(NULL);
- gtk_init(&argc, (char***) &argv);
+int
+gconf_mainsetup_gtk (int argc,
+ const char **argv,
+ struct PluginHandle *self,
+ struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct GNS_Context *gns,
+ const char *filename, int is_daemon)
+{
+ g_thread_init (NULL);
+ gtk_init (&argc, (char ***) &argv);
#if ENABLE_NLS
- bind_textdomain_codeset(PACKAGE, "UTF-8"); /* for gtk */
+ bind_textdomain_codeset (PACKAGE, "UTF-8"); /* for gtk */
#endif
#ifdef WINDOWS
- FreeConsole();
+ FreeConsole ();
#endif
- return gconf_main_post_init(self,
- ectx,
- cfg,
- gns,
- filename,
- is_daemon);
+ return gconf_main_post_init (self, ectx, cfg, gns, filename, is_daemon);
}
Modified: GNUnet/src/setup/gtk/gconf.h
===================================================================
--- GNUnet/src/setup/gtk/gconf.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/gtk/gconf.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -28,20 +28,18 @@
#ifndef GNUNET_SETUP_GCONF_H
#define GNUNET_SETUP_GCONF_H
-int gconf_mainsetup_gtk(int argc,
- const char ** argv,
- struct PluginHandle * self,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon);
+int gconf_mainsetup_gtk (int argc,
+ const char **argv,
+ struct PluginHandle *self,
+ struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct GNS_Context *gns,
+ const char *filename, int is_daemon);
-int gconf_main_post_init(struct PluginHandle * lib,
- struct GE_Context * e,
- struct GC_Configuration * c,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon);
+int gconf_main_post_init (struct PluginHandle *lib,
+ struct GE_Context *e,
+ struct GC_Configuration *c,
+ struct GNS_Context *gns,
+ const char *filename, int is_daemon);
#endif
Modified: GNUnet/src/setup/gtk/glade_support.c
===================================================================
--- GNUnet/src/setup/gtk/glade_support.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/setup/gtk/glade_support.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -25,112 +25,115 @@
/**
* Handle to the dynamic library (which contains this code)
*/
-static struct PluginHandle * library;
+static struct PluginHandle *library;
/**
* Current glade handle.
*/
-static GladeXML * mainXML_;
+static GladeXML *mainXML_;
-GladeXML * getMainXML() {
+GladeXML *
+getMainXML ()
+{
return mainXML_;
}
-void destroyMainXML() {
- GE_ASSERT(NULL, mainXML_ != NULL);
- g_object_unref(mainXML_);
+void
+destroyMainXML ()
+{
+ GE_ASSERT (NULL, mainXML_ != NULL);
+ g_object_unref (mainXML_);
mainXML_ = NULL;
}
-char * get_glade_filename() {
- char * path;
- char * gladeFile;
+char *
+get_glade_filename ()
+{
+ char *path;
+ char *gladeFile;
- path = os_get_installation_path(IPK_DATADIR);
- gladeFile = MALLOC(strlen(path) + 20);
- strcpy(gladeFile, path);
- strcat(gladeFile, "gnunet-setup.glade");
- FREE(path);
+ path = os_get_installation_path (IPK_DATADIR);
+ gladeFile = MALLOC (strlen (path) + 20);
+ strcpy (gladeFile, path);
+ strcat (gladeFile, "gnunet-setup.glade");
+ FREE (path);
return gladeFile;
}
-static void connector(const gchar *handler_name,
- GObject *object,
- const gchar *signal_name,
- const gchar *signal_data,
- GObject *connect_object,
- gboolean after,
- gpointer user_data) {
- GladeXML * xml = user_data;
- void * method;
+static void
+connector (const gchar * handler_name,
+ GObject * object,
+ const gchar * signal_name,
+ const gchar * signal_data,
+ GObject * connect_object, gboolean after, gpointer user_data)
+{
+ GladeXML *xml = user_data;
+ void *method;
- GE_ASSERT(NULL, xml != NULL);
- method = os_plugin_resolve_function(library,
- handler_name,
- YES);
+ GE_ASSERT (NULL, xml != NULL);
+ method = os_plugin_resolve_function (library, handler_name, YES);
if (method == NULL)
return;
- glade_xml_signal_connect(xml,
- handler_name,
- (GCallback) method);
+ glade_xml_signal_connect (xml, handler_name, (GCallback) method);
}
-GladeXML * load_xml(const char * dialog_name) {
- char * gladeFile;
- GladeXML * ret;
+GladeXML *
+load_xml (const char *dialog_name)
+{
+ char *gladeFile;
+ GladeXML *ret;
- gladeFile = get_glade_filename();
- ret = glade_xml_new(gladeFile,
- dialog_name,
- PACKAGE_NAME);
+ gladeFile = get_glade_filename ();
+ ret = glade_xml_new (gladeFile, dialog_name, PACKAGE_NAME);
if (ret == NULL)
- GE_DIE_STRERROR_FILE(NULL,
- GE_USER | GE_ADMIN | GE_FATAL | GE_IMMEDIATE,
- "open",
- gladeFile);
- FREE(gladeFile);
- glade_xml_signal_autoconnect_full(ret, &connector, ret);
+ GE_DIE_STRERROR_FILE (NULL,
+ GE_USER | GE_ADMIN | GE_FATAL | GE_IMMEDIATE,
+ "open", gladeFile);
+ FREE (gladeFile);
+ glade_xml_signal_autoconnect_full (ret, &connector, ret);
return ret;
}
-GtkWidget * lookup_widget(const char * name) {
- return glade_xml_get_widget(mainXML_, name);
+GtkWidget *
+lookup_widget (const char *name)
+{
+ return glade_xml_get_widget (mainXML_, name);
}
-GtkWidget * get_xml(const char * dialog_name) {
- mainXML_ = load_xml(dialog_name);
- return glade_xml_get_widget(mainXML_,
- dialog_name);
+GtkWidget *
+get_xml (const char *dialog_name)
+{
+ mainXML_ = load_xml (dialog_name);
+ return glade_xml_get_widget (mainXML_, dialog_name);
}
/**
* Helper function to just show a simple dialog
* that requires no initialization.
*/
-void showDialog(const char * name) {
- GtkWidget * msgSave;
- char * gladeFile;
- GladeXML * myXML;
+void
+showDialog (const char *name)
+{
+ GtkWidget *msgSave;
+ char *gladeFile;
+ GladeXML *myXML;
- gladeFile = get_glade_filename();
- myXML = glade_xml_new(gladeFile,
- name,
- PACKAGE_NAME);
+ gladeFile = get_glade_filename ();
+ myXML = glade_xml_new (gladeFile, name, PACKAGE_NAME);
if (mainXML_ == NULL)
- GE_DIE_STRERROR_FILE(NULL,
- GE_USER | GE_ADMIN | GE_FATAL | GE_IMMEDIATE,
- "open",
- gladeFile);
- FREE(gladeFile);
- glade_xml_signal_autoconnect_full(myXML, &connector, myXML);
- msgSave = glade_xml_get_widget(myXML,
- name);
- gtk_widget_show(msgSave);
- g_object_unref(myXML);
+ GE_DIE_STRERROR_FILE (NULL,
+ GE_USER | GE_ADMIN | GE_FATAL | GE_IMMEDIATE,
+ "open", gladeFile);
+ FREE (gladeFile);
+ glade_xml_signal_autoconnect_full (myXML, &connector, myXML);
+ msgSave = glade_xml_get_widget (myXML, name);
+ gtk_widget_show (msgSave);
+ g_object_unref (myXML);
}
-void setLibrary(struct PluginHandle * lib) {
+void
+setLibrary (struct PluginHandle *lib)
+{
library = lib;
}
-
Modified: GNUnet/src/setup/gtk/glade_support.h
===================================================================
--- GNUnet/src/setup/gtk/glade_support.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/setup/gtk/glade_support.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -27,22 +27,22 @@
#define mainXML getMainXML()
-GladeXML * getMainXML(void);
+GladeXML *getMainXML (void);
-void destroyMainXML(void);
+void destroyMainXML (void);
-void setLibrary(struct PluginHandle * lib);
+void setLibrary (struct PluginHandle *lib);
-GtkWidget * get_xml(const char * dialog_name);
+GtkWidget *get_xml (const char *dialog_name);
-GladeXML * load_xml(const char * dialog_name);
+GladeXML *load_xml (const char *dialog_name);
/**
* Helper function to just show a simple dialog
* that requires no initialization.
*/
-void showDialog(const char * name);
+void showDialog (const char *name);
-GtkWidget * lookup_widget(const char * name);
+GtkWidget *lookup_widget (const char *name);
#endif
Modified: GNUnet/src/setup/gtk/wizard_gtk.c
===================================================================
--- GNUnet/src/setup/gtk/wizard_gtk.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/gtk/wizard_gtk.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -39,7 +39,7 @@
/**
* Current open window.
*/
-static GtkWidget * curwnd;
+static GtkWidget *curwnd;
static int doOpenEnhConfigurator = 0;
@@ -47,9 +47,9 @@
static int doUpdate = YES;
-static char * user_name = NULL;
+static char *user_name = NULL;
-static char * group_name = NULL;
+static char *group_name = NULL;
static struct GC_Configuration *editCfg = NULL;
@@ -66,31 +66,36 @@
* Destroy the current window (without exiting).
* Also unrefs the current glade XML context.
*/
-static void destroyCurrentWindow() {
- GE_ASSERT(err_ctx, mainXML != NULL);
- GE_ASSERT(err_ctx, curwnd != NULL);
+static void
+destroyCurrentWindow ()
+{
+ GE_ASSERT (err_ctx, mainXML != NULL);
+ GE_ASSERT (err_ctx, curwnd != NULL);
quit = 0;
- gtk_widget_destroy(curwnd);
+ gtk_widget_destroy (curwnd);
curwnd = NULL;
- destroyMainXML();
+ destroyMainXML ();
quit = 1;
}
-void on_assi_destroysetup_gtk (GtkObject * object,
- gpointer user_data) {
+void
+on_assi_destroysetup_gtk (GtkObject * object, gpointer user_data)
+{
/* Don't terminate if the user just clicked "Next" */
if (quit)
- gtk_main_quit();
+ gtk_main_quit ();
}
-struct insert_nic_cls {
- GtkWidget * cmbNIC;
+struct insert_nic_cls
+{
+ GtkWidget *cmbNIC;
int nic_item_count;
};
-void on_cmbNIC_changedsetup_gtk (GtkComboBox * combobox,
- gpointer user_data) {
+void
+on_cmbNIC_changedsetup_gtk (GtkComboBox * combobox, gpointer user_data)
+{
GtkTreeIter iter;
GValue val;
char *entry;
@@ -102,357 +107,340 @@
#endif
GtkTreeModel *model;
- gtk_combo_box_get_active_iter(combobox, &iter);
- model = gtk_combo_box_get_model(combobox);
- memset(&val, 0, sizeof(val));
- gtk_tree_model_get_value(model, &iter, 0, &val);
- entry = (char *) g_value_get_string(&val);
+ gtk_combo_box_get_active_iter (combobox, &iter);
+ model = gtk_combo_box_get_model (combobox);
+ memset (&val, 0, sizeof (val));
+ gtk_tree_model_get_value (model, &iter, 0, &val);
+ entry = (char *) g_value_get_string (&val);
#ifdef MINGW
- idx = strrchr(entry, '-');
- if (! idx)
+ idx = strrchr (entry, '-');
+ if (!idx)
return;
idx += 2;
dst = nic;
- while(*idx)
+ while (*idx)
*dst++ = *idx++;
dst[-1] = 0;
#else
nic = entry;
#endif
- GC_set_configuration_value_string(editCfg,
- err_ctx,
- "NETWORK",
- "INTERFACE",
- nic);
- GC_set_configuration_value_string(editCfg,
- err_ctx,
- "LOAD",
- "INTERFACES",
- nic);
+ GC_set_configuration_value_string (editCfg,
+ err_ctx, "NETWORK", "INTERFACE", nic);
+ GC_set_configuration_value_string (editCfg,
+ err_ctx, "LOAD", "INTERFACES", nic);
}
-static int insert_nic(const char *name,
- int defaultNIC,
- void * cls) {
+static int
+insert_nic (const char *name, int defaultNIC, void *cls)
+{
gchar *utf8_name;
gsize unused;
- struct insert_nic_cls * inc = cls;
- GtkWidget * cmbNIC = inc->cmbNIC;
+ struct insert_nic_cls *inc = cls;
+ GtkWidget *cmbNIC = inc->cmbNIC;
- utf8_name = g_locale_to_utf8(name, -1, NULL, &unused, NULL);
+ utf8_name = g_locale_to_utf8 (name, -1, NULL, &unused, NULL);
if (!utf8_name)
- utf8_name = STRDUP(_("(unknown connection)"));
+ utf8_name = STRDUP (_("(unknown connection)"));
- gtk_combo_box_append_text(GTK_COMBO_BOX(cmbNIC), utf8_name);
- free(utf8_name);
- defaultNIC = wiz_is_nic_default(editCfg, name, defaultNIC);
+ gtk_combo_box_append_text (GTK_COMBO_BOX (cmbNIC), utf8_name);
+ free (utf8_name);
+ defaultNIC = wiz_is_nic_default (editCfg, name, defaultNIC);
if (defaultNIC)
- gtk_combo_box_set_active(GTK_COMBO_BOX(cmbNIC), inc->nic_item_count);
+ gtk_combo_box_set_active (GTK_COMBO_BOX (cmbNIC), inc->nic_item_count);
return OK;
}
-void load_step2setup_gtk(GtkButton * button,
- gpointer prev_window) {
- GtkWidget * entIP;
- GtkWidget * chkFW;
+void
+load_step2setup_gtk (GtkButton * button, gpointer prev_window)
+{
+ GtkWidget *entIP;
+ GtkWidget *chkFW;
GtkTreeIter iter;
GtkListStore *model;
struct insert_nic_cls cls;
- char * val;
+ char *val;
- destroyCurrentWindow();
- curwnd = get_xml("assi_step2");
- cls.cmbNIC = lookup_widget("cmbNIC");
- GE_ASSERT(err_ctx, cls.cmbNIC != NULL);
+ destroyCurrentWindow ();
+ curwnd = get_xml ("assi_step2");
+ cls.cmbNIC = lookup_widget ("cmbNIC");
+ GE_ASSERT (err_ctx, cls.cmbNIC != NULL);
cls.nic_item_count = 0;
- model = gtk_list_store_new(1, G_TYPE_STRING);
- gtk_combo_box_set_model(GTK_COMBO_BOX(cls.cmbNIC),
- GTK_TREE_MODEL(model));
- gtk_combo_box_entry_set_text_column(GTK_COMBO_BOX_ENTRY(cls.cmbNIC),
- 0);
+ model = gtk_list_store_new (1, G_TYPE_STRING);
+ gtk_combo_box_set_model (GTK_COMBO_BOX (cls.cmbNIC),
+ GTK_TREE_MODEL (model));
+ gtk_combo_box_entry_set_text_column (GTK_COMBO_BOX_ENTRY (cls.cmbNIC), 0);
- os_list_network_interfaces(err_ctx, &insert_nic, &cls);
+ os_list_network_interfaces (err_ctx, &insert_nic, &cls);
- if (cls.nic_item_count != 0) {
- GC_get_configuration_value_string(editCfg,
- "NETWORK",
- "INTERFACE",
- "eth0",
- &val);
- gtk_combo_box_append_text(GTK_COMBO_BOX(cls.cmbNIC), val);
- gtk_tree_model_get_iter_first(GTK_TREE_MODEL(model),
- &iter);
- gtk_combo_box_set_active_iter(GTK_COMBO_BOX(cls.cmbNIC), &iter);
- on_cmbNIC_changedsetup_gtk(GTK_COMBO_BOX(cls.cmbNIC), NULL);
- FREE(val);
- }
+ if (cls.nic_item_count != 0)
+ {
+ GC_get_configuration_value_string (editCfg,
+ "NETWORK",
+ "INTERFACE", "eth0", &val);
+ gtk_combo_box_append_text (GTK_COMBO_BOX (cls.cmbNIC), val);
+ gtk_tree_model_get_iter_first (GTK_TREE_MODEL (model), &iter);
+ gtk_combo_box_set_active_iter (GTK_COMBO_BOX (cls.cmbNIC), &iter);
+ on_cmbNIC_changedsetup_gtk (GTK_COMBO_BOX (cls.cmbNIC), NULL);
+ FREE (val);
+ }
- gtk_widget_set_usize(cls.cmbNIC, 10, -1);
+ gtk_widget_set_usize (cls.cmbNIC, 10, -1);
- entIP = lookup_widget("entIP");
- GC_get_configuration_value_string(editCfg,
- "NETWORK",
- "IP",
- "",
- &val);
- gtk_entry_set_text(GTK_ENTRY(entIP), val);
- FREE(val);
+ entIP = lookup_widget ("entIP");
+ GC_get_configuration_value_string (editCfg, "NETWORK", "IP", "", &val);
+ gtk_entry_set_text (GTK_ENTRY (entIP), val);
+ FREE (val);
- chkFW = lookup_widget("chkFW");
- gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(chkFW),
- GC_get_configuration_value_yesno(editCfg,
- "NAT",
- "LIMITED",
- NO) == YES);
+ chkFW = lookup_widget ("chkFW");
+ gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (chkFW),
+ GC_get_configuration_value_yesno (editCfg,
+ "NAT",
+ "LIMITED",
+ NO) == YES);
- gtk_widget_show(curwnd);
+ gtk_widget_show (curwnd);
}
-void load_step3setup_gtk(GtkButton * button,
- gpointer prev_window) {
- GtkWidget * entUp;
- GtkWidget * entDown;
- GtkWidget * radGNUnet;
- GtkWidget * radShare;
- GtkWidget * entCPU;
- char * val;
+void
+load_step3setup_gtk (GtkButton * button, gpointer prev_window)
+{
+ GtkWidget *entUp;
+ GtkWidget *entDown;
+ GtkWidget *radGNUnet;
+ GtkWidget *radShare;
+ GtkWidget *entCPU;
+ char *val;
- destroyCurrentWindow();
- curwnd = get_xml("assi_step3");
- entUp = lookup_widget("entUp");
- entDown = lookup_widget("entDown");
- radGNUnet = lookup_widget("radGNUnet");
- radShare = lookup_widget("radShare");
- entCPU = lookup_widget("entCPU");
- GC_get_configuration_value_string(editCfg,
- "LOAD",
- "MAXNETUPBPSTOTAL",
- "50000",
- &val);
- gtk_entry_set_text(GTK_ENTRY(entUp), val);
- FREE(val);
- GC_get_configuration_value_string(editCfg,
- "LOAD",
- "MAXNETDOWNBPSTOTAL",
- "50000",
- &val);
- gtk_entry_set_text(GTK_ENTRY(entDown), val);
- FREE(val);
+ destroyCurrentWindow ();
+ curwnd = get_xml ("assi_step3");
+ entUp = lookup_widget ("entUp");
+ entDown = lookup_widget ("entDown");
+ radGNUnet = lookup_widget ("radGNUnet");
+ radShare = lookup_widget ("radShare");
+ entCPU = lookup_widget ("entCPU");
+ GC_get_configuration_value_string (editCfg,
+ "LOAD",
+ "MAXNETUPBPSTOTAL", "50000", &val);
+ gtk_entry_set_text (GTK_ENTRY (entUp), val);
+ FREE (val);
+ GC_get_configuration_value_string (editCfg,
+ "LOAD",
+ "MAXNETDOWNBPSTOTAL", "50000", &val);
+ gtk_entry_set_text (GTK_ENTRY (entDown), val);
+ FREE (val);
gtk_toggle_button_set_active
(GTK_TOGGLE_BUTTON
- ((GC_get_configuration_value_yesno(editCfg,
- "LOAD",
- "BASICLIMITING",
- NO) == YES)
- ? radGNUnet
- : radShare ),
- TRUE);
- GC_get_configuration_value_string(editCfg,
- "LOAD",
- "MAXCPULOAD",
- "50",
- &val);
- gtk_entry_set_text(GTK_ENTRY(entCPU), val);
- FREE(val);
+ ((GC_get_configuration_value_yesno (editCfg,
+ "LOAD",
+ "BASICLIMITING",
+ NO) == YES)
+ ? radGNUnet : radShare), TRUE);
+ GC_get_configuration_value_string (editCfg,
+ "LOAD", "MAXCPULOAD", "50", &val);
+ gtk_entry_set_text (GTK_ENTRY (entCPU), val);
+ FREE (val);
- gtk_widget_show(curwnd);
+ gtk_widget_show (curwnd);
}
-void load_step4setup_gtk(GtkButton * button,
- gpointer prev_window) {
- GtkWidget * entUser;
- GtkWidget * entGroup;
- char * uname = NULL;
- char * gname = NULL;
+void
+load_step4setup_gtk (GtkButton * button, gpointer prev_window)
+{
+ GtkWidget *entUser;
+ GtkWidget *entGroup;
+ char *uname = NULL;
+ char *gname = NULL;
int cap;
- destroyCurrentWindow();
- curwnd = get_xml("assi_step4");
- entUser = lookup_widget("entUser");
- entGroup = lookup_widget("entGroup");
+ destroyCurrentWindow ();
+ curwnd = get_xml ("assi_step4");
+ entUser = lookup_widget ("entUser");
+ entGroup = lookup_widget ("entGroup");
- if (NULL != user_name) {
- GC_get_configuration_value_string(editCfg,
- "GNUNETD",
- "USER",
- "gnunet",
- &uname);
- }
+ if (NULL != user_name)
+ {
+ GC_get_configuration_value_string (editCfg,
+ "GNUNETD", "USER", "gnunet", &uname);
+ }
- if (NULL != group_name) {
- GC_get_configuration_value_string(editCfg,
- "GNUNETD",
- "GROUP",
- "gnunet",
- &gname);
- }
+ if (NULL != group_name)
+ {
+ GC_get_configuration_value_string (editCfg,
+ "GNUNETD",
+ "GROUP", "gnunet", &gname);
+ }
#ifndef MINGW
- if (NULL == uname || strlen(uname) == 0) {
- if((geteuid() == 0) || (NULL != getpwnam("gnunet")))
- user_name = STRDUP("gnunet");
- else {
- uname = getenv("USER");
- if (uname != NULL)
- user_name = STRDUP(uname);
+ if (NULL == uname || strlen (uname) == 0)
+ {
+ if ((geteuid () == 0) || (NULL != getpwnam ("gnunet")))
+ user_name = STRDUP ("gnunet");
else
- user_name = NULL;
+ {
+ uname = getenv ("USER");
+ if (uname != NULL)
+ user_name = STRDUP (uname);
+ else
+ user_name = NULL;
+ }
}
- } else {
- user_name = STRDUP(uname);
- }
- if(NULL == gname || strlen(gname) == 0)
- {
- struct group * grp;
- if((geteuid() == 0) || (NULL != getgrnam("gnunet")))
- group_name = STRDUP("gnunet");
- else {
- grp = getgrgid(getegid());
- if ( (grp != NULL) &&
- (grp->gr_name != NULL) )
- group_name = STRDUP(grp->gr_name);
+ else
+ {
+ user_name = STRDUP (uname);
+ }
+ if (NULL == gname || strlen (gname) == 0)
+ {
+ struct group *grp;
+ if ((geteuid () == 0) || (NULL != getgrnam ("gnunet")))
+ group_name = STRDUP ("gnunet");
else
- group_name = NULL;
+ {
+ grp = getgrgid (getegid ());
+ if ((grp != NULL) && (grp->gr_name != NULL))
+ group_name = STRDUP (grp->gr_name);
+ else
+ group_name = NULL;
+ }
}
- } else {
- group_name = STRDUP(gname);
- }
+ else
+ {
+ group_name = STRDUP (gname);
+ }
#else
- if (NULL == uname || strlen(uname) == 0)
- user_name = STRDUP("");
+ if (NULL == uname || strlen (uname) == 0)
+ user_name = STRDUP ("");
else
- user_name = STRDUP(uname);
- if (NULL == gname || strlen(gname) == 0)
- group_name = STRDUP("");
+ user_name = STRDUP (uname);
+ if (NULL == gname || strlen (gname) == 0)
+ group_name = STRDUP ("");
else
- group_name = STRDUP(gname);
+ group_name = STRDUP (gname);
#endif
if (user_name != NULL)
- gtk_entry_set_text(GTK_ENTRY(entUser), user_name);
+ gtk_entry_set_text (GTK_ENTRY (entUser), user_name);
if (group_name != NULL)
- gtk_entry_set_text(GTK_ENTRY(entGroup), group_name);
- cap = os_modify_autostart(err_ctx,
- 1,
- 1,
- NULL,
- NULL,
- NULL);
- gtk_widget_set_sensitive(entUser, cap);
+ gtk_entry_set_text (GTK_ENTRY (entGroup), group_name);
+ cap = os_modify_autostart (err_ctx, 1, 1, NULL, NULL, NULL);
+ gtk_widget_set_sensitive (entUser, cap);
#ifdef WINDOWS
cap = FALSE;
#endif
- gtk_widget_set_sensitive(entGroup, cap);
+ gtk_widget_set_sensitive (entGroup, cap);
- gtk_widget_show(curwnd);
+ gtk_widget_show (curwnd);
}
-void load_step5setup_gtk(GtkButton * button,
- gpointer prev_window) {
- GtkWidget * chkMigr;
- GtkWidget * entQuota;
- GtkWidget * chkEnh;
- GtkWidget * chkStart;
- char * val;
+void
+load_step5setup_gtk (GtkButton * button, gpointer prev_window)
+{
+ GtkWidget *chkMigr;
+ GtkWidget *entQuota;
+ GtkWidget *chkEnh;
+ GtkWidget *chkStart;
+ char *val;
- destroyCurrentWindow();
- curwnd = get_xml("assi_step5");
- entQuota = lookup_widget("entQuota");
- chkMigr = lookup_widget("chkMigr");
- chkStart = lookup_widget("chkStart");
- chkEnh = lookup_widget("chkEnh");
+ destroyCurrentWindow ();
+ curwnd = get_xml ("assi_step5");
+ entQuota = lookup_widget ("entQuota");
+ chkMigr = lookup_widget ("chkMigr");
+ chkStart = lookup_widget ("chkStart");
+ chkEnh = lookup_widget ("chkEnh");
- GC_get_configuration_value_string(editCfg,
- "FS",
- "QUOTA",
- "1024",
- &val);
- gtk_entry_set_text(GTK_ENTRY(entQuota), val);
- FREE(val);
+ GC_get_configuration_value_string (editCfg, "FS", "QUOTA", "1024", &val);
+ gtk_entry_set_text (GTK_ENTRY (entQuota), val);
+ FREE (val);
- gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(chkMigr),
- GC_get_configuration_value_yesno(editCfg,
- "FS",
- "ACTIVEMIGRATION",
- YES) == YES);
+ gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (chkMigr),
+ GC_get_configuration_value_yesno (editCfg,
+ "FS",
+
"ACTIVEMIGRATION",
+ YES) ==
+ YES);
- if (os_modify_autostart(err_ctx, 1, 1, NULL, NULL, NULL))
- gtk_widget_set_sensitive(chkStart, TRUE);
+ if (os_modify_autostart (err_ctx, 1, 1, NULL, NULL, NULL))
+ gtk_widget_set_sensitive (chkStart, TRUE);
- gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(chkStart),
- GC_get_configuration_value_yesno(editCfg, "GNUNETD", "AUTOSTART", NO) ==
YES);
+ gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (chkStart),
+ GC_get_configuration_value_yesno (editCfg,
+ "GNUNETD",
+ "AUTOSTART",
+ NO) == YES);
if (doOpenEnhConfigurator)
- gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(chkEnh), 1);
- gtk_widget_show(curwnd);
+ gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (chkEnh), 1);
+ gtk_widget_show (curwnd);
}
-void do_destroy_widgetsetup_gtk(GtkButton * button,
- gpointer user_data) {
- GtkWidget * msgSaveFailed = user_data;
- gtk_widget_destroy(msgSaveFailed);
+void
+do_destroy_widgetsetup_gtk (GtkButton * button, gpointer user_data)
+{
+ GtkWidget *msgSaveFailed = user_data;
+ gtk_widget_destroy (msgSaveFailed);
}
-static void showErr(const char * prefix,
- const char * error) {
- GtkWidget * dialog;
+static void
+showErr (const char *prefix, const char *error)
+{
+ GtkWidget *dialog;
char *err;
- err = MALLOC(strlen(prefix) + strlen(error) + 2);
- sprintf(err,
- "%s %s",
- prefix,
- error);
+ err = MALLOC (strlen (prefix) + strlen (error) + 2);
+ sprintf (err, "%s %s", prefix, error);
- dialog = gtk_message_dialog_new(NULL,
- GTK_DIALOG_MODAL,
- GTK_MESSAGE_ERROR,
- GTK_BUTTONS_OK,
- err);
- FREE(err);
- gtk_dialog_run(GTK_DIALOG(dialog));
- gtk_widget_destroy(dialog);
+ dialog = gtk_message_dialog_new (NULL,
+ GTK_DIALOG_MODAL,
+ GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, err);
+ FREE (err);
+ gtk_dialog_run (GTK_DIALOG (dialog));
+ gtk_widget_destroy (dialog);
}
-static int save_conf() {
- char * err;
- const char * prefix;
+static int
+save_conf ()
+{
+ char *err;
+ const char *prefix;
- if (GC_write_configuration(editCfg, cfg_fn)) {
- prefix = _("Unable to save configuration file `%s':");
+ if (GC_write_configuration (editCfg, cfg_fn))
+ {
+ prefix = _("Unable to save configuration file `%s':");
- err = MALLOC(strlen(cfg_fn) + strlen(prefix) + 1);
- sprintf(err, prefix, cfg_fn);
- showErr(err, STRERROR(errno));
- FREE(err);
- return SYSERR;
- }
+ err = MALLOC (strlen (cfg_fn) + strlen (prefix) + 1);
+ sprintf (err, prefix, cfg_fn);
+ showErr (err, STRERROR (errno));
+ FREE (err);
+ return SYSERR;
+ }
return OK;
}
-void on_abort_clickedsetup_gtk(GtkButton * button,
- gpointer user_data) {
- GtkWidget * dialog;
+void
+on_abort_clickedsetup_gtk (GtkButton * button, gpointer user_data)
+{
+ GtkWidget *dialog;
int ok, ret;
ok = OK;
- dialog = gtk_message_dialog_new(NULL,
- GTK_DIALOG_MODAL,
- GTK_MESSAGE_QUESTION,
- GTK_BUTTONS_YES_NO,
- _("Do you want to save the new configuration?"));
- ret = gtk_dialog_run(GTK_DIALOG(dialog));
- gtk_widget_destroy(dialog);
- switch (ret) {
+ dialog = gtk_message_dialog_new (NULL,
+ GTK_DIALOG_MODAL,
+ GTK_MESSAGE_QUESTION,
+ GTK_BUTTONS_YES_NO,
+ _
+ ("Do you want to save the new
configuration?"));
+ ret = gtk_dialog_run (GTK_DIALOG (dialog));
+ gtk_widget_destroy (dialog);
+ switch (ret)
+ {
case GTK_RESPONSE_YES:
- ok = save_conf();
+ ok = save_conf ();
break;
case GTK_RESPONSE_NO:
ok = OK;
@@ -460,261 +448,265 @@
case GTK_RESPONSE_CANCEL:
default:
ok = NO;
- }
+ }
if (ok)
- {
- quit = 1;
- gtk_widget_destroy(curwnd);
- }
+ {
+ quit = 1;
+ gtk_widget_destroy (curwnd);
+ }
}
-void on_finish_clickedsetup_gtk (GtkButton * button,
- gpointer user_data) {
- char * gup;
- char * bin;
+void
+on_finish_clickedsetup_gtk (GtkButton * button, gpointer user_data)
+{
+ char *gup;
+ char *bin;
if (doAutoStart && (user_name != NULL))
- if (!wiz_createGroupUser(group_name,
- user_name)) {
+ if (!wiz_createGroupUser (group_name, user_name))
+ {
#ifndef MINGW
- showErr(_("Unable to create user account:"),
- STRERROR(errno));
+ showErr (_("Unable to create user account:"), STRERROR (errno));
#endif
- return;
- }
+ return;
+ }
- if (wiz_autostartService(doAutoStart,
- user_name,
- group_name) != OK) {
+ if (wiz_autostartService (doAutoStart, user_name, group_name) != OK)
+ {
#ifndef MINGW
- showErr(_("Unable to change startup process:"),
- STRERROR(errno));
+ showErr (_("Unable to change startup process:"), STRERROR (errno));
#endif
- }
+ }
- if (OK != save_conf())
+ if (OK != save_conf ())
return;
- if (doUpdate) {
- bin = os_get_installation_path(IPK_BINDIR);
- gup = MALLOC(strlen(bin) + 30 + strlen(cfg_fn));
- strcpy(gup, bin);
- FREE(bin);
- strcat(gup, "/gnunet-update -c ");
- strcat(gup, cfg_fn);
- if (system(gup) != 0)
- showErr(_("Running gnunet-update failed.\n"
- "This maybe due to insufficient permissions, please check your
configuration.\n"
- "Finally, run gnunet-update manually."), "");
- FREE(gup);
- }
- gtk_widget_destroy(curwnd);
+ if (doUpdate)
+ {
+ bin = os_get_installation_path (IPK_BINDIR);
+ gup = MALLOC (strlen (bin) + 30 + strlen (cfg_fn));
+ strcpy (gup, bin);
+ FREE (bin);
+ strcat (gup, "/gnunet-update -c ");
+ strcat (gup, cfg_fn);
+ if (system (gup) != 0)
+ showErr (_("Running gnunet-update failed.\n"
+ "This maybe due to insufficient permissions, please check
your configuration.\n"
+ "Finally, run gnunet-update manually."), "");
+ FREE (gup);
+ }
+ gtk_widget_destroy (curwnd);
}
-void on_updateFailedOK_clickedsetup_gtk (GtkButton * button,
- gpointer user_data) {
- GtkWidget * dialog = user_data;
- gtk_widget_destroy(dialog);
+void
+on_updateFailedOK_clickedsetup_gtk (GtkButton * button, gpointer user_data)
+{
+ GtkWidget *dialog = user_data;
+ gtk_widget_destroy (dialog);
}
-void on_entIP_changedsetup_gtk (GtkEditable * editable,
- gpointer user_data) {
- gchar * ret;
+void
+on_entIP_changedsetup_gtk (GtkEditable * editable, gpointer user_data)
+{
+ gchar *ret;
- ret = gtk_editable_get_chars(editable, 0, -1);
- GC_set_configuration_value_string(editCfg,
- err_ctx,
- "NETWORK",
- "IP",
- ret);
- g_free(ret);
+ ret = gtk_editable_get_chars (editable, 0, -1);
+ GC_set_configuration_value_string (editCfg, err_ctx, "NETWORK", "IP", ret);
+ g_free (ret);
}
-void on_chkFW_toggledsetup_gtk (GtkToggleButton * togglebutton,
- gpointer user_data) {
- GC_set_configuration_value_choice(editCfg, err_ctx, "LIMITED", "NAT",
- gtk_toggle_button_get_active(togglebutton) ? "YES" : "NO");
+void
+on_chkFW_toggledsetup_gtk (GtkToggleButton * togglebutton, gpointer user_data)
+{
+ GC_set_configuration_value_choice (editCfg, err_ctx, "LIMITED", "NAT",
+ gtk_toggle_button_get_active
+ (togglebutton) ? "YES" : "NO");
}
-void on_entUp_changedsetup_gtk (GtkEditable * editable,
- gpointer user_data) {
- gchar * ret;
+void
+on_entUp_changedsetup_gtk (GtkEditable * editable, gpointer user_data)
+{
+ gchar *ret;
- ret = gtk_editable_get_chars(editable, 0, -1);
- GC_set_configuration_value_string(editCfg,
- err_ctx,
- "LOAD",
- "MAXNETUPBPSTOTAL",
- ret);
- g_free(ret);
+ ret = gtk_editable_get_chars (editable, 0, -1);
+ GC_set_configuration_value_string (editCfg,
+ err_ctx,
+ "LOAD", "MAXNETUPBPSTOTAL", ret);
+ g_free (ret);
}
-void on_entDown_changedsetup_gtk (GtkEditable * editable,
- gpointer user_data) {
- gchar * ret;
+void
+on_entDown_changedsetup_gtk (GtkEditable * editable, gpointer user_data)
+{
+ gchar *ret;
- ret = gtk_editable_get_chars(editable, 0, -1);
- GC_set_configuration_value_string(editCfg,
- err_ctx,
- "LOAD",
- "MAXNETDOWNBPSTOTAL",
- ret);
- g_free(ret);
+ ret = gtk_editable_get_chars (editable, 0, -1);
+ GC_set_configuration_value_string (editCfg,
+ err_ctx,
+ "LOAD", "MAXNETDOWNBPSTOTAL", ret);
+ g_free (ret);
}
-void on_radGNUnet_toggledsetup_gtk(GtkToggleButton * togglebutton,
- gpointer user_data) {
- GC_set_configuration_value_choice(editCfg,
- err_ctx,
- "LOAD",
- "BASICLIMITING",
- gtk_toggle_button_get_active(togglebutton)
- ? "YES"
- : "NO");
+void
+on_radGNUnet_toggledsetup_gtk (GtkToggleButton * togglebutton,
+ gpointer user_data)
+{
+ GC_set_configuration_value_choice (editCfg,
+ err_ctx,
+ "LOAD",
+ "BASICLIMITING",
+ gtk_toggle_button_get_active
+ (togglebutton) ? "YES" : "NO");
}
-void on_radShare_toggledsetup_gtk (GtkToggleButton * togglebutton,
- gpointer user_data) {
- GC_set_configuration_value_choice(editCfg,
- err_ctx,
- "LOAD",
- "BASICLIMITING",
- gtk_toggle_button_get_active(togglebutton)
- ? "NO"
- : "YES");
+void
+on_radShare_toggledsetup_gtk (GtkToggleButton * togglebutton,
+ gpointer user_data)
+{
+ GC_set_configuration_value_choice (editCfg,
+ err_ctx,
+ "LOAD",
+ "BASICLIMITING",
+ gtk_toggle_button_get_active
+ (togglebutton) ? "NO" : "YES");
}
-void on_entCPU_changedsetup_gtk (GtkEditable * editable,
- gpointer user_data) {
- gchar * ret;
+void
+on_entCPU_changedsetup_gtk (GtkEditable * editable, gpointer user_data)
+{
+ gchar *ret;
int num;
- ret = gtk_editable_get_chars(editable, 0, -1);
- num = atoi(ret);
- GC_set_configuration_value_number(editCfg, err_ctx, "LOAD", "MAXCPULOAD",
num);
- g_free(ret);
+ ret = gtk_editable_get_chars (editable, 0, -1);
+ num = atoi (ret);
+ GC_set_configuration_value_number (editCfg, err_ctx, "LOAD", "MAXCPULOAD",
+ num);
+ g_free (ret);
}
-void on_chkMigr_toggledsetup_gtk (GtkToggleButton * togglebutton,
- gpointer user_data) {
- GC_set_configuration_value_choice(editCfg,
- err_ctx,
- "FS",
- "ACTIVEMIGRATION",
- gtk_toggle_button_get_active(togglebutton)
- ? "YES"
- : "NO");
+void
+on_chkMigr_toggledsetup_gtk (GtkToggleButton * togglebutton,
+ gpointer user_data)
+{
+ GC_set_configuration_value_choice (editCfg,
+ err_ctx,
+ "FS",
+ "ACTIVEMIGRATION",
+ gtk_toggle_button_get_active
+ (togglebutton) ? "YES" : "NO");
}
-void on_entQuota_changedsetup_gtk (GtkEditable * editable,
- gpointer user_data) {
- gchar * ret;
+void
+on_entQuota_changedsetup_gtk (GtkEditable * editable, gpointer user_data)
+{
+ gchar *ret;
- ret = gtk_editable_get_chars(editable, 0, -1);
- GC_set_configuration_value_string(editCfg, err_ctx, "FS", "QUOTA", ret);
- g_free(ret);
+ ret = gtk_editable_get_chars (editable, 0, -1);
+ GC_set_configuration_value_string (editCfg, err_ctx, "FS", "QUOTA", ret);
+ g_free (ret);
}
-void on_chkStart_toggledsetup_gtk (GtkToggleButton * togglebutton,
- gpointer user_data) {
- doAutoStart = gtk_toggle_button_get_active(togglebutton);
- GC_set_configuration_value_choice(editCfg,
- err_ctx,
- "AUTOSTART",
- "GNUNETD",
- doAutoStart ? "YES" : "NO");
+void
+on_chkStart_toggledsetup_gtk (GtkToggleButton * togglebutton,
+ gpointer user_data)
+{
+ doAutoStart = gtk_toggle_button_get_active (togglebutton);
+ GC_set_configuration_value_choice (editCfg,
+ err_ctx,
+ "AUTOSTART",
+ "GNUNETD", doAutoStart ? "YES" : "NO");
}
-void on_chkEnh_toggledsetup_gtk (GtkToggleButton * togglebutton,
- gpointer user_data) {
- doOpenEnhConfigurator = gtk_toggle_button_get_active(togglebutton);
+void
+on_chkEnh_toggledsetup_gtk (GtkToggleButton * togglebutton,
+ gpointer user_data)
+{
+ doOpenEnhConfigurator = gtk_toggle_button_get_active (togglebutton);
}
-void on_chkUpdate_toggledsetup_gtk(GtkToggleButton * togglebutton,
- gpointer user_data) {
- doUpdate = gtk_toggle_button_get_active(togglebutton);
+void
+on_chkUpdate_toggledsetup_gtk (GtkToggleButton * togglebutton,
+ gpointer user_data)
+{
+ doUpdate = gtk_toggle_button_get_active (togglebutton);
}
-void on_entUser_changedsetup_gtk (GtkEditable * editable,
- gpointer user_data) {
- gchar * ret;
+void
+on_entUser_changedsetup_gtk (GtkEditable * editable, gpointer user_data)
+{
+ gchar *ret;
- ret = gtk_editable_get_chars(editable, 0, -1);
- GE_ASSERT(err_ctx, ret != NULL);
- GC_set_configuration_value_string(editCfg, err_ctx, "GNUNETD", "USER", ret);
- FREENONNULL(user_name);
- if (strlen(ret) != 0)
- user_name = STRDUP(ret);
+ ret = gtk_editable_get_chars (editable, 0, -1);
+ GE_ASSERT (err_ctx, ret != NULL);
+ GC_set_configuration_value_string (editCfg, err_ctx, "GNUNETD", "USER",
+ ret);
+ FREENONNULL (user_name);
+ if (strlen (ret) != 0)
+ user_name = STRDUP (ret);
else
user_name = NULL;
- g_free(ret);
+ g_free (ret);
}
-void on_entGroup_changedsetup_gtk (GtkEditable * editable,
- gpointer user_data) {
- gchar * ret;
+void
+on_entGroup_changedsetup_gtk (GtkEditable * editable, gpointer user_data)
+{
+ gchar *ret;
- FREENONNULL(group_name);
- ret = gtk_editable_get_chars(editable, 0, -1);
- GE_ASSERT(err_ctx, ret != NULL);
- GC_set_configuration_value_string(editCfg,
- err_ctx,
- "GNUNETD",
- "GROUP",
- ret);
- if (strlen(ret) != 0)
- group_name = STRDUP(ret);
+ FREENONNULL (group_name);
+ ret = gtk_editable_get_chars (editable, 0, -1);
+ GE_ASSERT (err_ctx, ret != NULL);
+ GC_set_configuration_value_string (editCfg,
+ err_ctx, "GNUNETD", "GROUP", ret);
+ if (strlen (ret) != 0)
+ group_name = STRDUP (ret);
else
group_name = NULL;
- g_free(ret);
+ g_free (ret);
}
-int gtk_wizard_mainsetup_gtk(int argc,
- char * const * argv,
- struct PluginHandle * self,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon) {
- GE_ASSERT(ectx, is_daemon);
- g_thread_init(NULL);
- gtk_init(&argc, (char ***) &argv);
+int
+gtk_wizard_mainsetup_gtk (int argc,
+ char *const *argv,
+ struct PluginHandle *self,
+ struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct GNS_Context *gns,
+ const char *filename, int is_daemon)
+{
+ GE_ASSERT (ectx, is_daemon);
+ g_thread_init (NULL);
+ gtk_init (&argc, (char ***) &argv);
#ifdef ENABLE_NLS
- bind_textdomain_codeset(PACKAGE, "UTF-8"); /* for gtk */
+ bind_textdomain_codeset (PACKAGE, "UTF-8"); /* for gtk */
#endif
#ifdef WINDOWS
- FreeConsole();
+ FreeConsole ();
#endif
editCfg = cfg;
err_ctx = ectx;
cfg_fn = filename;
daemon_config = is_daemon;
- setLibrary(self);
- curwnd = get_xml("assi_step1");
- gtk_widget_show(curwnd);
- gdk_threads_enter();
- gtk_main();
- gdk_threads_leave();
- destroyMainXML();
+ setLibrary (self);
+ curwnd = get_xml ("assi_step1");
+ gtk_widget_show (curwnd);
+ gdk_threads_enter ();
+ gtk_main ();
+ gdk_threads_leave ();
+ destroyMainXML ();
if (doOpenEnhConfigurator)
- gconf_main_post_init(self,
- ectx,
- cfg,
- gns,
- filename,
- is_daemon);
- FREENONNULL(user_name);
- FREENONNULL(group_name);
- setLibrary(NULL);
+ gconf_main_post_init (self, ectx, cfg, gns, filename, is_daemon);
+ FREENONNULL (user_name);
+ FREENONNULL (group_name);
+ setLibrary (NULL);
return 0;
}
Modified: GNUnet/src/setup/gtk/wizard_gtk.h
===================================================================
--- GNUnet/src/setup/gtk/wizard_gtk.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/gtk/wizard_gtk.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -31,13 +31,12 @@
#include "gnunet_setup_lib.h"
#include "wizard_util.h"
-int gtk_wizard_mainsetup_gtk(int argc,
- char * const * argv,
- struct PluginHandle * self,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon);
+int gtk_wizard_mainsetup_gtk (int argc,
+ char *const *argv,
+ struct PluginHandle *self,
+ struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct GNS_Context *gns,
+ const char *filename, int is_daemon);
#endif
Modified: GNUnet/src/setup/lib/gns.c
===================================================================
--- GNUnet/src/setup/lib/gns.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/lib/gns.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -30,46 +30,50 @@
#include "tree.h"
-typedef struct GNS_TCL {
+typedef struct GNS_TCL
+{
GNS_TreeChangeListener l;
- void * c;
+ void *c;
- struct GNS_TCL * next;
+ struct GNS_TCL *next;
} GNS_TCL;
/**
* @brief gnunet setup context
*/
-struct GNS_Context {
+struct GNS_Context
+{
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
- struct GNS_Tree * root;
+ struct GNS_Tree *root;
- GNS_TCL * listeners;
+ GNS_TCL *listeners;
unsigned int in_notify;
};
-static void notify_listeners(void * ctx,
- struct GNS_Tree * tree) {
- struct GNS_Context * g = ctx;
- GNS_TCL * lpos;
+static void
+notify_listeners (void *ctx, struct GNS_Tree *tree)
+{
+ struct GNS_Context *g = ctx;
+ GNS_TCL *lpos;
if (g->in_notify > 0)
- return; /* do not do recursive notifications! */
+ return; /* do not do recursive notifications! */
g->in_notify++;
lpos = g->listeners;
- while (lpos != NULL) {
- lpos->l(tree, lpos->c);
- lpos = lpos->next;
- }
+ while (lpos != NULL)
+ {
+ lpos->l (tree, lpos->c);
+ lpos = lpos->next;
+ }
g->in_notify--;
}
@@ -83,166 +87,177 @@
* @return 0 if the change is ok, -1 if the change must be
* refused
*/
-int configChangeListener(void * ctx,
- struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option) {
- struct GNS_Context * g = ctx;
- struct GNS_Tree * pos;
+int
+configChangeListener (void *ctx,
+ struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section, const char *option)
+{
+ struct GNS_Context *g = ctx;
+ struct GNS_Tree *pos;
- pos = tree_lookup(g->root,
- section,
- option);
- if (pos == NULL) {
- GE_LOG(g->ectx,
- GE_DEVELOPER | GE_BULK | GE_ERROR,
- "Tree lookup for unknown option `%s' in section `%s'!\n",
- option,
- section);
- return 0; /* or refuse? */
- }
+ pos = tree_lookup (g->root, section, option);
+ if (pos == NULL)
+ {
+ GE_LOG (g->ectx,
+ GE_DEVELOPER | GE_BULK | GE_ERROR,
+ "Tree lookup for unknown option `%s' in section `%s'!\n",
+ option, section);
+ return 0; /* or refuse? */
+ }
/* first, check if value is valid */
- if ((pos->type & GNS_KindMask) != GNS_Leaf) {
- GE_LOG(g->ectx,
- GE_DEVELOPER | GE_BULK | GE_ERROR,
- "Tree value change for non-leaf option `%s' in section `%s'!\n",
- option,
- section);
- return 0;
- }
- switch (pos->type & GNS_TypeMask) {
- case GNS_Boolean: {
- int val;
-
- val = GC_get_configuration_value_yesno(cfg,
- section,
- option,
- pos->value.Boolean.def);
- if (val == SYSERR) {
- return SYSERR;
+ if ((pos->type & GNS_KindMask) != GNS_Leaf)
+ {
+ GE_LOG (g->ectx,
+ GE_DEVELOPER | GE_BULK | GE_ERROR,
+ "Tree value change for non-leaf option `%s' in section `%s'!\n",
+ option, section);
+ return 0;
}
- pos->value.Boolean.val = val;
- break;
- }
- case GNS_UInt64: {
- unsigned long long val;
+ switch (pos->type & GNS_TypeMask)
+ {
+ case GNS_Boolean:
+ {
+ int val;
- if (SYSERR == GC_get_configuration_value_number(cfg,
- section,
- option,
- pos->value.UInt64.min,
- pos->value.UInt64.max,
- pos->value.UInt64.def,
- &val)) {
- return SYSERR;
- }
- pos->value.UInt64.val = val;
- break;
- }
- case GNS_Double: {
- char * s;
- double d;
+ val = GC_get_configuration_value_yesno (cfg,
+ section,
+ option,
+ pos->value.Boolean.def);
+ if (val == SYSERR)
+ {
+ return SYSERR;
+ }
+ pos->value.Boolean.val = val;
+ break;
+ }
+ case GNS_UInt64:
+ {
+ unsigned long long val;
- s = NULL;
- GC_get_configuration_value_string(cfg,
- section,
- option,
- NULL,
- &s);
- if (s == NULL) {
- pos->value.Double.val = pos->value.Double.def;
- } else {
- if (1 != sscanf(s, "%lf", &d)) {
- GE_LOG(ectx,
- GE_USER | GE_ERROR | GE_IMMEDIATE,
- "`%s' is not a valid double-precision floating point number.\n",
- s);
- FREE(s);
- return SYSERR;
+ if (SYSERR == GC_get_configuration_value_number (cfg,
+ section,
+ option,
+ pos->value.UInt64.
+ min,
+ pos->value.UInt64.
+ max,
+ pos->value.UInt64.
+ def, &val))
+ {
+ return SYSERR;
+ }
+ pos->value.UInt64.val = val;
+ break;
}
- pos->value.Double.val = d;
- FREE(s);
- }
- break;
- }
- case GNS_String:
- case GNS_MC: {
- char * val;
+ case GNS_Double:
+ {
+ char *s;
+ double d;
- if (SYSERR == GC_get_configuration_value_string(cfg,
- section,
- option,
- pos->value.String.def,
- &val))
- return SYSERR;
- FREE(pos->value.String.val);
- pos->value.String.val = val;
- break;
- }
- case GNS_SC: {
- const char * ival;
+ s = NULL;
+ GC_get_configuration_value_string (cfg, section, option, NULL, &s);
+ if (s == NULL)
+ {
+ pos->value.Double.val = pos->value.Double.def;
+ }
+ else
+ {
+ if (1 != sscanf (s, "%lf", &d))
+ {
+ GE_LOG (ectx,
+ GE_USER | GE_ERROR | GE_IMMEDIATE,
+ "`%s' is not a valid double-precision floating point
number.\n",
+ s);
+ FREE (s);
+ return SYSERR;
+ }
+ pos->value.Double.val = d;
+ FREE (s);
+ }
+ break;
+ }
+ case GNS_String:
+ case GNS_MC:
+ {
+ char *val;
- if (SYSERR == GC_get_configuration_value_choice(cfg,
- section,
- option,
- (const char**)
pos->value.String.legalRange,
- pos->value.String.def,
- &ival))
- return SYSERR;
- FREE(pos->value.String.val);
- pos->value.String.val = STRDUP(ival);
- break;
- }
- }
+ if (SYSERR == GC_get_configuration_value_string (cfg,
+ section,
+ option,
+ pos->value.String.
+ def, &val))
+ return SYSERR;
+ FREE (pos->value.String.val);
+ pos->value.String.val = val;
+ break;
+ }
+ case GNS_SC:
+ {
+ const char *ival;
+ if (SYSERR == GC_get_configuration_value_choice (cfg,
+ section,
+ option,
+ (const char **) pos->
+ value.String.
+ legalRange,
+ pos->value.String.
+ def, &ival))
+ return SYSERR;
+ FREE (pos->value.String.val);
+ pos->value.String.val = STRDUP (ival);
+ break;
+ }
+ }
+
/* notify client about value change */
- notify_listeners(g, pos);
+ notify_listeners (g, pos);
/* allow tree to update visibility */
- tree_notify_change(cfg,
- ¬ify_listeners,
- g,
- g->ectx,
- g->root,
- pos);
+ tree_notify_change (cfg, ¬ify_listeners, g, g->ectx, g->root, pos);
return 0;
}
-static void free_tree(struct GNS_Tree * t) {
+static void
+free_tree (struct GNS_Tree *t)
+{
int i;
i = 0;
- while (t->children[i] != NULL) {
- free_tree(t->children[i]);
- i++;
- }
- switch (t->type & GNS_TypeMask) {
- case 0:
- break; /* no value */
- case GNS_Boolean:
- case GNS_UInt64:
- case GNS_Double:
- break; /* nothing to free */
- case GNS_String:
- case GNS_MC:
- case GNS_SC:
- i = 0;
- while (t->value.String.legalRange[i] != NULL) {
- FREE(t->value.String.legalRange[i]);
+ while (t->children[i] != NULL)
+ {
+ free_tree (t->children[i]);
i++;
}
- FREE(t->value.String.legalRange);
- FREE(t->value.String.val);
- break;
- default:
- GE_BREAK(NULL, 0);
- break;
- }
- FREE(t->description);
- FREE(t->help);
- FREE(t->children);
- FREE(t);
+ switch (t->type & GNS_TypeMask)
+ {
+ case 0:
+ break; /* no value */
+ case GNS_Boolean:
+ case GNS_UInt64:
+ case GNS_Double:
+ break; /* nothing to free */
+ case GNS_String:
+ case GNS_MC:
+ case GNS_SC:
+ i = 0;
+ while (t->value.String.legalRange[i] != NULL)
+ {
+ FREE (t->value.String.legalRange[i]);
+ i++;
+ }
+ FREE (t->value.String.legalRange);
+ FREE (t->value.String.val);
+ break;
+ default:
+ GE_BREAK (NULL, 0);
+ break;
+ }
+ FREE (t->description);
+ FREE (t->help);
+ FREE (t->children);
+ FREE (t);
}
@@ -256,31 +271,32 @@
* @return NULL on error (i.e. specification file not found)
*/
struct GNS_Context *
-GNS_load_specification(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * specification) {
- struct GNS_Context * ctx;
- struct GNS_Tree * root;
+GNS_load_specification (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *specification)
+{
+ struct GNS_Context *ctx;
+ struct GNS_Tree *root;
- root = tree_parse(ectx, specification);
+ root = tree_parse (ectx, specification);
if (root == NULL)
return NULL;
- ctx = MALLOC(sizeof(struct GNS_Context));
+ ctx = MALLOC (sizeof (struct GNS_Context));
ctx->ectx = ectx;
ctx->cfg = cfg;
ctx->root = root;
ctx->in_notify = 0;
- if (-1 == GC_attach_change_listener(cfg,
- &configChangeListener,
- ctx)) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("Configuration does not satisfy constraints of configuration
specification file `%s'!\n"),
- specification);
- FREE(ctx);
- free_tree(root);
- return NULL;
- }
+ if (-1 == GC_attach_change_listener (cfg, &configChangeListener, ctx))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _
+ ("Configuration does not satisfy constraints of configuration
specification file `%s'!\n"),
+ specification);
+ FREE (ctx);
+ free_tree (root);
+ return NULL;
+ }
return ctx;
}
@@ -293,7 +309,8 @@
* @return NULL on error
*/
struct GNS_Tree *
-GNS_get_tree(struct GNS_Context * ctx) {
+GNS_get_tree (struct GNS_Context *ctx)
+{
return ctx->root;
}
@@ -301,13 +318,12 @@
* Free resources associated with the GNS context.
*/
void
-GNS_free_specification(struct GNS_Context * ctx) {
- GC_detach_change_listener(ctx->cfg,
- &configChangeListener,
- ctx);
- free_tree(ctx->root);
- GE_ASSERT(ctx->ectx, ctx->listeners == NULL);
- FREE(ctx);
+GNS_free_specification (struct GNS_Context *ctx)
+{
+ GC_detach_change_listener (ctx->cfg, &configChangeListener, ctx);
+ free_tree (ctx->root);
+ GE_ASSERT (ctx->ectx, ctx->listeners == NULL);
+ FREE (ctx);
}
/**
@@ -316,12 +332,12 @@
* @param listener callback to call whenever the tree changes
*/
void
-GNS_register_tree_change_listener(struct GNS_Context * ctx,
- GNS_TreeChangeListener listener,
- void * cls) {
- GNS_TCL * n;
+GNS_register_tree_change_listener (struct GNS_Context *ctx,
+ GNS_TreeChangeListener listener, void *cls)
+{
+ GNS_TCL *n;
- n = MALLOC(sizeof(GNS_TCL));
+ n = MALLOC (sizeof (GNS_TCL));
n->l = listener;
n->c = cls;
n->next = ctx->listeners;
@@ -333,27 +349,29 @@
* in the future for change events).
*/
void
-GNS_unregister_tree_change_listener(struct GNS_Context * ctx,
- GNS_TreeChangeListener listener,
- void * cls) {
- GNS_TCL * pos;
- GNS_TCL * prev;
+GNS_unregister_tree_change_listener (struct GNS_Context *ctx,
+ GNS_TreeChangeListener listener,
+ void *cls)
+{
+ GNS_TCL *pos;
+ GNS_TCL *prev;
prev = NULL;
pos = ctx->listeners;
- while (pos != NULL) {
- if ( (pos->l == listener) &&
- (pos->c == cls)) {
- if (prev == NULL)
- ctx->listeners = pos->next;
- else
- prev->next = pos->next;
- FREE(pos);
- return; /* only unregister one! */
+ while (pos != NULL)
+ {
+ if ((pos->l == listener) && (pos->c == cls))
+ {
+ if (prev == NULL)
+ ctx->listeners = pos->next;
+ else
+ prev->next = pos->next;
+ FREE (pos);
+ return; /* only unregister one! */
+ }
+ prev = pos;
+ pos = pos->next;
}
- prev = pos;
- pos = pos->next;
- }
}
/**
@@ -363,30 +381,31 @@
* @return NULL on error
*/
char *
-GNS_get_default_value_as_string(GNS_Type type,
- const GNS_Value * value) {
+GNS_get_default_value_as_string (GNS_Type type, const GNS_Value * value)
+{
char buf[48];
if (value == NULL)
return NULL;
- switch (type & GNS_TypeMask) {
- case GNS_Boolean:
- if (value->Boolean.def)
- return STRDUP("YES");
- return STRDUP("NO");
- case GNS_String:
- case GNS_MC:
- case GNS_SC:
- if (value->String.def == NULL)
+ switch (type & GNS_TypeMask)
+ {
+ case GNS_Boolean:
+ if (value->Boolean.def)
+ return STRDUP ("YES");
+ return STRDUP ("NO");
+ case GNS_String:
+ case GNS_MC:
+ case GNS_SC:
+ if (value->String.def == NULL)
+ return NULL;
+ return STRDUP (value->String.def);
+ case GNS_Double:
+ SNPRINTF (buf, 48, "%f", value->Double.def);
+ return STRDUP (buf);
+ case GNS_UInt64:
+ SNPRINTF (buf, 48, "%llu", value->UInt64.def);
+ return STRDUP (buf);
+ default:
return NULL;
- return STRDUP(value->String.def);
- case GNS_Double:
- SNPRINTF(buf, 48, "%f", value->Double.def);
- return STRDUP(buf);
- case GNS_UInt64:
- SNPRINTF(buf, 48, "%llu", value->UInt64.def);
- return STRDUP(buf);
- default:
- return NULL;
- }
+ }
}
Modified: GNUnet/src/setup/lib/tree.c
===================================================================
--- GNUnet/src/setup/lib/tree.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/lib/tree.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -31,11 +31,12 @@
#include <libguile.h>
-typedef struct {
+typedef struct
+{
VisibilityChangeListener vcl;
- void * ctx;
- struct GNS_Tree * root;
- struct GC_Configuration * cfg;
+ void *ctx;
+ struct GNS_Tree *root;
+ struct GC_Configuration *cfg;
} TC;
/* ********************** scheme smob boxing ***************** */
@@ -45,7 +46,8 @@
static scm_t_bits tree_tag;
static SCM
-box_tc(TC * tc) {
+box_tc (TC * tc)
+{
SCM smob;
SCM_NEWSMOB (smob, tc_tag, tc);
@@ -53,7 +55,8 @@
}
static SCM
-box_tree(struct GNS_Tree * tree) {
+box_tree (struct GNS_Tree *tree)
+{
SCM smob;
SCM_NEWSMOB (smob, tree_tag, tree);
@@ -61,14 +64,14 @@
}
static size_t
-free_box(SCM smob) {
+free_box (SCM smob)
+{
return 0;
}
static int
-print_tc(SCM tc_smob,
- SCM port,
- scm_print_state *pstate) {
+print_tc (SCM tc_smob, SCM port, scm_print_state * pstate)
+{
/* TC * tc = (TC *) SCM_SMOB_DATA (tc_smob); */
scm_puts ("TC", port);
/* non-zero means success */
@@ -76,9 +79,8 @@
}
static int
-print_tree(SCM tree_smob,
- SCM port,
- scm_print_state *pstate) {
+print_tree (SCM tree_smob, SCM port, scm_print_state * pstate)
+{
/* struct GNS_Tree * tree = (struct GNS_Tree *) SCM_SMOB_DATA (tree_smob); */
scm_puts ("Tree", port);
@@ -89,63 +91,61 @@
/* **************************** tree API ****************** */
struct GNS_Tree *
-tree_lookup(struct GNS_Tree * root,
- const char * section,
- const char * option) {
+tree_lookup (struct GNS_Tree *root, const char *section, const char *option)
+{
int i;
- struct GNS_Tree * ret;
+ struct GNS_Tree *ret;
- if ( (root->section != NULL) &&
- (root->option != NULL) &&
- (0 == strcmp(section, root->section)) &&
- (0 == strcmp(option, root->option)) )
+ if ((root->section != NULL) &&
+ (root->option != NULL) &&
+ (0 == strcmp (section, root->section)) &&
+ (0 == strcmp (option, root->option)))
return root;
i = 0;
- while (root->children[i] != NULL) {
- ret = tree_lookup(root->children[i],
- section,
- option);
- if (ret != NULL)
- return ret;
- i++;
- }
+ while (root->children[i] != NULL)
+ {
+ ret = tree_lookup (root->children[i], section, option);
+ if (ret != NULL)
+ return ret;
+ i++;
+ }
return NULL;
}
-SCM get_option(SCM smob,
- SCM section,
- SCM option) {
- TC * tc;
- char * opt;
- char * sec;
- struct GNS_Tree * t;
+SCM
+get_option (SCM smob, SCM section, SCM option)
+{
+ TC *tc;
+ char *opt;
+ char *sec;
+ struct GNS_Tree *t;
- SCM_ASSERT(SCM_SMOB_PREDICATE(tc_tag, smob), smob, SCM_ARG1, "get_option");
- SCM_ASSERT(scm_string_p(option), option, SCM_ARG2, "get_option");
- SCM_ASSERT(scm_string_p(section), section, SCM_ARG3, "get_option");
- tc = (TC *) SCM_SMOB_DATA(smob);
- opt = scm_to_locale_string(option);
- sec = scm_to_locale_string(section);
- t = tree_lookup(tc->root,
- sec,
- opt);
+ SCM_ASSERT (SCM_SMOB_PREDICATE (tc_tag, smob), smob, SCM_ARG1,
+ "get_option");
+ SCM_ASSERT (scm_string_p (option), option, SCM_ARG2, "get_option");
+ SCM_ASSERT (scm_string_p (section), section, SCM_ARG3, "get_option");
+ tc = (TC *) SCM_SMOB_DATA (smob);
+ opt = scm_to_locale_string (option);
+ sec = scm_to_locale_string (section);
+ t = tree_lookup (tc->root, sec, opt);
if (t == NULL)
return SCM_EOL;
- switch (t->type & GNS_TypeMask) {
- case 0:
- return SCM_EOL; /* no value */
- case GNS_Boolean:
- return (t->value.Boolean.val) ? SCM_BOOL_T : SCM_BOOL_F;
- case GNS_UInt64:
- return scm_from_uint64(t->value.UInt64.val);
- case GNS_Double:
- return scm_from_double(t->value.Double.val);
- case GNS_String:
- case GNS_MC:
- case GNS_SC:
- return scm_from_locale_string(t->value.String.val);
- }
- GE_BREAK(NULL, 0);
+ switch (t->type & GNS_TypeMask)
+ {
+ case 0:
+ return SCM_EOL; /* no value */
+ case GNS_Boolean:
+ return (t->value.Boolean.val) ? SCM_BOOL_T : SCM_BOOL_F;
+ case GNS_UInt64:
+ return scm_from_uint64 (t->value.UInt64.val);
+ case GNS_Double:
+ return scm_from_double (t->value.Double.val);
+ case GNS_String:
+ case GNS_MC:
+ case GNS_SC:
+ return scm_from_locale_string (t->value.String.val);
+ }
+ GE_BREAK (NULL, 0);
return SCM_EOL;
}
@@ -153,79 +153,75 @@
* Change the visibility of an entry in the
* tree (and notify listeners about change).
*/
-SCM change_visible(SCM smob,
- SCM section,
- SCM option,
- SCM yesno) {
- TC * tc;
- char * opt;
- char * sec;
+SCM
+change_visible (SCM smob, SCM section, SCM option, SCM yesno)
+{
+ TC *tc;
+ char *opt;
+ char *sec;
int val;
- struct GNS_Tree * t;
+ struct GNS_Tree *t;
- SCM_ASSERT(SCM_SMOB_PREDICATE(tc_tag, smob), smob, SCM_ARG1,
"change_visible");
- SCM_ASSERT(scm_string_p(option), option, SCM_ARG2, "change_visible");
- SCM_ASSERT(scm_string_p(section), section, SCM_ARG3, "change_visible");
- SCM_ASSERT(scm_boolean_p(yesno), yesno, SCM_ARG4, "change_visible");
+ SCM_ASSERT (SCM_SMOB_PREDICATE (tc_tag, smob), smob, SCM_ARG1,
+ "change_visible");
+ SCM_ASSERT (scm_string_p (option), option, SCM_ARG2, "change_visible");
+ SCM_ASSERT (scm_string_p (section), section, SCM_ARG3, "change_visible");
+ SCM_ASSERT (scm_boolean_p (yesno), yesno, SCM_ARG4, "change_visible");
- tc = (TC *) SCM_SMOB_DATA(smob);
- opt = scm_to_locale_string(option);
- sec = scm_to_locale_string(section);
- val = scm_is_true(yesno) ? 1 : 0;
- if ( (opt == NULL) ||
- (sec == NULL) ) {
- GE_BREAK(NULL, 0);
- return SCM_EOL;
- }
- t = tree_lookup(tc->root,
- sec,
- opt);
- if (t != NULL) {
- t->visible = val;
- tc->vcl(tc->ctx,
- t);
- } else {
- fprintf(stderr,
- _("Internal error: entry `%s' in section `%s' not found for visibility
change!\n"),
- opt,
- sec);
- }
- free(sec);
- free(opt);
+ tc = (TC *) SCM_SMOB_DATA (smob);
+ opt = scm_to_locale_string (option);
+ sec = scm_to_locale_string (section);
+ val = scm_is_true (yesno) ? 1 : 0;
+ if ((opt == NULL) || (sec == NULL))
+ {
+ GE_BREAK (NULL, 0);
+ return SCM_EOL;
+ }
+ t = tree_lookup (tc->root, sec, opt);
+ if (t != NULL)
+ {
+ t->visible = val;
+ tc->vcl (tc->ctx, t);
+ }
+ else
+ {
+ fprintf (stderr,
+ _
+ ("Internal error: entry `%s' in section `%s' not found for
visibility change!\n"),
+ opt, sec);
+ }
+ free (sec);
+ free (opt);
return SCM_EOL;
}
/**
* Set an option.
*/
-SCM set_option(SCM smob,
- SCM section,
- SCM option,
- SCM value) {
- TC * tc;
- char * opt;
- char * sec;
- char * val;
+SCM
+set_option (SCM smob, SCM section, SCM option, SCM value)
+{
+ TC *tc;
+ char *opt;
+ char *sec;
+ char *val;
- SCM_ASSERT(SCM_SMOB_PREDICATE(tc_tag, smob), smob, SCM_ARG1, "set_option");
- SCM_ASSERT(scm_string_p(option), option, SCM_ARG2, "set_option");
- SCM_ASSERT(scm_string_p(section), section, SCM_ARG3, "set_option");
- SCM_ASSERT(scm_string_p(value), value, SCM_ARG4, "set_option");
- tc = (TC *) SCM_SMOB_DATA(smob);
- opt = scm_to_locale_string(option);
- sec = scm_to_locale_string(section);
- val = scm_to_locale_string(value);
- GC_set_configuration_value_string(tc->cfg,
- NULL,
- sec,
- opt,
- val);
+ SCM_ASSERT (SCM_SMOB_PREDICATE (tc_tag, smob), smob, SCM_ARG1,
+ "set_option");
+ SCM_ASSERT (scm_string_p (option), option, SCM_ARG2, "set_option");
+ SCM_ASSERT (scm_string_p (section), section, SCM_ARG3, "set_option");
+ SCM_ASSERT (scm_string_p (value), value, SCM_ARG4, "set_option");
+ tc = (TC *) SCM_SMOB_DATA (smob);
+ opt = scm_to_locale_string (option);
+ sec = scm_to_locale_string (section);
+ val = scm_to_locale_string (value);
+ GC_set_configuration_value_string (tc->cfg, NULL, sec, opt, val);
if (sec != NULL)
- free(sec);
+ free (sec);
if (val != NULL)
- free(val);
+ free (val);
if (opt != NULL)
- free(opt);
+ free (opt);
return SCM_EOL;
}
@@ -237,121 +233,139 @@
* maybe list of strings for string values or pair
* min/max for integers
*/
-SCM build_tree_node(SCM section,
- SCM option,
- SCM description,
- SCM help,
- SCM children,
- SCM visible,
- SCM value,
- SCM range) {
- struct GNS_Tree * tree;
+SCM
+build_tree_node (SCM section,
+ SCM option,
+ SCM description,
+ SCM help, SCM children, SCM visible, SCM value, SCM range)
+{
+ struct GNS_Tree *tree;
SCM child;
int i;
int clen;
int len;
- char * type;
+ char *type;
/* verify arguments */
- SCM_ASSERT(scm_string_p(section), section, SCM_ARG1, "build_tree_node");
- SCM_ASSERT(scm_string_p(option), option, SCM_ARG2, "build_tree_node");
- SCM_ASSERT(scm_string_p(description), description, SCM_ARG3,
"build_tree_node");
- SCM_ASSERT(scm_string_p(help), help, SCM_ARG4, "build_tree_node");
- SCM_ASSERT(scm_list_p(children), children, SCM_ARG5, "build_tree_node");
- clen = scm_to_int(scm_length(children));
- for (i=0;i<clen;i++) {
- child = scm_list_ref(children, scm_from_signed_integer(i));
- SCM_ASSERT(SCM_SMOB_PREDICATE(tree_tag, child),
- children, SCM_ARG5, "build_tree_node");
- }
- SCM_ASSERT(scm_boolean_p(visible), visible, SCM_ARG6, "build_tree_node");
- if (scm_is_string(value)) {
- SCM_ASSERT(scm_list_p(range), range, SCM_ARGn, "build_tree_node");
- len = scm_to_int(scm_length(range));
- for (i=0;i<len;i++)
- SCM_ASSERT(scm_string_p(scm_list_ref(range,
- scm_from_signed_integer(i))),
- range, SCM_ARGn, "build_tree_node");
- } else if (scm_is_integer(value)) {
- SCM_ASSERT(scm_pair_p(range),
- range, SCM_ARGn, "build_tree_node");
- SCM_ASSERT(scm_is_integer(SCM_CAR(range)),
- range, SCM_ARGn, "build_tree_node");
- SCM_ASSERT(scm_is_integer(SCM_CDR(range)),
- range, SCM_ARGn, "build_tree_node");
- } else if (scm_is_true(scm_real_p(value))) {
- /* no checks */
- } else if (scm_is_true(scm_boolean_p(value))) {
- /* no checks */
- } else {
- SCM_ASSERT(0,
- range,
- SCM_ARG7,
- "build_tree_node"); /* invalid type */
- }
+ SCM_ASSERT (scm_string_p (section), section, SCM_ARG1, "build_tree_node");
+ SCM_ASSERT (scm_string_p (option), option, SCM_ARG2, "build_tree_node");
+ SCM_ASSERT (scm_string_p (description), description, SCM_ARG3,
+ "build_tree_node");
+ SCM_ASSERT (scm_string_p (help), help, SCM_ARG4, "build_tree_node");
+ SCM_ASSERT (scm_list_p (children), children, SCM_ARG5, "build_tree_node");
+ clen = scm_to_int (scm_length (children));
+ for (i = 0; i < clen; i++)
+ {
+ child = scm_list_ref (children, scm_from_signed_integer (i));
+ SCM_ASSERT (SCM_SMOB_PREDICATE (tree_tag, child),
+ children, SCM_ARG5, "build_tree_node");
+ }
+ SCM_ASSERT (scm_boolean_p (visible), visible, SCM_ARG6, "build_tree_node");
+ if (scm_is_string (value))
+ {
+ SCM_ASSERT (scm_list_p (range), range, SCM_ARGn, "build_tree_node");
+ len = scm_to_int (scm_length (range));
+ for (i = 0; i < len; i++)
+ SCM_ASSERT (scm_string_p (scm_list_ref (range,
+ scm_from_signed_integer (i))),
+ range, SCM_ARGn, "build_tree_node");
+ }
+ else if (scm_is_integer (value))
+ {
+ SCM_ASSERT (scm_pair_p (range), range, SCM_ARGn, "build_tree_node");
+ SCM_ASSERT (scm_is_integer (SCM_CAR (range)),
+ range, SCM_ARGn, "build_tree_node");
+ SCM_ASSERT (scm_is_integer (SCM_CDR (range)),
+ range, SCM_ARGn, "build_tree_node");
+ }
+ else if (scm_is_true (scm_real_p (value)))
+ {
+ /* no checks */
+ }
+ else if (scm_is_true (scm_boolean_p (value)))
+ {
+ /* no checks */
+ }
+ else
+ {
+ SCM_ASSERT (0, range, SCM_ARG7, "build_tree_node"); /* invalid
type */
+ }
/* construct C object */
- tree = MALLOC(sizeof(struct GNS_Tree));
- tree->section = scm_to_locale_string(section);
- tree->option = scm_to_locale_string(option);
- tree->description = scm_to_locale_string(description);
- tree->help = scm_to_locale_string(help);
- tree->children = MALLOC(sizeof(struct GNS_Tree*) * (clen + 1));
- for (i=0;i<clen;i++) {
- child = scm_list_ref(children, scm_from_signed_integer(i));
- tree->children[i] = (struct GNS_Tree*) SCM_SMOB_DATA(child);
- }
+ tree = MALLOC (sizeof (struct GNS_Tree));
+ tree->section = scm_to_locale_string (section);
+ tree->option = scm_to_locale_string (option);
+ tree->description = scm_to_locale_string (description);
+ tree->help = scm_to_locale_string (help);
+ tree->children = MALLOC (sizeof (struct GNS_Tree *) * (clen + 1));
+ for (i = 0; i < clen; i++)
+ {
+ child = scm_list_ref (children, scm_from_signed_integer (i));
+ tree->children[i] = (struct GNS_Tree *) SCM_SMOB_DATA (child);
+ }
tree->children[clen] = NULL;
tree->type = (clen == 0) ? GNS_Leaf : GNS_Node;
- tree->visible = scm_is_true(visible);
+ tree->visible = scm_is_true (visible);
- if (scm_is_string(value)) {
- tree->value.String.val = scm_to_locale_string(value);
- tree->value.String.def = scm_to_locale_string(value);
- len = scm_to_int(scm_length(range));
- tree->value.String.legalRange = MALLOC(sizeof(char*) * (len+1));
- for (i=0;i<len-1;i++)
- tree->value.String.legalRange[i]
- = scm_to_locale_string(scm_list_ref(range,
- scm_from_signed_integer(i+1)));
- if (len == 0)
- tree->value.String.legalRange[len] = NULL;
- else
- tree->value.String.legalRange[len-1] = NULL;
- if (len > 0)
- type = scm_to_locale_string(scm_list_ref(range,
- scm_from_signed_integer(0)));
- else
- type = STRDUP("*");
- GE_ASSERT(NULL, type != NULL);
- if (0 == strcasecmp(type,
- "MC")) {
- tree->type |= GNS_MC;
- } else if (0 == strcasecmp(type,
- "SC")) {
- tree->type |= GNS_SC;
- } else {
- GE_BREAK(NULL, 0 == strcasecmp(type, "*"));
- tree->type |= GNS_String;
+ if (scm_is_string (value))
+ {
+ tree->value.String.val = scm_to_locale_string (value);
+ tree->value.String.def = scm_to_locale_string (value);
+ len = scm_to_int (scm_length (range));
+ tree->value.String.legalRange = MALLOC (sizeof (char *) * (len + 1));
+ for (i = 0; i < len - 1; i++)
+ tree->value.String.legalRange[i]
+ = scm_to_locale_string (scm_list_ref (range,
+ scm_from_signed_integer (i +
+ 1)));
+ if (len == 0)
+ tree->value.String.legalRange[len] = NULL;
+ else
+ tree->value.String.legalRange[len - 1] = NULL;
+ if (len > 0)
+ type = scm_to_locale_string (scm_list_ref (range,
+ scm_from_signed_integer
+ (0)));
+ else
+ type = STRDUP ("*");
+ GE_ASSERT (NULL, type != NULL);
+ if (0 == strcasecmp (type, "MC"))
+ {
+ tree->type |= GNS_MC;
+ }
+ else if (0 == strcasecmp (type, "SC"))
+ {
+ tree->type |= GNS_SC;
+ }
+ else
+ {
+ GE_BREAK (NULL, 0 == strcasecmp (type, "*"));
+ tree->type |= GNS_String;
+ }
+ FREE (type);
}
- FREE(type);
- } else if (scm_is_integer(value)) {
- tree->value.UInt64.val = scm_to_uint64(value);
- tree->value.UInt64.def = scm_to_uint64(value);
- tree->value.UInt64.min = scm_to_uint64(SCM_CAR(range));
- tree->value.UInt64.max = scm_to_uint64(SCM_CDR(range));
- tree->type |= GNS_UInt64;
- } else if (scm_is_true(scm_real_p(value))) {
- tree->value.Double.val = scm_to_double(value);
- tree->value.Double.def = scm_to_double(value);
- tree->type |= GNS_Double;
- } else if (scm_is_true(scm_boolean_p(value))) {
- tree->value.Boolean.val = scm_is_true(value);
- tree->value.Boolean.def = scm_is_true(value);
- tree->type |= GNS_Boolean;
- }
+ else if (scm_is_integer (value))
+ {
+ tree->value.UInt64.val = scm_to_uint64 (value);
+ tree->value.UInt64.def = scm_to_uint64 (value);
+ tree->value.UInt64.min = scm_to_uint64 (SCM_CAR (range));
+ tree->value.UInt64.max = scm_to_uint64 (SCM_CDR (range));
+ tree->type |= GNS_UInt64;
+ }
+ else if (scm_is_true (scm_real_p (value)))
+ {
+ tree->value.Double.val = scm_to_double (value);
+ tree->value.Double.def = scm_to_double (value);
+ tree->type |= GNS_Double;
+ }
+ else if (scm_is_true (scm_boolean_p (value)))
+ {
+ tree->value.Boolean.val = scm_is_true (value);
+ tree->value.Boolean.def = scm_is_true (value);
+ tree->type |= GNS_Boolean;
+ }
/* box and return */
- return box_tree(tree);
+ return box_tree (tree);
}
/**
@@ -359,38 +373,40 @@
* Set all values to defaults.
*/
static void *
-parse_internal(void * spec) {
- const char * specification = spec;
+parse_internal (void *spec)
+{
+ const char *specification = spec;
SCM proc;
SCM smob;
- scm_c_primitive_load(specification);
- proc = scm_variable_ref(scm_c_lookup("gnunet-config-setup"));
- smob = scm_apply_0(proc, SCM_EOL);
- return (void*) SCM_SMOB_DATA(smob);
+ scm_c_primitive_load (specification);
+ proc = scm_variable_ref (scm_c_lookup ("gnunet-config-setup"));
+ smob = scm_apply_0 (proc, SCM_EOL);
+ return (void *) SCM_SMOB_DATA (smob);
}
struct GNS_Tree *
-tree_parse(struct GE_Context * ectx,
- const char * specification) {
- struct GNS_Tree * ret;
+tree_parse (struct GE_Context *ectx, const char *specification)
+{
+ struct GNS_Tree *ret;
- ret = parse_internal((void*) specification);
+ ret = parse_internal ((void *) specification);
if (ret != NULL)
ret->type = GNS_Root;
return ret;
}
static void *
-notify_change_internal(void * cls) {
- TC * tc = cls;
+notify_change_internal (void *cls)
+{
+ TC *tc = cls;
SCM smob_ctx;
SCM proc;
- proc = scm_variable_ref(scm_c_lookup("gnunet-config-change"));
- smob_ctx = box_tc(tc);
- scm_apply_1(proc, smob_ctx, SCM_EOL);
+ proc = scm_variable_ref (scm_c_lookup ("gnunet-config-change"));
+ smob_ctx = box_tc (tc);
+ scm_apply_1 (proc, smob_ctx, SCM_EOL);
return NULL;
}
@@ -401,19 +417,20 @@
*
* Update visibility (and notify about changes).
*/
-void tree_notify_change(struct GC_Configuration * cfg,
- VisibilityChangeListener vcl,
- void * ctx,
- struct GE_Context * ectx,
- struct GNS_Tree * root,
- struct GNS_Tree * change) {
+void
+tree_notify_change (struct GC_Configuration *cfg,
+ VisibilityChangeListener vcl,
+ void *ctx,
+ struct GE_Context *ectx,
+ struct GNS_Tree *root, struct GNS_Tree *change)
+{
TC tc;
tc.cfg = cfg;
tc.vcl = vcl;
tc.ctx = ctx;
tc.root = root;
- notify_change_internal(&tc);
+ notify_change_internal (&tc);
}
/**
@@ -422,32 +439,34 @@
* If not, we'll have to move it into the
* _internal methods.
*/
-void __attribute__ ((constructor)) gns_scheme_init() {
+void __attribute__ ((constructor)) gns_scheme_init ()
+{
#ifdef MINGW
char *oldpath, *env;
char load[MAX_PATH + 1];
int len;
- InitWinEnv();
+ InitWinEnv ();
/* add path of "system" .scm files to guile's load path */
- plibc_conv_to_win_path("/share/guile/1.8/", load);
+ plibc_conv_to_win_path ("/share/guile/1.8/", load);
len = 0;
- oldpath = getenv("GUILE_LOAD_PATH");
+ oldpath = getenv ("GUILE_LOAD_PATH");
if (oldpath)
- len = strlen(oldpath);
- env = malloc(len + strlen(load) + 18);
- strcpy(env, "GUILE_LOAD_PATH=");
- if (oldpath) {
- strcat(env, oldpath);
- strcat(env, ";");
- }
- strcat(env, load);
- putenv(env);
- free(env);
+ len = strlen (oldpath);
+ env = malloc (len + strlen (load) + 18);
+ strcpy (env, "GUILE_LOAD_PATH=");
+ if (oldpath)
+ {
+ strcat (env, oldpath);
+ strcat (env, ";");
+ }
+ strcat (env, load);
+ putenv (env);
+ free (env);
#endif
- scm_init_guile();
+ scm_init_guile ();
tc_tag = scm_make_smob_type ("tc", 0);
scm_set_smob_mark (tc_tag, NULL);
@@ -458,23 +477,16 @@
scm_set_smob_mark (tree_tag, NULL);
scm_set_smob_free (tree_tag, free_box);
scm_set_smob_print (tree_tag, print_tree);
- scm_c_define_gsubr("change-visible",
- 4, 0, 0,
- &change_visible);
- scm_c_define_gsubr("build-tree-node",
- 8, 0, 0,
- &build_tree_node);
- scm_c_define_gsubr("get-option",
- 3, 0, 0,
- &get_option);
- scm_c_define_gsubr("set-option",
- 4, 0, 0,
- &set_option);
+ scm_c_define_gsubr ("change-visible", 4, 0, 0, &change_visible);
+ scm_c_define_gsubr ("build-tree-node", 8, 0, 0, &build_tree_node);
+ scm_c_define_gsubr ("get-option", 3, 0, 0, &get_option);
+ scm_c_define_gsubr ("set-option", 4, 0, 0, &set_option);
}
-void __attribute__ ((destructor)) gns_scheme_fin() {
+void __attribute__ ((destructor)) gns_scheme_fin ()
+{
#ifdef MINGW
- ShutdownWinEnv();
+ ShutdownWinEnv ();
#endif
}
Modified: GNUnet/src/setup/lib/tree.h
===================================================================
--- GNUnet/src/setup/lib/tree.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/lib/tree.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -28,26 +28,20 @@
* Parse the specification file and create the tree.
* Set all values to defaults.
*/
-struct GNS_Tree *
-tree_parse(struct GE_Context * ectx,
- const char * specification);
+struct GNS_Tree *tree_parse (struct GE_Context *ectx,
+ const char *specification);
-struct GNS_Tree *
-tree_lookup(struct GNS_Tree * root,
- const char * section,
- const char * option);
+struct GNS_Tree *tree_lookup (struct GNS_Tree *root,
+ const char *section, const char *option);
-typedef void (*VisibilityChangeListener)(void * ctx,
- struct GNS_Tree * tree);
+typedef void (*VisibilityChangeListener) (void *ctx, struct GNS_Tree * tree);
/**
* A value in the tree has been changed.
* Update visibility (and notify about changes).
*/
-void tree_notify_change(struct GC_Configuration * cfg,
- VisibilityChangeListener vcl,
- void * ctx,
- struct GE_Context * ectx,
- struct GNS_Tree * root,
- struct GNS_Tree * change);
-
+void tree_notify_change (struct GC_Configuration *cfg,
+ VisibilityChangeListener vcl,
+ void *ctx,
+ struct GE_Context *ectx,
+ struct GNS_Tree *root, struct GNS_Tree *change);
Modified: GNUnet/src/setup/lib/wizard_util.c
===================================================================
--- GNUnet/src/setup/lib/wizard_util.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/lib/wizard_util.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -31,39 +31,43 @@
/**
* @brief Determine whether a NIC makes a good default
*/
-int wiz_is_nic_default(struct GC_Configuration *cfg, const char *name, int
suggestion) {
+int
+wiz_is_nic_default (struct GC_Configuration *cfg, const char *name,
+ int suggestion)
+{
char *nic;
- GC_get_configuration_value_string(cfg, "NETWORK", "INTERFACE", "eth0", &nic);
+ GC_get_configuration_value_string (cfg, "NETWORK", "INTERFACE", "eth0",
+ &nic);
#ifdef WINDOWS
/* default NIC for unixes */
- if (strcmp(nic, "eth0") == 0)
- {
- FREE(nic);
- nic = NULL;
- }
+ if (strcmp (nic, "eth0") == 0)
+ {
+ FREE (nic);
+ nic = NULL;
+ }
#endif
if (nic)
- {
- /* The user has selected a NIC before */
- int niclen, inslen;
+ {
+ /* The user has selected a NIC before */
+ int niclen, inslen;
- niclen = strlen(nic);
- inslen = strlen(name);
- suggestion = 0;
+ niclen = strlen (nic);
+ inslen = strlen (name);
+ suggestion = 0;
- if (inslen >= niclen)
- {
+ if (inslen >= niclen)
+ {
#ifdef WINDOWS
- if (strncmp(name + inslen - niclen - 1, nic, niclen) == 0)
+ if (strncmp (name + inslen - niclen - 1, nic, niclen) == 0)
#else
- if (strcmp(name, nic) == 0)
+ if (strcmp (name, nic) == 0)
#endif
- suggestion = 1; /* This is the previous selection */
+ suggestion = 1; /* This is the previous selection */
+ }
}
- }
return suggestion;
}
@@ -76,66 +80,69 @@
* @param groupname name of the group to use
* @return OK on success, SYSERR on error
*/
-int wiz_autostartService(int doAutoStart, char *username, char *groupname) {
+int
+wiz_autostartService (int doAutoStart, char *username, char *groupname)
+{
int ret;
char *exe;
- exe = os_get_installation_path(IPK_BINDIR);
- exe = (char *) REALLOC(exe, strlen(exe) + 12); /* 11 = "gnunetd.exe" */
- strcat(exe,
+ exe = os_get_installation_path (IPK_BINDIR);
+ exe = (char *) REALLOC (exe, strlen (exe) + 12); /* 11 = "gnunetd.exe"
*/
+ strcat (exe,
#ifndef WINDOWS
- "gnunetd");
+ "gnunetd");
#else
- "gnunetd.exe");
+ "gnunetd.exe");
#endif
- ret = os_modify_autostart(NULL /* FIXME 0.7.1 NILS */, 0, doAutoStart, exe,
- username, groupname);
- FREE(exe);
- if (ret != YES) {
+ ret =
+ os_modify_autostart (NULL /* FIXME 0.7.1 NILS */ , 0, doAutoStart, exe,
+ username, groupname);
+ FREE (exe);
+ if (ret != YES)
+ {
#ifdef WINDOWS
- char *err = NULL;
+ char *err = NULL;
- switch(ret) {
- case 1:
- err = winErrorStr(_("Can't open Service Control Manager"),
- GetLastError());
- break;
- case 2:
- if (GetLastError() != ERROR_SERVICE_EXISTS) {
- err = winErrorStr(_("Can't create service"),
- GetLastError());
+ switch (ret)
+ {
+ case 1:
+ err = winErrorStr (_("Can't open Service Control Manager"),
+ GetLastError ());
+ break;
+ case 2:
+ if (GetLastError () != ERROR_SERVICE_EXISTS)
+ {
+ err = winErrorStr (_("Can't create service"), GetLastError ());
+ }
+ break;
+ case 3:
+ err = winErrorStr (_("Error changing the permissions of"
+ " the GNUnet directory"), GetLastError ());
+ break;
+ case 4:
+ err =
+ winErrorStr (_("Cannot write to the regisitry"), GetLastError ());
+ break;
+ case 5:
+ err = winErrorStr (_("Can't access the service"), GetLastError ());
+ break;
+ case 6:
+ err = winErrorStr (_("Can't delete the service"), GetLastError ());
+ break;
+ default:
+ err = winErrorStr (_("Unknown error"), GetLastError ());
}
- break;
- case 3:
- err = winErrorStr(_("Error changing the permissions of"
- " the GNUnet directory"), GetLastError());
- break;
- case 4:
- err = winErrorStr(_("Cannot write to the regisitry"), GetLastError());
- break;
- case 5:
- err = winErrorStr(_("Can't access the service"),
- GetLastError());
- break;
- case 6:
- err = winErrorStr(_("Can't delete the service"),
- GetLastError());
- break;
- default:
- err = winErrorStr(_("Unknown error"), GetLastError());
- }
- if (err) {
- MessageBox(GetActiveWindow(),
- err,
- _("Error"),
- MB_ICONSTOP | MB_OK);
- free(err);
- }
+ if (err)
+ {
+ MessageBox (GetActiveWindow (),
+ err, _("Error"), MB_ICONSTOP | MB_OK);
+ free (err);
+ }
#endif
- return SYSERR;
- }
+ return SYSERR;
+ }
return OK;
}
@@ -145,40 +152,51 @@
* @param name the name of the new user
* @return 1 on success
*/
-int wiz_createGroupUser(char *group_name, char *user_name) {
+int
+wiz_createGroupUser (char *group_name, char *user_name)
+{
int ret;
- ret = os_modify_user(0, 1, user_name, group_name);
+ ret = os_modify_user (0, 1, user_name, group_name);
- if (ret) {
+ if (ret)
+ {
#ifdef MINGW
- char *err;
+ char *err;
- switch(ret) {
- case 1:
- err = _("This version of Windows does not support "
- "multiple users.");
- break;
- case 2:
- err = winErrorStr(_("Error creating user"), GetLastError());
- break;
- case 3:
- err = winErrorStr(_("Error accessing local security policy"),
GetLastError());
- break;
- case 4:
- err = winErrorStr(_("Error granting service right to user"),
GetLastError());
- break;
- default:
- err = winErrorStr(_("Unknown error while creating a new user"),
GetLastError());
- }
+ switch (ret)
+ {
+ case 1:
+ err = _("This version of Windows does not support "
+ "multiple users.");
+ break;
+ case 2:
+ err = winErrorStr (_("Error creating user"), GetLastError ());
+ break;
+ case 3:
+ err =
+ winErrorStr (_("Error accessing local security policy"),
+ GetLastError ());
+ break;
+ case 4:
+ err =
+ winErrorStr (_("Error granting service right to user"),
+ GetLastError ());
+ break;
+ default:
+ err =
+ winErrorStr (_("Unknown error while creating a new user"),
+ GetLastError ());
+ }
- if (err) {
- MessageBox(0, err, _("Error"), MB_ICONSTOP | MB_OK);
- free(err);
+ if (err)
+ {
+ MessageBox (0, err, _("Error"), MB_ICONSTOP | MB_OK);
+ free (err);
+ }
+#endif
+ return 0;
}
-#endif
- return 0;
- }
return 1;
}
Modified: GNUnet/src/setup/lib/wizard_util.h
===================================================================
--- GNUnet/src/setup/lib/wizard_util.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/lib/wizard_util.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -27,9 +27,10 @@
#ifndef WIZARD_UTIL_H_
#define WIZARD_UTIL_H_
-int wiz_is_nic_default(struct GC_Configuration *cfg, const char *name, int
suggestion);
-int wiz_autostartService(int doAutoStart, char *username, char *groupname);
-int wiz_createGroupUser(char *group_name, char *user_name);
+int wiz_is_nic_default (struct GC_Configuration *cfg, const char *name,
+ int suggestion);
+int wiz_autostartService (int doAutoStart, char *username, char *groupname);
+int wiz_createGroupUser (char *group_name, char *user_name);
-#endif /*WIZARD_UTIL_H_*/
+#endif /*WIZARD_UTIL_H_ */
Modified: GNUnet/src/setup/ncurses/mconf.c
===================================================================
--- GNUnet/src/setup/ncurses/mconf.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/ncurses/mconf.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -38,36 +38,34 @@
#include <termios.h>
#endif
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static void show_help(const char * option,
- const char * helptext) {
+static void
+show_help (const char *option, const char *helptext)
+{
dialog_vars.help_button = 0;
- dialog_msgbox(option,
- gettext(helptext),
- 20,
- 70,
- TRUE);
+ dialog_msgbox (option, gettext (helptext), 20, 70, TRUE);
dialog_vars.help_button = 1;
}
-static void run_menu(struct GNS_Context * ctx,
- struct GNS_Tree * pos,
- struct GC_Configuration * cfg) {
+static void
+run_menu (struct GNS_Context *ctx,
+ struct GNS_Tree *pos, struct GC_Configuration *cfg)
+{
int st;
int i;
- DIALOG_LISTITEM * items;
+ DIALOG_LISTITEM *items;
int msel;
DIALOG_FORMITEM fitem;
unsigned long long lval;
double dval;
- GNS_Value * val;
- char * tmp;
+ GNS_Value *val;
+ char *tmp;
size_t tlen;
fitem.type = 0;
fitem.name = pos->description;
- fitem.name_len = strlen(pos->description);
+ fitem.name_len = strlen (pos->description);
fitem.name_y = 3;
fitem.name_x = 5;
fitem.name_free = 0;
@@ -79,467 +77,468 @@
fitem.help_free = 0;
msel = 0;
- while (1) {
- switch (pos->type & GNS_KindMask) {
- case GNS_Root:
- dialog_vars.cancel_label = _("Exit");
- break;
- case GNS_Node:
- dialog_vars.cancel_label = _("Up");
- break;
- default:
- dialog_vars.cancel_label = _("Cancel");
- break;
- }
- switch (pos->type & GNS_KindMask) {
- case GNS_Root:
- /* fall-through! */
- case GNS_Node:
- st = 0;
- i = 0;
- while (pos->children[i] != NULL) {
- if (pos->children[i]->visible)
- st++;
- i++;
- }
- if (st == 0)
- return; /* no visible entries */
- items = MALLOC(sizeof(DIALOG_LISTITEM) * st);
- i = 0;
- st = 0;
- while (pos->children[i] != NULL) {
- if (pos->children[i]->visible) {
- items[st].name = pos->children[i]->option;
- items[st].text = gettext(pos->children[i]->description);
- items[st].help = gettext(pos->children[i]->help);
- if (st == msel)
- items[st].state = 1;
- else
- items[st].state = 0;
- st++;
- }
- i++;
- }
- st = dlg_menu(gettext(pos->description),
- "Select configuration option to change",
- 20,
- 70,
- 13,
- st,
- items,
- &msel,
- NULL);
- FREE(items);
- switch (st) {
- case DLG_EXIT_OK:
- i = 0;
- st = msel;
- while (pos->children[i] != NULL) {
- if (pos->children[i]->visible) {
- if (st == 0)
- run_menu(ctx,
- pos->children[i],
- cfg);
- st--;
- }
- i++;
- }
- break;
- case DLG_EXIT_HELP:
- show_help(pos->children[msel]->option,
- pos->children[msel]->help);
- break;
- case DLG_EXIT_ESC:
- case DLG_EXIT_ERROR:
- case DLG_EXIT_CANCEL:
- default:
- return;
- }
- break;
+ while (1)
+ {
+ switch (pos->type & GNS_KindMask)
+ {
+ case GNS_Root:
+ dialog_vars.cancel_label = _("Exit");
+ break;
+ case GNS_Node:
+ dialog_vars.cancel_label = _("Up");
+ break;
+ default:
+ dialog_vars.cancel_label = _("Cancel");
+ break;
+ }
+ switch (pos->type & GNS_KindMask)
+ {
+ case GNS_Root:
+ /* fall-through! */
+ case GNS_Node:
+ st = 0;
+ i = 0;
+ while (pos->children[i] != NULL)
+ {
+ if (pos->children[i]->visible)
+ st++;
+ i++;
+ }
+ if (st == 0)
+ return; /* no visible entries */
+ items = MALLOC (sizeof (DIALOG_LISTITEM) * st);
+ i = 0;
+ st = 0;
+ while (pos->children[i] != NULL)
+ {
+ if (pos->children[i]->visible)
+ {
+ items[st].name = pos->children[i]->option;
+ items[st].text = gettext (pos->children[i]->description);
+ items[st].help = gettext (pos->children[i]->help);
+ if (st == msel)
+ items[st].state = 1;
+ else
+ items[st].state = 0;
+ st++;
+ }
+ i++;
+ }
+ st = dlg_menu (gettext (pos->description),
+ "Select configuration option to change",
+ 20, 70, 13, st, items, &msel, NULL);
+ FREE (items);
+ switch (st)
+ {
+ case DLG_EXIT_OK:
+ i = 0;
+ st = msel;
+ while (pos->children[i] != NULL)
+ {
+ if (pos->children[i]->visible)
+ {
+ if (st == 0)
+ run_menu (ctx, pos->children[i], cfg);
+ st--;
+ }
+ i++;
+ }
+ break;
+ case DLG_EXIT_HELP:
+ show_help (pos->children[msel]->option,
+ pos->children[msel]->help);
+ break;
+ case DLG_EXIT_ESC:
+ case DLG_EXIT_ERROR:
+ case DLG_EXIT_CANCEL:
+ default:
+ return;
+ }
+ break;
- case GNS_Leaf:
- switch (pos->type & GNS_TypeMask) {
- case GNS_Boolean:
- st = dialog_yesno(pos->option,
- gettext(pos->description),
- 5, 60);
- switch (st) {
- case DLG_EXIT_OK:
- case DLG_EXIT_CANCEL:
- if (0 != GC_set_configuration_value_string(cfg,
- ectx,
- pos->section,
- pos->option,
- st == DLG_EXIT_OK ? "YES" : "NO"))
{
- show_help(pos->option,
- gettext_noop("Internal error! (Choice invalid?)"));
- break;
- }
- return;
- case DLG_EXIT_HELP:
- show_help(pos->option, pos->help);
- break;
- case DLG_EXIT_ESC:
- return;
- default:
- GE_BREAK(ectx, 0);
- return;
- }
- break;
- case GNS_String:
- /* free form */
- fitem.text = MALLOC(65536);
- strcpy(fitem.text,
- pos->value.String.val);
- fitem.text_len = strlen(fitem.text);
- fitem.help = pos->help;
- msel = 0;
- st = dlg_form(pos->option,
- "",
- 20,
- 70,
- 15,
- 1,
- &fitem,
- &msel);
- switch (st) {
- case DLG_EXIT_OK:
- if (0 != GC_set_configuration_value_string(cfg,
- ectx,
- pos->section,
- pos->option,
- fitem.text)) {
- show_help(pos->option,
- gettext_noop("Internal error! (Value invalid?)"));
- break;
- }
- FREE(fitem.text);
- return;
- case DLG_EXIT_HELP:
- show_help(pos->option, pos->help);
- break;
- case DLG_EXIT_CANCEL:
- case DLG_EXIT_ERROR:
- case DLG_EXIT_ESC:
- FREE(fitem.text);
- return;
- default:
- break;
- }
- FREE(fitem.text);
- /* end free form */
- break;
- case GNS_SC:
- /* begin single choice */
- val = &pos->value;
- i = 0;
- while (val->String.legalRange[i] != NULL)
- i++;
- GE_ASSERT(ectx, i != 0);
- items = MALLOC(sizeof(DIALOG_LISTITEM) * i);
- i = 0;
- msel = -1;
+ case GNS_Leaf:
+ switch (pos->type & GNS_TypeMask)
+ {
+ case GNS_Boolean:
+ st = dialog_yesno (pos->option,
+ gettext (pos->description), 5, 60);
+ switch (st)
+ {
+ case DLG_EXIT_OK:
+ case DLG_EXIT_CANCEL:
+ if (0 != GC_set_configuration_value_string (cfg,
+ ectx,
+ pos->section,
+ pos->option,
+ st ==
+ DLG_EXIT_OK ?
+ "YES" : "NO"))
+ {
+ show_help (pos->option,
+ gettext_noop
+ ("Internal error! (Choice invalid?)"));
+ break;
+ }
+ return;
+ case DLG_EXIT_HELP:
+ show_help (pos->option, pos->help);
+ break;
+ case DLG_EXIT_ESC:
+ return;
+ default:
+ GE_BREAK (ectx, 0);
+ return;
+ }
+ break;
+ case GNS_String:
+ /* free form */
+ fitem.text = MALLOC (65536);
+ strcpy (fitem.text, pos->value.String.val);
+ fitem.text_len = strlen (fitem.text);
+ fitem.help = pos->help;
+ msel = 0;
+ st = dlg_form (pos->option, "", 20, 70, 15, 1, &fitem, &msel);
+ switch (st)
+ {
+ case DLG_EXIT_OK:
+ if (0 != GC_set_configuration_value_string (cfg,
+ ectx,
+ pos->section,
+ pos->option,
+ fitem.text))
+ {
+ show_help (pos->option,
+ gettext_noop
+ ("Internal error! (Value invalid?)"));
+ break;
+ }
+ FREE (fitem.text);
+ return;
+ case DLG_EXIT_HELP:
+ show_help (pos->option, pos->help);
+ break;
+ case DLG_EXIT_CANCEL:
+ case DLG_EXIT_ERROR:
+ case DLG_EXIT_ESC:
+ FREE (fitem.text);
+ return;
+ default:
+ break;
+ }
+ FREE (fitem.text);
+ /* end free form */
+ break;
+ case GNS_SC:
+ /* begin single choice */
+ val = &pos->value;
+ i = 0;
+ while (val->String.legalRange[i] != NULL)
+ i++;
+ GE_ASSERT (ectx, i != 0);
+ items = MALLOC (sizeof (DIALOG_LISTITEM) * i);
+ i = 0;
+ msel = -1;
- while (val->String.legalRange[i] != NULL) {
- items[i].name = "";
- items[i].text = val->String.legalRange[i];
- items[i].help = "";
- items[i].state = 0;
- if (0 == strcmp(val->String.legalRange[i],
- val->String.val)) {
- items[i].state = 1;
- msel = i;
- }
- if ( (msel == -1) &&
- (0 == strcmp(val->String.legalRange[i],
- val->String.def)) )
- msel = i;
- i++;
- }
- st = dlg_checklist(gettext(pos->option),
- gettext(pos->description),
- 20,
- 70,
- 13,
- i,
- items,
- " *",
- FLAG_RADIO,
- &msel);
- FREE(items);
- switch (st) {
- case DLG_EXIT_OK:
- if (0 != GC_set_configuration_value_choice(cfg,
- ectx,
- pos->section,
- pos->option,
- val->String.legalRange[msel])) {
- show_help(pos->option,
- gettext_noop("Internal error! (Choice invalid?)"));
- break;
- }
- return;
- case DLG_EXIT_HELP:
- show_help(pos->option,
- pos->help);
- break;
- case DLG_EXIT_ESC:
- case DLG_EXIT_ERROR:
- case DLG_EXIT_CANCEL:
- default:
- return;
- }
- break;
- case GNS_MC:
- /* begin multiple choice */
- val = &pos->value;
- i = 0;
- tlen = 2;
- while (val->String.legalRange[i] != NULL)
- i++;
- GE_ASSERT(ectx, i != 0);
- items = MALLOC(sizeof(DIALOG_LISTITEM) * i);
- i = 0;
- msel = 0;
- while (val->String.legalRange[i] != NULL) {
- items[i].name = "";
- items[i].text = val->String.legalRange[i];
- tlen += strlen(val->String.legalRange[i]) + 1;
- items[i].help = "";
- items[i].state = 0;
+ while (val->String.legalRange[i] != NULL)
+ {
+ items[i].name = "";
+ items[i].text = val->String.legalRange[i];
+ items[i].help = "";
+ items[i].state = 0;
+ if (0 == strcmp (val->String.legalRange[i],
+ val->String.val))
+ {
+ items[i].state = 1;
+ msel = i;
+ }
+ if ((msel == -1) &&
+ (0 == strcmp (val->String.legalRange[i],
+ val->String.def)))
+ msel = i;
+ i++;
+ }
+ st = dlg_checklist (gettext (pos->option),
+ gettext (pos->description),
+ 20,
+ 70, 13, i, items, " *", FLAG_RADIO, &msel);
+ FREE (items);
+ switch (st)
+ {
+ case DLG_EXIT_OK:
+ if (0 != GC_set_configuration_value_choice (cfg,
+ ectx,
+ pos->section,
+ pos->option,
+ val->String.
+ legalRange
+ [msel]))
+ {
+ show_help (pos->option,
+ gettext_noop
+ ("Internal error! (Choice invalid?)"));
+ break;
+ }
+ return;
+ case DLG_EXIT_HELP:
+ show_help (pos->option, pos->help);
+ break;
+ case DLG_EXIT_ESC:
+ case DLG_EXIT_ERROR:
+ case DLG_EXIT_CANCEL:
+ default:
+ return;
+ }
+ break;
+ case GNS_MC:
+ /* begin multiple choice */
+ val = &pos->value;
+ i = 0;
+ tlen = 2;
+ while (val->String.legalRange[i] != NULL)
+ i++;
+ GE_ASSERT (ectx, i != 0);
+ items = MALLOC (sizeof (DIALOG_LISTITEM) * i);
+ i = 0;
+ msel = 0;
+ while (val->String.legalRange[i] != NULL)
+ {
+ items[i].name = "";
+ items[i].text = val->String.legalRange[i];
+ tlen += strlen (val->String.legalRange[i]) + 1;
+ items[i].help = "";
+ items[i].state = 0;
- tmp = val->String.val;
- while (NULL != (tmp = strstr(tmp,
- val->String.legalRange[i]))) {
- if ( ( (tmp == val->String.val) ||
- (tmp[-1] == ' ') ) &&
- ( (strlen(tmp) == strlen(val->String.legalRange[i])) ||
- (tmp[strlen(val->String.legalRange[i])] == ' ') ) ) {
- items[i].state = 1;
- break;
- }
- tmp++; /* make sure strstr advances */
- }
- i++;
- }
- st = dlg_checklist(gettext(pos->option),
- gettext(pos->description),
- 20,
- 70,
- 13,
- i,
- items,
- " *",
- FLAG_CHECK,
- &msel);
- switch (st) {
- case DLG_EXIT_OK:
- tmp = MALLOC(tlen);
- tmp[0] = '\0';
- i = 0;
- while (val->String.legalRange[i] != NULL) {
- if (items[i].state == 1) {
- strcat(tmp, items[i].text);
- strcat(tmp, " ");
- }
- i++;
- }
- if (strlen(tmp) > 0)
- tmp[strlen(tmp)-1] = '\0';
- if (0 != GC_set_configuration_value_choice(cfg,
- ectx,
- pos->section,
- pos->option,
- tmp)) {
- FREE(tmp);
- show_help(pos->option,
- gettext_noop("Internal error! (Choice invalid?)"));
- break;
- }
- FREE(tmp);
- FREE(items);
- return;
- case DLG_EXIT_HELP:
- show_help(pos->option,
- pos->help);
- break;
- case DLG_EXIT_ESC:
- case DLG_EXIT_ERROR:
- case DLG_EXIT_CANCEL:
- default:
- FREE(items);
- return;
- }
- FREE(items);
- break;
- case GNS_Double:
- fitem.text = MALLOC(64);
- SNPRINTF(fitem.text,
- 64,
- "%f",
- pos->value.Double.val);
- fitem.text_len = strlen(fitem.text);
- fitem.help = pos->help;
- st = DLG_EXIT_HELP;
- msel = 0;
- st = dlg_form(pos->option,
- "",
- 20,
- 70,
- 15,
- 1,
- &fitem,
- &msel);
- switch (st) {
- case DLG_EXIT_OK:
- if (1 != sscanf(fitem.text,
- "%lf",
- &dval)) {
- show_help(pos->option,
- gettext_noop("Invalid input, expecting floating point value."));
- break;
- }
- if (0 != GC_set_configuration_value_string(cfg,
- ectx,
- pos->section,
- pos->option,
- fitem.text)) {
- show_help(pos->option,
- gettext_noop("Internal error! (Value invalid?)"));
- break;
- }
- FREE(fitem.text);
- return;
- case DLG_EXIT_HELP:
- show_help(pos->option, pos->help);
- break;
- default:
- break;
- }
- FREE(fitem.text);
- break;
+ tmp = val->String.val;
+ while (NULL != (tmp = strstr (tmp,
+ val->String.legalRange[i])))
+ {
+ if (((tmp == val->String.val) ||
+ (tmp[-1] == ' ')) &&
+ ((strlen (tmp) ==
+ strlen (val->String.legalRange[i]))
+ || (tmp[strlen (val->String.legalRange[i])] ==
+ ' ')))
+ {
+ items[i].state = 1;
+ break;
+ }
+ tmp++; /* make sure strstr advances */
+ }
+ i++;
+ }
+ st = dlg_checklist (gettext (pos->option),
+ gettext (pos->description),
+ 20,
+ 70, 13, i, items, " *", FLAG_CHECK, &msel);
+ switch (st)
+ {
+ case DLG_EXIT_OK:
+ tmp = MALLOC (tlen);
+ tmp[0] = '\0';
+ i = 0;
+ while (val->String.legalRange[i] != NULL)
+ {
+ if (items[i].state == 1)
+ {
+ strcat (tmp, items[i].text);
+ strcat (tmp, " ");
+ }
+ i++;
+ }
+ if (strlen (tmp) > 0)
+ tmp[strlen (tmp) - 1] = '\0';
+ if (0 != GC_set_configuration_value_choice (cfg,
+ ectx,
+ pos->section,
+ pos->option,
+ tmp))
+ {
+ FREE (tmp);
+ show_help (pos->option,
+ gettext_noop
+ ("Internal error! (Choice invalid?)"));
+ break;
+ }
+ FREE (tmp);
+ FREE (items);
+ return;
+ case DLG_EXIT_HELP:
+ show_help (pos->option, pos->help);
+ break;
+ case DLG_EXIT_ESC:
+ case DLG_EXIT_ERROR:
+ case DLG_EXIT_CANCEL:
+ default:
+ FREE (items);
+ return;
+ }
+ FREE (items);
+ break;
+ case GNS_Double:
+ fitem.text = MALLOC (64);
+ SNPRINTF (fitem.text, 64, "%f", pos->value.Double.val);
+ fitem.text_len = strlen (fitem.text);
+ fitem.help = pos->help;
+ st = DLG_EXIT_HELP;
+ msel = 0;
+ st = dlg_form (pos->option, "", 20, 70, 15, 1, &fitem, &msel);
+ switch (st)
+ {
+ case DLG_EXIT_OK:
+ if (1 != sscanf (fitem.text, "%lf", &dval))
+ {
+ show_help (pos->option,
+ gettext_noop
+ ("Invalid input, expecting floating point
value."));
+ break;
+ }
+ if (0 != GC_set_configuration_value_string (cfg,
+ ectx,
+ pos->section,
+ pos->option,
+ fitem.text))
+ {
+ show_help (pos->option,
+ gettext_noop
+ ("Internal error! (Value invalid?)"));
+ break;
+ }
+ FREE (fitem.text);
+ return;
+ case DLG_EXIT_HELP:
+ show_help (pos->option, pos->help);
+ break;
+ default:
+ break;
+ }
+ FREE (fitem.text);
+ break;
- case GNS_UInt64:
- fitem.text = MALLOC(64);
- SNPRINTF(fitem.text,
- 64,
- "%llu",
- pos->value.UInt64.val);
- fitem.text_len = strlen(fitem.text);
- fitem.help = pos->help;
- st = DLG_EXIT_HELP;
- msel = 0;
- while (st == DLG_EXIT_HELP) {
- st = dlg_form(pos->option,
- "",
- 20,
- 70,
- 15,
- 1,
- &fitem,
- &msel);
- switch (st) {
- case DLG_EXIT_OK:
- if (1 != sscanf(fitem.text,
- "%llu",
- &lval)) {
- show_help(pos->option,
- gettext_noop("Invalid input, expecting integer."));
- continue;
- }
- if ( (lval < pos->value.UInt64.min) ||
- (lval > pos->value.UInt64.max)) {
- show_help(pos->option,
- gettext_noop("Value is not in legal range."));
- continue;
- }
- if (0 != GC_set_configuration_value_number(cfg,
- ectx,
- pos->section,
- pos->option,
- lval)) {
- show_help(pos->option,
- gettext_noop("Internal error! (Choice invalid?)"));
- continue;
- }
- break;
- case DLG_EXIT_HELP:
- show_help(pos->option, pos->help);
- break;
- default:
- break;
- }
- }
- FREE(fitem.text);
- return;
- default:
- GE_BREAK(ectx, 0);
- return;
- } /* end switch type & type */
- break;
+ case GNS_UInt64:
+ fitem.text = MALLOC (64);
+ SNPRINTF (fitem.text, 64, "%llu", pos->value.UInt64.val);
+ fitem.text_len = strlen (fitem.text);
+ fitem.help = pos->help;
+ st = DLG_EXIT_HELP;
+ msel = 0;
+ while (st == DLG_EXIT_HELP)
+ {
+ st = dlg_form (pos->option,
+ "", 20, 70, 15, 1, &fitem, &msel);
+ switch (st)
+ {
+ case DLG_EXIT_OK:
+ if (1 != sscanf (fitem.text, "%llu", &lval))
+ {
+ show_help (pos->option,
+ gettext_noop
+ ("Invalid input, expecting integer."));
+ continue;
+ }
+ if ((lval < pos->value.UInt64.min) ||
+ (lval > pos->value.UInt64.max))
+ {
+ show_help (pos->option,
+ gettext_noop
+ ("Value is not in legal range."));
+ continue;
+ }
+ if (0 != GC_set_configuration_value_number (cfg,
+ ectx,
+ pos->
+ section,
+ pos->option,
+ lval))
+ {
+ show_help (pos->option,
+ gettext_noop
+ ("Internal error! (Choice invalid?)"));
+ continue;
+ }
+ break;
+ case DLG_EXIT_HELP:
+ show_help (pos->option, pos->help);
+ break;
+ default:
+ break;
+ }
+ }
+ FREE (fitem.text);
+ return;
+ default:
+ GE_BREAK (ectx, 0);
+ return;
+ } /* end switch type & type */
+ break;
- default:
- GE_BREAK(ectx, 0);
- break;
+ default:
+ GE_BREAK (ectx, 0);
+ break;
- } /* end switch type & Kind */
- } /* end while(1) */
+ } /* end switch type & Kind */
+ } /* end while(1) */
}
-int mconf_mainsetup_curses(int argc,
- const char **argv,
- struct PluginHandle * self,
- struct GE_Context * e,
- struct GC_Configuration * cfg,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon) {
+int
+mconf_mainsetup_curses (int argc,
+ const char **argv,
+ struct PluginHandle *self,
+ struct GE_Context *e,
+ struct GC_Configuration *cfg,
+ struct GNS_Context *gns,
+ const char *filename, int is_daemon)
+{
int ret;
struct termios ios_org;
ectx = e;
#ifndef MINGW
- tcgetattr(1, &ios_org);
+ tcgetattr (1, &ios_org);
#endif
dialog_vars.backtitle = _("GNUnet Configuration");
dialog_vars.item_help = 1;
dialog_vars.help_button = 1;
- init_dialog(stdin, stderr);
+ init_dialog (stdin, stderr);
- run_menu(gns,
- GNS_get_tree(gns),
- cfg);
+ run_menu (gns, GNS_get_tree (gns), cfg);
ret = 0;
- if ( (0 == GC_test_dirty(cfg)) &&
- (0 == ACCESS(filename, R_OK)) ) {
- end_dialog();
- printf(_("Configuration unchanged, no need to save.\n"));
- } else {
- dialog_vars.help_button = 0;
- ret = dialog_yesno(NULL,
- _("Do you wish to save your new configuration?"),
- 5, 60);
- end_dialog();
- if (ret == DLG_EXIT_OK) {
- if (0 != GC_write_configuration(cfg,
- filename)) {
- /* error message already printed... */
- ret = 1;
- } else {
- ret = 0;
- }
- printf(_("\nEnd of configuration.\n"));
- } else {
- ret = 0;
- printf(_("\nYour configuration changes were NOT saved.\n"));
+ if ((0 == GC_test_dirty (cfg)) && (0 == ACCESS (filename, R_OK)))
+ {
+ end_dialog ();
+ printf (_("Configuration unchanged, no need to save.\n"));
}
- }
+ else
+ {
+ dialog_vars.help_button = 0;
+ ret = dialog_yesno (NULL,
+ _("Do you wish to save your new configuration?"),
+ 5, 60);
+ end_dialog ();
+ if (ret == DLG_EXIT_OK)
+ {
+ if (0 != GC_write_configuration (cfg, filename))
+ {
+ /* error message already printed... */
+ ret = 1;
+ }
+ else
+ {
+ ret = 0;
+ }
+ printf (_("\nEnd of configuration.\n"));
+ }
+ else
+ {
+ ret = 0;
+ printf (_("\nYour configuration changes were NOT saved.\n"));
+ }
+ }
#ifndef MINGW
- tcsetattr(1, TCSAFLUSH, &ios_org);
+ tcsetattr (1, TCSAFLUSH, &ios_org);
#endif
return ret;
}
Modified: GNUnet/src/setup/ncurses/mconf.h
===================================================================
--- GNUnet/src/setup/ncurses/mconf.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/ncurses/mconf.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -28,13 +28,12 @@
#ifndef MCONF_H
#define MCONF_H
-int main_setup_ncurses(int argc,
- const char **argv,
- struct PluginHandle * self,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon);
+int main_setup_ncurses (int argc,
+ const char **argv,
+ struct PluginHandle *self,
+ struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct GNS_Context *gns,
+ const char *filename, int is_daemon);
#endif
Modified: GNUnet/src/setup/ncurses/wizard_curs.c
===================================================================
--- GNUnet/src/setup/ncurses/wizard_curs.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/setup/ncurses/wizard_curs.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -47,54 +47,44 @@
#include <grp.h>
#endif
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
static int last;
-static const char * cfg_fn;
+static const char *cfg_fn;
-static void showCursErr(const char * prefix,
- const char * error) {
- char * err;
+static void
+showCursErr (const char *prefix, const char *error)
+{
+ char *err;
- err = MALLOC(strlen(prefix) + strlen(error) + 2);
- sprintf(err,
- "%s %s",
- prefix,
- error);
- dialog_msgbox(_("Error"),
- err,
- 70,
- 15,
- 1);
- FREE(err);
+ err = MALLOC (strlen (prefix) + strlen (error) + 2);
+ sprintf (err, "%s %s", prefix, error);
+ dialog_msgbox (_("Error"), err, 70, 15, 1);
+ FREE (err);
}
-static void show_help(const char * helptext) {
+static void
+show_help (const char *helptext)
+{
dialog_vars.help_button = 0;
- dialog_msgbox(_("Help"),
- helptext,
- 20,
- 70,
- TRUE);
+ dialog_msgbox (_("Help"), helptext, 20, 70, TRUE);
}
-static void show_error(const char * msg) {
+static void
+show_error (const char *msg)
+{
dialog_vars.help_button = 0;
- dialog_msgbox(_("Error!"),
- msg,
- 20,
- 70,
- TRUE);
+ dialog_msgbox (_("Error!"), msg, 20, 70, TRUE);
}
-static int query_yesno(const char * title,
- const char * question,
- const char * help,
- const char * section,
- const char * option) {
+static int
+query_yesno (const char *title,
+ const char *question,
+ const char *help, const char *section, const char *option)
+{
int ret;
if (help == NULL)
@@ -103,45 +93,44 @@
dialog_vars.help_button = 1;
dialog_vars.cancel_label = _("No");
dialog_vars.ok_label = _("Yes");
- while (true) {
- ret = dialog_yesno(title,
- question,
- 20,
- 70);
- switch(ret) {
- case DLG_EXIT_OK:
- case DLG_EXIT_CANCEL:
- if (0 != GC_set_configuration_value_string(cfg,
- ectx,
- section,
- option,
- ret == DLG_EXIT_OK
- ? "YES"
- : "NO")) {
- show_error(_("Internal error! (Choice invalid?)"));
- break;
- }
- return 1; /* advance */
- case DLG_EXIT_ESC:
- return 0; /* abort */
- case DLG_EXIT_HELP:
- show_help(help);
- break;
- case DLG_EXIT_EXTRA:
- return -1; /* back */
- default:
- GE_BREAK(ectx, 0);
- break;
+ while (true)
+ {
+ ret = dialog_yesno (title, question, 20, 70);
+ switch (ret)
+ {
+ case DLG_EXIT_OK:
+ case DLG_EXIT_CANCEL:
+ if (0 != GC_set_configuration_value_string (cfg,
+ ectx,
+ section,
+ option,
+ ret == DLG_EXIT_OK
+ ? "YES" : "NO"))
+ {
+ show_error (_("Internal error! (Choice invalid?)"));
+ break;
+ }
+ return 1; /* advance */
+ case DLG_EXIT_ESC:
+ return 0; /* abort */
+ case DLG_EXIT_HELP:
+ show_help (help);
+ break;
+ case DLG_EXIT_EXTRA:
+ return -1; /* back */
+ default:
+ GE_BREAK (ectx, 0);
+ break;
+ }
}
- }
}
-static int query_string(const char * title,
- const char * question,
- const char * help,
- const char * section,
- const char * option,
- const char * def) {
+static int
+query_string (const char *title,
+ const char *question,
+ const char *help,
+ const char *section, const char *option, const char *def)
+{
int ret;
int msel;
DIALOG_FORMITEM fitem;
@@ -153,8 +142,8 @@
dialog_vars.cancel_label = _("Abort");
dialog_vars.ok_label = _("Ok");
fitem.type = 0;
- fitem.name = STRDUP(question);
- fitem.name_len = strlen(question);
+ fitem.name = STRDUP (question);
+ fitem.name_len = strlen (question);
fitem.name_y = 3;
fitem.name_x = 5;
fitem.name_free = 0;
@@ -164,96 +153,94 @@
fitem.text_ilen = 63;
fitem.text_free = 0;
fitem.help_free = 0;
- fitem.text = MALLOC(65536);
- strcpy(fitem.text,
- def);
- fitem.text_len = strlen(fitem.text);
- fitem.help = STRDUP(help);
+ fitem.text = MALLOC (65536);
+ strcpy (fitem.text, def);
+ fitem.text_len = strlen (fitem.text);
+ fitem.help = STRDUP (help);
msel = 0;
ret = 2;
- while (ret == 2) {
- ret = dlg_form(title,
- "",
- 20,
- 70,
- 15,
- 1,
- &fitem,
- &msel);
- switch(ret) {
- case DLG_EXIT_OK:
- if (0 != GC_set_configuration_value_string(cfg,
- ectx,
- section,
- option,
- fitem.text)) {
- show_error(_("Internal error! (Choice invalid?)"));
- ret = 2;
- } else {
- ret = 1; /* advance */
- }
- break;
- case DLG_EXIT_CANCEL:
- case DLG_EXIT_ESC:
- ret = 0; /* abort */
- break;
- case DLG_EXIT_HELP:
- show_help(help);
- ret = 2;
- break;
- case DLG_EXIT_EXTRA:
- ret = -1; /* back */
- break;
- default:
- GE_BREAK(ectx, 0);
- ret = 0;
- break;
+ while (ret == 2)
+ {
+ ret = dlg_form (title, "", 20, 70, 15, 1, &fitem, &msel);
+ switch (ret)
+ {
+ case DLG_EXIT_OK:
+ if (0 != GC_set_configuration_value_string (cfg,
+ ectx,
+ section,
+ option, fitem.text))
+ {
+ show_error (_("Internal error! (Choice invalid?)"));
+ ret = 2;
+ }
+ else
+ {
+ ret = 1; /* advance */
+ }
+ break;
+ case DLG_EXIT_CANCEL:
+ case DLG_EXIT_ESC:
+ ret = 0; /* abort */
+ break;
+ case DLG_EXIT_HELP:
+ show_help (help);
+ ret = 2;
+ break;
+ case DLG_EXIT_EXTRA:
+ ret = -1; /* back */
+ break;
+ default:
+ GE_BREAK (ectx, 0);
+ ret = 0;
+ break;
+ }
}
- }
- FREE(fitem.name);
- FREE(fitem.text);
- FREE(fitem.help);
+ FREE (fitem.name);
+ FREE (fitem.text);
+ FREE (fitem.help);
return ret;
}
-static int welcome() {
+static int
+welcome ()
+{
dialog_vars.help_button = 0;
- dialog_msgbox(_("GNUnet configuration"),
- _("Welcome to GNUnet!\n\nThis assistant will ask you a few basic
questions "
- "in order to configure GNUnet.\n\nPlease visit our homepage at\n\t"
- "http://gnunet.org/\nand join our community at\n\t"
- "http://gnunet.org/drupal/\n\nHave a lot of fun,\n\nthe GNUnet team"),
- 20,
- 70,
- TRUE);
+ dialog_msgbox (_("GNUnet configuration"),
+ _
+ ("Welcome to GNUnet!\n\nThis assistant will ask you a few
basic questions "
+ "in order to configure GNUnet.\n\nPlease visit our homepage
at\n\t"
+ "http://gnunet.org/\nand join our community at\n\t"
+ "http://gnunet.org/drupal/\n\nHave a lot of fun,\n\nthe
GNUnet team"),
+ 20, 70, TRUE);
return 1;
}
#define MAX_NIC 64
-static int insert_nic_curs(const char * name,
- int defaultNIC,
- void * cls) {
- DIALOG_LISTITEM * nic_items = cls;
- DIALOG_LISTITEM * item;
+static int
+insert_nic_curs (const char *name, int defaultNIC, void *cls)
+{
+ DIALOG_LISTITEM *nic_items = cls;
+ DIALOG_LISTITEM *item;
unsigned int pos;
pos = 0;
- while ( (pos < MAX_NIC) &&
- (nic_items[pos].text != NULL) )
+ while ((pos < MAX_NIC) && (nic_items[pos].text != NULL))
pos++;
if (pos == MAX_NIC)
return SYSERR;
item = &nic_items[pos];
item->name = "";
- item->text = STRDUP(name);
+ item->text = STRDUP (name);
item->help = "";
item->state = defaultNIC;
return OK;
}
-static int network_interface() {
+static int
+network_interface ()
+{
DIALOG_LISTITEM nic_items[MAX_NIC];
unsigned int total;
int ret;
@@ -262,7 +249,7 @@
fitem.type = 0;
fitem.name = "";
- fitem.name_len = strlen(fitem.name);
+ fitem.name_len = strlen (fitem.name);
fitem.name_y = 3;
fitem.name_x = 5;
fitem.name_free = 0;
@@ -272,282 +259,267 @@
fitem.text_ilen = 63;
fitem.text_free = 0;
fitem.help_free = 0;
- memset(nic_items,
- 0,
- sizeof(DIALOG_LISTITEM) * MAX_NIC);
- os_list_network_interfaces(NULL,
- &insert_nic_curs,
- nic_items);
+ memset (nic_items, 0, sizeof (DIALOG_LISTITEM) * MAX_NIC);
+ os_list_network_interfaces (NULL, &insert_nic_curs, nic_items);
total = 0;
- while ( (total < MAX_NIC) &&
- (nic_items[total].text != NULL) ) {
- if (nic_items[total].state)
- msel = total;
- total++;
- }
- if (total > 0) {
- while (true) {
- ret = dlg_menu(_("GNUnet configuration"),
- _("Choose the network interface that connects your computer to "
- "the internet from the list below."),
- 20,
- 70,
- 10,
- total,
- nic_items,
- &msel,
- NULL);
- switch (ret) {
- case DLG_EXIT_OK:
- if (0 != GC_set_configuration_value_choice(cfg,
- ectx,
- "NETWORK",
- "INTERFACE",
- nic_items[msel].name)) {
- show_error(_("Internal error! (Choice invalid?)"));
- break;
- }
- return 1;
- case DLG_EXIT_HELP:
- show_help(_("The \"Network interface\" is the device "
- "that connects your computer to the internet. This is usually a
modem, "
- "an ISDN card or a network card in case you are using DSL."));
- break;
- case DLG_EXIT_ESC:
- case DLG_EXIT_ERROR:
- case DLG_EXIT_CANCEL:
- return 0;
- }
+ while ((total < MAX_NIC) && (nic_items[total].text != NULL))
+ {
+ if (nic_items[total].state)
+ msel = total;
+ total++;
}
- }
- return query_string(_("Network configuration: interface"),
- _("What is the name of the network interface that connects your
computer to the Internet?"),
- _("The \"Network interface\" is the device "
- "that connects your computer to the internet. This is usually a
modem, "
- "an ISDN card or a network card in case you are using DSL."),
- "NETWORK",
- "INTERFACE",
- "eth0");
+ if (total > 0)
+ {
+ while (true)
+ {
+ ret = dlg_menu (_("GNUnet configuration"),
+ _
+ ("Choose the network interface that connects your
computer to "
+ "the internet from the list below."), 20, 70, 10,
+ total, nic_items, &msel, NULL);
+ switch (ret)
+ {
+ case DLG_EXIT_OK:
+ if (0 != GC_set_configuration_value_choice (cfg,
+ ectx,
+ "NETWORK",
+ "INTERFACE",
+ nic_items[msel].
+ name))
+ {
+ show_error (_("Internal error! (Choice invalid?)"));
+ break;
+ }
+ return 1;
+ case DLG_EXIT_HELP:
+ show_help (_("The \"Network interface\" is the device "
+ "that connects your computer to the internet. This
is usually a modem, "
+ "an ISDN card or a network card in case you are
using DSL."));
+ break;
+ case DLG_EXIT_ESC:
+ case DLG_EXIT_ERROR:
+ case DLG_EXIT_CANCEL:
+ return 0;
+ }
+ }
+ }
+ return query_string (_("Network configuration: interface"),
+ _
+ ("What is the name of the network interface that
connects your computer to the Internet?"),
+ _("The \"Network interface\" is the device "
+ "that connects your computer to the internet. This is
usually a modem, "
+ "an ISDN card or a network card in case you are using
DSL."),
+ "NETWORK", "INTERFACE", "eth0");
}
-static int nat_limited() {
+static int
+nat_limited ()
+{
/* TODO: try autodetect! */
- return query_yesno(_("Network configuration: NAT"),
- _("Is this machine behind "
- "NAT?\n\nIf you are connected to the internet through another
computer "
- "doing SNAT, a router or a \"hardware firewall\" and other
computers "
- "on the internet cannot connect to this computer, say \"yes\"
here. "
- "Answer \"no\" on direct connections through modems, ISDN cards
and "
- "DNAT (also known as \"port forwarding\")."),
- NULL,
- "NAT",
- "LIMITED");
+ return query_yesno (_("Network configuration: NAT"),
+ _("Is this machine behind "
+ "NAT?\n\nIf you are connected to the internet through
another computer "
+ "doing SNAT, a router or a \"hardware firewall\" and
other computers "
+ "on the internet cannot connect to this computer, say
\"yes\" here. "
+ "Answer \"no\" on direct connections through modems,
ISDN cards and "
+ "DNAT (also known as \"port forwarding\")."),
+ NULL, "NAT", "LIMITED");
}
-static int ip_address() {
+static int
+ip_address ()
+{
/* TODO: try autodetect! */
- return query_string(_("Network configuration: IP"),
- _("What is this computer's public IP address or hostname?"),
- _("If your provider always assigns the same "
- "IP-Address to you (a \"static\" IP-Address), enter it into the
"
- "\"IP-Address\" field. If your IP-Address changes every now and
then "
- "(\"dynamic\" IP-Address) but there's a hostname that always
points "
- "to your actual IP-Address (\"Dynamic DNS\"), you can also
enter it "
- "here.\n"
- "If left empty, GNUnet will try to automatically detect the
IP.\n"
- "You can specify a hostname, GNUnet will then use DNS to
resolve it.\n"
- "If in doubt, leave this empty."),
- "NETWORK",
- "IP",
- "");
+ return query_string (_("Network configuration: IP"),
+ _
+ ("What is this computer's public IP address or
hostname?"),
+ _("If your provider always assigns the same "
+ "IP-Address to you (a \"static\" IP-Address), enter
it into the "
+ "\"IP-Address\" field. If your IP-Address changes
every now and then "
+ "(\"dynamic\" IP-Address) but there's a hostname that
always points "
+ "to your actual IP-Address (\"Dynamic DNS\"), you can
also enter it "
+ "here.\n"
+ "If left empty, GNUnet will try to automatically
detect the IP.\n"
+ "You can specify a hostname, GNUnet will then use DNS
to resolve it.\n"
+ "If in doubt, leave this empty."), "NETWORK", "IP",
+ "");
}
-static int network_load_up() {
- return query_string(_("Bandwidth configuration: upload"),
- _("How much upstream bandwidth (in bytes/s) may be used?"),
- _("You can limit GNUnet's resource usage "
- "here.\n\nThe \"upstream\" is the data channel through which
data "
- "is *sent* to the internet. The limit is the maximum amount"
- "which GNUnet is allowed to use. If you have a flatrate, you
can set it to "
- "the maximum speed of your internet connection. You should not
use a value "
- "that is higher than what your actual connection allows."),
- "LOAD",
- "MAXNETUPBPSTOTAL",
- "50000");
+static int
+network_load_up ()
+{
+ return query_string (_("Bandwidth configuration: upload"),
+ _
+ ("How much upstream bandwidth (in bytes/s) may be
used?"),
+ _("You can limit GNUnet's resource usage "
+ "here.\n\nThe \"upstream\" is the data channel
through which data "
+ "is *sent* to the internet. The limit is the maximum
amount"
+ "which GNUnet is allowed to use. If you have a
flatrate, you can set it to "
+ "the maximum speed of your internet connection. You
should not use a value "
+ "that is higher than what your actual connection
allows."),
+ "LOAD", "MAXNETUPBPSTOTAL", "50000");
}
-static int network_load_down() {
- return query_string(_("Bandwidth configuration: download"),
- _("How much downstream bandwidth (in bytes/s) may be used?"),
- _("You can limit GNUnet's resource usage "
- "here.\n\nThe \"downstream\" is the data channel through which
data "
- "is *received* from the internet. The limit is the maximum
amount"
- "which GNUnet is allowed to use. If you have a flatrate, you
can set it to "
- "the maximum speed of your internet connection. You should not
use a value "
- "that is higher than what your actual connection allows."),
- "LOAD",
- "MAXNETDOWNBPSTOTAL",
- "50000");
+static int
+network_load_down ()
+{
+ return query_string (_("Bandwidth configuration: download"),
+ _
+ ("How much downstream bandwidth (in bytes/s) may be
used?"),
+ _("You can limit GNUnet's resource usage "
+ "here.\n\nThe \"downstream\" is the data channel
through which data "
+ "is *received* from the internet. The limit is the
maximum amount"
+ "which GNUnet is allowed to use. If you have a
flatrate, you can set it to "
+ "the maximum speed of your internet connection. You
should not use a value "
+ "that is higher than what your actual connection
allows."),
+ "LOAD", "MAXNETDOWNBPSTOTAL", "50000");
}
-static int disk_quota() {
- return query_string(_("Quota configuration"),
- _("What is the maximum size of the datastore in MB?"),
- _("The GNUnet datastore contains all content that "
- "GNUnet needs to store (indexed, inserted and migrated
content)."),
- "FS",
- "QUOTA",
- "1024");
+static int
+disk_quota ()
+{
+ return query_string (_("Quota configuration"),
+ _("What is the maximum size of the datastore in MB?"),
+ _("The GNUnet datastore contains all content that "
+ "GNUnet needs to store (indexed, inserted and
migrated content)."),
+ "FS", "QUOTA", "1024");
}
-static int user() {
- if (YES != os_modify_user(YES,
- YES,
- "gnunet",
- "gnunet"))
- return last; /* ignore option */
- return query_string(_("Daemon configuration: user account"),
- _("As which user should gnunetd be run?"),
- _("For security reasons, it is a good idea to let this setup
create "
- "a new user account under which the GNUnet service is started "
- "at system startup.\n\n"
- "However, GNUnet may not be able to access files other than its
own. "
- "This includes files you want to publish in GNUnet. You'll have
to "
- "grant read permissions to the user specified below.\n\n"
- "Leave the field empty to run GNUnet with system
privileges.\n"),
- "GNUNETD",
- "USER",
- "gnunet");
+static int
+user ()
+{
+ if (YES != os_modify_user (YES, YES, "gnunet", "gnunet"))
+ return last; /* ignore option */
+ return query_string (_("Daemon configuration: user account"),
+ _("As which user should gnunetd be run?"),
+ _
+ ("For security reasons, it is a good idea to let this
setup create "
+ "a new user account under which the GNUnet service is
started "
+ "at system startup.\n\n"
+ "However, GNUnet may not be able to access files other
than its own. "
+ "This includes files you want to publish in GNUnet.
You'll have to "
+ "grant read permissions to the user specified
below.\n\n"
+ "Leave the field empty to run GNUnet with system
privileges.\n"),
+ "GNUNETD", "USER", "gnunet");
}
-static int group() {
- if (YES != os_modify_user(YES,
- YES,
- "gnunet",
- "gnunet"))
- return last; /* ignore option */
- return query_string(_("Daemon configuration: group account"),
- _("As which group should gnunetd be run?"),
- _("For security reasons, it is a good idea to let this setup
create "
- "a new group for the chosen user account.\n\n"
- "You can also specify a already existant group here.\n\n"
- "Only members of this group will be allowed to start and stop
the "
- "the GNUnet server and have access to GNUnet server data.\n"),
- "GNUNETD",
- "GROUP",
- "gnunet");
+static int
+group ()
+{
+ if (YES != os_modify_user (YES, YES, "gnunet", "gnunet"))
+ return last; /* ignore option */
+ return query_string (_("Daemon configuration: group account"),
+ _("As which group should gnunetd be run?"),
+ _
+ ("For security reasons, it is a good idea to let this
setup create "
+ "a new group for the chosen user account.\n\n"
+ "You can also specify a already existant group
here.\n\n"
+ "Only members of this group will be allowed to start
and stop the "
+ "the GNUnet server and have access to GNUnet server
data.\n"),
+ "GNUNETD", "GROUP", "gnunet");
}
-static int autostart() {
- return query_yesno(_("GNUnet configuration"),
- _("Do you want to automatically launch GNUnet as a system
service?"),
- _("If you say \"yes\" here, the GNUnet background process will be "
- "automatically started when you turn on your computer. If you
say \"no\""
- " here, you have to launch GNUnet yourself each time you want to
use it."),
- "GNUNETD",
- "AUTOSTART");
+static int
+autostart ()
+{
+ return query_yesno (_("GNUnet configuration"),
+ _
+ ("Do you want to automatically launch GNUnet as a system
service?"),
+ _
+ ("If you say \"yes\" here, the GNUnet background process
will be "
+ "automatically started when you turn on your computer.
If you say \"no\""
+ " here, you have to launch GNUnet yourself each time
you want to use it."),
+ "GNUNETD", "AUTOSTART");
}
/**
* Save configuration, setup username, group and autostart.
*/
-static int finish() {
- const char * prefix;
- char * err;
+static int
+finish ()
+{
+ const char *prefix;
+ char *err;
int ret;
- char * user_name;
- char * group_name;
+ char *user_name;
+ char *group_name;
ret = OK;
- if ( (0 != GC_test_dirty(cfg)) &&
- (0 != GC_write_configuration(cfg, cfg_fn)) ) {
- prefix = _("Unable to save configuration file `%s':");
- err = MALLOC(strlen(cfg_fn) + strlen(prefix) + 1);
- sprintf(err, prefix, cfg_fn);
- showCursErr(err, STRERROR(errno));
- ret = SYSERR;
- }
+ if ((0 != GC_test_dirty (cfg)) &&
+ (0 != GC_write_configuration (cfg, cfg_fn)))
+ {
+ prefix = _("Unable to save configuration file `%s':");
+ err = MALLOC (strlen (cfg_fn) + strlen (prefix) + 1);
+ sprintf (err, prefix, cfg_fn);
+ showCursErr (err, STRERROR (errno));
+ ret = SYSERR;
+ }
user_name = NULL;
- GC_get_configuration_value_string(cfg,
- "GNUNETD",
- "USER",
- "",
- &user_name);
- GC_get_configuration_value_string(cfg,
- "GNUNETD",
- "GROUP",
- "",
- &group_name);
- if ( ( (strlen(user_name) > 0) ||
- (strlen(group_name) > 0) ) &&
- (OK == os_modify_user(YES,
- YES,
- user_name,
- group_name)) &&
- (OK != os_modify_user(NO,
- YES,
- user_name,
- group_name)) ) {
- showCursErr(_("Unable to create user account for daemon."),
- "");
- ret = SYSERR;
- }
- if ( (YES == GC_get_configuration_value_yesno(cfg,
- "GNUNETD",
- "AUTOSTART",
- NO)) &&
- (YES != os_modify_autostart(ectx,
- NO,
- YES,
- "gnunetd", /* specify full path? */
- user_name,
- group_name)) ) {
- showCursErr(_("Unable to setup autostart for daemon."),
- "");
- ret = SYSERR;
- }
- FREE(user_name);
- FREE(group_name);
+ GC_get_configuration_value_string (cfg, "GNUNETD", "USER", "", &user_name);
+ GC_get_configuration_value_string (cfg,
+ "GNUNETD", "GROUP", "", &group_name);
+ if (((strlen (user_name) > 0) ||
+ (strlen (group_name) > 0)) &&
+ (OK == os_modify_user (YES,
+ YES,
+ user_name,
+ group_name)) &&
+ (OK != os_modify_user (NO, YES, user_name, group_name)))
+ {
+ showCursErr (_("Unable to create user account for daemon."), "");
+ ret = SYSERR;
+ }
+ if ((YES == GC_get_configuration_value_yesno (cfg, "GNUNETD", "AUTOSTART",
NO)) && (YES != os_modify_autostart (ectx, NO, YES, "gnunetd", /* specify
full path? */
+
user_name,
+
group_name)))
+ {
+ showCursErr (_("Unable to setup autostart for daemon."), "");
+ ret = SYSERR;
+ }
+ FREE (user_name);
+ FREE (group_name);
return ret;
}
-static int save_config() {
+static int
+save_config ()
+{
int ret;
/* TODO: check configuration changed! */
dialog_vars.help_button = 0;
- ret = dialog_yesno(_("Save configuration?"),
- _("Save configuration now?"),
- 5,
- 60);
- switch(ret) {
- case DLG_EXIT_OK:
- if (OK != finish())
- return 0; /* error */
- return 1;
- case DLG_EXIT_CANCEL:
- return 1; /* advance */
- case DLG_EXIT_ESC:
- return 0; /* abort */
- case DLG_EXIT_EXTRA:
- return -1; /* back */
- default:
- GE_BREAK(ectx, 0);
- break;
- }
+ ret = dialog_yesno (_("Save configuration?"),
+ _("Save configuration now?"), 5, 60);
+ switch (ret)
+ {
+ case DLG_EXIT_OK:
+ if (OK != finish ())
+ return 0; /* error */
+ return 1;
+ case DLG_EXIT_CANCEL:
+ return 1; /* advance */
+ case DLG_EXIT_ESC:
+ return 0; /* abort */
+ case DLG_EXIT_EXTRA:
+ return -1; /* back */
+ default:
+ GE_BREAK (ectx, 0);
+ break;
+ }
return 1;
}
-int wizard_curs_mainsetup_curses(int argc,
- const char **argv,
- struct PluginHandle * self,
- struct GE_Context * e,
- struct GC_Configuration * c,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon) {
+int
+wizard_curs_mainsetup_curses (int argc,
+ const char **argv,
+ struct PluginHandle *self,
+ struct GE_Context *e,
+ struct GC_Configuration *c,
+ struct GNS_Context *gns,
+ const char *filename, int is_daemon)
+{
struct termios ios_org;
unsigned int phase;
int ret;
@@ -557,69 +529,71 @@
cfg = c;
cfg_fn = filename;
#ifndef MINGW
- tcgetattr(1, &ios_org);
+ tcgetattr (1, &ios_org);
#endif
dialog_vars.backtitle = _("GNUnet Configuration");
dialog_vars.item_help = 1;
dialog_vars.help_button = 1;
dialog_vars.extra_button = 1;
dialog_vars.extra_label = _("Back");
- init_dialog(stdin, stderr);
+ init_dialog (stdin, stderr);
phase = 0;
ret = NO;
- while (ret == NO) {
- switch(phase) {
- case 0:
- dir = welcome();
- break;
- case 1:
- dir = network_interface();
- break;
- case 2:
- dir = nat_limited();
- break;
- case 3:
- dir = ip_address();
- break;
- case 4:
- dir = network_load_up();
- break;
- case 5:
- dir = network_load_down();
- break;
- case 6:
- dir = disk_quota();
- break;
- case 7:
- dir = user();
- break;
- case 8:
- dir = group();
- break;
- case 9:
- dir = autostart();
- break;
- case 10:
- dir = save_config();
- break;
- case 11:
- dir = 0;
- ret = OK;
- break;
- default:
- GE_BREAK(NULL, 0);
- dir = 0;
- break;
+ while (ret == NO)
+ {
+ switch (phase)
+ {
+ case 0:
+ dir = welcome ();
+ break;
+ case 1:
+ dir = network_interface ();
+ break;
+ case 2:
+ dir = nat_limited ();
+ break;
+ case 3:
+ dir = ip_address ();
+ break;
+ case 4:
+ dir = network_load_up ();
+ break;
+ case 5:
+ dir = network_load_down ();
+ break;
+ case 6:
+ dir = disk_quota ();
+ break;
+ case 7:
+ dir = user ();
+ break;
+ case 8:
+ dir = group ();
+ break;
+ case 9:
+ dir = autostart ();
+ break;
+ case 10:
+ dir = save_config ();
+ break;
+ case 11:
+ dir = 0;
+ ret = OK;
+ break;
+ default:
+ GE_BREAK (NULL, 0);
+ dir = 0;
+ break;
+ }
+ phase += dir;
+ last = dir;
+ if (dir == 0)
+ ret = SYSERR;
}
- phase += dir;
- last = dir;
- if (dir == 0)
- ret = SYSERR;
- }
- end_dialog();
+ end_dialog ();
#ifndef MINGW
- tcsetattr(1, TCSAFLUSH, &ios_org);
+ tcsetattr (1, TCSAFLUSH, &ios_org);
#endif
return ret;
}
Modified: GNUnet/src/setup/ncurses/wizard_curs.h
===================================================================
--- GNUnet/src/setup/ncurses/wizard_curs.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/setup/ncurses/wizard_curs.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -28,13 +28,12 @@
#ifndef WIZARD_CURS_H
#define WIZARD_CURS_H
-int wizard_curs_mainsetup_curses(int argc,
- const char **argv,
- struct PluginHandle * self,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon);
+int wizard_curs_mainsetup_curses (int argc,
+ const char **argv,
+ struct PluginHandle *self,
+ struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct GNS_Context *gns,
+ const char *filename, int is_daemon);
#endif
Modified: GNUnet/src/setup/text/conf.c
===================================================================
--- GNUnet/src/setup/text/conf.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/text/conf.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -38,510 +38,502 @@
#include "platform.h"
#include <termios.h>
-static char rd() {
+static char
+rd ()
+{
size_t ret;
char c;
- ret = fread(&c, 1, 1, stdin);
+ ret = fread (&c, 1, 1, stdin);
if (ret == 1)
return c;
- return 'q'; /* quit */
+ return 'q'; /* quit */
}
/**
* printf with indentation
*/
-static void iprintf(int indent,
- const char * format,
- ...) {
+static void
+iprintf (int indent, const char *format, ...)
+{
int i;
va_list va;
- for (i=0;i<indent;i++)
- printf(" ");
- va_start(va, format);
- vfprintf(stdout, format, va);
- va_end(va);
- fflush(stdout);
+ for (i = 0; i < indent; i++)
+ printf (" ");
+ va_start (va, format);
+ vfprintf (stdout, format, va);
+ va_end (va);
+ fflush (stdout);
}
-static char * getValueAsString(GNS_Type type,
- GNS_Value * val) {
+static char *
+getValueAsString (GNS_Type type, GNS_Value * val)
+{
char buf[92];
- switch (type & GNS_TypeMask) {
- case GNS_Boolean:
- if (val->Boolean.val)
- return STRDUP(_("yes"));
- return STRDUP(_("no"));
- case GNS_String:
- case GNS_SC:
- case GNS_MC:
- return STRDUP(val->String.val);
- case GNS_Double:
- SNPRINTF(buf, 92,
- "%f",
- val->Double.val);
- return STRDUP(buf);
- case GNS_UInt64:
- SNPRINTF(buf, 92,
- "%llu",
- val->UInt64.val);
- return STRDUP(buf);
- }
- return STRDUP("Internal error.");
+ switch (type & GNS_TypeMask)
+ {
+ case GNS_Boolean:
+ if (val->Boolean.val)
+ return STRDUP (_("yes"));
+ return STRDUP (_("no"));
+ case GNS_String:
+ case GNS_SC:
+ case GNS_MC:
+ return STRDUP (val->String.val);
+ case GNS_Double:
+ SNPRINTF (buf, 92, "%f", val->Double.val);
+ return STRDUP (buf);
+ case GNS_UInt64:
+ SNPRINTF (buf, 92, "%llu", val->UInt64.val);
+ return STRDUP (buf);
+ }
+ return STRDUP ("Internal error.");
}
-static void printChoice(int indent,
- GNS_Type type,
- GNS_Value * val) {
+static void
+printChoice (int indent, GNS_Type type, GNS_Value * val)
+{
int i;
char defLet;
- switch (type & GNS_TypeMask) {
- case GNS_Boolean:
- iprintf(indent,
- _("\tEnter yes (%s), no (%s) or help (%s): "),
- val->Boolean.def ? "Y" : "y",
- val->Boolean.def ? "n" : "N",
- "d",
- "?");
- break;
- case GNS_String:
- case GNS_MC:
- i = 0;
- defLet = '\0';
- if (val->String.legalRange[0] != NULL)
- iprintf(indent,
- _("\tPossible choices:\n"));
- while (val->String.legalRange[i] != NULL) {
- iprintf(indent,
- "\t %s\n",
- val->String.legalRange[i]);
- i++;
+ switch (type & GNS_TypeMask)
+ {
+ case GNS_Boolean:
+ iprintf (indent,
+ _("\tEnter yes (%s), no (%s) or help (%s): "),
+ val->Boolean.def ? "Y" : "y",
+ val->Boolean.def ? "n" : "N", "d", "?");
+ break;
+ case GNS_String:
+ case GNS_MC:
+ i = 0;
+ defLet = '\0';
+ if (val->String.legalRange[0] != NULL)
+ iprintf (indent, _("\tPossible choices:\n"));
+ while (val->String.legalRange[i] != NULL)
+ {
+ iprintf (indent, "\t %s\n", val->String.legalRange[i]);
+ i++;
+ }
+ iprintf (indent,
+ _
+ ("\tUse single space prefix to avoid conflicts with
hotkeys!\n"));
+ iprintf (indent,
+ _("\tEnter string (type '%s' for default value `%s'): "), "d",
+ val->String.def);
+ break;
+ case GNS_SC:
+ i = 0;
+ defLet = '\0';
+ while (val->String.legalRange[i] != NULL)
+ {
+ iprintf (indent,
+ "\t (%c) %s\n",
+ (i < 10) ? '0' + i : 'a' + i - 10,
+ val->String.legalRange[i]);
+ if (0 == strcmp (val->String.legalRange[i], val->String.def))
+ defLet = (i < 10) ? '0' + i : 'a' + i - 10;
+ i++;
+ }
+ GE_ASSERT (NULL, defLet != '\0');
+ iprintf (indent, "\n\t (?) Help\n");
+ iprintf (indent, _("\t Enter choice (default is %c): "), defLet);
+ break;
+ case GNS_Double:
+ iprintf (indent,
+ _("\tEnter floating point (type '%s' for default value %f): "),
+ "d", val->Double.def);
+ break;
+ case GNS_UInt64:
+ iprintf (indent,
+ _
+ ("\tEnter unsigned integer in interval [%llu,%llu] (type '%s'
for default value %llu): "),
+ val->UInt64.min, val->UInt64.max, "d", val->UInt64.def);
+ break;
+ default:
+ return;
}
- iprintf(indent,
- _("\tUse single space prefix to avoid conflicts with hotkeys!\n"));
- iprintf(indent,
- _("\tEnter string (type '%s' for default value `%s'): "),
- "d",
- val->String.def);
- break;
- case GNS_SC:
- i = 0;
- defLet = '\0';
- while (val->String.legalRange[i] != NULL) {
- iprintf(indent,
- "\t (%c) %s\n",
- (i < 10) ? '0' + i : 'a' + i - 10,
- val->String.legalRange[i]);
- if (0 == strcmp(val->String.legalRange[i],
- val->String.def))
- defLet = (i < 10) ? '0' + i : 'a' + i - 10;
- i++;
- }
- GE_ASSERT(NULL, defLet != '\0');
- iprintf(indent,
- "\n\t (?) Help\n");
- iprintf(indent,
- _("\t Enter choice (default is %c): "),
- defLet);
- break;
- case GNS_Double:
- iprintf(indent,
- _("\tEnter floating point (type '%s' for default value %f): "),
- "d",
- val->Double.def);
- break;
- case GNS_UInt64:
- iprintf(indent,
- _("\tEnter unsigned integer in interval [%llu,%llu] (type '%s' for
default value %llu): "),
- val->UInt64.min,
- val->UInt64.max,
- "d",
- val->UInt64.def);
- break;
- default:
- return;
- }
}
/**
* @return OK on success, NO to display help, SYSERR to abort
*/
-static int readValue(GNS_Type type,
- GNS_Value * val) {
+static int
+readValue (GNS_Type type, GNS_Value * val)
+{
int c;
char buf[1024];
int i;
int j;
unsigned long long l;
- switch (type & GNS_TypeMask) {
- case GNS_Boolean:
- while (1) {
- c = rd();
- switch (c) {
- case '\n':
- printf("\n");
- return YES; /* skip */
- case 'y':
- case 'Y':
- val->Boolean.val = 1;
- printf(_("Yes\n"));
- return YES;
- case 'n':
- case 'N':
- val->Boolean.val = 0;
- printf(_("No\n"));
- return YES;
- case '?':
- printf(_("Help\n"));
- return NO;
- case 'q':
- printf(_("Abort\n"));
- return SYSERR;
- default:
- break;
- }
- }
- break;
- case GNS_String:
- case GNS_MC:
- i = 0;
- while (1) {
- buf[i] = rd();
- if (buf[i] == 'q') {
- printf(_("Abort\n"));
- return SYSERR;
- }
+ switch (type & GNS_TypeMask)
+ {
+ case GNS_Boolean:
+ while (1)
+ {
+ c = rd ();
+ switch (c)
+ {
+ case '\n':
+ printf ("\n");
+ return YES; /* skip */
+ case 'y':
+ case 'Y':
+ val->Boolean.val = 1;
+ printf (_("Yes\n"));
+ return YES;
+ case 'n':
+ case 'N':
+ val->Boolean.val = 0;
+ printf (_("No\n"));
+ return YES;
+ case '?':
+ printf (_("Help\n"));
+ return NO;
+ case 'q':
+ printf (_("Abort\n"));
+ return SYSERR;
+ default:
+ break;
+ }
+ }
+ break;
+ case GNS_String:
+ case GNS_MC:
+ i = 0;
+ while (1)
+ {
+ buf[i] = rd ();
+ if (buf[i] == 'q')
+ {
+ printf (_("Abort\n"));
+ return SYSERR;
+ }
#if 0
- if (buf[i] == '\b') {
- if (i > 0) {
- printf("\b"); /* this does not work */
- i--;
- }
- continue;
- }
+ if (buf[i] == '\b')
+ {
+ if (i > 0)
+ {
+ printf ("\b"); /* this does not work */
+ i--;
+ }
+ continue;
+ }
#endif
- if ( (buf[i] == 'd') && (i == 0) ) {
- printf("%s\n",
- val->String.def);
- FREE(val->String.val);
- val->String.val = STRDUP(val->String.def);
- return YES;
- }
- if ( (buf[i] == '?') && (i == 0) ) {
- printf(_("Help\n"));
- return NO;
- }
- if ( (buf[i] == '\n') && (i == 0) ) {
- printf("%s\n",
- val->String.val);
- return YES; /* keep */
- }
- if (buf[i] != '\n') {
- if (i < 1023) {
- printf("%c", buf[i]);
- fflush(stdout);
- i++;
- }
- continue;
- }
- break;
- }
- FREE(val->String.val);
- val->String.val = STRDUP(buf[0] == ' ' ? &buf[1] : buf);
- printf("\n");
- return OK;
- case GNS_SC:
- while (1) {
- c = rd();
- if (c == '?') {
- printf(_("Help\n"));
- return NO;
- }
- if (c == '\n') {
- printf("%s\n",
- val->String.val);
- return YES;
- }
- if (c == 'q') {
- printf(_("Abort\n"));
- return SYSERR;
- }
- i = -1;
- if ( (c >= '0') && (c <= '9') )
- i = c - '0';
- else if ( (c >= 'a') && (c <= 'z') )
- i = c - 'a' + 10;
- else
- continue; /* invalid entry */
- for (j=0;j<=i;j++)
- if (val->String.legalRange[j] == NULL) {
- i = -1;
- break;
- }
- if (i == -1)
- continue; /* invalid entry */
- FREE(val->String.val);
- val->String.val = STRDUP(val->String.legalRange[i]);
- printf("%s\n",
- val->String.val);
+ if ((buf[i] == 'd') && (i == 0))
+ {
+ printf ("%s\n", val->String.def);
+ FREE (val->String.val);
+ val->String.val = STRDUP (val->String.def);
+ return YES;
+ }
+ if ((buf[i] == '?') && (i == 0))
+ {
+ printf (_("Help\n"));
+ return NO;
+ }
+ if ((buf[i] == '\n') && (i == 0))
+ {
+ printf ("%s\n", val->String.val);
+ return YES; /* keep */
+ }
+ if (buf[i] != '\n')
+ {
+ if (i < 1023)
+ {
+ printf ("%c", buf[i]);
+ fflush (stdout);
+ i++;
+ }
+ continue;
+ }
+ break;
+ }
+ FREE (val->String.val);
+ val->String.val = STRDUP (buf[0] == ' ' ? &buf[1] : buf);
+ printf ("\n");
return OK;
- }
- /* unreachable */
- case GNS_Double:
- i = 0;
- while (1) {
- buf[i] = rd();
- if (buf[i] == 'q') {
- printf(_("Abort\n"));
- return SYSERR;
- }
+ case GNS_SC:
+ while (1)
+ {
+ c = rd ();
+ if (c == '?')
+ {
+ printf (_("Help\n"));
+ return NO;
+ }
+ if (c == '\n')
+ {
+ printf ("%s\n", val->String.val);
+ return YES;
+ }
+ if (c == 'q')
+ {
+ printf (_("Abort\n"));
+ return SYSERR;
+ }
+ i = -1;
+ if ((c >= '0') && (c <= '9'))
+ i = c - '0';
+ else if ((c >= 'a') && (c <= 'z'))
+ i = c - 'a' + 10;
+ else
+ continue; /* invalid entry */
+ for (j = 0; j <= i; j++)
+ if (val->String.legalRange[j] == NULL)
+ {
+ i = -1;
+ break;
+ }
+ if (i == -1)
+ continue; /* invalid entry */
+ FREE (val->String.val);
+ val->String.val = STRDUP (val->String.legalRange[i]);
+ printf ("%s\n", val->String.val);
+ return OK;
+ }
+ /* unreachable */
+ case GNS_Double:
+ i = 0;
+ while (1)
+ {
+ buf[i] = rd ();
+ if (buf[i] == 'q')
+ {
+ printf (_("Abort\n"));
+ return SYSERR;
+ }
#if 0
- if (buf[i] == '\b') {
- if (i > 0) {
- printf("\b"); /* this does not work */
- i--;
- }
- continue;
- }
+ if (buf[i] == '\b')
+ {
+ if (i > 0)
+ {
+ printf ("\b"); /* this does not work */
+ i--;
+ }
+ continue;
+ }
#endif
- if ( (buf[i] == 'd') && (i == 0) ) {
- val->Double.val = val->Double.def;
- printf("%f\n",
- val->Double.val);
- return YES; /* default */
- }
- if (buf[i] == '?') {
- printf(_("Help\n"));
- return NO;
- }
- if (buf[i] != '\n') {
- if (i < 1023) {
- printf("%c", buf[i]);
- fflush(stdout);
- i++;
- }
- continue;
- }
- if (i == 0) {
- printf("%f\n",
- val->Double.val);
- return YES; /* keep */
- }
- buf[i+1] = '\0';
- if (1 == sscanf(buf,
- "%lf",
- &val->Double.val)) {
- printf("\n");
- return OK;
- }
+ if ((buf[i] == 'd') && (i == 0))
+ {
+ val->Double.val = val->Double.def;
+ printf ("%f\n", val->Double.val);
+ return YES; /* default */
+ }
+ if (buf[i] == '?')
+ {
+ printf (_("Help\n"));
+ return NO;
+ }
+ if (buf[i] != '\n')
+ {
+ if (i < 1023)
+ {
+ printf ("%c", buf[i]);
+ fflush (stdout);
+ i++;
+ }
+ continue;
+ }
+ if (i == 0)
+ {
+ printf ("%f\n", val->Double.val);
+ return YES; /* keep */
+ }
+ buf[i + 1] = '\0';
+ if (1 == sscanf (buf, "%lf", &val->Double.val))
+ {
+ printf ("\n");
+ return OK;
+ }
+ i = 0;
+ printf (_("\nInvalid entry, try again (use '?' for help): "));
+ fflush (stdout);
+ }
+ break;
+ case GNS_UInt64:
i = 0;
- printf(_("\nInvalid entry, try again (use '?' for help): "));
- fflush(stdout);
- }
- break;
- case GNS_UInt64:
- i = 0;
- while (1) {
- buf[i] = rd();
- if (buf[i] == 'q') {
- printf(_("Abort\n"));
- return SYSERR;
- }
+ while (1)
+ {
+ buf[i] = rd ();
+ if (buf[i] == 'q')
+ {
+ printf (_("Abort\n"));
+ return SYSERR;
+ }
#if 0
- if (buf[i] == '\b') {
- if (i > 0) {
- printf("\b"); /* does not work */
- i--;
- }
- continue;
- }
+ if (buf[i] == '\b')
+ {
+ if (i > 0)
+ {
+ printf ("\b"); /* does not work */
+ i--;
+ }
+ continue;
+ }
#endif
- if ( (buf[i] == 'd') && (i == 0) ) {
- val->UInt64.val = val->UInt64.def;
- printf("%llu\n",
- val->UInt64.val);
- return YES; /* default */
- }
- if (buf[i] == '?') {
- printf(_("Help\n"));
- return NO;
- }
- if (buf[i] != '\n') {
- if (i < 1023) {
- printf("%c", buf[i]);
- fflush(stdout);
- i++;
- }
- continue;
- }
- if (i == 0) {
- printf("%llu\n",
- val->UInt64.val);
- return YES; /* keep */
- }
- buf[i+1] = '\0';
- if ( (1 == sscanf(buf,
- "%llu",
- &l)) &&
- (l >= val->UInt64.min) &&
- (l <= val->UInt64.max) ) {
- val->UInt64.val = l;
- printf("\n");
- return OK;
- }
- i = 0;
- printf(_("\nInvalid entry, try again (use '?' for help): "));
- fflush(stdout);
+ if ((buf[i] == 'd') && (i == 0))
+ {
+ val->UInt64.val = val->UInt64.def;
+ printf ("%llu\n", val->UInt64.val);
+ return YES; /* default */
+ }
+ if (buf[i] == '?')
+ {
+ printf (_("Help\n"));
+ return NO;
+ }
+ if (buf[i] != '\n')
+ {
+ if (i < 1023)
+ {
+ printf ("%c", buf[i]);
+ fflush (stdout);
+ i++;
+ }
+ continue;
+ }
+ if (i == 0)
+ {
+ printf ("%llu\n", val->UInt64.val);
+ return YES; /* keep */
+ }
+ buf[i + 1] = '\0';
+ if ((1 == sscanf (buf,
+ "%llu",
+ &l)) &&
+ (l >= val->UInt64.min) && (l <= val->UInt64.max))
+ {
+ val->UInt64.val = l;
+ printf ("\n");
+ return OK;
+ }
+ i = 0;
+ printf (_("\nInvalid entry, try again (use '?' for help): "));
+ fflush (stdout);
+ }
+ break;
+ default:
+ fprintf (stderr,
+ _("Unknown kind %x (internal error). Skipping option.\n"),
+ type & GNS_TypeMask);
+ return OK;
}
- break;
- default:
- fprintf(stderr,
- _("Unknown kind %x (internal error). Skipping option.\n"),
- type & GNS_TypeMask);
- return OK;
- }
return OK;
}
-static int conf(int indent,
- struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- struct GNS_Tree * tree) {
+static int
+conf (int indent,
+ struct GC_Configuration *cfg,
+ struct GE_Context *ectx, struct GNS_Tree *tree)
+{
char choice;
- char * value;
- char * ovalue;
+ char *value;
+ char *ovalue;
int i;
- if (! tree->visible)
+ if (!tree->visible)
return OK;
- switch (tree->type & GNS_KindMask) {
- case GNS_Leaf:
- ovalue = getValueAsString(tree->type,
- &tree->value);
- while (1) {
- iprintf(indent,
- "[%s] %s = \"%s\"\n",
- tree->section,
- tree->option,
- ovalue);
- iprintf(indent,
- "%s\n",
- gettext(tree->description));
- printChoice(indent,
- tree->type,
- &tree->value);
- i = readValue(tree->type,
- &tree->value);
- if (i == SYSERR) {
- FREE(ovalue);
- return SYSERR;
- }
- if (i == OK)
- break;
- printf("\n\n");
- iprintf(0,
- "%s\n",
- gettext(tree->help));
- printf("\n");
+ switch (tree->type & GNS_KindMask)
+ {
+ case GNS_Leaf:
+ ovalue = getValueAsString (tree->type, &tree->value);
+ while (1)
+ {
+ iprintf (indent,
+ "[%s] %s = \"%s\"\n", tree->section, tree->option, ovalue);
+ iprintf (indent, "%s\n", gettext (tree->description));
+ printChoice (indent, tree->type, &tree->value);
+ i = readValue (tree->type, &tree->value);
+ if (i == SYSERR)
+ {
+ FREE (ovalue);
+ return SYSERR;
+ }
+ if (i == OK)
+ break;
+ printf ("\n\n");
+ iprintf (0, "%s\n", gettext (tree->help));
+ printf ("\n");
+ }
+ value = getValueAsString (tree->type, &tree->value);
+ if ((0 != strcmp (value, ovalue)) &&
+ (0 != GC_set_configuration_value_string (cfg,
+ ectx,
+ tree->section,
+ tree->option, value)))
+ {
+ FREE (value);
+ FREE (ovalue);
+ return conf (indent, cfg, ectx, tree); /* try again */
+ }
+ FREE (value);
+ FREE (ovalue);
+ return OK;
+ case GNS_Node:
+ choice = '\0';
+ while (choice == '\0')
+ {
+ iprintf (indent, "%s\n", gettext (tree->description));
+ iprintf (indent, _( /* do not translate y/n/? */
+ "\tDescend? (y/n/?) "));
+ choice = rd ();
+ switch (choice)
+ {
+ case 'N':
+ case 'n':
+ iprintf (indent, "%c\n", choice);
+ return OK;
+ case 'q':
+ iprintf (indent, _("Aborted.\n"));
+ return SYSERR; /* escape */
+ case '?':
+ iprintf (indent, "%c\n", choice);
+ iprintf (indent, "%s\n", gettext (tree->help));
+ choice = '\0';
+ break;
+ case 'Y':
+ case 'y':
+ iprintf (indent, "%c\n", choice);
+ break;
+ default:
+ iprintf (indent, "%c\n", choice);
+ iprintf (indent, _("Invalid entry.\n"));
+ choice = '\0';
+ break;
+ }
+ }
+ /* fall-through! */
+ case GNS_Root:
+ i = 0;
+ while (tree->children[i] != NULL)
+ {
+ if (SYSERR == conf (indent + 1, cfg, ectx, tree->children[i]))
+ return SYSERR;
+ i++;
+ }
+ return OK;
+ default:
+ fprintf (stderr,
+ _("Unknown kind %x (internal error). Aborting.\n"),
+ tree->type & GNS_KindMask);
+ return SYSERR;
}
- value = getValueAsString(tree->type,
- &tree->value);
- if ( (0 != strcmp(value, ovalue)) &&
- (0 != GC_set_configuration_value_string(cfg,
- ectx,
- tree->section,
- tree->option,
- value)) ) {
- FREE(value);
- FREE(ovalue);
- return conf(indent,
- cfg,
- ectx,
- tree); /* try again */
- }
- FREE(value);
- FREE(ovalue);
- return OK;
- case GNS_Node:
- choice = '\0';
- while (choice == '\0') {
- iprintf(indent,
- "%s\n",
- gettext(tree->description));
- iprintf(indent,
- _(/* do not translate y/n/? */
- "\tDescend? (y/n/?) "));
- choice = rd();
- switch(choice) {
- case 'N':
- case 'n':
- iprintf(indent,
- "%c\n",
- choice);
- return OK;
- case 'q':
- iprintf(indent,
- _("Aborted.\n"));
- return SYSERR; /* escape */
- case '?':
- iprintf(indent,
- "%c\n",
- choice);
- iprintf(indent,
- "%s\n",
- gettext(tree->help));
- choice = '\0';
- break;
- case 'Y':
- case 'y':
- iprintf(indent,
- "%c\n",
- choice);
- break;
- default:
- iprintf(indent,
- "%c\n",
- choice);
- iprintf(indent,
- _("Invalid entry.\n"));
- choice = '\0';
- break;
- }
- }
- /* fall-through! */
- case GNS_Root:
- i = 0;
- while (tree->children[i] != NULL) {
- if (SYSERR == conf(indent + 1,
- cfg,
- ectx,
- tree->children[i]))
return SYSERR;
- i++;
- }
- return OK;
- default:
- fprintf(stderr,
- _("Unknown kind %x (internal error). Aborting.\n"),
- tree->type & GNS_KindMask);
- return SYSERR;
- }
- return SYSERR;
}
-int main_setup_text(int argc,
- const char **argv,
- struct PluginHandle * self,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon) {
- struct GNS_Tree * root;
+int
+main_setup_text (int argc,
+ const char **argv,
+ struct PluginHandle *self,
+ struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct GNS_Context *gns, const char *filename, int is_daemon)
+{
+ struct GNS_Tree *root;
struct termios oldT;
struct termios newT;
char c;
@@ -551,54 +543,59 @@
# define TCGETS TIOCGETA
# define TCSETS TIOCSETA
#endif
- ioctl(0, TCGETS, &oldT);
+ ioctl (0, TCGETS, &oldT);
newT = oldT;
newT.c_lflag &= ~ECHO;
newT.c_lflag &= ~ICANON;
- ioctl(0, TCSETS, &newT);
+ ioctl (0, TCSETS, &newT);
- printf(_("You can always press ENTER to keep the current value.\n"));
- printf(_("Use the '%s' key to abort.\n"),
- "q");
- root = GNS_get_tree(gns);
+ printf (_("You can always press ENTER to keep the current value.\n"));
+ printf (_("Use the '%s' key to abort.\n"), "q");
+ root = GNS_get_tree (gns);
c = 'r';
- while (c == 'r') {
- if (OK != conf(-1,
- cfg,
- ectx,
- root)) {
- ioctl(0, TCSETS, &oldT);
- return 1;
+ while (c == 'r')
+ {
+ if (OK != conf (-1, cfg, ectx, root))
+ {
+ ioctl (0, TCSETS, &oldT);
+ return 1;
+ }
+ if ((0 == GC_test_dirty (cfg)) && (0 == ACCESS (filename, R_OK)))
+ {
+ printf (_("Configuration unchanged, no need to save.\n"));
+ ioctl (0, TCSETS, &oldT);
+ return 0;
+ }
+ printf ("\n");
+ printf (_
+ ("Save configuration? Answer 'y' for yes, 'n' for no, 'r' to
repeat configuration. "));
+ fflush (stdout);
+ do
+ {
+ c = rd ();
+ }
+ while ((c != 'y') && (c != 'n') && (c != 'r'));
+ printf ("%c\n", c);
+ fflush (stdout);
}
- if ( (0 == GC_test_dirty(cfg)) &&
- (0 == ACCESS(filename, R_OK)) ) {
- printf(_("Configuration unchanged, no need to save.\n"));
- ioctl(0, TCSETS, &oldT);
- return 0;
+ if (c == 'y')
+ {
+ ret = GC_write_configuration (cfg, filename);
+ if (ret == 1)
+ {
+ printf (_("Configuration was unchanged, no need to save.\n"));
+ }
+ else if (ret == -1)
+ { /* error */
+ ioctl (0, TCSETS, &oldT);
+ return 1;
+ }
+ else
+ {
+ printf (_("Configuration file `%s' written.\n"), filename);
+ }
}
- printf("\n");
- printf(_("Save configuration? Answer 'y' for yes, 'n' for no, 'r' to
repeat configuration. "));
- fflush(stdout);
- do {
- c = rd();
- } while ( (c != 'y') && (c != 'n') && (c != 'r') );
- printf("%c\n", c);
- fflush(stdout);
- }
- if (c == 'y') {
- ret = GC_write_configuration(cfg,
- filename);
- if (ret == 1) {
- printf(_("Configuration was unchanged, no need to save.\n"));
- } else if (ret == -1) { /* error */
- ioctl(0, TCSETS, &oldT);
- return 1;
- } else {
- printf(_("Configuration file `%s' written.\n"),
- filename);
- }
- }
- ioctl(0, TCSETS, &oldT);
+ ioctl (0, TCSETS, &oldT);
return 0;
}
@@ -606,14 +603,13 @@
/**
* Generate defaults, runs without user interaction.
*/
-int dump_setup_text(int argc,
- const char **argv,
- struct PluginHandle * self,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon) {
- return GC_write_configuration(cfg,
- filename);
+int
+dump_setup_text (int argc,
+ const char **argv,
+ struct PluginHandle *self,
+ struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct GNS_Context *gns, const char *filename, int is_daemon)
+{
+ return GC_write_configuration (cfg, filename);
}
Modified: GNUnet/src/setup/text/conf.h
===================================================================
--- GNUnet/src/setup/text/conf.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/setup/text/conf.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -31,22 +31,20 @@
#include "gnunet_util.h"
#include "gnunet_setup_lib.h"
-int main_setup_text(int argc,
- const char ** argv,
- struct PluginHandle * self,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon);
+int main_setup_text (int argc,
+ const char **argv,
+ struct PluginHandle *self,
+ struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct GNS_Context *gns,
+ const char *filename, int is_daemon);
-int dump_setup_text(int argc,
- const char ** argv,
- struct PluginHandle * self,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- struct GNS_Context * gns,
- const char * filename,
- int is_daemon);
+int dump_setup_text (int argc,
+ const char **argv,
+ struct PluginHandle *self,
+ struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ struct GNS_Context *gns,
+ const char *filename, int is_daemon);
#endif
Modified: GNUnet/src/transports/http.c
===================================================================
--- GNUnet/src/transports/http.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/http.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -65,7 +65,8 @@
/**
* Host-Address in a HTTP network.
*/
-typedef struct {
+typedef struct
+{
/**
* claimed IP of the sender, network byte order
*/
@@ -83,12 +84,13 @@
} HostAddress;
-struct HTTPPutData {
- struct HTTPPutData * next;
+struct HTTPPutData
+{
+ struct HTTPPutData *next;
- char * msg;
+ char *msg;
- CURL * curl_put;
+ CURL *curl_put;
unsigned int size;
@@ -101,27 +103,28 @@
/**
* Transport Session handle.
*/
-typedef struct {
+typedef struct
+{
/**
* mutex for synchronized access to struct
*/
- struct MUTEX * lock;
+ struct MUTEX *lock;
/**
* Read buffer for the header.
*/
- char rbuff1[sizeof(MESSAGE_HEADER)];
+ char rbuff1[sizeof (MESSAGE_HEADER)];
/**
* The read buffer (used only for the actual data).
*/
- char * rbuff2;
+ char *rbuff2;
/**
* The write buffer.
*/
- char * wbuff;
+ char *wbuff;
/**
* Last time this connection was used
@@ -182,39 +185,42 @@
/**
* TSession for this session.
*/
- TSession * tsession;
+ TSession *tsession;
/**
* Data maintained for the http client-server connection
* (depends on if we are client or server).
*/
- union {
+ union
+ {
- struct {
+ struct
+ {
/**
* GET session response handle
*/
- struct MHD_Response * get;
+ struct MHD_Response *get;
} server;
- struct {
+ struct
+ {
/**
* GET operation
*/
- CURL * get;
+ CURL *get;
/**
* URL of the get and put operations.
*/
- char * url;
+ char *url;
/**
* Linked list of PUT operations.
*/
- struct HTTPPutData * puts;
+ struct HTTPPutData *puts;
} client;
@@ -227,9 +233,9 @@
/**
* apis (our advertised API and the core api )
*/
-static CoreAPIForTransport * coreAPI;
+static CoreAPIForTransport *coreAPI;
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static int stat_bytesReceived;
@@ -237,17 +243,17 @@
static int stat_bytesDropped;
-static char * proxy;
+static char *proxy;
/**
* Daemon for listening for new connections.
*/
-static struct MHD_Daemon * mhd_daemon;
+static struct MHD_Daemon *mhd_daemon;
/**
* Curl multi for managing client operations.
*/
-static CURLM * curl_multi;
+static CURLM *curl_multi;
/**
* Set to YES while the transport is running.
@@ -257,12 +263,12 @@
/**
* Thread running libcurl activities.
*/
-static struct PTHREAD * curl_thread;
+static struct PTHREAD *curl_thread;
/**
* Array of currently active HTTP sessions.
*/
-static TSession ** tsessions;
+static TSession **tsessions;
static unsigned int tsessionCount;
@@ -271,12 +277,12 @@
/**
* Blacklist configuration
*/
-static struct CIDRNetwork * filteredNetworks_;
+static struct CIDRNetwork *filteredNetworks_;
/**
* Universal plug & play (firewall hole punching)
*/
-static UPnP_ServiceAPI * upnp;
+static UPnP_ServiceAPI *upnp;
/**
@@ -291,32 +297,33 @@
* prevent the select thread from operating and removing
* is done by the only therad that reads from the array.
*/
-static struct MUTEX * httplock;
+static struct MUTEX *httplock;
/**
* Check if we are allowed to connect to the given IP.
*/
-static int acceptPolicyCallback(void * cls,
- const struct sockaddr * addr,
- socklen_t addr_len) {
+static int
+acceptPolicyCallback (void *cls,
+ const struct sockaddr *addr, socklen_t addr_len)
+{
IPaddr ip;
int ret;
- if (addr_len == sizeof(struct sockaddr_in)) {
- memcpy(&ip,
- &((struct sockaddr_in*) addr)->sin_addr,
- sizeof(IPaddr));
- } else if (addr_len == sizeof(IPaddr)) {
- memcpy(&ip,
- addr,
- addr_len);
- } else {
- return MHD_NO;
- }
- MUTEX_LOCK(httplock);
- ret = check_ipv4_listed(filteredNetworks_,
- ip);
- MUTEX_UNLOCK(httplock);
+ if (addr_len == sizeof (struct sockaddr_in))
+ {
+ memcpy (&ip, &((struct sockaddr_in *) addr)->sin_addr, sizeof (IPaddr));
+ }
+ else if (addr_len == sizeof (IPaddr))
+ {
+ memcpy (&ip, addr, addr_len);
+ }
+ else
+ {
+ return MHD_NO;
+ }
+ MUTEX_LOCK (httplock);
+ ret = check_ipv4_listed (filteredNetworks_, ip);
+ MUTEX_UNLOCK (httplock);
if (YES == ret)
return MHD_NO;
return MHD_YES;
@@ -332,60 +339,64 @@
* @param tsession the session that is closed
* @return OK on success, SYSERR if the operation failed
*/
-static int httpDisconnect(TSession * tsession) {
- HTTPSession * httpsession = tsession->internal;
- struct HTTPPutData * pos;
- struct HTTPPutData * next;
+static int
+httpDisconnect (TSession * tsession)
+{
+ HTTPSession *httpsession = tsession->internal;
+ struct HTTPPutData *pos;
+ struct HTTPPutData *next;
int i;
- if (httpsession == NULL) {
- FREE(tsession);
- return OK;
- }
- MUTEX_LOCK(httpsession->lock);
+ if (httpsession == NULL)
+ {
+ FREE (tsession);
+ return OK;
+ }
+ MUTEX_LOCK (httpsession->lock);
httpsession->users--;
- if (httpsession->users > 0) {
- MUTEX_UNLOCK(httpsession->lock);
- return OK;
- }
+ if (httpsession->users > 0)
+ {
+ MUTEX_UNLOCK (httpsession->lock);
+ return OK;
+ }
httpsession->destroyed = YES;
- MUTEX_UNLOCK(httpsession->lock);
- MUTEX_LOCK(httplock);
- for (i=0;i<tsessionCount;i++) {
- if (tsessions[i] == tsession) {
- tsessions[i] = tsessions[--tsessionCount];
- break;
+ MUTEX_UNLOCK (httpsession->lock);
+ MUTEX_LOCK (httplock);
+ for (i = 0; i < tsessionCount; i++)
+ {
+ if (tsessions[i] == tsession)
+ {
+ tsessions[i] = tsessions[--tsessionCount];
+ break;
+ }
}
- }
- MUTEX_UNLOCK(httplock);
- if (httpsession->is_client) {
- curl_multi_remove_handle(curl_multi,
- httpsession->cs.client.get);
- curl_easy_cleanup(httpsession->cs.client.get);
- FREE(httpsession->cs.client.url);
- pos = httpsession->cs.client.puts;
- while (pos != NULL) {
- next = pos->next;
- curl_multi_remove_handle(curl_multi,
- pos->curl_put);
- curl_easy_cleanup(pos->curl_put);
- FREE(pos->msg);
- FREE(pos);
- pos = next;
- }
+ MUTEX_UNLOCK (httplock);
+ if (httpsession->is_client)
+ {
+ curl_multi_remove_handle (curl_multi, httpsession->cs.client.get);
+ curl_easy_cleanup (httpsession->cs.client.get);
+ FREE (httpsession->cs.client.url);
+ pos = httpsession->cs.client.puts;
+ while (pos != NULL)
+ {
+ next = pos->next;
+ curl_multi_remove_handle (curl_multi, pos->curl_put);
+ curl_easy_cleanup (pos->curl_put);
+ FREE (pos->msg);
+ FREE (pos);
+ pos = next;
+ }
- } else {
- MHD_destroy_response(httpsession->cs.server.get);
- }
- GROW(httpsession->rbuff2,
- httpsession->rsize2,
- 0);
- GROW(httpsession->wbuff,
- httpsession->wsize,
- 0);
- MUTEX_DESTROY(httpsession->lock);
- FREE(httpsession);
- FREE(tsession);
+ }
+ else
+ {
+ MHD_destroy_response (httpsession->cs.server.get);
+ }
+ GROW (httpsession->rbuff2, httpsession->rsize2, 0);
+ GROW (httpsession->wbuff, httpsession->wsize, 0);
+ MUTEX_DESTROY (httpsession->lock);
+ FREE (httpsession);
+ FREE (tsession);
return OK;
}
@@ -393,16 +404,14 @@
* Get the GNUnet HTTP port from the configuration, or from
* /etc/services if it is not specified in the config file.
*/
-static unsigned short getGNUnetHTTPPort() {
+static unsigned short
+getGNUnetHTTPPort ()
+{
unsigned long long port;
- if (-1 == GC_get_configuration_value_number(coreAPI->cfg,
- "HTTP",
- "PORT",
- 0,
- 65535,
- 1080,
- &port))
+ if (-1 == GC_get_configuration_value_number (coreAPI->cfg,
+ "HTTP",
+ "PORT", 0, 65535, 1080, &port))
port = 1080;
return (unsigned short) port;
}
@@ -426,21 +435,25 @@
* @return OK if the session could be associated,
* SYSERR if not.
*/
-static int httpAssociate(TSession * tsession) {
- HTTPSession * httpSession;
+static int
+httpAssociate (TSession * tsession)
+{
+ HTTPSession *httpSession;
- if (tsession == NULL) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
+ if (tsession == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
httpSession = tsession->internal;
- MUTEX_LOCK(httpSession->lock);
- if (httpSession->destroyed == YES) {
- MUTEX_UNLOCK(httpSession->lock);
- return SYSERR;
- }
+ MUTEX_LOCK (httpSession->lock);
+ if (httpSession->destroyed == YES)
+ {
+ MUTEX_UNLOCK (httpSession->lock);
+ return SYSERR;
+ }
httpSession->users++;
- MUTEX_UNLOCK(httpSession->lock);
+ MUTEX_UNLOCK (httpSession->lock);
return OK;
}
@@ -454,18 +467,20 @@
* (the signature/crc have been verified before)
* @return OK on success, SYSERR on error
*/
-static int verifyHello(const P2P_hello_MESSAGE * hello) {
- const HostAddress * haddr;
+static int
+verifyHello (const P2P_hello_MESSAGE * hello)
+{
+ const HostAddress *haddr;
- haddr = (const HostAddress*) &hello[1];
- if ( (ntohs(hello->senderAddressSize) != sizeof(HostAddress)) ||
- (ntohs(hello->header.size) != P2P_hello_MESSAGE_size(hello)) ||
- (ntohs(hello->header.type) != p2p_PROTO_hello) ||
- (ntohs(hello->protocol) != HTTP_PROTOCOL_NUMBER) ||
- (MHD_NO == acceptPolicyCallback(NULL,
- (const struct sockaddr*) haddr,
- sizeof(IPaddr))) )
- return SYSERR; /* obviously invalid */
+ haddr = (const HostAddress *) &hello[1];
+ if ((ntohs (hello->senderAddressSize) != sizeof (HostAddress)) ||
+ (ntohs (hello->header.size) != P2P_hello_MESSAGE_size (hello)) ||
+ (ntohs (hello->header.type) != p2p_PROTO_hello) ||
+ (ntohs (hello->protocol) != HTTP_PROTOCOL_NUMBER) ||
+ (MHD_NO == acceptPolicyCallback (NULL,
+ (const struct sockaddr *) haddr,
+ sizeof (IPaddr))))
+ return SYSERR; /* obviously invalid */
return OK;
}
@@ -476,45 +491,48 @@
*
* @return hello on success, NULL on error
*/
-static P2P_hello_MESSAGE * createhello() {
- P2P_hello_MESSAGE * msg;
- HostAddress * haddr;
+static P2P_hello_MESSAGE *
+createhello ()
+{
+ P2P_hello_MESSAGE *msg;
+ HostAddress *haddr;
unsigned short port;
- port = getGNUnetHTTPPort();
- if (0 == port) {
- GE_LOG(NULL,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "HTTP port is 0, will only send using HTTP.\n");
- return NULL; /* HTTP transport is configured SEND-only! */
- }
- msg = MALLOC(sizeof(P2P_hello_MESSAGE) + sizeof(HostAddress));
- haddr = (HostAddress*) &msg[1];
+ port = getGNUnetHTTPPort ();
+ if (0 == port)
+ {
+ GE_LOG (NULL,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "HTTP port is 0, will only send using HTTP.\n");
+ return NULL; /* HTTP transport is configured SEND-only! */
+ }
+ msg = MALLOC (sizeof (P2P_hello_MESSAGE) + sizeof (HostAddress));
+ haddr = (HostAddress *) & msg[1];
- if (! ( ( (upnp != NULL) &&
- (OK == upnp->get_ip(port,
- "TCP",
- &haddr->ip)) ) ||
- (SYSERR != getPublicIPAddress(coreAPI->cfg,
- coreAPI->ectx,
- &haddr->ip)) ) ) {
- FREE(msg);
- GE_LOG(coreAPI->ectx,
- GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
- _("HTTP: Could not determine my public IP address.\n"));
- return NULL;
- }
+ if (!(((upnp != NULL) &&
+ (OK == upnp->get_ip (port,
+ "TCP",
+ &haddr->ip))) ||
+ (SYSERR != getPublicIPAddress (coreAPI->cfg,
+ coreAPI->ectx, &haddr->ip))))
+ {
+ FREE (msg);
+ GE_LOG (coreAPI->ectx,
+ GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
+ _("HTTP: Could not determine my public IP address.\n"));
+ return NULL;
+ }
#if DEBUG_HTTP
- GE_LOG(coreAPI->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "HTTP uses IP address %u.%u.%u.%u.\n",
- PRIP(ntohl(*(int*)&haddr->ip)));
+ GE_LOG (coreAPI->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "HTTP uses IP address %u.%u.%u.%u.\n",
+ PRIP (ntohl (*(int *) &haddr->ip)));
#endif
- haddr->port = htons(port);
- haddr->reserved = htons(0);
- msg->senderAddressSize = htons(sizeof(HostAddress));
- msg->protocol = htons(HTTP_PROTOCOL_NUMBER);
- msg->MTU = htonl(0);
+ haddr->port = htons (port);
+ haddr->reserved = htons (0);
+ msg->senderAddressSize = htons (sizeof (HostAddress));
+ msg->protocol = htons (HTTP_PROTOCOL_NUMBER);
+ msg->MTU = htonl (0);
return msg;
}
@@ -525,42 +543,40 @@
* calling. It is ok to call this function without holding httplock if
* the return value is ignored.
*/
-static unsigned int addTSession(TSession * tsession) {
+static unsigned int
+addTSession (TSession * tsession)
+{
unsigned int i;
- MUTEX_LOCK(httplock);
+ MUTEX_LOCK (httplock);
if (tsessionCount == tsessionArrayLength)
- GROW(tsessions,
- tsessionArrayLength,
- tsessionArrayLength * 2);
+ GROW (tsessions, tsessionArrayLength, tsessionArrayLength * 2);
i = tsessionCount;
tsessions[tsessionCount++] = tsession;
- MUTEX_UNLOCK(httplock);
+ MUTEX_UNLOCK (httplock);
return i;
}
-static int contentReaderCallback(void * cls,
- size_t pos,
- char * buf,
- int max) {
- HTTPSession * session = cls;
+static int
+contentReaderCallback (void *cls, size_t pos, char *buf, int max)
+{
+ HTTPSession *session = cls;
- MUTEX_LOCK(session->lock);
- if (session->destroyed) {
- MUTEX_UNLOCK(session->lock);
- return -1;
- }
+ MUTEX_LOCK (session->lock);
+ if (session->destroyed)
+ {
+ MUTEX_UNLOCK (session->lock);
+ return -1;
+ }
if (session->wpos < max)
max = session->wpos;
- memcpy(buf,
- &session->wbuff[session->woff],
- max);
+ memcpy (buf, &session->wbuff[session->woff], max);
session->wpos -= max;
session->woff += max;
- session->lastUse = get_time();
+ session->lastUse = get_time ();
if (session->wpos == 0)
- session->woff = 0;
- MUTEX_UNLOCK(session->lock);
+ session->woff = 0;
+ MUTEX_UNLOCK (session->lock);
return max;
}
@@ -568,8 +584,10 @@
* Notification that libmicrohttpd no longer needs the
* response object.
*/
-static void contentReaderFreeCallback(void * cls) {
- HTTPSession * session = cls;
+static void
+contentReaderFreeCallback (void *cls)
+{
+ HTTPSession *session = cls;
session->destroyed = YES;
}
@@ -579,127 +597,135 @@
* socket. Adds the session to the array of sessions watched
* by the select thread.
*/
-static int accessHandlerCallback(void * cls,
- struct MHD_Session * session,
- const char * url,
- const char * method,
- const char * upload_data,
- unsigned int * upload_data_size) {
- TSession * tsession;
- struct MHD_Response * response;
- HTTPSession * httpSession;
+static int
+accessHandlerCallback (void *cls,
+ struct MHD_Session *session,
+ const char *url,
+ const char *method,
+ const char *upload_data,
+ unsigned int *upload_data_size)
+{
+ TSession *tsession;
+ struct MHD_Response *response;
+ HTTPSession *httpSession;
HashCode512 client;
int i;
unsigned int have;
- MESSAGE_HEADER * hdr;
- P2P_PACKET * mp;
+ MESSAGE_HEADER *hdr;
+ P2P_PACKET *mp;
unsigned int cpy;
unsigned int poff;
- if ( (strlen(url) < 2) ||
- (OK != enc2hash(&url[1],
- &client)) ) {
- return MHD_NO;
- }
+ if ((strlen (url) < 2) || (OK != enc2hash (&url[1], &client)))
+ {
+ return MHD_NO;
+ }
/* check if we already have a session for this */
- MUTEX_LOCK(httplock);
- for (i=0;i<tsessionCount;i++) {
- tsession = tsessions[i];
- httpSession = tsession->internal;
- if (0 == memcmp(&httpSession->sender,
- &client,
- sizeof(HashCode512)))
- break;
- tsession = NULL;
- httpSession = NULL;
- }
- if (tsession != NULL) {
- MUTEX_LOCK(httpSession->lock);
- httpSession->users++;
- MUTEX_UNLOCK(httpSession->lock);
- }
- MUTEX_UNLOCK(httplock);
+ MUTEX_LOCK (httplock);
+ for (i = 0; i < tsessionCount; i++)
+ {
+ tsession = tsessions[i];
+ httpSession = tsession->internal;
+ if (0 == memcmp (&httpSession->sender, &client, sizeof (HashCode512)))
+ break;
+ tsession = NULL;
+ httpSession = NULL;
+ }
+ if (tsession != NULL)
+ {
+ MUTEX_LOCK (httpSession->lock);
+ httpSession->users++;
+ MUTEX_UNLOCK (httpSession->lock);
+ }
+ MUTEX_UNLOCK (httplock);
- if (httpSession == NULL) {
- httpSession = MALLOC(sizeof(HTTPSession));
- memset(httpSession,
- 0,
- sizeof(HTTPSession));
- httpSession->sender = *(coreAPI->myIdentity);
- httpSession->lock = MUTEX_CREATE(YES);
- httpSession->users = 1; /* us only, core has not seen this tsession! */
- httpSession->lastUse = get_time();
- tsession = MALLOC(sizeof(TSession));
- tsession->ttype = HTTP_PROTOCOL_NUMBER;
- tsession->internal = httpSession;
- tsession->peer = *(coreAPI->myIdentity);
- httpSession->tsession = tsession;
- addTSession(tsession);
- }
- if (0 == strcmp("GET", method)) {
- /* handle get */
- response = MHD_create_response_from_callback(-1,
- contentReaderCallback,
- httpSession,
- contentReaderFreeCallback);
- httpSession->cs.client.get = response;
- MHD_queue_response(session,
- MHD_HTTP_OK,
- response);
- } else if (0 == strcmp("PUT", method)) {
- /* handle put (upload_data!) */
- MUTEX_LOCK(httpSession->lock);
- poff = 0;
- have = *upload_data_size;
- *upload_data_size = 0; /* we will always process everything */
- while (have > 0) {
- if (httpSession->rpos1 < sizeof(MESSAGE_HEADER)) {
- cpy = sizeof(MESSAGE_HEADER) - httpSession->rpos1;
- if (cpy > have)
- cpy = have;
- memcpy(&httpSession->rbuff1[httpSession->rpos1],
- &upload_data[poff],
- cpy);
- httpSession->rpos1 += cpy;
- have -= cpy;
- poff += cpy;
- httpSession->rpos2 = 0;
- }
- if (httpSession->rpos1 < sizeof(MESSAGE_HEADER))
- break;
- hdr = (MESSAGE_HEADER *) httpSession->rbuff1;
- GROW(httpSession->rbuff2,
- httpSession->rsize2,
- ntohs(hdr->size) - sizeof(MESSAGE_HEADER));
- if (httpSession->rpos2 < ntohs(hdr->size) - sizeof(MESSAGE_HEADER)) {
- cpy = ntohs(hdr->size) - sizeof(MESSAGE_HEADER) - httpSession->rpos2;
- if (cpy > have)
- cpy = have;
- memcpy(&httpSession->rbuff2[httpSession->rpos2],
- &upload_data[poff],
- cpy);
- have -= cpy;
- poff += cpy;
- httpSession->rpos2 += cpy;
- }
- if (httpSession->rpos2 < ntohs(hdr->size) - sizeof(MESSAGE_HEADER))
- break;
- mp = MALLOC(sizeof(P2P_PACKET));
- mp->msg = httpSession->rbuff2;
- mp->sender = httpSession->sender;
- mp->tsession = httpSession->tsession;
- mp->size = ntohs(hdr->size) - sizeof(MESSAGE_HEADER);
- coreAPI->receive(mp);
- httpSession->rbuff2 = NULL;
- httpSession->rpos2 = 0;
- httpSession->rsize2 = 0;
- httpSession->rpos1 = 0;
+ if (httpSession == NULL)
+ {
+ httpSession = MALLOC (sizeof (HTTPSession));
+ memset (httpSession, 0, sizeof (HTTPSession));
+ httpSession->sender = *(coreAPI->myIdentity);
+ httpSession->lock = MUTEX_CREATE (YES);
+ httpSession->users = 1; /* us only, core has not seen this tsession! */
+ httpSession->lastUse = get_time ();
+ tsession = MALLOC (sizeof (TSession));
+ tsession->ttype = HTTP_PROTOCOL_NUMBER;
+ tsession->internal = httpSession;
+ tsession->peer = *(coreAPI->myIdentity);
+ httpSession->tsession = tsession;
+ addTSession (tsession);
}
- MUTEX_UNLOCK(httpSession->lock);
- } else {
- return MHD_NO; /* must be get or put! */
- }
+ if (0 == strcmp ("GET", method))
+ {
+ /* handle get */
+ response = MHD_create_response_from_callback (-1,
+ contentReaderCallback,
+ httpSession,
+ contentReaderFreeCallback);
+ httpSession->cs.client.get = response;
+ MHD_queue_response (session, MHD_HTTP_OK, response);
+ }
+ else if (0 == strcmp ("PUT", method))
+ {
+ /* handle put (upload_data!) */
+ MUTEX_LOCK (httpSession->lock);
+ poff = 0;
+ have = *upload_data_size;
+ *upload_data_size = 0; /* we will always process everything */
+ while (have > 0)
+ {
+ if (httpSession->rpos1 < sizeof (MESSAGE_HEADER))
+ {
+ cpy = sizeof (MESSAGE_HEADER) - httpSession->rpos1;
+ if (cpy > have)
+ cpy = have;
+ memcpy (&httpSession->rbuff1[httpSession->rpos1],
+ &upload_data[poff], cpy);
+ httpSession->rpos1 += cpy;
+ have -= cpy;
+ poff += cpy;
+ httpSession->rpos2 = 0;
+ }
+ if (httpSession->rpos1 < sizeof (MESSAGE_HEADER))
+ break;
+ hdr = (MESSAGE_HEADER *) httpSession->rbuff1;
+ GROW (httpSession->rbuff2,
+ httpSession->rsize2,
+ ntohs (hdr->size) - sizeof (MESSAGE_HEADER));
+ if (httpSession->rpos2 <
+ ntohs (hdr->size) - sizeof (MESSAGE_HEADER))
+ {
+ cpy =
+ ntohs (hdr->size) - sizeof (MESSAGE_HEADER) -
+ httpSession->rpos2;
+ if (cpy > have)
+ cpy = have;
+ memcpy (&httpSession->rbuff2[httpSession->rpos2],
+ &upload_data[poff], cpy);
+ have -= cpy;
+ poff += cpy;
+ httpSession->rpos2 += cpy;
+ }
+ if (httpSession->rpos2 <
+ ntohs (hdr->size) - sizeof (MESSAGE_HEADER))
+ break;
+ mp = MALLOC (sizeof (P2P_PACKET));
+ mp->msg = httpSession->rbuff2;
+ mp->sender = httpSession->sender;
+ mp->tsession = httpSession->tsession;
+ mp->size = ntohs (hdr->size) - sizeof (MESSAGE_HEADER);
+ coreAPI->receive (mp);
+ httpSession->rbuff2 = NULL;
+ httpSession->rpos2 = 0;
+ httpSession->rsize2 = 0;
+ httpSession->rpos1 = 0;
+ }
+ MUTEX_UNLOCK (httpSession->lock);
+ }
+ else
+ {
+ return MHD_NO; /* must be get or put! */
+ }
return MHD_YES;
}
@@ -707,66 +733,63 @@
* Process downloaded bits
*/
static size_t
-receiveContentCallback(void * ptr,
- size_t size,
- size_t nmemb,
- void * ctx) {
- HTTPSession * httpSession = ctx;
- const char * inbuf = ptr;
+receiveContentCallback (void *ptr, size_t size, size_t nmemb, void *ctx)
+{
+ HTTPSession *httpSession = ctx;
+ const char *inbuf = ptr;
size_t have = size * nmemb;
size_t poff = 0;
size_t cpy;
- MESSAGE_HEADER * hdr;
- P2P_PACKET * mp;
+ MESSAGE_HEADER *hdr;
+ P2P_PACKET *mp;
- printf("Receiving %u bytes from GET\n",
- have);
- while (have > 0) {
- if (httpSession->rpos1 < sizeof(MESSAGE_HEADER)) {
- cpy = sizeof(MESSAGE_HEADER) - httpSession->rpos1;
- if (cpy > have)
- cpy = have;
- memcpy(&httpSession->rbuff1[httpSession->rpos1],
- &inbuf[poff],
- cpy);
- httpSession->rpos1 += cpy;
- have -= cpy;
- poff += cpy;
+ printf ("Receiving %u bytes from GET\n", have);
+ while (have > 0)
+ {
+ if (httpSession->rpos1 < sizeof (MESSAGE_HEADER))
+ {
+ cpy = sizeof (MESSAGE_HEADER) - httpSession->rpos1;
+ if (cpy > have)
+ cpy = have;
+ memcpy (&httpSession->rbuff1[httpSession->rpos1],
+ &inbuf[poff], cpy);
+ httpSession->rpos1 += cpy;
+ have -= cpy;
+ poff += cpy;
+ httpSession->rpos2 = 0;
+ }
+ if (httpSession->rpos1 < sizeof (MESSAGE_HEADER))
+ return size * nmemb;
+ hdr = (MESSAGE_HEADER *) httpSession->rbuff1;
+ GROW (httpSession->rbuff2,
+ httpSession->rsize2, ntohs (hdr->size) - sizeof (MESSAGE_HEADER));
+ printf ("Expecting message of %u bytes via GET\n", ntohs (hdr->size));
+ if (httpSession->rpos2 < ntohs (hdr->size) - sizeof (MESSAGE_HEADER))
+ {
+ cpy =
+ ntohs (hdr->size) - sizeof (MESSAGE_HEADER) - httpSession->rpos2;
+ if (cpy > have)
+ cpy = have;
+ memcpy (&httpSession->rbuff2[httpSession->rpos2],
+ &inbuf[poff], cpy);
+ have -= cpy;
+ poff += cpy;
+ httpSession->rpos2 += cpy;
+ }
+ if (httpSession->rpos2 < ntohs (hdr->size) - sizeof (MESSAGE_HEADER))
+ return size * nmemb;
+ mp = MALLOC (sizeof (P2P_PACKET));
+ mp->msg = httpSession->rbuff2;
+ mp->sender = httpSession->sender;
+ mp->tsession = httpSession->tsession;
+ mp->size = ntohs (hdr->size) - sizeof (MESSAGE_HEADER);
+ printf ("Passing message from GET to core!\n");
+ coreAPI->receive (mp);
+ httpSession->rbuff2 = NULL;
httpSession->rpos2 = 0;
+ httpSession->rsize2 = 0;
+ httpSession->rpos1 = 0;
}
- if (httpSession->rpos1 < sizeof(MESSAGE_HEADER))
- return size * nmemb;
- hdr = (MESSAGE_HEADER *) httpSession->rbuff1;
- GROW(httpSession->rbuff2,
- httpSession->rsize2,
- ntohs(hdr->size) - sizeof(MESSAGE_HEADER));
- printf("Expecting message of %u bytes via GET\n",
- ntohs(hdr->size));
- if (httpSession->rpos2 < ntohs(hdr->size) - sizeof(MESSAGE_HEADER)) {
- cpy = ntohs(hdr->size) - sizeof(MESSAGE_HEADER) - httpSession->rpos2;
- if (cpy > have)
- cpy = have;
- memcpy(&httpSession->rbuff2[httpSession->rpos2],
- &inbuf[poff],
- cpy);
- have -= cpy;
- poff += cpy;
- httpSession->rpos2 += cpy;
- }
- if (httpSession->rpos2 < ntohs(hdr->size) - sizeof(MESSAGE_HEADER))
- return size * nmemb;
- mp = MALLOC(sizeof(P2P_PACKET));
- mp->msg = httpSession->rbuff2;
- mp->sender = httpSession->sender;
- mp->tsession = httpSession->tsession;
- mp->size = ntohs(hdr->size) - sizeof(MESSAGE_HEADER);
- printf("Passing message from GET to core!\n");
- coreAPI->receive(mp);
- httpSession->rbuff2 = NULL;
- httpSession->rpos2 = 0;
- httpSession->rsize2 = 0;
- httpSession->rpos1 = 0;
- }
return size * nmemb;
}
@@ -774,18 +797,14 @@
* Provide bits for upload
*/
static size_t
-sendContentCallback(void * ptr,
- size_t size,
- size_t nmemb,
- void * ctx) {
- struct HTTPPutData * put = ctx;
+sendContentCallback (void *ptr, size_t size, size_t nmemb, void *ctx)
+{
+ struct HTTPPutData *put = ctx;
size_t max = size * nmemb;
if (max > put->size - put->pos)
max = put->size - put->pos;
- memcpy(ptr,
- &put->msg[put->pos],
- max);
+ memcpy (ptr, &put->msg[put->pos], max);
put->pos += max;
return max;
}
@@ -799,174 +818,130 @@
* @param tsessionPtr the session handle that is set
* @return OK on success, SYSERR if the operation failed
*/
-static int httpConnect(const P2P_hello_MESSAGE * hello,
- TSession ** tsessionPtr) {
- const HostAddress * haddr = (const HostAddress*) &hello[1];
- TSession * tsession;
- HTTPSession * httpSession;
- CURL * curl_get;
+static int
+httpConnect (const P2P_hello_MESSAGE * hello, TSession ** tsessionPtr)
+{
+ const HostAddress *haddr = (const HostAddress *) &hello[1];
+ TSession *tsession;
+ HTTPSession *httpSession;
+ CURL *curl_get;
CURLcode ret;
CURLMcode mret;
- char * url;
+ char *url;
EncName enc;
int i;
/* check if we have a session pending for this peer */
tsession = NULL;
- MUTEX_LOCK(httplock);
- for (i=0;i<tsessionCount;i++) {
- if (0 == memcmp(&hello->senderIdentity,
- &tsessions[i]->peer,
- sizeof(PeerIdentity))) {
- tsession = tsessions[i];
- break;
+ MUTEX_LOCK (httplock);
+ for (i = 0; i < tsessionCount; i++)
+ {
+ if (0 == memcmp (&hello->senderIdentity,
+ &tsessions[i]->peer, sizeof (PeerIdentity)))
+ {
+ tsession = tsessions[i];
+ break;
+ }
}
- }
- if ( (tsession != NULL) &&
- (OK == httpAssociate(tsession)) ) {
- *tsessionPtr = tsession;
- MUTEX_UNLOCK(httplock);
- return OK;
- }
- MUTEX_UNLOCK(httplock);
+ if ((tsession != NULL) && (OK == httpAssociate (tsession)))
+ {
+ *tsessionPtr = tsession;
+ MUTEX_UNLOCK (httplock);
+ return OK;
+ }
+ MUTEX_UNLOCK (httplock);
/* no session pending, initiate a new one! */
- curl_get = curl_easy_init();
+ curl_get = curl_easy_init ();
if (curl_get == NULL)
return SYSERR;
- hash2enc(&hello->senderIdentity.hashPubKey,
- &enc);
- url = MALLOC(64 + sizeof(EncName));
- SNPRINTF(url,
- 64 + sizeof(EncName),
- "http://%u.%u.%u.%u:%u/%s",
- PRIP(ntohl(*(int*)&haddr->ip.addr)),
- ntohs(haddr->port),
- &enc);
+ hash2enc (&hello->senderIdentity.hashPubKey, &enc);
+ url = MALLOC (64 + sizeof (EncName));
+ SNPRINTF (url,
+ 64 + sizeof (EncName),
+ "http://%u.%u.%u.%u:%u/%s",
+ PRIP (ntohl (*(int *) &haddr->ip.addr)),
+ ntohs (haddr->port), &enc);
/* create GET */
- CURL_EASY_SETOPT(curl_get,
- CURLOPT_FAILONERROR,
- 1);
- CURL_EASY_SETOPT(curl_get,
- CURLOPT_URL,
- url);
- if (strlen(proxy) > 0)
- CURL_EASY_SETOPT(curl_get,
- CURLOPT_PROXY,
- proxy);
- CURL_EASY_SETOPT(curl_get,
- CURLOPT_BUFFERSIZE,
- 32 * 1024);
- if (0 == strncmp(url,
- "http",
- 4))
- CURL_EASY_SETOPT(curl_get,
- CURLOPT_USERAGENT,
- "GNUnet-http");
- CURL_EASY_SETOPT(curl_get,
- CURLOPT_CONNECTTIMEOUT,
- 150L);
- CURL_EASY_SETOPT(curl_get,
- CURLOPT_TIMEOUT,
- 150L);
- CURL_EASY_SETOPT(curl_get,
- CURLOPT_WRITEFUNCTION,
- &receiveContentCallback);
+ CURL_EASY_SETOPT (curl_get, CURLOPT_FAILONERROR, 1);
+ CURL_EASY_SETOPT (curl_get, CURLOPT_URL, url);
+ if (strlen (proxy) > 0)
+ CURL_EASY_SETOPT (curl_get, CURLOPT_PROXY, proxy);
+ CURL_EASY_SETOPT (curl_get, CURLOPT_BUFFERSIZE, 32 * 1024);
+ if (0 == strncmp (url, "http", 4))
+ CURL_EASY_SETOPT (curl_get, CURLOPT_USERAGENT, "GNUnet-http");
+ CURL_EASY_SETOPT (curl_get, CURLOPT_CONNECTTIMEOUT, 150L);
+ CURL_EASY_SETOPT (curl_get, CURLOPT_TIMEOUT, 150L);
+ CURL_EASY_SETOPT (curl_get, CURLOPT_WRITEFUNCTION, &receiveContentCallback);
- httpSession = MALLOC(sizeof(HTTPSession));
- memset(httpSession,
- 0,
- sizeof(HTTPSession));
+ httpSession = MALLOC (sizeof (HTTPSession));
+ memset (httpSession, 0, sizeof (HTTPSession));
httpSession->cs.client.url = url;
- CURL_EASY_SETOPT(curl_get,
- CURLOPT_WRITEDATA,
- httpSession);
+ CURL_EASY_SETOPT (curl_get, CURLOPT_WRITEDATA, httpSession);
if (ret != CURLE_OK)
goto cleanup;
- mret = curl_multi_add_handle(curl_multi, curl_get);
- if (mret != CURLM_OK) {
- GE_LOG(coreAPI->ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- _("%s failed at %s:%d: `%s'\n"),
- "curl_multi_add_handle",
- __FILE__,
- __LINE__,
- curl_multi_strerror(mret));
- goto cleanup;
- }
+ mret = curl_multi_add_handle (curl_multi, curl_get);
+ if (mret != CURLM_OK)
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ _("%s failed at %s:%d: `%s'\n"),
+ "curl_multi_add_handle",
+ __FILE__, __LINE__, curl_multi_strerror (mret));
+ goto cleanup;
+ }
/* create SESSION */
httpSession->sender = hello->senderIdentity;
- httpSession->lock = MUTEX_CREATE(YES);
- httpSession->users = 1; /* us only, core has not seen this tsession! */
- httpSession->lastUse = get_time();
+ httpSession->lock = MUTEX_CREATE (YES);
+ httpSession->users = 1; /* us only, core has not seen this tsession! */
+ httpSession->lastUse = get_time ();
httpSession->is_client = YES;
httpSession->cs.client.get = curl_get;
- tsession = MALLOC(sizeof(TSession));
+ tsession = MALLOC (sizeof (TSession));
httpSession->tsession = tsession;
tsession->ttype = HTTP_PROTOCOL_NUMBER;
tsession->internal = httpSession;
- addTSession(tsession);
+ addTSession (tsession);
*tsessionPtr = tsession;
return OK;
- cleanup:
- curl_easy_cleanup(curl_get);
- FREE(url);
- FREE(proxy);
- FREE(httpSession);
+cleanup:
+ curl_easy_cleanup (curl_get);
+ FREE (url);
+ FREE (proxy);
+ FREE (httpSession);
return SYSERR;
}
static CURL *
-create_curl_put(HTTPSession * httpSession,
- struct HTTPPutData * put,
- unsigned int size) {
- CURL * curl_put;
+create_curl_put (HTTPSession * httpSession,
+ struct HTTPPutData *put, unsigned int size)
+{
+ CURL *curl_put;
CURLcode ret;
- curl_put = curl_easy_init();
+ curl_put = curl_easy_init ();
if (curl_put == NULL)
return NULL;
- CURL_EASY_SETOPT(curl_put,
- CURLOPT_FAILONERROR,
- 1);
- CURL_EASY_SETOPT(curl_put,
- CURLOPT_URL,
- httpSession->cs.client.url);
- if (strlen(proxy) > 0)
- CURL_EASY_SETOPT(curl_put,
- CURLOPT_PROXY,
- proxy);
- CURL_EASY_SETOPT(curl_put,
- CURLOPT_BUFFERSIZE,
- 32 * 1024);
- if (0 == strncmp(httpSession->cs.client.url,
- "http",
- 4))
- CURL_EASY_SETOPT(curl_put,
- CURLOPT_USERAGENT,
- "GNUnet-http");
- CURL_EASY_SETOPT(curl_put,
- CURLOPT_UPLOAD,
- 1);
- CURL_EASY_SETOPT(curl_put,
- CURLOPT_CONNECTTIMEOUT,
- 150L);
- CURL_EASY_SETOPT(curl_put,
- CURLOPT_INFILESIZE_LARGE,
- size);
- CURL_EASY_SETOPT(curl_put,
- CURLOPT_READFUNCTION,
- &sendContentCallback);
- CURL_EASY_SETOPT(curl_put,
- CURLOPT_READDATA,
- put);
- if (ret != CURLE_OK) {
- curl_easy_cleanup(curl_put);
- return NULL;
- }
+ CURL_EASY_SETOPT (curl_put, CURLOPT_FAILONERROR, 1);
+ CURL_EASY_SETOPT (curl_put, CURLOPT_URL, httpSession->cs.client.url);
+ if (strlen (proxy) > 0)
+ CURL_EASY_SETOPT (curl_put, CURLOPT_PROXY, proxy);
+ CURL_EASY_SETOPT (curl_put, CURLOPT_BUFFERSIZE, 32 * 1024);
+ if (0 == strncmp (httpSession->cs.client.url, "http", 4))
+ CURL_EASY_SETOPT (curl_put, CURLOPT_USERAGENT, "GNUnet-http");
+ CURL_EASY_SETOPT (curl_put, CURLOPT_UPLOAD, 1);
+ CURL_EASY_SETOPT (curl_put, CURLOPT_CONNECTTIMEOUT, 150L);
+ CURL_EASY_SETOPT (curl_put, CURLOPT_INFILESIZE_LARGE, size);
+ CURL_EASY_SETOPT (curl_put, CURLOPT_READFUNCTION, &sendContentCallback);
+ CURL_EASY_SETOPT (curl_put, CURLOPT_READDATA, put);
+ if (ret != CURLE_OK)
+ {
+ curl_easy_cleanup (curl_put);
+ return NULL;
+ }
return curl_put;
}
@@ -978,105 +953,106 @@
* @param size the size of the message
* @return SYSERR on error, OK on success, NO if queue is full
*/
-static int httpSend(TSession * tsession,
- const void * msg,
- unsigned int size,
- int important) {
- HTTPSession * httpSession = tsession->internal;
- struct HTTPPutData * putData;
- CURL * curl_put;
+static int
+httpSend (TSession * tsession,
+ const void *msg, unsigned int size, int important)
+{
+ HTTPSession *httpSession = tsession->internal;
+ struct HTTPPutData *putData;
+ CURL *curl_put;
CURLMcode mret;
- MESSAGE_HEADER * hdr;
- char * tmp;
+ MESSAGE_HEADER *hdr;
+ char *tmp;
- if (httpSession->is_client) {
- if (size >= MAX_BUFFER_SIZE)
- return SYSERR;
- if (size == 0) {
- GE_BREAK(NULL, 0);
- return SYSERR;
+ if (httpSession->is_client)
+ {
+ if (size >= MAX_BUFFER_SIZE)
+ return SYSERR;
+ if (size == 0)
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ putData = MALLOC (sizeof (struct HTTPPutData));
+ memset (putData, 0, sizeof (struct HTTPPutData));
+ putData->msg = MALLOC (size + sizeof (MESSAGE_HEADER));
+ hdr = (MESSAGE_HEADER *) putData->msg;
+ hdr->size = htons (size + sizeof (MESSAGE_HEADER));
+ hdr->type = htons (0);
+ memcpy (&putData->msg[sizeof (MESSAGE_HEADER)], msg, size);
+ putData->size = size + sizeof (MESSAGE_HEADER);
+ MUTEX_LOCK (httpSession->lock);
+ curl_put = create_curl_put (httpSession,
+ putData, size + sizeof (MESSAGE_HEADER));
+ if (curl_put == NULL)
+ {
+ MUTEX_UNLOCK (httpSession->lock);
+ FREE (putData->msg);
+ FREE (putData);
+ return SYSERR;
+ }
+ putData->curl_put = curl_put;
+ putData->next = httpSession->cs.client.puts;
+ httpSession->cs.client.puts = putData;
+ MUTEX_UNLOCK (httpSession->lock);
+ MUTEX_LOCK (httplock);
+ mret = curl_multi_add_handle (curl_multi, curl_put);
+ if (mret != CURLM_OK)
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ _("%s failed at %s:%d: `%s'\n"),
+ "curl_multi_add_handle",
+ __FILE__, __LINE__, curl_multi_strerror (mret));
+ putData->done = YES;
+ MUTEX_UNLOCK (httplock);
+ return SYSERR;
+ }
+ MUTEX_UNLOCK (httplock);
+ return OK;
}
- putData = MALLOC(sizeof(struct HTTPPutData));
- memset(putData,
- 0,
- sizeof(struct HTTPPutData));
- putData->msg = MALLOC(size + sizeof(MESSAGE_HEADER));
- hdr = (MESSAGE_HEADER*) putData->msg;
- hdr->size = htons(size + sizeof(MESSAGE_HEADER));
- hdr->type = htons(0);
- memcpy(&putData->msg[sizeof(MESSAGE_HEADER)],
- msg,
- size);
- putData->size = size + sizeof(MESSAGE_HEADER);
- MUTEX_LOCK(httpSession->lock);
- curl_put = create_curl_put(httpSession,
- putData,
- size + sizeof(MESSAGE_HEADER));
- if (curl_put == NULL) {
- MUTEX_UNLOCK(httpSession->lock);
- FREE(putData->msg);
- FREE(putData);
- return SYSERR;
+ else
+ { /* httpSession->isClient == false */
+ MUTEX_LOCK (httpSession->lock);
+ if (httpSession->wsize == 0)
+ GROW (httpSession->wbuff, httpSession->wsize, HTTP_BUF_SIZE);
+ if (httpSession->wpos + size > httpSession->wsize)
+ {
+ /* need to grow or discard */
+ if (!important)
+ {
+ MUTEX_UNLOCK (httpSession->lock);
+ return NO;
+ }
+ tmp = MALLOC (httpSession->wpos + size);
+ memcpy (tmp,
+ &httpSession->wbuff[httpSession->woff], httpSession->wpos);
+ FREE (httpSession->wbuff);
+ httpSession->wbuff = tmp;
+ httpSession->wsize = httpSession->wpos + size;
+ httpSession->woff = 0;
+ httpSession->wpos = httpSession->wpos + size;
+ }
+ else
+ {
+ /* fits without growing */
+ if (httpSession->wpos + httpSession->woff + size >
+ httpSession->wsize)
+ {
+ /* need to compact first */
+ memmove (httpSession->wbuff,
+ &httpSession->wbuff[httpSession->woff],
+ httpSession->wpos);
+ httpSession->woff = 0;
+ }
+ /* append */
+ memcpy (&httpSession->wbuff[httpSession->woff + httpSession->wpos],
+ msg, size);
+ httpSession->wpos += size;
+ }
+ MUTEX_UNLOCK (httpSession->lock);
+ return OK;
}
- putData->curl_put = curl_put;
- putData->next = httpSession->cs.client.puts;
- httpSession->cs.client.puts = putData;
- MUTEX_UNLOCK(httpSession->lock);
- MUTEX_LOCK(httplock);
- mret = curl_multi_add_handle(curl_multi, curl_put);
- if (mret != CURLM_OK) {
- GE_LOG(coreAPI->ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- _("%s failed at %s:%d: `%s'\n"),
- "curl_multi_add_handle",
- __FILE__,
- __LINE__,
- curl_multi_strerror(mret));
- putData->done = YES;
- MUTEX_UNLOCK(httplock);
- return SYSERR;
- }
- MUTEX_UNLOCK(httplock);
- return OK;
- } else { /* httpSession->isClient == false */
- MUTEX_LOCK(httpSession->lock);
- if (httpSession->wsize == 0)
- GROW(httpSession->wbuff,
- httpSession->wsize,
- HTTP_BUF_SIZE);
- if (httpSession->wpos + size > httpSession->wsize) {
- /* need to grow or discard */
- if (! important) {
- MUTEX_UNLOCK(httpSession->lock);
- return NO;
- }
- tmp = MALLOC(httpSession->wpos + size);
- memcpy(tmp,
- &httpSession->wbuff[httpSession->woff],
- httpSession->wpos);
- FREE(httpSession->wbuff);
- httpSession->wbuff = tmp;
- httpSession->wsize = httpSession->wpos + size;
- httpSession->woff = 0;
- httpSession->wpos = httpSession->wpos + size;
- } else {
- /* fits without growing */
- if (httpSession->wpos + httpSession->woff + size > httpSession->wsize) {
- /* need to compact first */
- memmove(httpSession->wbuff,
- &httpSession->wbuff[httpSession->woff],
- httpSession->wpos);
- httpSession->woff = 0;
- }
- /* append */
- memcpy(&httpSession->wbuff[httpSession->woff + httpSession->wpos],
- msg,
- size);
- httpSession->wpos += size;
- }
- MUTEX_UNLOCK(httpSession->lock);
- return OK;
- }
}
/**
@@ -1085,60 +1061,67 @@
* etc.).
*/
static void
-cleanup_connections() {
+cleanup_connections ()
+{
int i;
- HTTPSession * s;
- struct HTTPPutData * prev;
- struct HTTPPutData * pos;
+ HTTPSession *s;
+ struct HTTPPutData *prev;
+ struct HTTPPutData *pos;
- MUTEX_LOCK(httplock);
- for (i=0;i<tsessionCount;i++) {
- s = tsessions[i]->internal;
- MUTEX_LOCK(s->lock);
- if (s->is_client) {
- prev = NULL;
- pos = s->cs.client.puts;
- while (pos != NULL) {
- /* FIXME: check if CURL has timed out
- the GET operation! If so, clean up!
- (and make sure we re-establish GET
- as needed!) */
+ MUTEX_LOCK (httplock);
+ for (i = 0; i < tsessionCount; i++)
+ {
+ s = tsessions[i]->internal;
+ MUTEX_LOCK (s->lock);
+ if (s->is_client)
+ {
+ prev = NULL;
+ pos = s->cs.client.puts;
+ while (pos != NULL)
+ {
+ /* FIXME: check if CURL has timed out
+ the GET operation! If so, clean up!
+ (and make sure we re-establish GET
+ as needed!) */
- if (pos->done) {
- if (prev == NULL)
- s->cs.client.puts = pos->next;
- else
- prev->next = pos->next;
- FREE(pos->msg);
- curl_multi_remove_handle(curl_multi,
- pos->curl_put);
- curl_easy_cleanup(pos->curl_put);
- FREE(pos);
- if (prev == NULL)
- pos = s->cs.client.puts;
- else
- pos = pos->next;
- continue;
- }
- prev = pos;
- pos = pos->next;
- }
- } else {
- /* FIXME: add code to close MHD connection
- from the server side (timeout!); need
- to
- A) tell GET callback to return "end of transmission"
- B) destroy response object
- */
+ if (pos->done)
+ {
+ if (prev == NULL)
+ s->cs.client.puts = pos->next;
+ else
+ prev->next = pos->next;
+ FREE (pos->msg);
+ curl_multi_remove_handle (curl_multi, pos->curl_put);
+ curl_easy_cleanup (pos->curl_put);
+ FREE (pos);
+ if (prev == NULL)
+ pos = s->cs.client.puts;
+ else
+ pos = pos->next;
+ continue;
+ }
+ prev = pos;
+ pos = pos->next;
+ }
+ }
+ else
+ {
+ /* FIXME: add code to close MHD connection
+ from the server side (timeout!); need
+ to
+ A) tell GET callback to return "end of transmission"
+ B) destroy response object
+ */
+ }
+ MUTEX_UNLOCK (s->lock);
}
- MUTEX_UNLOCK(s->lock);
- }
- MUTEX_UNLOCK(httplock);
+ MUTEX_UNLOCK (httplock);
}
static void *
-curl_runner(void * unused) {
+curl_runner (void *unused)
+{
CURLMcode mret;
fd_set rs;
fd_set ws;
@@ -1147,48 +1130,36 @@
struct timeval tv;
int running;
- while (YES == http_running) {
- max = 0;
- FD_ZERO(&rs);
- FD_ZERO(&ws);
- FD_ZERO(&es);
- mret = curl_multi_fdset(curl_multi,
- &rs,
- &ws,
- &es,
- &max);
- if (mret != CURLM_OK) {
- GE_LOG(coreAPI->ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- _("%s failed at %s:%d: `%s'\n"),
- "curl_multi_fdset",
- __FILE__,
- __LINE__,
- curl_multi_strerror(mret));
- break;
+ while (YES == http_running)
+ {
+ max = 0;
+ FD_ZERO (&rs);
+ FD_ZERO (&ws);
+ FD_ZERO (&es);
+ mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max);
+ if (mret != CURLM_OK)
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ _("%s failed at %s:%d: `%s'\n"),
+ "curl_multi_fdset",
+ __FILE__, __LINE__, curl_multi_strerror (mret));
+ break;
+ }
+ if (mhd_daemon != NULL)
+ MHD_get_fdset (mhd_daemon, &rs, &ws, &es, &max);
+ /* CURL requires a regular timeout... */
+ tv.tv_sec = 0;
+ tv.tv_usec = 1000;
+ SELECT (max + 1, &rs, &ws, &es, &tv);
+ if (YES != http_running)
+ break;
+ running = 0;
+ curl_multi_perform (curl_multi, &running);
+ if (mhd_daemon != NULL)
+ MHD_run (mhd_daemon);
+ cleanup_connections ();
}
- if (mhd_daemon != NULL)
- MHD_get_fdset(mhd_daemon,
- &rs,
- &ws,
- &es,
- &max);
- /* CURL requires a regular timeout... */
- tv.tv_sec = 0;
- tv.tv_usec = 1000;
- SELECT(max + 1,
- &rs,
- &ws,
- &es,
- &tv);
- if (YES != http_running)
- break;
- running = 0;
- curl_multi_perform(curl_multi, &running);
- if (mhd_daemon != NULL)
- MHD_run(mhd_daemon);
- cleanup_connections();
- }
return NULL;
}
@@ -1196,33 +1167,29 @@
* Start the server process to receive inbound traffic.
* @return OK on success, SYSERR if the operation failed
*/
-static int startTransportServer() {
+static int
+startTransportServer ()
+{
unsigned short port;
- if ( (curl_multi != NULL) ||
- (http_running == YES) )
+ if ((curl_multi != NULL) || (http_running == YES))
return SYSERR;
- curl_multi = curl_multi_init();
+ curl_multi = curl_multi_init ();
if (curl_multi == NULL)
return SYSERR;
- port = getGNUnetHTTPPort();
- if ( (mhd_daemon == NULL) &&
- (port != 0) ) {
- mhd_daemon = MHD_start_daemon(MHD_USE_IPv4,
- port,
- &acceptPolicyCallback,
- NULL,
- &accessHandlerCallback,
- NULL);
- }
+ port = getGNUnetHTTPPort ();
+ if ((mhd_daemon == NULL) && (port != 0))
+ {
+ mhd_daemon = MHD_start_daemon (MHD_USE_IPv4,
+ port,
+ &acceptPolicyCallback,
+ NULL, &accessHandlerCallback, NULL);
+ }
http_running = YES;
- curl_thread = PTHREAD_CREATE(&curl_runner,
- NULL,
- 32 * 1024);
+ curl_thread = PTHREAD_CREATE (&curl_runner, NULL, 32 * 1024);
if (curl_thread == NULL)
- GE_DIE_STRERROR(coreAPI->ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "pthread_create");
+ GE_DIE_STRERROR (coreAPI->ectx,
+ GE_FATAL | GE_ADMIN | GE_IMMEDIATE, "pthread_create");
return OK;
}
@@ -1230,20 +1197,22 @@
* Shutdown the server process (stop receiving inbound
* traffic). May be restarted later!
*/
-static int stopTransportServer() {
- void * unused;
+static int
+stopTransportServer ()
+{
+ void *unused;
- if ( (http_running == NO) ||
- (curl_multi == NULL) )
+ if ((http_running == NO) || (curl_multi == NULL))
return SYSERR;
http_running = NO;
- PTHREAD_STOP_SLEEP(curl_thread);
- PTHREAD_JOIN(curl_thread, &unused);
- if (mhd_daemon != NULL) {
- MHD_stop_daemon(mhd_daemon);
- mhd_daemon = NULL;
- }
- curl_multi_cleanup(curl_multi);
+ PTHREAD_STOP_SLEEP (curl_thread);
+ PTHREAD_JOIN (curl_thread, &unused);
+ if (mhd_daemon != NULL)
+ {
+ MHD_stop_daemon (mhd_daemon);
+ mhd_daemon = NULL;
+ }
+ curl_multi_cleanup (curl_multi);
curl_multi = NULL;
return OK;
}
@@ -1252,27 +1221,23 @@
* Reload the configuration. Should never fail (keep old
* configuration on error, syslog errors!)
*/
-static int reloadConfiguration(void * ctx,
- struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option) {
- char * ch;
+static int
+reloadConfiguration (void *ctx,
+ struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section, const char *option)
+{
+ char *ch;
- if (0 != strcmp(section, "HTTP"))
- return 0; /* fast path */
- MUTEX_LOCK(httplock);
- FREENONNULL(filteredNetworks_);
+ if (0 != strcmp (section, "HTTP"))
+ return 0; /* fast path */
+ MUTEX_LOCK (httplock);
+ FREENONNULL (filteredNetworks_);
ch = NULL;
- GC_get_configuration_value_string(cfg,
- "HTTP",
- "BLACKLIST",
- "",
- &ch);
- filteredNetworks_ = parse_ipv4_network_specification(ectx,
- ch);
- FREE(ch);
- MUTEX_UNLOCK(httplock);
+ GC_get_configuration_value_string (cfg, "HTTP", "BLACKLIST", "", &ch);
+ filteredNetworks_ = parse_ipv4_network_specification (ectx, ch);
+ FREE (ch);
+ MUTEX_UNLOCK (httplock);
return 0;
}
@@ -1280,22 +1245,18 @@
* Convert HTTP hello to IP address
*/
static int
-helloToAddress(const P2P_hello_MESSAGE * hello,
- void ** sa,
- unsigned int * sa_len) {
- const HostAddress * haddr = (const HostAddress*) &hello[1];
- struct sockaddr_in * serverAddr;
+helloToAddress (const P2P_hello_MESSAGE * hello,
+ void **sa, unsigned int *sa_len)
+{
+ const HostAddress *haddr = (const HostAddress *) &hello[1];
+ struct sockaddr_in *serverAddr;
- *sa_len = sizeof(struct sockaddr_in);
- serverAddr = MALLOC(sizeof(struct sockaddr_in));
+ *sa_len = sizeof (struct sockaddr_in);
+ serverAddr = MALLOC (sizeof (struct sockaddr_in));
*sa = serverAddr;
- memset(serverAddr,
- 0,
- sizeof(struct sockaddr_in));
- serverAddr->sin_family = AF_INET;
- memcpy(&serverAddr->sin_addr,
- haddr,
- sizeof(IPaddr));
+ memset (serverAddr, 0, sizeof (struct sockaddr_in));
+ serverAddr->sin_family = AF_INET;
+ memcpy (&serverAddr->sin_addr, haddr, sizeof (IPaddr));
serverAddr->sin_port = haddr->port;
return OK;
}
@@ -1308,89 +1269,86 @@
* via a global and returns the udp transport API.
*/
TransportAPI *
-inittransport_http(CoreAPIForTransport * core) {
+inittransport_http (CoreAPIForTransport * core)
+{
static TransportAPI httpAPI;
coreAPI = core;
- httplock = MUTEX_CREATE(YES);
- if (0 != GC_attach_change_listener(coreAPI->cfg,
- &reloadConfiguration,
- NULL)) {
- MUTEX_DESTROY(httplock);
- return NULL;
- }
- if (0 != curl_global_init(CURL_GLOBAL_WIN32)) {
- GE_BREAK(NULL, 0);
- GC_detach_change_listener(coreAPI->cfg,
- &reloadConfiguration,
- NULL);
- MUTEX_DESTROY(httplock);
- return NULL;
- }
+ httplock = MUTEX_CREATE (YES);
+ if (0 != GC_attach_change_listener (coreAPI->cfg,
+ &reloadConfiguration, NULL))
+ {
+ MUTEX_DESTROY (httplock);
+ return NULL;
+ }
+ if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+ {
+ GE_BREAK (NULL, 0);
+ GC_detach_change_listener (coreAPI->cfg, &reloadConfiguration, NULL);
+ MUTEX_DESTROY (httplock);
+ return NULL;
+ }
tsessionCount = 0;
tsessionArrayLength = 0;
- GROW(tsessions,
- tsessionArrayLength,
- 32);
- if (GC_get_configuration_value_yesno(coreAPI->cfg,
- "HTTP",
- "UPNP",
- YES) == YES) {
- upnp = coreAPI->requestService("upnp");
+ GROW (tsessions, tsessionArrayLength, 32);
+ if (GC_get_configuration_value_yesno (coreAPI->cfg,
+ "HTTP", "UPNP", YES) == YES)
+ {
+ upnp = coreAPI->requestService ("upnp");
- if (upnp == NULL) {
- GE_LOG(coreAPI->ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("The UPnP service could not be loaded. To disable UPnP, set the " \
- "configuration option \"UPNP\" in section \"HTTP\" to \"NO\"\n"));
+ if (upnp == NULL)
+ {
+ GE_LOG (coreAPI->ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _
+ ("The UPnP service could not be loaded. To disable UPnP, set
the "
+ "configuration option \"UPNP\" in section \"HTTP\" to
\"NO\"\n"));
+ }
}
- }
- stats = coreAPI->requestService("stats");
- if (stats != NULL) {
- stat_bytesReceived
- = stats->create(gettext_noop("# bytes received via HTTP"));
- stat_bytesSent
- = stats->create(gettext_noop("# bytes sent via HTTP"));
- stat_bytesDropped
- = stats->create(gettext_noop("# bytes dropped by HTTP (outgoing)"));
- }
- GC_get_configuration_value_string(coreAPI->cfg,
- "GNUNETD",
- "HTTP-PROXY",
- "",
- &proxy);
+ stats = coreAPI->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_bytesReceived
+ = stats->create (gettext_noop ("# bytes received via HTTP"));
+ stat_bytesSent = stats->create (gettext_noop ("# bytes sent via HTTP"));
+ stat_bytesDropped
+ = stats->create (gettext_noop ("# bytes dropped by HTTP (outgoing)"));
+ }
+ GC_get_configuration_value_string (coreAPI->cfg,
+ "GNUNETD", "HTTP-PROXY", "", &proxy);
- httpAPI.protocolNumber = HTTP_PROTOCOL_NUMBER;
- httpAPI.mtu = 0;
- httpAPI.cost = 20000; /* about equal to udp */
- httpAPI.verifyHello = &verifyHello;
- httpAPI.createhello = &createhello;
- httpAPI.connect = &httpConnect;
- httpAPI.associate = &httpAssociate;
- httpAPI.send = &httpSend;
- httpAPI.disconnect = &httpDisconnect;
+ httpAPI.protocolNumber = HTTP_PROTOCOL_NUMBER;
+ httpAPI.mtu = 0;
+ httpAPI.cost = 20000; /* about equal to udp */
+ httpAPI.verifyHello = &verifyHello;
+ httpAPI.createhello = &createhello;
+ httpAPI.connect = &httpConnect;
+ httpAPI.associate = &httpAssociate;
+ httpAPI.send = &httpSend;
+ httpAPI.disconnect = &httpDisconnect;
httpAPI.startTransportServer = &startTransportServer;
- httpAPI.stopTransportServer = &stopTransportServer;
- httpAPI.helloToAddress = &helloToAddress;
+ httpAPI.stopTransportServer = &stopTransportServer;
+ httpAPI.helloToAddress = &helloToAddress;
return &httpAPI;
}
-void donetransport_http() {
- GC_detach_change_listener(coreAPI->cfg,
- &reloadConfiguration,
- NULL);
- coreAPI->releaseService(stats);
+void
+donetransport_http ()
+{
+ GC_detach_change_listener (coreAPI->cfg, &reloadConfiguration, NULL);
+ coreAPI->releaseService (stats);
stats = NULL;
- if (upnp != NULL) {
- coreAPI->releaseService(upnp);
- stats = NULL;
- }
- FREENONNULL(filteredNetworks_);
- MUTEX_DESTROY(httplock);
- curl_global_cleanup();
- FREENONNULL(proxy);
+ if (upnp != NULL)
+ {
+ coreAPI->releaseService (upnp);
+ stats = NULL;
+ }
+ FREENONNULL (filteredNetworks_);
+ MUTEX_DESTROY (httplock);
+ curl_global_cleanup ();
+ FREENONNULL (proxy);
proxy = NULL;
}
Modified: GNUnet/src/transports/ip.c
===================================================================
--- GNUnet/src/transports/ip.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/ip.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -37,73 +37,77 @@
* Get the IP address for the local machine.
* @return SYSERR on error, OK on success
*/
-int getPublicIPAddress(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- IPaddr * address) {
+int
+getPublicIPAddress (struct GC_Configuration *cfg,
+ struct GE_Context *ectx, IPaddr * address)
+{
static IPaddr myAddress;
static cron_t last;
static cron_t lastError;
cron_t now;
- char * ips;
+ char *ips;
- now = get_time();
- if (last + cronMINUTES < now) {
- if (lastError + 30 * cronSECONDS > now)
- return SYSERR;
- ips = network_get_local_ip(cfg,
- ectx,
- &myAddress);
- if (ips == NULL) {
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Failed to obtain my (external) %s address!\n"),
- "IP");
- lastError = now;
- return SYSERR;
+ now = get_time ();
+ if (last + cronMINUTES < now)
+ {
+ if (lastError + 30 * cronSECONDS > now)
+ return SYSERR;
+ ips = network_get_local_ip (cfg, ectx, &myAddress);
+ if (ips == NULL)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Failed to obtain my (external) %s address!\n"), "IP");
+ lastError = now;
+ return SYSERR;
+ }
+ FREE (ips);
+ last = now;
}
- FREE(ips);
- last = now;
- }
- memcpy(address,
- &myAddress,
- sizeof(IPaddr));
+ memcpy (address, &myAddress, sizeof (IPaddr));
return OK;
}
-struct PICache {
- struct PICache * next;
- void * address;
+struct PICache
+{
+ struct PICache *next;
+ void *address;
unsigned int len;
PeerIdentity peer;
cron_t expire;
};
-static struct PICache * pi_head;
+static struct PICache *pi_head;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-static void expirePICache() {
- struct PICache * pos;
- struct PICache * next;
- struct PICache * prev;
+static void
+expirePICache ()
+{
+ struct PICache *pos;
+ struct PICache *next;
+ struct PICache *prev;
cron_t now;
- now = get_time();
+ now = get_time ();
pos = pi_head;
prev = NULL;
- while (pos != NULL) {
- next = pos->next;
- if (pos->expire < now) {
- FREE(pos->address);
- FREE(pos);
- if (prev == NULL)
- pi_head = next;
+ while (pos != NULL)
+ {
+ next = pos->next;
+ if (pos->expire < now)
+ {
+ FREE (pos->address);
+ FREE (pos);
+ if (prev == NULL)
+ pi_head = next;
+ else
+ prev->next = next;
+ }
else
- prev->next = next;
- } else
- prev = pos;
- pos = next;
- }
+ prev = pos;
+ pos = next;
+ }
}
@@ -116,29 +120,28 @@
* @param sa set to the address
* @return OK if we found an address, SYSERR if not
*/
-int getIPaddressFromPID(const PeerIdentity * peer,
- void ** sa,
- unsigned int * salen) {
- struct PICache * cache;
+int
+getIPaddressFromPID (const PeerIdentity * peer,
+ void **sa, unsigned int *salen)
+{
+ struct PICache *cache;
- MUTEX_LOCK(lock);
- expirePICache();
+ MUTEX_LOCK (lock);
+ expirePICache ();
cache = pi_head;
- while (cache != NULL) {
- if (0 == memcmp(peer,
- &cache->peer,
- sizeof(PeerIdentity))) {
- *salen = cache->len;
- *sa = MALLOC(cache->len);
- memcpy(*sa,
- cache->address,
- cache->len);
- MUTEX_UNLOCK(lock);
- return OK;
+ while (cache != NULL)
+ {
+ if (0 == memcmp (peer, &cache->peer, sizeof (PeerIdentity)))
+ {
+ *salen = cache->len;
+ *sa = MALLOC (cache->len);
+ memcpy (*sa, cache->address, cache->len);
+ MUTEX_UNLOCK (lock);
+ return OK;
+ }
+ cache = cache->next;
}
- cache = cache->next;
- }
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
return SYSERR;
}
@@ -150,66 +153,65 @@
* NOT validated (and it may well be impossible for
* us to validate the address).
*/
-void setIPaddressFromPID(const PeerIdentity * peer,
- const void * sa,
- unsigned int salen) {
- struct PICache * next;
+void
+setIPaddressFromPID (const PeerIdentity * peer,
+ const void *sa, unsigned int salen)
+{
+ struct PICache *next;
- MUTEX_LOCK(lock);
+ MUTEX_LOCK (lock);
next = pi_head;
- while (next != NULL) {
- if (0 == memcmp(peer,
- &next->peer,
- sizeof(PeerIdentity))) {
- next->expire = get_time() + 12 * cronHOURS;
- if ( (salen == next->len) &&
- (0 == memcmp(sa,
- next->address,
- salen)) ) {
- MUTEX_UNLOCK(lock);
- return;
- }
- FREE(next->address);
- next->address = MALLOC(salen);
- next->len = salen;
- memcpy(next->address,
- sa,
- salen);
- MUTEX_UNLOCK(lock);
- return;
+ while (next != NULL)
+ {
+ if (0 == memcmp (peer, &next->peer, sizeof (PeerIdentity)))
+ {
+ next->expire = get_time () + 12 * cronHOURS;
+ if ((salen == next->len) &&
+ (0 == memcmp (sa, next->address, salen)))
+ {
+ MUTEX_UNLOCK (lock);
+ return;
+ }
+ FREE (next->address);
+ next->address = MALLOC (salen);
+ next->len = salen;
+ memcpy (next->address, sa, salen);
+ MUTEX_UNLOCK (lock);
+ return;
+ }
+ next = next->next;
}
- next = next->next;
- }
- next = MALLOC(sizeof(struct PICache));
+ next = MALLOC (sizeof (struct PICache));
next->peer = *peer;
- next->address = MALLOC(salen);
- memcpy(next->address,
- sa,
- salen);
+ next->address = MALLOC (salen);
+ memcpy (next->address, sa, salen);
next->len = salen;
- next->expire = get_time() + 12 * cronHOURS;
- expirePICache();
+ next->expire = get_time () + 12 * cronHOURS;
+ expirePICache ();
next->next = pi_head;
pi_head = next;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
}
-void __attribute__ ((constructor)) gnunet_ip_ltdl_init() {
- lock = MUTEX_CREATE(YES);
+void __attribute__ ((constructor)) gnunet_ip_ltdl_init ()
+{
+ lock = MUTEX_CREATE (YES);
}
-void __attribute__ ((destructor)) gnunet_ip_ltdl_fini() {
- struct PICache * ppos;
- MUTEX_DESTROY(lock);
- while (pi_head != NULL) {
- ppos = pi_head->next;
- FREE(pi_head->address);
- FREE(pi_head);
- pi_head = ppos;
- }
+void __attribute__ ((destructor)) gnunet_ip_ltdl_fini ()
+{
+ struct PICache *ppos;
+ MUTEX_DESTROY (lock);
+ while (pi_head != NULL)
+ {
+ ppos = pi_head->next;
+ FREE (pi_head->address);
+ FREE (pi_head);
+ pi_head = ppos;
+ }
}
Modified: GNUnet/src/transports/ip.h
===================================================================
--- GNUnet/src/transports/ip.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/ip.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -45,9 +45,8 @@
*
* @return SYSERR on error, OK on success
*/
-int getPublicIPAddress(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- IPaddr * address);
+int getPublicIPAddress (struct GC_Configuration *cfg,
+ struct GE_Context *ectx, IPaddr * address);
/**
* We only have the PeerIdentity. Do we have any
@@ -58,9 +57,8 @@
* @param sa set to the address
* @return OK if we found an address, SYSERR if not
*/
-int getIPaddressFromPID(const PeerIdentity * peer,
- void ** sa,
- unsigned int * salen);
+int getIPaddressFromPID (const PeerIdentity * peer,
+ void **sa, unsigned int *salen);
/**
* We have accepted a connection from a particular
@@ -70,8 +68,7 @@
* NOT validated (and it may well be impossible for
* us to validate the address).
*/
-void setIPaddressFromPID(const PeerIdentity * peer,
- const void * sa,
- unsigned int salen);
+void setIPaddressFromPID (const PeerIdentity * peer,
+ const void *sa, unsigned int salen);
#endif
Modified: GNUnet/src/transports/ip6.c
===================================================================
--- GNUnet/src/transports/ip6.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/ip6.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -50,91 +50,91 @@
* (connection information), conInfo.
* @return SYSERR on failure, OK on success
*/
-static int getAddress6FromHostname(struct GE_Context * ectx,
- IP6addr * identity) {
+static int
+getAddress6FromHostname (struct GE_Context *ectx, IP6addr * identity)
+{
char hostname[MAX_HOSTNAME];
- struct hostent * ip;
+ struct hostent *ip;
- if (0 != gethostname(hostname, MAX_HOSTNAME)) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "gethostname");
- return SYSERR;
- }
+ if (0 != gethostname (hostname, MAX_HOSTNAME))
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "gethostname");
+ return SYSERR;
+ }
/* GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- " looking up $HOSTNAME (%s) to obtain local IP\n",
- hostname); */
+ " looking up $HOSTNAME (%s) to obtain local IP\n",
+ hostname); */
- ip = gethostbyname2(hostname, AF_INET6);
- if (ip == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- _("Could not find IP of host `%s': %s\n"),
- hostname,
- hstrerror(h_errno));
- return SYSERR;
- }
- if (ip->h_addrtype != AF_INET6) {
- GE_BREAK(ectx,
- 0);
- return SYSERR;
- }
- GE_ASSERT(ectx,
- sizeof(struct in6_addr) == sizeof(identity->addr));
- memcpy(&identity->addr[0],
- ip->h_addr_list[0],
- sizeof(struct in6_addr));
+ ip = gethostbyname2 (hostname, AF_INET6);
+ if (ip == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ _("Could not find IP of host `%s': %s\n"),
+ hostname, hstrerror (h_errno));
+ return SYSERR;
+ }
+ if (ip->h_addrtype != AF_INET6)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ GE_ASSERT (ectx, sizeof (struct in6_addr) == sizeof (identity->addr));
+ memcpy (&identity->addr[0], ip->h_addr_list[0], sizeof (struct in6_addr));
return OK;
}
#if HAVE_GETIFADDRS && HAVE_FREEIFADDRS
-static int getAddress6FromGetIfAddrs(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- IP6addr * identity) {
- char * interfaces;
+static int
+getAddress6FromGetIfAddrs (struct GC_Configuration *cfg,
+ struct GE_Context *ectx, IP6addr * identity)
+{
+ char *interfaces;
struct ifaddrs *ifa_first;
- if (-1 == GC_get_configuration_value_string(cfg,
- "NETWORK",
- "INTERFACE",
- "eth0",
- &interfaces)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("No interface specified in section `%s' under `%s'!\n"),
- "NETWORK",
- "INTERFACE");
- return SYSERR; /* that won't work! */
- }
+ if (-1 == GC_get_configuration_value_string (cfg,
+ "NETWORK",
+ "INTERFACE",
+ "eth0", &interfaces))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("No interface specified in section `%s' under `%s'!\n"),
+ "NETWORK", "INTERFACE");
+ return SYSERR; /* that won't work! */
+ }
- if (getifaddrs(&ifa_first) == 0) {
- struct ifaddrs *ifa_ptr;
+ if (getifaddrs (&ifa_first) == 0)
+ {
+ struct ifaddrs *ifa_ptr;
- ifa_ptr = ifa_first;
- for (ifa_ptr = ifa_first; ifa_ptr != NULL; ifa_ptr = ifa_ptr->ifa_next) {
- if (ifa_ptr->ifa_name != NULL &&
- ifa_ptr->ifa_addr != NULL &&
- (ifa_ptr->ifa_flags & IFF_UP) != 0) {
- if (strcmp(interfaces, (char *)ifa_ptr->ifa_name) != 0)
- continue;
- if (ifa_ptr->ifa_addr->sa_family != AF_INET6)
- continue;
- memcpy(identity,
- &(((struct sockaddr_in6 *)ifa_ptr->ifa_addr)->sin6_addr),
- sizeof(struct in6_addr));
- freeifaddrs(ifa_first);
- FREE(interfaces);
- return OK;
- }
+ ifa_ptr = ifa_first;
+ for (ifa_ptr = ifa_first; ifa_ptr != NULL; ifa_ptr = ifa_ptr->ifa_next)
+ {
+ if (ifa_ptr->ifa_name != NULL &&
+ ifa_ptr->ifa_addr != NULL && (ifa_ptr->ifa_flags & IFF_UP) != 0)
+ {
+ if (strcmp (interfaces, (char *) ifa_ptr->ifa_name) != 0)
+ continue;
+ if (ifa_ptr->ifa_addr->sa_family != AF_INET6)
+ continue;
+ memcpy (identity,
+ &(((struct sockaddr_in6 *) ifa_ptr->ifa_addr)->
+ sin6_addr), sizeof (struct in6_addr));
+ freeifaddrs (ifa_first);
+ FREE (interfaces);
+ return OK;
+ }
+ }
+ freeifaddrs (ifa_first);
}
- freeifaddrs(ifa_first);
- }
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Could not obtain IP for interface `%s' using `%s'.\n"),
- interfaces,
- "getifaddrs");
- FREE(interfaces);
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Could not obtain IP for interface `%s' using `%s'.\n"),
+ interfaces, "getifaddrs");
+ FREE (interfaces);
return SYSERR;
}
#endif
@@ -143,57 +143,53 @@
* Get the IP address for the local machine.
* @return SYSERR on error, OK on success
*/
-static int getAddress6(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- IP6addr * address){
- char * ipString;
+static int
+getAddress6 (struct GC_Configuration *cfg,
+ struct GE_Context *ectx, IP6addr * address)
+{
+ char *ipString;
int retval;
- struct hostent * ip; /* for the lookup of the IP in gnunet.conf */
+ struct hostent *ip; /* for the lookup of the IP in gnunet.conf */
retval = SYSERR;
- if (GC_have_configuration_value(cfg,
- "NETWORK",
- "IP6")) {
- ipString = NULL;
- GC_get_configuration_value_string(cfg,
- "NETWORK",
- "IP6",
- "",
- &ipString);
- if (strlen(ipString) > 0) {
- ip = gethostbyname2(ipString,
- AF_INET6);
- if (ip == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- _("Could not resolve `%s': %s\n"),
- ipString,
- hstrerror(h_errno));
- } else if (ip->h_addrtype != AF_INET6) {
- GE_ASSERT(ectx,
- 0);
- retval = SYSERR;
- } else {
- GE_ASSERT(ectx,
- sizeof(struct in6_addr) == sizeof(address->addr));
- memcpy(&address->addr[0],
- ip->h_addr_list[0],
- sizeof(struct in6_addr));
- retval = OK;
- }
+ if (GC_have_configuration_value (cfg, "NETWORK", "IP6"))
+ {
+ ipString = NULL;
+ GC_get_configuration_value_string (cfg,
+ "NETWORK", "IP6", "", &ipString);
+ if (strlen (ipString) > 0)
+ {
+ ip = gethostbyname2 (ipString, AF_INET6);
+ if (ip == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ _("Could not resolve `%s': %s\n"),
+ ipString, hstrerror (h_errno));
+ }
+ else if (ip->h_addrtype != AF_INET6)
+ {
+ GE_ASSERT (ectx, 0);
+ retval = SYSERR;
+ }
+ else
+ {
+ GE_ASSERT (ectx,
+ sizeof (struct in6_addr) == sizeof (address->addr));
+ memcpy (&address->addr[0],
+ ip->h_addr_list[0], sizeof (struct in6_addr));
+ retval = OK;
+ }
+ }
+ FREE (ipString);
}
- FREE(ipString);
- }
#if HAVE_GETIFADDRS && HAVE_FREEIFADDRS
if (retval == SYSERR)
- if (OK == getAddress6FromGetIfAddrs(cfg,
- ectx,
- address))
+ if (OK == getAddress6FromGetIfAddrs (cfg, ectx, address))
retval = OK;
#endif
if (retval == SYSERR)
- retval = getAddress6FromHostname(ectx,
- address);
+ retval = getAddress6FromHostname (ectx, address);
return retval;
}
@@ -201,33 +197,31 @@
* Get the IPv6 address for the local machine.
* @return SYSERR on error, OK on success
*/
-int getPublicIP6Address(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- IP6addr * address) {
+int
+getPublicIP6Address (struct GC_Configuration *cfg,
+ struct GE_Context *ectx, IP6addr * address)
+{
static IP6addr myAddress;
static cron_t last;
static cron_t lastError;
cron_t now;
- now = get_time();
- if (last + cronMINUTES < now) {
- if (lastError + 30 * cronSECONDS > now)
- return SYSERR;
- if (SYSERR == getAddress6(cfg,
- ectx,
- &myAddress)) {
- lastError = now;
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Failed to obtain my (external) %s address!\n"),
- "IPv6");
- return SYSERR;
+ now = get_time ();
+ if (last + cronMINUTES < now)
+ {
+ if (lastError + 30 * cronSECONDS > now)
+ return SYSERR;
+ if (SYSERR == getAddress6 (cfg, ectx, &myAddress))
+ {
+ lastError = now;
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Failed to obtain my (external) %s address!\n"), "IPv6");
+ return SYSERR;
+ }
+ last = now;
}
- last = now;
- }
- memcpy(address,
- &myAddress,
- sizeof(IP6addr));
+ memcpy (address, &myAddress, sizeof (IP6addr));
return OK;
}
Modified: GNUnet/src/transports/ip6.h
===================================================================
--- GNUnet/src/transports/ip6.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/ip6.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,8 +33,7 @@
*
* @return SYSERR on error, OK on success
*/
-int getPublicIP6Address(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- IP6addr * address);
+int getPublicIP6Address (struct GC_Configuration *cfg,
+ struct GE_Context *ectx, IP6addr * address);
#endif
Modified: GNUnet/src/transports/nat.c
===================================================================
--- GNUnet/src/transports/nat.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/nat.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -37,7 +37,8 @@
* NAT is that it can not be contacted from the outside,
* the address is empty.
*/
-typedef struct {
+typedef struct
+{
} HostAddress;
/* *********** globals ************* */
@@ -45,7 +46,7 @@
/* apis (our advertised API and the core api ) */
static TransportAPI natAPI;
-static CoreAPIForTransport * coreAPI;
+static CoreAPIForTransport *coreAPI;
/* *************** API implementation *************** */
@@ -58,23 +59,24 @@
* (the signature/crc have been verified before)
* @return OK on success, SYSERR on failure
*/
-static int verifyHello(const P2P_hello_MESSAGE * hello) {
- if ( (ntohs(hello->senderAddressSize) != sizeof(HostAddress)) ||
- (ntohs(hello->header.size) != P2P_hello_MESSAGE_size(hello)) ||
- (ntohs(hello->header.type) != p2p_PROTO_hello) )
- return SYSERR; /* obviously invalid */
- if (YES == GC_get_configuration_value_yesno(coreAPI->cfg,
- "NAT",
- "LIMITED",
- NO)) {
- /* if WE are a NAT and this is not our hello,
- it is invalid since NAT-to-NAT is not possible! */
- if (0 == memcmp(&coreAPI->myIdentity->hashPubKey,
- &hello->senderIdentity.hashPubKey,
- sizeof(HashCode512)))
- return OK;
- return SYSERR;
- }
+static int
+verifyHello (const P2P_hello_MESSAGE * hello)
+{
+ if ((ntohs (hello->senderAddressSize) != sizeof (HostAddress)) ||
+ (ntohs (hello->header.size) != P2P_hello_MESSAGE_size (hello)) ||
+ (ntohs (hello->header.type) != p2p_PROTO_hello))
+ return SYSERR; /* obviously invalid */
+ if (YES == GC_get_configuration_value_yesno (coreAPI->cfg,
+ "NAT", "LIMITED", NO))
+ {
+ /* if WE are a NAT and this is not our hello,
+ it is invalid since NAT-to-NAT is not possible! */
+ if (0 == memcmp (&coreAPI->myIdentity->hashPubKey,
+ &hello->senderIdentity.hashPubKey,
+ sizeof (HashCode512)))
+ return OK;
+ return SYSERR;
+ }
return OK;
}
@@ -85,18 +87,18 @@
*
* @return hello on success, NULL on error
*/
-static P2P_hello_MESSAGE * createhello() {
- P2P_hello_MESSAGE * msg;
+static P2P_hello_MESSAGE *
+createhello ()
+{
+ P2P_hello_MESSAGE *msg;
- if (NO == GC_get_configuration_value_yesno(coreAPI->cfg,
- "NAT",
- "LIMITED",
- NO))
+ if (NO == GC_get_configuration_value_yesno (coreAPI->cfg,
+ "NAT", "LIMITED", NO))
return NULL;
- msg = MALLOC(sizeof(P2P_hello_MESSAGE) + sizeof(HostAddress));
- msg->senderAddressSize = htons(sizeof(HostAddress));
- msg->protocol = htons(NAT_PROTOCOL_NUMBER);
- msg->MTU = htonl(0);
+ msg = MALLOC (sizeof (P2P_hello_MESSAGE) + sizeof (HostAddress));
+ msg->senderAddressSize = htons (sizeof (HostAddress));
+ msg->protocol = htons (NAT_PROTOCOL_NUMBER);
+ msg->MTU = htonl (0);
return msg;
}
@@ -106,8 +108,9 @@
* @param tsessionPtr the session handle that is to be set
* @return always fails (returns SYSERR)
*/
-static int natConnect(const P2P_hello_MESSAGE * hello,
- TSession ** tsessionPtr) {
+static int
+natConnect (const P2P_hello_MESSAGE * hello, TSession ** tsessionPtr)
+{
return SYSERR;
}
@@ -122,8 +125,10 @@
* @return OK if the session could be associated,
* SYSERR if not.
*/
-int natAssociate(TSession * tsession) {
- return SYSERR; /* NAT connections can never be associated */
+int
+natAssociate (TSession * tsession)
+{
+ return SYSERR; /* NAT connections can never be associated */
}
/**
@@ -134,10 +139,10 @@
* @param size the size of the message
* @return SYSERR (always fails)
*/
-static int natSend(TSession * tsession,
- const void * message,
- const unsigned int size,
- int important) {
+static int
+natSend (TSession * tsession,
+ const void *message, const unsigned int size, int important)
+{
return SYSERR;
}
@@ -147,7 +152,9 @@
* @param tsession the session that is closed
* @return always SYSERR
*/
-static int natDisconnect(TSession * tsession) {
+static int
+natDisconnect (TSession * tsession)
+{
return SYSERR;
}
@@ -156,7 +163,9 @@
*
* @return OK on success, SYSERR if the operation failed
*/
-static int startTransportServer() {
+static int
+startTransportServer ()
+{
return OK;
}
@@ -164,24 +173,25 @@
* Shutdown the server process (stop receiving inbound traffic). Maybe
* restarted later!
*/
-static int stopTransportServer() {
+static int
+stopTransportServer ()
+{
return OK;
}
/**
* Convert NAT address to a string.
*/
-static int helloToAddress(const P2P_hello_MESSAGE * hello,
- void ** sa,
- unsigned int * sa_len) {
- return getIPaddressFromPID(&hello->senderIdentity,
- sa,
- sa_len);
+static int
+helloToAddress (const P2P_hello_MESSAGE * hello,
+ void **sa, unsigned int *sa_len)
+{
+ return getIPaddressFromPID (&hello->senderIdentity, sa, sa_len);
}
-static int testWouldTry(TSession * tsession,
- unsigned int size,
- int important) {
+static int
+testWouldTry (TSession * tsession, unsigned int size, int important)
+{
return SYSERR;
}
@@ -189,26 +199,30 @@
* The exported method. Makes the core api available via a global and
* returns the nat transport API.
*/
-TransportAPI * inittransport_nat(CoreAPIForTransport * core) {
+TransportAPI *
+inittransport_nat (CoreAPIForTransport * core)
+{
coreAPI = core;
- natAPI.protocolNumber = NAT_PROTOCOL_NUMBER;
- natAPI.mtu = 0;
- natAPI.cost = 30000;
- natAPI.verifyHello = &verifyHello;
- natAPI.createhello = &createhello;
- natAPI.connect = &natConnect;
- natAPI.send = &natSend;
- natAPI.associate = &natAssociate;
- natAPI.disconnect = &natDisconnect;
+ natAPI.protocolNumber = NAT_PROTOCOL_NUMBER;
+ natAPI.mtu = 0;
+ natAPI.cost = 30000;
+ natAPI.verifyHello = &verifyHello;
+ natAPI.createhello = &createhello;
+ natAPI.connect = &natConnect;
+ natAPI.send = &natSend;
+ natAPI.associate = &natAssociate;
+ natAPI.disconnect = &natDisconnect;
natAPI.startTransportServer = &startTransportServer;
- natAPI.stopTransportServer = &stopTransportServer;
- natAPI.helloToAddress = &helloToAddress;
- natAPI.testWouldTry = &testWouldTry;
+ natAPI.stopTransportServer = &stopTransportServer;
+ natAPI.helloToAddress = &helloToAddress;
+ natAPI.testWouldTry = &testWouldTry;
return &natAPI;
}
-void donetransport_nat() {
+void
+donetransport_nat ()
+{
}
/* end of nat.c */
Modified: GNUnet/src/transports/smtp.c
===================================================================
--- GNUnet/src/transports/smtp.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/smtp.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -48,7 +48,8 @@
/**
* Host-Address in a SMTP network.
*/
-typedef struct {
+typedef struct
+{
/**
* Filter line that every sender must include in the E-mails such
@@ -70,7 +71,8 @@
* Encapsulation of a GNUnet message in the SMTP mail body (before
* base64 encoding).
*/
-typedef struct {
+typedef struct
+{
/* this struct is always preceeded by n bytes of p2p messages
that the GNUnet core will process */
@@ -92,16 +94,16 @@
/**
* apis (our advertised API and the core api )
*/
-static CoreAPIForTransport * coreAPI;
+static CoreAPIForTransport *coreAPI;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
static TransportAPI smtpAPI;
/**
* Thread that listens for inbound messages
*/
-static struct PTHREAD * dispatchThread;
+static struct PTHREAD *dispatchThread;
/**
* Flag to indicate that server has been shut down.
@@ -112,9 +114,8 @@
/** ******************** Base64 encoding ***********/
#define FILLCHAR '='
-static char * cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\
- "abcdefghijklmnopqrstuvwxyz"\
- "0123456789+/";
+static char *cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz" "0123456789+/";
/**
* Encode into Base64.
@@ -125,9 +126,9 @@
* is allocated)
* @return the size of the output
*/
-static unsigned int base64_encode(char * data,
- unsigned int len,
- char ** output) {
+static unsigned int
+base64_encode (char *data, unsigned int len, char **output)
+{
unsigned int i;
char c;
unsigned int ret;
@@ -138,37 +139,44 @@
(*output)[ret++] = '\n'; \
}
ret = 0;
- *output = MALLOC( (((len * 4 / 3) + 8) * (MAX_CHAR_PER_LINE+2))/
- MAX_CHAR_PER_LINE);
- for (i = 0; i < len; ++i) {
- c = (data[i] >> 2) & 0x3f;
- (*output)[ret++] = cvt[(int)c];
- CHECKLINE;
- c = (data[i] << 4) & 0x3f;
- if (++i < len)
- c |= (data[i] >> 4) & 0x0f;
- (*output)[ret++] = cvt[(int)c];
- CHECKLINE;
- if (i < len) {
- c = (data[i] << 2) & 0x3f;
+ *output = MALLOC ((((len * 4 / 3) + 8) * (MAX_CHAR_PER_LINE + 2)) /
+ MAX_CHAR_PER_LINE);
+ for (i = 0; i < len; ++i)
+ {
+ c = (data[i] >> 2) & 0x3f;
+ (*output)[ret++] = cvt[(int) c];
+ CHECKLINE;
+ c = (data[i] << 4) & 0x3f;
if (++i < len)
- c |= (data[i] >> 6) & 0x03;
- (*output)[ret++] = cvt[(int)c];
+ c |= (data[i] >> 4) & 0x0f;
+ (*output)[ret++] = cvt[(int) c];
CHECKLINE;
- } else {
- ++i;
- (*output)[ret++] = FILLCHAR;
- CHECKLINE;
+ if (i < len)
+ {
+ c = (data[i] << 2) & 0x3f;
+ if (++i < len)
+ c |= (data[i] >> 6) & 0x03;
+ (*output)[ret++] = cvt[(int) c];
+ CHECKLINE;
+ }
+ else
+ {
+ ++i;
+ (*output)[ret++] = FILLCHAR;
+ CHECKLINE;
+ }
+ if (i < len)
+ {
+ c = data[i] & 0x3f;
+ (*output)[ret++] = cvt[(int) c];
+ CHECKLINE;
+ }
+ else
+ {
+ (*output)[ret++] = FILLCHAR;
+ CHECKLINE;
+ }
}
- if (i < len) {
- c = data[i] & 0x3f;
- (*output)[ret++] = cvt[(int)c];
- CHECKLINE;
- } else {
- (*output)[ret++] = FILLCHAR;
- CHECKLINE;
- }
- }
(*output)[ret++] = FILLCHAR;
return ret;
}
@@ -187,13 +195,13 @@
* is allocated)
* @return the size of the output
*/
-static unsigned int base64_decode(char * data,
- unsigned int len,
- char ** output) {
+static unsigned int
+base64_decode (char *data, unsigned int len, char **output)
+{
unsigned int i;
char c;
char c1;
- unsigned int ret=0;
+ unsigned int ret = 0;
#define CHECK_CRLF while (data[i] == '\r' || data[i] == '\n') {\
GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER, "ignoring
CR/LF\n"); \
@@ -201,41 +209,45 @@
if (i >= len) goto END; \
}
- *output = MALLOC((len * 3 / 4) + 8);
+ *output = MALLOC ((len * 3 / 4) + 8);
#if DEBUG_SMTP
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER, "base64_decode decoding
len=%d\n", len);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "base64_decode decoding len=%d\n", len);
#endif
- for (i = 0; i < len; ++i) {
- CHECK_CRLF;
- if (data[i] == FILLCHAR)
+ for (i = 0; i < len; ++i)
+ {
+ CHECK_CRLF;
+ if (data[i] == FILLCHAR)
break;
- c = (char) cvtfind(data[i]);
- ++i;
- CHECK_CRLF;
- c1 = (char) cvtfind(data[i]);
- c = (c << 2) | ((c1 >> 4) & 0x3);
- (*output)[ret++] = c;
- if (++i < len) {
+ c = (char) cvtfind (data[i]);
+ ++i;
CHECK_CRLF;
- c = data[i];
- if (FILLCHAR == c)
- break;
- c = (char) cvtfind(c);
- c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
- (*output)[ret++] = c1;
- }
- if (++i < len) {
- CHECK_CRLF;
- c1 = data[i];
- if (FILLCHAR == c1)
- break;
+ c1 = (char) cvtfind (data[i]);
+ c = (c << 2) | ((c1 >> 4) & 0x3);
+ (*output)[ret++] = c;
+ if (++i < len)
+ {
+ CHECK_CRLF;
+ c = data[i];
+ if (FILLCHAR == c)
+ break;
+ c = (char) cvtfind (c);
+ c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
+ (*output)[ret++] = c1;
+ }
+ if (++i < len)
+ {
+ CHECK_CRLF;
+ c1 = data[i];
+ if (FILLCHAR == c1)
+ break;
- c1 = (char) cvtfind(c1);
- c = ((c << 6) & 0xc0) | c1;
- (*output)[ret++] = c;
+ c1 = (char) cvtfind (c1);
+ c = ((c << 6) & 0xc0) | c1;
+ (*output)[ret++] = c;
+ }
}
- }
- END:
+END:
return ret;
}
@@ -246,26 +258,24 @@
/**
* Listen to the pipe, decode messages and send to core.
*/
-static void * listenAndDistribute(void * unused) {
- char * pipename;
- char * line;
+static void *
+listenAndDistribute (void *unused)
+{
+ char *pipename;
+ char *line;
unsigned int LINESIZE;
- SMTPMessage * mp;
+ SMTPMessage *mp;
- pipename = getFileName("SMTP",
- "PIPE",
- _("You must specify the name of a "
- "pipe for the SMTP transport in section `%s' under
`%s'.\n"));
- GE_ASSERT(ectx, pipename != NULL);
- UNLINK(pipename);
- if (0 != mkfifo(pipename,
- S_IWUSR|S_IRUSR))
- GE_DIE_STRERROR(ectx,
- GE_ADMIN | GE_BULK | GE_FATAL,
- "mkfifo");
- LINESIZE = ((smtpAPI.mtu * 4 / 3) + 8) * (MAX_CHAR_PER_LINE+2)/
- MAX_CHAR_PER_LINE; /* maximum size of a line supported */
- line = MALLOC(LINESIZE + 2); /* 2 bytes for off-by-one errors, just to be
safe... */
+ pipename = getFileName ("SMTP",
+ "PIPE",
+ _("You must specify the name of a "
+ "pipe for the SMTP transport in section `%s' under
`%s'.\n"));
+ GE_ASSERT (ectx, pipename != NULL);
+ UNLINK (pipename);
+ if (0 != mkfifo (pipename, S_IWUSR | S_IRUSR))
+ GE_DIE_STRERROR (ectx, GE_ADMIN | GE_BULK | GE_FATAL, "mkfifo");
+ LINESIZE = ((smtpAPI.mtu * 4 / 3) + 8) * (MAX_CHAR_PER_LINE + 2) /
MAX_CHAR_PER_LINE; /* maximum size of a line supported */
+ line = MALLOC (LINESIZE + 2); /* 2 bytes for off-by-one errors, just to be
safe... */
#define READLINE(l,limit) \
do { retl = fgets(l, limit, fdes); \
@@ -276,97 +286,107 @@
} while (0)
- while (smtp_shutdown == NO ) {
- FILE * fdes;
- char * retl;
- char * boundary;
- char * out;
- unsigned int size;
- P2P_PACKET * coreMP;
- int fd;
+ while (smtp_shutdown == NO)
+ {
+ FILE *fdes;
+ char *retl;
+ char *boundary;
+ char *out;
+ unsigned int size;
+ P2P_PACKET *coreMP;
+ int fd;
- fd = disk_file_open(ectx,
- pipename,
- O_RDONLY);
- if (fd == -1) {
- if (smtp_shutdown == NO)
- PTHREAD_SLEEP(5 * cronSECONDS);
- continue;
- }
- fdes = fdopen(fd, "r");
- while (smtp_shutdown == NO ) {
- do {
- READLINE(line, LINESIZE);
- } while (0 != strAUTOncmp(line, CONTENT_TYPE_MULTIPART));
- READLINE(line, LINESIZE);
- if (strlen(line) < strlen(" boundary=\"")) {
- goto END;
- }
- boundary = STRDUP(&line[strlen(" boundary=\"")-2]);
- if (boundary[strlen(boundary)-2] != '\"') {
- FREE(boundary);
- goto END; /* format error */
- } else {
- boundary[strlen(boundary)-2] = '\0';
- boundary[0] = boundary[1] = '-';
- }
- do {
- READLINE(line, LINESIZE);
- } while (0 != strAUTOncmp(line, boundary));
- do {
- READLINE(line, LINESIZE); /* content type, etc. */
- } while (0 != strAUTOncmp(line, ""));
- READLINE(line, LINESIZE); /* read base64 encoded message; decode,
process */
- while ( (line[strlen(line)-2] != FILLCHAR) &&
- (strlen(line) < LINESIZE) )
- READLINE(&line[strlen(line)-1], LINESIZE - strlen(line));
- size = base64_decode(line, strlen(line)-1, &out);
- if (size < sizeof(SMTPMessage)) {
- GE_BREAK(ectx, 0);
- FREE(out);
- goto END;
- }
+ fd = disk_file_open (ectx, pipename, O_RDONLY);
+ if (fd == -1)
+ {
+ if (smtp_shutdown == NO)
+ PTHREAD_SLEEP (5 * cronSECONDS);
+ continue;
+ }
+ fdes = fdopen (fd, "r");
+ while (smtp_shutdown == NO)
+ {
+ do
+ {
+ READLINE (line, LINESIZE);
+ }
+ while (0 != strAUTOncmp (line, CONTENT_TYPE_MULTIPART));
+ READLINE (line, LINESIZE);
+ if (strlen (line) < strlen (" boundary=\""))
+ {
+ goto END;
+ }
+ boundary = STRDUP (&line[strlen (" boundary=\"") - 2]);
+ if (boundary[strlen (boundary) - 2] != '\"')
+ {
+ FREE (boundary);
+ goto END; /* format error */
+ }
+ else
+ {
+ boundary[strlen (boundary) - 2] = '\0';
+ boundary[0] = boundary[1] = '-';
+ }
+ do
+ {
+ READLINE (line, LINESIZE);
+ }
+ while (0 != strAUTOncmp (line, boundary));
+ do
+ {
+ READLINE (line, LINESIZE); /* content type, etc. */
+ }
+ while (0 != strAUTOncmp (line, ""));
+ READLINE (line, LINESIZE); /* read base64 encoded message;
decode, process */
+ while ((line[strlen (line) - 2] != FILLCHAR) &&
+ (strlen (line) < LINESIZE))
+ READLINE (&line[strlen (line) - 1], LINESIZE - strlen (line));
+ size = base64_decode (line, strlen (line) - 1, &out);
+ if (size < sizeof (SMTPMessage))
+ {
+ GE_BREAK (ectx, 0);
+ FREE (out);
+ goto END;
+ }
- mp = (SMTPMessage*)&out[size-sizeof(SMTPMessage)];
- if (ntohs(mp->size) != size) {
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Received malformed message via SMTP (size mismatch).\n"));
+ mp = (SMTPMessage *) & out[size - sizeof (SMTPMessage)];
+ if (ntohs (mp->size) != size)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _
+ ("Received malformed message via SMTP (size
mismatch).\n"));
#if DEBUG_SMTP
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Size returned by base64=%d, in the msg=%d.\n",
- size,
- ntohl(mp->size));
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Size returned by base64=%d, in the msg=%d.\n",
+ size, ntohl (mp->size));
#endif
- goto END;
- }
- coreMP = MALLOC(sizeof(P2P_PACKET));
- coreMP->msg = out;
- coreMP->size = size - sizeof(SMTPMessage);
- coreMP->tsession = NULL;
- memcpy(&coreMP->sender,
- &mp->sender,
- sizeof(PeerIdentity));
+ goto END;
+ }
+ coreMP = MALLOC (sizeof (P2P_PACKET));
+ coreMP->msg = out;
+ coreMP->size = size - sizeof (SMTPMessage);
+ coreMP->tsession = NULL;
+ memcpy (&coreMP->sender, &mp->sender, sizeof (PeerIdentity));
#if DEBUG_SMTP
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SMTP message passed to the core.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "SMTP message passed to the core.\n");
#endif
- coreAPI->receive(coreMP);
- READLINE(line, LINESIZE); /* new line at the end */
- }
- END:
+ coreAPI->receive (coreMP);
+ READLINE (line, LINESIZE); /* new line at the end */
+ }
+ END:
#if DEBUG_SMTP
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "SMTP message processed.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER, "SMTP message processed.\n");
#endif
- if (fdes != NULL)
- fclose(fdes);
- }
- UNLINK(pipename);
- FREE(pipename);
+ if (fdes != NULL)
+ fclose (fdes);
+ }
+ UNLINK (pipename);
+ FREE (pipename);
return NULL;
}
@@ -382,23 +402,29 @@
* (the signature/crc have been verified before)
* @return OK on success, SYSERR on error
*/
-static int verifyHelo(const P2P_hello_MESSAGE * helo) {
- EmailAddress * maddr;
+static int
+verifyHelo (const P2P_hello_MESSAGE * helo)
+{
+ EmailAddress *maddr;
- maddr = (EmailAddress*) &helo[1];
- if ((ntohs(helo->header.size)!=
- sizeof(P2P_hello_MESSAGE)+ntohs(helo->senderAddressSize)) ||
-
(maddr->senderAddress[ntohs(helo->senderAddressSize)-1-FILTER_STRING_SIZE]!='\0'))
{
- GE_BREAK(ectx, 0);
- return SYSERR; /* obviously invalid */
- } else {
+ maddr = (EmailAddress *) & helo[1];
+ if ((ntohs (helo->header.size) !=
+ sizeof (P2P_hello_MESSAGE) + ntohs (helo->senderAddressSize)) ||
+ (maddr->
+ senderAddress[ntohs (helo->senderAddressSize) - 1 -
+ FILTER_STRING_SIZE] != '\0'))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR; /* obviously invalid */
+ }
+ else
+ {
#if DEBUG_SMTP
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Verified SMTP helo from `%s'.\n",
- &maddr->senderAddress[0]);
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Verified SMTP helo from `%s'.\n", &maddr->senderAddress[0]);
#endif
- return OK;
- }
+ return OK;
+ }
}
/**
@@ -408,60 +434,56 @@
*
* @return hello on success, NULL on error
*/
-static P2P_hello_MESSAGE * createhello() {
- P2P_hello_MESSAGE * msg;
- char * email;
- char * filter;
- EmailAddress * haddr;
+static P2P_hello_MESSAGE *
+createhello ()
+{
+ P2P_hello_MESSAGE *msg;
+ char *email;
+ char *filter;
+ EmailAddress *haddr;
int i;
- email = getConfigurationString("SMTP",
- "EMAIL");
- if (email == NULL) {
- static int once;
- if (once == 0) {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- "No email-address specified, cannot create SMTP advertisement.\n");
- once = 1;
+ email = getConfigurationString ("SMTP", "EMAIL");
+ if (email == NULL)
+ {
+ static int once;
+ if (once == 0)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ "No email-address specified, cannot create SMTP
advertisement.\n");
+ once = 1;
+ }
+ return NULL;
}
- return NULL;
- }
- filter = getConfigurationString("SMTP",
- "FILTER");
- if (filter == NULL) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("No filter for E-mail specified, cannot create SMTP advertisement.\n"));
- FREE(email);
- return NULL;
- }
- if (strlen(filter) > FILTER_STRING_SIZE) {
- filter[FILTER_STRING_SIZE] = '\0';
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("SMTP filter string to long, capped to `%s'\n"),
- filter);
- }
- i = (strlen(email) + 8) & (~7); /* make multiple of 8 */
- msg = MALLOC(sizeof(P2P_hello_MESSAGE) + sizeof(EmailAddress) + i);
- memset(msg,
- 0,
- sizeof(P2P_hello_MESSAGE) + sizeof(EmailAddress) + i);
- haddr = (EmailAddress*) &msg[1];
- memset(&haddr->filter[0],
- 0,
- FILTER_STRING_SIZE);
- strcpy(&haddr->filter[0],
- filter);
- memcpy(&haddr->senderAddress[0],
- email,
- strlen(email)+1);
- msg->senderAddressSize = htons(strlen(email)+1+sizeof(EmailAddress));
- msg->protocol = htons(SMTP_PROTOCOL_NUMBER);
- msg->MTU = htonl(smtpAPI.mtu);
- msg->header.size
- = htons(P2P_hello_MESSAGE_size(msg));
- FREE(email);
- if (verifyHelo(msg) == SYSERR)
- GE_ASSERT(ectx, 0);
+ filter = getConfigurationString ("SMTP", "FILTER");
+ if (filter == NULL)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("No filter for E-mail specified, cannot create SMTP
advertisement.\n"));
+ FREE (email);
+ return NULL;
+ }
+ if (strlen (filter) > FILTER_STRING_SIZE)
+ {
+ filter[FILTER_STRING_SIZE] = '\0';
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("SMTP filter string to long, capped to `%s'\n"), filter);
+ }
+ i = (strlen (email) + 8) & (~7); /* make multiple of 8 */
+ msg = MALLOC (sizeof (P2P_hello_MESSAGE) + sizeof (EmailAddress) + i);
+ memset (msg, 0, sizeof (P2P_hello_MESSAGE) + sizeof (EmailAddress) + i);
+ haddr = (EmailAddress *) & msg[1];
+ memset (&haddr->filter[0], 0, FILTER_STRING_SIZE);
+ strcpy (&haddr->filter[0], filter);
+ memcpy (&haddr->senderAddress[0], email, strlen (email) + 1);
+ msg->senderAddressSize = htons (strlen (email) + 1 + sizeof (EmailAddress));
+ msg->protocol = htons (SMTP_PROTOCOL_NUMBER);
+ msg->MTU = htonl (smtpAPI.mtu);
+ msg->header.size = htons (P2P_hello_MESSAGE_size (msg));
+ FREE (email);
+ if (verifyHelo (msg) == SYSERR)
+ GE_ASSERT (ectx, 0);
return msg;
}
@@ -471,16 +493,15 @@
* @param tsessionPtr the session handle that is to be set
* @return OK on success, SYSERR if the operation failed
*/
-static int smtpConnect(const P2P_hello_MESSAGE * hello,
- TSession ** tsessionPtr) {
- TSession * tsession;
+static int
+smtpConnect (const P2P_hello_MESSAGE * hello, TSession ** tsessionPtr)
+{
+ TSession *tsession;
- tsession = MALLOC(sizeof(TSession));
- tsession->internal = MALLOC(P2P_hello_MESSAGE_size(hello));
+ tsession = MALLOC (sizeof (TSession));
+ tsession->internal = MALLOC (P2P_hello_MESSAGE_size (hello));
tsession->peer = hello->senderIdentity;
- memcpy(tsession->internal,
- hello,
- P2P_hello_MESSAGE_size(hello));
+ memcpy (tsession->internal, hello, P2P_hello_MESSAGE_size (hello));
tsession->ttype = smtpAPI.protocolNumber;
(*tsessionPtr) = tsession;
return OK;
@@ -499,8 +520,10 @@
* @return OK if the session could be associated,
* SYSERR if not.
*/
-int smtpAssociate(TSession * tsession) {
- return SYSERR; /* SMTP connections can never be associated */
+int
+smtpAssociate (TSession * tsession)
+{
+ return SYSERR; /* SMTP connections can never be associated */
}
/**
@@ -511,15 +534,15 @@
* @param size the size of the message
* @return SYSERR on error, OK on success
*/
-static int smtpSend(TSession * tsession,
- const void * message,
- const unsigned int size,
- int important) {
- char * msg;
- SMTPMessage * mp;
- P2P_hello_MESSAGE * helo;
- EmailAddress * haddr;
- char * ebody;
+static int
+smtpSend (TSession * tsession,
+ const void *message, const unsigned int size, int important)
+{
+ char *msg;
+ SMTPMessage *mp;
+ P2P_hello_MESSAGE *helo;
+ EmailAddress *haddr;
+ char *ebody;
int res;
int ssize;
int ssize2;
@@ -527,92 +550,87 @@
smtp_message_t message;
smtp_recipient_t recipient;
char ebuf[EBUF_LEN];
- char * smtpServer;
+ char *smtpServer;
if (smtp_shutdown == YES)
return SYSERR;
- if ( (size == 0) ||
- (size > smtpAPI.mtu) ) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- helo = (P2P_hello_MESSAGE*)tsession->internal;
+ if ((size == 0) || (size > smtpAPI.mtu))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ helo = (P2P_hello_MESSAGE *) tsession->internal;
if (helo == NULL)
return SYSERR;
- smtp_sock = smtp_create_session();
- if (smtp_sock == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_IMMEDIATE,
- _("Failed to initialize libesmtp: %s.\n"),
- smtp_strerror(smtp_errno(), ebuf, EBUF_LEN));
- return NULL;
- }
+ smtp_sock = smtp_create_session ();
+ if (smtp_sock == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_IMMEDIATE,
+ _("Failed to initialize libesmtp: %s.\n"),
+ smtp_strerror (smtp_errno (), ebuf, EBUF_LEN));
+ return NULL;
+ }
smtpServer = "localhost:587"; /* fixme */
- smtp_set_server(smtp_sock, smtpServer);
+ smtp_set_server (smtp_sock, smtpServer);
- haddr = (EmailAddress*) &helo[1];
- ssize2 = ssize = size + sizeof(SMTPMessage);
- msg = MALLOC(ssize);
- mp = (SMTPMessage*) &msg[size];
- mp->size = htons(ssize);
- mp->sender = *coreAPI->myIdentity;
- memcpy(msg,
- message,
- size);
+ haddr = (EmailAddress *) & helo[1];
+ ssize2 = ssize = size + sizeof (SMTPMessage);
+ msg = MALLOC (ssize);
+ mp = (SMTPMessage *) & msg[size];
+ mp->size = htons (ssize);
+ mp->sender = *coreAPI->myIdentity;
+ memcpy (msg, message, size);
ebody = NULL;
#if DEBUG_SMTP
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Base64-encoding %d byte message.\n",
- ssize);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Base64-encoding %d byte message.\n", ssize);
#endif
- ssize = base64_encode(msg, ssize, &ebody);
+ ssize = base64_encode (msg, ssize, &ebody);
#if DEBUG_SMTP
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Base64-encoded message size is %d bytes.\n",
- ssize);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Base64-encoded message size is %d bytes.\n", ssize);
#endif
- FREE(msg);
+ FREE (msg);
res = SYSERR;
- message = smtp_add_message(smtp_sock);
- if (message == NULL) {
- GE_LOG(ectx,
- GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
- "Failed to create smtp message: %s\n",
- smtp_strerror(smtp_errno(), ebuf, EBUF_LEN));
- return SYSERR;
- }
- smtp_size_set_estimate(message,
- ssize);
- smtp_set_messagecb(message,
- &getMessage,
- &msg);
+ message = smtp_add_message (smtp_sock);
+ if (message == NULL)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
+ "Failed to create smtp message: %s\n",
+ smtp_strerror (smtp_errno (), ebuf, EBUF_LEN));
+ return SYSERR;
+ }
+ smtp_size_set_estimate (message, ssize);
+ smtp_set_messagecb (message, &getMessage, &msg);
#if 0
- if (OK == writeSMTPLine(smtp_sock,
- "%-*s\r\n",
- MIN(FILTER_STRING_SIZE,
- strlen(&haddr->filter[0])),
- &haddr->filter[0])) {
- }
+ if (OK == writeSMTPLine (smtp_sock,
+ "%-*s\r\n",
+ MIN (FILTER_STRING_SIZE,
+ strlen (&haddr->filter[0])),
+ &haddr->filter[0]))
+ {
+ }
#endif
- recipient = smtp_add_recipient(message,
- haddr->senderAddress);
- if (recipient == NULL) {
- /* FIXME */
- }
+ recipient = smtp_add_recipient (message, haddr->senderAddress);
+ if (recipient == NULL)
+ {
+ /* FIXME */
+ }
if (res != OK)
- GE_LOG(ectx,
- GE_WARNING | GE_BULK | GE_USER,
- _("Sending E-mail to `%s' failed.\n"),
- &haddr->senderAddress[0]);
- incrementBytesSent(ssize);
- FREE(ebody);
- smtp_destroy_session(smtp_sock);
+ GE_LOG (ectx,
+ GE_WARNING | GE_BULK | GE_USER,
+ _("Sending E-mail to `%s' failed.\n"), &haddr->senderAddress[0]);
+ incrementBytesSent (ssize);
+ FREE (ebody);
+ smtp_destroy_session (smtp_sock);
return res;
@@ -624,12 +642,15 @@
* @param tsession the session that is closed
* @return OK on success, SYSERR if the operation failed
*/
-static int smtpDisconnect(TSession * tsession) {
- if (tsession != NULL) {
- if (tsession->internal != NULL)
- FREE(tsession->internal);
- FREE(tsession);
- }
+static int
+smtpDisconnect (TSession * tsession)
+{
+ if (tsession != NULL)
+ {
+ if (tsession->internal != NULL)
+ FREE (tsession->internal);
+ FREE (tsession);
+ }
return OK;
}
@@ -637,16 +658,14 @@
* Start the server process to receive inbound traffic.
* @return OK on success, SYSERR if the operation failed
*/
-static int startTransportServer(void) {
+static int
+startTransportServer (void)
+{
smtp_shutdown = NO;
/* initialize SMTP network */
- dispatchThread = PTHREAD_CREATE(&listenAndDistribute,
- NULL,
- 1024*4);
+ dispatchThread = PTHREAD_CREATE (&listenAndDistribute, NULL, 1024 * 4);
if (dispatchThread == NULL)
- GE_DIE_STRERROR(ectx,
- GE_ADMIN | GE_BULK | GE_FATAL,
- "pthread_create");
+ GE_DIE_STRERROR (ectx, GE_ADMIN | GE_BULK | GE_FATAL, "pthread_create");
return OK;
}
@@ -654,32 +673,34 @@
* Shutdown the server process (stop receiving inbound traffic). Maybe
* restarted later!
*/
-static int stopTransportServer() {
- void * unused;
+static int
+stopTransportServer ()
+{
+ void *unused;
smtp_shutdown = YES;
- PTHREAD_STOP_SLEEP(dispatchThread);
- PTHREAD_JOIN(dispatchThread, &unused);
+ PTHREAD_STOP_SLEEP (dispatchThread);
+ PTHREAD_JOIN (dispatchThread, &unused);
return OK;
}
/**
* Convert TCP address to a string.
*/
-static char * addressToString(const P2P_hello_MESSAGE * helo) {
- char * ret;
- EmailAddress * addr;
+static char *
+addressToString (const P2P_hello_MESSAGE * helo)
+{
+ char *ret;
+ EmailAddress *addr;
size_t n;
- addr = (EmailAddress*) &helo[1];
- n = FILTER_STRING_SIZE + strlen(addr->senderAddress) + 16;
- ret = MALLOC(n);
- SNPRINTF(ret,
- n,
- _("%.*s filter %s (SMTP)"),
- FILTER_STRING_SIZE,
- addr->filter,
- addr->senderAddress);
+ addr = (EmailAddress *) & helo[1];
+ n = FILTER_STRING_SIZE + strlen (addr->senderAddress) + 16;
+ ret = MALLOC (n);
+ SNPRINTF (ret,
+ n,
+ _("%.*s filter %s (SMTP)"),
+ FILTER_STRING_SIZE, addr->filter, addr->senderAddress);
return ret;
}
@@ -692,38 +713,42 @@
* The exported method. Makes the core api available via a global and
* returns the smtp transport API.
*/
-TransportAPI * inittransport_smtp(CoreAPIForTransport * core) {
+TransportAPI *
+inittransport_smtp (CoreAPIForTransport * core)
+{
int mtu;
coreAPI = core;
ectx = core->ectx;
- mtu = getConfigurationInt("SMTP",
- "MTU");
+ mtu = getConfigurationInt ("SMTP", "MTU");
if (mtu == 0)
mtu = MESSAGE_SIZE;
if (mtu < 1200)
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("MTU for `%s' is probably too low (fragmentation not implemented!)\n"),
- "SMTP");
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _
+ ("MTU for `%s' is probably too low (fragmentation not
implemented!)\n"),
+ "SMTP");
if (mtu > MESSAGE_SIZE)
mtu = MESSAGE_SIZE;
- smtpAPI.protocolNumber = SMTP_PROTOCOL_NUMBER;
- smtpAPI.mtu = mtu - sizeof(SMTPMessage);
- smtpAPI.cost = 50;
- smtpAPI.verifyHelo = &verifyHelo;
- smtpAPI.createhello = &createhello;
- smtpAPI.connect = &smtpConnect;
- smtpAPI.send = &smtpSend;
- smtpAPI.associate = &smtpAssociate;
- smtpAPI.disconnect = &smtpDisconnect;
+ smtpAPI.protocolNumber = SMTP_PROTOCOL_NUMBER;
+ smtpAPI.mtu = mtu - sizeof (SMTPMessage);
+ smtpAPI.cost = 50;
+ smtpAPI.verifyHelo = &verifyHelo;
+ smtpAPI.createhello = &createhello;
+ smtpAPI.connect = &smtpConnect;
+ smtpAPI.send = &smtpSend;
+ smtpAPI.associate = &smtpAssociate;
+ smtpAPI.disconnect = &smtpDisconnect;
smtpAPI.startTransportServer = &startTransportServer;
- smtpAPI.stopTransportServer = &stopTransportServer;
- smtpAPI.addressToString = &addressToString;
+ smtpAPI.stopTransportServer = &stopTransportServer;
+ smtpAPI.addressToString = &addressToString;
return &smtpAPI;
}
-void donetransport_smtp() {
+void
+donetransport_smtp ()
+{
}
/* end of smtp.c */
Modified: GNUnet/src/transports/tcp.c
===================================================================
--- GNUnet/src/transports/tcp.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/tcp.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -59,7 +59,8 @@
/**
* Host-Address in a TCP network.
*/
-typedef struct {
+typedef struct
+{
/**
* claimed IP of the sender, network byte order
*/
@@ -81,51 +82,51 @@
static TransportAPI tcpAPI;
-static UPnP_ServiceAPI * upnp;
+static UPnP_ServiceAPI *upnp;
-static struct CIDRNetwork * filteredNetworks_;
+static struct CIDRNetwork *filteredNetworks_;
-static struct CIDRNetwork * allowedNetworks_;
+static struct CIDRNetwork *allowedNetworks_;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static struct MUTEX * tcpblacklistlock;
+static struct MUTEX *tcpblacklistlock;
/**
* Check if we are allowed to connect to the given IP.
*/
-static int isBlacklisted(const void * addr,
- unsigned int addr_len) {
+static int
+isBlacklisted (const void *addr, unsigned int addr_len)
+{
IPaddr ip;
int ret;
- if (addr_len == sizeof(struct sockaddr_in)) {
- memcpy(&ip,
- &((struct sockaddr_in*) addr)->sin_addr,
- sizeof(IPaddr));
- } else if (addr_len == sizeof(IPaddr)) {
- memcpy(&ip,
- addr,
- addr_len);
- } else {
+ if (addr_len == sizeof (struct sockaddr_in))
+ {
+ memcpy (&ip, &((struct sockaddr_in *) addr)->sin_addr, sizeof (IPaddr));
+ }
+ else if (addr_len == sizeof (IPaddr))
+ {
+ memcpy (&ip, addr, addr_len);
+ }
+ else
+ {
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_ADMIN | GE_BULK,
- "Rejecting connection (invalid address length %u)\n",
- addr_len);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_ADMIN | GE_BULK,
+ "Rejecting connection (invalid address length %u)\n", addr_len);
#endif
- return SYSERR;
- }
- MUTEX_LOCK(tcpblacklistlock);
- ret = check_ipv4_listed(filteredNetworks_,
- ip);
- MUTEX_UNLOCK(tcpblacklistlock);
+ return SYSERR;
+ }
+ MUTEX_LOCK (tcpblacklistlock);
+ ret = check_ipv4_listed (filteredNetworks_, ip);
+ MUTEX_UNLOCK (tcpblacklistlock);
#if DEBUG_TCP
if (ret != NO)
- GE_LOG(ectx,
- GE_DEBUG | GE_ADMIN | GE_BULK,
- "Rejecting connection from address %u.%u.%u.%u (blacklisted)\n",
- PRIP(ntohl(*(int*)addr)));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_ADMIN | GE_BULK,
+ "Rejecting connection from address %u.%u.%u.%u (blacklisted)\n",
+ PRIP (ntohl (*(int *) addr)));
#endif
return ret;
}
@@ -133,51 +134,52 @@
/**
* Check if we are allowed to connect to the given IP.
*/
-static int isWhitelisted(const void * addr,
- unsigned int addr_len) {
+static int
+isWhitelisted (const void *addr, unsigned int addr_len)
+{
IPaddr ip;
int ret;
- if (addr_len == sizeof(struct sockaddr_in)) {
- memcpy(&ip,
- &((struct sockaddr_in*) addr)->sin_addr,
- sizeof(IPaddr));
- } else if (addr_len == sizeof(IPaddr)) {
- memcpy(&ip,
- addr,
- addr_len);
- } else {
+ if (addr_len == sizeof (struct sockaddr_in))
+ {
+ memcpy (&ip, &((struct sockaddr_in *) addr)->sin_addr, sizeof (IPaddr));
+ }
+ else if (addr_len == sizeof (IPaddr))
+ {
+ memcpy (&ip, addr, addr_len);
+ }
+ else
+ {
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_ADMIN | GE_BULK,
- "Rejecting connection (invalid address length %u)\n",
- addr_len);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_ADMIN | GE_BULK,
+ "Rejecting connection (invalid address length %u)\n", addr_len);
#endif
- return SYSERR;
- }
+ return SYSERR;
+ }
ret = YES;
- MUTEX_LOCK(tcpblacklistlock);
+ MUTEX_LOCK (tcpblacklistlock);
if (allowedNetworks_ != NULL)
- ret = check_ipv4_listed(allowedNetworks_,
- ip);
- MUTEX_UNLOCK(tcpblacklistlock);
- if (ret != YES) {
+ ret = check_ipv4_listed (allowedNetworks_, ip);
+ MUTEX_UNLOCK (tcpblacklistlock);
+ if (ret != YES)
+ {
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_ADMIN | GE_BULK,
- "Rejecting HELLO from address %u.%u.%u.%u (not whitelisted)\n",
- PRIP(ntohl(*(int*)addr)));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_ADMIN | GE_BULK,
+ "Rejecting HELLO from address %u.%u.%u.%u (not whitelisted)\n",
+ PRIP (ntohl (*(int *) addr)));
#endif
- }
+ }
return ret;
}
-static int isRejected(const void * addr,
- unsigned int addr_len) {
- if ((NO != isBlacklisted(addr,
- addr_len)) ||
- (YES != isWhitelisted(addr,
- addr_len)))
+static int
+isRejected (const void *addr, unsigned int addr_len)
+{
+ if ((NO != isBlacklisted (addr,
+ addr_len)) ||
+ (YES != isWhitelisted (addr, addr_len)))
return YES;
return NO;
}
@@ -187,22 +189,21 @@
* or from /etc/services if it is not specified in
* the config file.
*/
-static unsigned short getGNUnetTCPPort() {
- struct servent * pse; /* pointer to service information entry */
+static unsigned short
+getGNUnetTCPPort ()
+{
+ struct servent *pse; /* pointer to service information entry
*/
unsigned long long port;
- if (-1 == GC_get_configuration_value_number(cfg,
- "TCP",
- "PORT",
- 0,
- 65535,
- 2086,
- &port)) {
- if ((pse = getservbyname("gnunet", "tcp")))
- port = htons(pse->s_port);
- else
- port = 0;
- }
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "TCP",
+ "PORT", 0, 65535, 2086, &port))
+ {
+ if ((pse = getservbyname ("gnunet", "tcp")))
+ port = htons (pse->s_port);
+ else
+ port = 0;
+ }
return (unsigned short) port;
}
@@ -215,30 +216,30 @@
* (the signature/crc have been verified before)
* @return OK on success, SYSERR on error
*/
-static int verifyHello(const P2P_hello_MESSAGE * hello) {
- HostAddress * haddr;
+static int
+verifyHello (const P2P_hello_MESSAGE * hello)
+{
+ HostAddress *haddr;
- haddr = (HostAddress*) &hello[1];
- if ( (ntohs(hello->senderAddressSize) != sizeof(HostAddress)) ||
- (ntohs(hello->header.size) != P2P_hello_MESSAGE_size(hello)) ||
- (ntohs(hello->header.type) != p2p_PROTO_hello) ||
- (ntohs(hello->protocol) != TCP_PROTOCOL_NUMBER) ||
- (YES == isBlacklisted(&haddr->ip,
- sizeof(IPaddr))) ||
- (YES != isWhitelisted(&haddr->ip,
- sizeof(IPaddr))) ) {
+ haddr = (HostAddress *) & hello[1];
+ if ((ntohs (hello->senderAddressSize) != sizeof (HostAddress)) ||
+ (ntohs (hello->header.size) != P2P_hello_MESSAGE_size (hello)) ||
+ (ntohs (hello->header.type) != p2p_PROTO_hello) ||
+ (ntohs (hello->protocol) != TCP_PROTOCOL_NUMBER) ||
+ (YES == isBlacklisted (&haddr->ip,
+ sizeof (IPaddr))) ||
+ (YES != isWhitelisted (&haddr->ip, sizeof (IPaddr))))
+ {
#if DEBUG_TCP
- EncName enc;
+ EncName enc;
- hash2enc(&hello->senderIdentity.hashPubKey,
- &enc);
- GE_LOG(ectx,
- GE_DEBUG | GE_ADMIN | GE_BULK,
- "Rejecting HELLO from `%s'\n",
- &enc);
+ hash2enc (&hello->senderIdentity.hashPubKey, &enc);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_ADMIN | GE_BULK,
+ "Rejecting HELLO from `%s'\n", &enc);
#endif
- return SYSERR; /* obviously invalid */
- }
+ return SYSERR; /* obviously invalid */
+ }
return OK;
}
@@ -249,49 +250,52 @@
*
* @return hello on success, NULL on error
*/
-static P2P_hello_MESSAGE * createhello() {
- P2P_hello_MESSAGE * msg;
- HostAddress * haddr;
+static P2P_hello_MESSAGE *
+createhello ()
+{
+ P2P_hello_MESSAGE *msg;
+ HostAddress *haddr;
unsigned short port;
- port = getGNUnetTCPPort();
- if (0 == port) {
- static int once = 0;
- if (once == 0) {
- once = 1;
+ port = getGNUnetTCPPort ();
+ if (0 == port)
+ {
+ static int once = 0;
+ if (once == 0)
+ {
+ once = 1;
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "TCP port is 0, will only send using TCP.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "TCP port is 0, will only send using TCP.\n");
#endif
+ }
+ return NULL; /* TCP transport is configured SEND-only! */
}
- return NULL; /* TCP transport is configured SEND-only! */
- }
- msg = MALLOC(sizeof(P2P_hello_MESSAGE) + sizeof(HostAddress));
- haddr = (HostAddress*) &msg[1];
+ msg = MALLOC (sizeof (P2P_hello_MESSAGE) + sizeof (HostAddress));
+ haddr = (HostAddress *) & msg[1];
- if (! ( ( (upnp != NULL) &&
- (OK == upnp->get_ip(port,
- "TCP",
- &haddr->ip)) ) ||
- (SYSERR != getPublicIPAddress(cfg,
- ectx,
- &haddr->ip)) ) ) {
- FREE(msg);
- GE_LOG(ectx,
- GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
- _("TCP: Could not determine my public IP address.\n"));
- return NULL;
- }
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "TCP uses IP address %u.%u.%u.%u.\n",
- PRIP(ntohl(*(int*)&haddr->ip)));
- haddr->port = htons(port);
- haddr->reserved = htons(0);
- msg->senderAddressSize = htons(sizeof(HostAddress));
- msg->protocol = htons(TCP_PROTOCOL_NUMBER);
- msg->MTU = htonl(tcpAPI.mtu);
+ if (!(((upnp != NULL) &&
+ (OK == upnp->get_ip (port,
+ "TCP",
+ &haddr->ip))) ||
+ (SYSERR != getPublicIPAddress (cfg, ectx, &haddr->ip))))
+ {
+ FREE (msg);
+ GE_LOG (ectx,
+ GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
+ _("TCP: Could not determine my public IP address.\n"));
+ return NULL;
+ }
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "TCP uses IP address %u.%u.%u.%u.\n",
+ PRIP (ntohl (*(int *) &haddr->ip)));
+ haddr->port = htons (port);
+ haddr->reserved = htons (0);
+ msg->senderAddressSize = htons (sizeof (HostAddress));
+ msg->protocol = htons (TCP_PROTOCOL_NUMBER);
+ msg->MTU = htonl (tcpAPI.mtu);
return msg;
}
@@ -302,181 +306,155 @@
* @param tsessionPtr the session handle that is set
* @return OK on success, SYSERR if the operation failed
*/
-static int tcpConnect(const P2P_hello_MESSAGE * hello,
- TSession ** tsessionPtr) {
+static int
+tcpConnect (const P2P_hello_MESSAGE * hello, TSession ** tsessionPtr)
+{
static int zero = 0;
- HostAddress * haddr;
+ HostAddress *haddr;
int sock;
struct sockaddr_in soaddr;
- struct SocketHandle * s;
+ struct SocketHandle *s;
int i;
- TCPSession * session;
+ TCPSession *session;
if (selector == NULL)
return SYSERR;
- MUTEX_LOCK(tcplock);
+ MUTEX_LOCK (tcplock);
session = sessions;
- while (session != NULL) {
- if (0 == memcmp(&session->sender,
- &hello->senderIdentity,
- sizeof(PeerIdentity))) {
- MUTEX_LOCK(session->lock);
- if (session->in_select) {
- session->users++;
- MUTEX_UNLOCK(session->lock);
- MUTEX_UNLOCK(tcplock);
- *tsessionPtr = session->tsession;
- return OK;
- }
- MUTEX_UNLOCK(session->lock);
+ while (session != NULL)
+ {
+ if (0 == memcmp (&session->sender,
+ &hello->senderIdentity, sizeof (PeerIdentity)))
+ {
+ MUTEX_LOCK (session->lock);
+ if (session->in_select)
+ {
+ session->users++;
+ MUTEX_UNLOCK (session->lock);
+ MUTEX_UNLOCK (tcplock);
+ *tsessionPtr = session->tsession;
+ return OK;
+ }
+ MUTEX_UNLOCK (session->lock);
+ }
+ session = session->next;
}
- session = session->next;
- }
- MUTEX_UNLOCK(tcplock);
- haddr = (HostAddress*) &hello[1];
+ MUTEX_UNLOCK (tcplock);
+ haddr = (HostAddress *) & hello[1];
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Creating TCP connection to %u.%u.%u.%u:%u.\n",
- PRIP(ntohl(*(int*)&haddr->ip.addr)),
- ntohs(haddr->port));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "Creating TCP connection to %u.%u.%u.%u:%u.\n",
+ PRIP (ntohl (*(int *) &haddr->ip.addr)), ntohs (haddr->port));
#endif
- sock = SOCKET(PF_INET,
- SOCK_STREAM,
- 6); /* 6: TCP */
- if (sock == -1) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "socket");
- return SYSERR;
- }
- s = socket_create(ectx,
- coreAPI->load_monitor,
- sock);
+ sock = SOCKET (PF_INET, SOCK_STREAM, 6); /* 6: TCP */
+ if (sock == -1)
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_ADMIN | GE_BULK, "socket");
+ return SYSERR;
+ }
+ s = socket_create (ectx, coreAPI->load_monitor, sock);
#if TCP_SYNCNT
/* only try a single packet to establish connection,
if that does not work, abort instantly */
- setsockopt(sock,
- IPPROTO_TCP,
- TCP_SYNCNT,
- &zero,
- sizeof(zero));
+ setsockopt (sock, IPPROTO_TCP, TCP_SYNCNT, &zero, sizeof (zero));
#endif
- if (-1 == socket_set_blocking(s, NO)) {
- socket_destroy(s);
- return SYSERR;
- }
- memset(&soaddr,
- 0,
- sizeof(soaddr));
+ if (-1 == socket_set_blocking (s, NO))
+ {
+ socket_destroy (s);
+ return SYSERR;
+ }
+ memset (&soaddr, 0, sizeof (soaddr));
soaddr.sin_family = AF_INET;
- GE_ASSERT(ectx,
- sizeof(struct in_addr) == sizeof(IPaddr));
- memcpy(&soaddr.sin_addr,
- &haddr->ip,
- sizeof(IPaddr));
+ GE_ASSERT (ectx, sizeof (struct in_addr) == sizeof (IPaddr));
+ memcpy (&soaddr.sin_addr, &haddr->ip, sizeof (IPaddr));
soaddr.sin_port = haddr->port;
- i = CONNECT(sock,
- (struct sockaddr*)&soaddr,
- sizeof(soaddr));
- if ( (i < 0) &&
- (errno != EINPROGRESS) && (errno != EWOULDBLOCK) ) {
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- _("Cannot connect to %u.%u.%u.%u:%u: %s\n"),
- PRIP(ntohl(*(int*)&haddr->ip)),
- ntohs(haddr->port),
- STRERROR(errno));
- socket_destroy(s);
- return SYSERR;
- }
+ i = CONNECT (sock, (struct sockaddr *) &soaddr, sizeof (soaddr));
+ if ((i < 0) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ _("Cannot connect to %u.%u.%u.%u:%u: %s\n"),
+ PRIP (ntohl (*(int *) &haddr->ip)),
+ ntohs (haddr->port), STRERROR (errno));
+ socket_destroy (s);
+ return SYSERR;
+ }
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_USER | GE_BULK,
- "Establishing connection to %u.%u.%u.%u:%u\n",
- PRIP(ntohl(*(int*)&haddr->ip)),
- ntohs(haddr->port));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_USER | GE_BULK,
+ "Establishing connection to %u.%u.%u.%u:%u\n",
+ PRIP (ntohl (*(int *) &haddr->ip)), ntohs (haddr->port));
#endif
- return tcpConnectHelper(hello,
- s,
- tcpAPI.protocolNumber,
- tsessionPtr);
+ return tcpConnectHelper (hello, s, tcpAPI.protocolNumber, tsessionPtr);
}
/**
* Start the server process to receive inbound traffic.
* @return OK on success, SYSERR if the operation failed
*/
-static int startTransportServer() {
+static int
+startTransportServer ()
+{
struct sockaddr_in serverAddr;
const int on = 1;
unsigned short port;
int s;
- if (selector != NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- port = getGNUnetTCPPort();
- if (port != 0) {
- s = SOCKET(PF_INET,
- SOCK_STREAM,
- 0);
- if (s < 0) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "socket");
+ if (selector != NULL)
+ {
+ GE_BREAK (ectx, 0);
return SYSERR;
}
- if (SETSOCKOPT(s,
- SOL_SOCKET,
- SO_REUSEADDR,
- &on,
- sizeof(on)) < 0 )
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "setsockopt");
- memset((char *) &serverAddr,
- 0,
- sizeof(serverAddr));
- serverAddr.sin_family = AF_INET;
- serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
- serverAddr.sin_port = htons(getGNUnetTCPPort());
- if (BIND(s,
- (struct sockaddr *) &serverAddr,
- sizeof(serverAddr)) < 0) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_IMMEDIATE,
- "bind");
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_IMMEDIATE,
- _("Failed to start transport service on port %d.\n"),
- getGNUnetTCPPort());
- if (0 != CLOSE(s))
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "close");
- return SYSERR;
+ port = getGNUnetTCPPort ();
+ if (port != 0)
+ {
+ s = SOCKET (PF_INET, SOCK_STREAM, 0);
+ if (s < 0)
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_ADMIN | GE_BULK, "socket");
+ return SYSERR;
+ }
+ if (SETSOCKOPT (s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0)
+ GE_DIE_STRERROR (ectx,
+ GE_FATAL | GE_ADMIN | GE_IMMEDIATE, "setsockopt");
+ memset ((char *) &serverAddr, 0, sizeof (serverAddr));
+ serverAddr.sin_family = AF_INET;
+ serverAddr.sin_addr.s_addr = htonl (INADDR_ANY);
+ serverAddr.sin_port = htons (getGNUnetTCPPort ());
+ if (BIND (s, (struct sockaddr *) &serverAddr, sizeof (serverAddr)) < 0)
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_ADMIN | GE_IMMEDIATE, "bind");
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_IMMEDIATE,
+ _("Failed to start transport service on port %d.\n"),
+ getGNUnetTCPPort ());
+ if (0 != CLOSE (s))
+ GE_LOG_STRERROR (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "close");
+ return SYSERR;
+ }
}
- } else {
- s = -1; /* no listening! */
- }
- selector = select_create("tcp",
- NO,
- ectx,
- coreAPI->load_monitor,
- s,
- sizeof(struct sockaddr_in),
- TCP_FAST_TIMEOUT,
- &select_message_handler,
- NULL,
- &select_accept_handler,
- &isRejected,
- &select_close_handler,
- NULL,
- 128 * 1024 /* max memory */,
- 128 /* max sockets */);
+ else
+ {
+ s = -1; /* no listening! */
+ }
+ selector = select_create ("tcp",
+ NO,
+ ectx,
+ coreAPI->load_monitor,
+ s,
+ sizeof (struct sockaddr_in),
+ TCP_FAST_TIMEOUT,
+ &select_message_handler,
+ NULL,
+ &select_accept_handler,
+ &isRejected,
+ &select_close_handler,
+ NULL, 128 * 1024 /* max memory */ ,
+ 128 /* max sockets */ );
return OK;
}
@@ -484,41 +462,32 @@
* Reload the configuration. Should never fail (keep old
* configuration on error, syslog errors!)
*/
-static int reloadConfiguration(void * ctx,
- struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option) {
- char * ch;
+static int
+reloadConfiguration (void *ctx,
+ struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section, const char *option)
+{
+ char *ch;
- if (0 != strcmp(section, "TCP"))
- return 0; /* fast path */
+ if (0 != strcmp (section, "TCP"))
+ return 0; /* fast path */
- MUTEX_LOCK(tcpblacklistlock);
- FREENONNULL(filteredNetworks_);
- FREENONNULL(allowedNetworks_);
+ MUTEX_LOCK (tcpblacklistlock);
+ FREENONNULL (filteredNetworks_);
+ FREENONNULL (allowedNetworks_);
ch = NULL;
- GC_get_configuration_value_string(cfg,
- "TCP",
- "BLACKLIST",
- "",
- &ch);
- filteredNetworks_ = parse_ipv4_network_specification(ectx,
- ch);
- FREE(ch);
+ GC_get_configuration_value_string (cfg, "TCP", "BLACKLIST", "", &ch);
+ filteredNetworks_ = parse_ipv4_network_specification (ectx, ch);
+ FREE (ch);
ch = NULL;
- GC_get_configuration_value_string(cfg,
- "TCP",
- "WHITELIST",
- "",
- &ch);
- if (strlen(ch) > 0)
- allowedNetworks_ = parse_ipv4_network_specification(ectx,
- ch);
+ GC_get_configuration_value_string (cfg, "TCP", "WHITELIST", "", &ch);
+ if (strlen (ch) > 0)
+ allowedNetworks_ = parse_ipv4_network_specification (ectx, ch);
else
allowedNetworks_ = NULL;
- FREE(ch);
- MUTEX_UNLOCK(tcpblacklistlock);
+ FREE (ch);
+ MUTEX_UNLOCK (tcpblacklistlock);
/* TODO: error handling! */
return 0;
}
@@ -527,22 +496,18 @@
* Convert TCP hello to IP address
*/
static int
-helloToAddress(const P2P_hello_MESSAGE * hello,
- void ** sa,
- unsigned int * sa_len) {
- const HostAddress * haddr = (const HostAddress*) &hello[1];
- struct sockaddr_in * serverAddr;
+helloToAddress (const P2P_hello_MESSAGE * hello,
+ void **sa, unsigned int *sa_len)
+{
+ const HostAddress *haddr = (const HostAddress *) &hello[1];
+ struct sockaddr_in *serverAddr;
- *sa_len = sizeof(struct sockaddr_in);
- serverAddr = MALLOC(sizeof(struct sockaddr_in));
+ *sa_len = sizeof (struct sockaddr_in);
+ serverAddr = MALLOC (sizeof (struct sockaddr_in));
*sa = serverAddr;
- memset(serverAddr,
- 0,
- sizeof(struct sockaddr_in));
- serverAddr->sin_family = AF_INET;
- memcpy(&serverAddr->sin_addr,
- haddr,
- sizeof(IPaddr));
+ memset (serverAddr, 0, sizeof (struct sockaddr_in));
+ serverAddr->sin_family = AF_INET;
+ memcpy (&serverAddr->sin_addr, haddr, sizeof (IPaddr));
serverAddr->sin_port = haddr->port;
return OK;
}
@@ -554,80 +519,83 @@
* The exported method. Makes the core api available
* via a global and returns the udp transport API.
*/
-TransportAPI * inittransport_tcp(CoreAPIForTransport * core) {
+TransportAPI *
+inittransport_tcp (CoreAPIForTransport * core)
+{
ectx = core->ectx;
cfg = core->cfg;
- GE_ASSERT(ectx, sizeof(HostAddress) == 8);
- GE_ASSERT(ectx, sizeof(MESSAGE_HEADER) == 4);
- GE_ASSERT(ectx, sizeof(TCPWelcome) == 68);
- tcplock = MUTEX_CREATE(YES);
- tcpblacklistlock = MUTEX_CREATE(YES);
- if (0 != GC_attach_change_listener(cfg,
- &reloadConfiguration,
- NULL)) {
- MUTEX_DESTROY(tcplock);
- MUTEX_DESTROY(tcpblacklistlock);
- tcplock = NULL;
- tcpblacklistlock = NULL;
- return NULL;
- }
+ GE_ASSERT (ectx, sizeof (HostAddress) == 8);
+ GE_ASSERT (ectx, sizeof (MESSAGE_HEADER) == 4);
+ GE_ASSERT (ectx, sizeof (TCPWelcome) == 68);
+ tcplock = MUTEX_CREATE (YES);
+ tcpblacklistlock = MUTEX_CREATE (YES);
+ if (0 != GC_attach_change_listener (cfg, &reloadConfiguration, NULL))
+ {
+ MUTEX_DESTROY (tcplock);
+ MUTEX_DESTROY (tcpblacklistlock);
+ tcplock = NULL;
+ tcpblacklistlock = NULL;
+ return NULL;
+ }
coreAPI = core;
- if (GC_get_configuration_value_yesno(cfg,
- "TCP",
- "UPNP",
- YES) == YES) {
- upnp = coreAPI->requestService("upnp");
+ if (GC_get_configuration_value_yesno (cfg, "TCP", "UPNP", YES) == YES)
+ {
+ upnp = coreAPI->requestService ("upnp");
- if (upnp == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("The UPnP service could not be loaded. To disable UPnP, set the " \
- "configuration option \"UPNP\" in section \"TCP\" to \"NO\"\n"));
+ if (upnp == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _
+ ("The UPnP service could not be loaded. To disable UPnP, set
the "
+ "configuration option \"UPNP\" in section \"TCP\" to
\"NO\"\n"));
+ }
}
- }
- stats = coreAPI->requestService("stats");
- if (stats != NULL) {
- stat_bytesReceived
- = stats->create(gettext_noop("# bytes received via TCP"));
- stat_bytesSent
- = stats->create(gettext_noop("# bytes sent via TCP"));
- stat_bytesDropped
- = stats->create(gettext_noop("# bytes dropped by TCP (outgoing)"));
- }
- tcpAPI.protocolNumber = TCP_PROTOCOL_NUMBER;
- tcpAPI.mtu = 0;
- tcpAPI.cost = 20000; /* about equal to udp */
- tcpAPI.verifyHello = &verifyHello;
- tcpAPI.createhello = &createhello;
- tcpAPI.connect = &tcpConnect;
- tcpAPI.associate = &tcpAssociate;
- tcpAPI.send = &tcpSend;
- tcpAPI.disconnect = &tcpDisconnect;
+ stats = coreAPI->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_bytesReceived
+ = stats->create (gettext_noop ("# bytes received via TCP"));
+ stat_bytesSent = stats->create (gettext_noop ("# bytes sent via TCP"));
+ stat_bytesDropped
+ = stats->create (gettext_noop ("# bytes dropped by TCP (outgoing)"));
+ }
+ tcpAPI.protocolNumber = TCP_PROTOCOL_NUMBER;
+ tcpAPI.mtu = 0;
+ tcpAPI.cost = 20000; /* about equal to udp */
+ tcpAPI.verifyHello = &verifyHello;
+ tcpAPI.createhello = &createhello;
+ tcpAPI.connect = &tcpConnect;
+ tcpAPI.associate = &tcpAssociate;
+ tcpAPI.send = &tcpSend;
+ tcpAPI.disconnect = &tcpDisconnect;
tcpAPI.startTransportServer = &startTransportServer;
- tcpAPI.stopTransportServer = &stopTransportServer;
- tcpAPI.helloToAddress = &helloToAddress;
- tcpAPI.testWouldTry = &tcpTestWouldTry;
+ tcpAPI.stopTransportServer = &stopTransportServer;
+ tcpAPI.helloToAddress = &helloToAddress;
+ tcpAPI.testWouldTry = &tcpTestWouldTry;
return &tcpAPI;
}
-void donetransport_tcp() {
- GC_detach_change_listener(cfg,
- &reloadConfiguration,
- NULL);
- if (stats != NULL) {
- coreAPI->releaseService(stats);
- stats = NULL;
- }
- if (upnp != NULL) {
- coreAPI->releaseService(upnp);
- upnp = NULL;
- }
- FREENONNULL(filteredNetworks_);
- FREENONNULL(allowedNetworks_);
- MUTEX_DESTROY(tcplock);
- MUTEX_DESTROY(tcpblacklistlock);
+void
+donetransport_tcp ()
+{
+ GC_detach_change_listener (cfg, &reloadConfiguration, NULL);
+ if (stats != NULL)
+ {
+ coreAPI->releaseService (stats);
+ stats = NULL;
+ }
+ if (upnp != NULL)
+ {
+ coreAPI->releaseService (upnp);
+ upnp = NULL;
+ }
+ FREENONNULL (filteredNetworks_);
+ FREENONNULL (allowedNetworks_);
+ MUTEX_DESTROY (tcplock);
+ MUTEX_DESTROY (tcpblacklistlock);
}
/* end of tcp.c */
Modified: GNUnet/src/transports/tcp6.c
===================================================================
--- GNUnet/src/transports/tcp6.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/tcp6.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -59,7 +59,8 @@
/**
* @brief Host-Address in a TCP6 network.
*/
-typedef struct {
+typedef struct
+{
/**
* claimed IP of the sender, network byte order
*/
@@ -81,76 +82,80 @@
static TransportAPI tcp6API;
-static struct CIDR6Network * filteredNetworks_;
+static struct CIDR6Network *filteredNetworks_;
-static struct CIDR6Network * allowedNetworks_;
+static struct CIDR6Network *allowedNetworks_;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static struct MUTEX * tcpblacklistlock;
+static struct MUTEX *tcpblacklistlock;
/* ******************** helper functions *********************** */
/**
* Check if we are allowed to connect to the given IP.
*/
-static int isBlacklisted(const void * addr,
- unsigned int addr_len) {
+static int
+isBlacklisted (const void *addr, unsigned int addr_len)
+{
IP6addr ip;
int ret;
- if (addr_len == sizeof(IP6addr)) {
- memcpy(&ip,
- addr,
- sizeof(IP6addr));
- } else if (addr_len == sizeof(struct sockaddr_in6)) {
- memcpy(&ip,
- &((struct sockaddr_in6*) addr)->sin6_addr,
- sizeof(IP6addr));
- } else {
- return SYSERR;
- }
- MUTEX_LOCK(tcpblacklistlock);
- ret = check_ipv6_listed(filteredNetworks_,
- ip);
- MUTEX_UNLOCK(tcpblacklistlock);
+ if (addr_len == sizeof (IP6addr))
+ {
+ memcpy (&ip, addr, sizeof (IP6addr));
+ }
+ else if (addr_len == sizeof (struct sockaddr_in6))
+ {
+ memcpy (&ip,
+ &((struct sockaddr_in6 *) addr)->sin6_addr, sizeof (IP6addr));
+ }
+ else
+ {
+ return SYSERR;
+ }
+ MUTEX_LOCK (tcpblacklistlock);
+ ret = check_ipv6_listed (filteredNetworks_, ip);
+ MUTEX_UNLOCK (tcpblacklistlock);
return ret;
}
/**
* Check if we are allowed to connect to the given IP.
*/
-static int isWhitelisted(const void * addr,
- unsigned int addr_len) {
+static int
+isWhitelisted (const void *addr, unsigned int addr_len)
+{
IP6addr ip;
int ret;
- if (addr_len == sizeof(IP6addr)) {
- memcpy(&ip,
- addr,
- sizeof(IP6addr));
- } else if (addr_len == sizeof(struct sockaddr_in6)) {
- memcpy(&ip,
- &((struct sockaddr_in6*) addr)->sin6_addr,
- sizeof(IP6addr));
- } else {
- return SYSERR;
- }
+ if (addr_len == sizeof (IP6addr))
+ {
+ memcpy (&ip, addr, sizeof (IP6addr));
+ }
+ else if (addr_len == sizeof (struct sockaddr_in6))
+ {
+ memcpy (&ip,
+ &((struct sockaddr_in6 *) addr)->sin6_addr, sizeof (IP6addr));
+ }
+ else
+ {
+ return SYSERR;
+ }
ret = OK;
- MUTEX_LOCK(tcpblacklistlock);
+ MUTEX_LOCK (tcpblacklistlock);
if (allowedNetworks_ != NULL)
- ret = check_ipv6_listed(filteredNetworks_,
- ip);
- MUTEX_UNLOCK(tcpblacklistlock);
+ ret = check_ipv6_listed (filteredNetworks_, ip);
+ MUTEX_UNLOCK (tcpblacklistlock);
return ret;
}
-static int isRejected(const void * addr,
- unsigned int addr_len) {
- if ((YES == isBlacklisted(addr,
- addr_len)) ||
- (YES != isWhitelisted(addr,
- addr_len)))
+static int
+isRejected (const void *addr, unsigned int addr_len)
+{
+ if ((YES == isBlacklisted (addr,
+ addr_len)) ||
+ (YES != isWhitelisted (addr, addr_len)))
return YES;
return NO;
}
@@ -160,22 +165,21 @@
* or from /etc/services if it is not specified in
* the config file.
*/
-static unsigned short getGNUnetTCP6Port() {
- struct servent * pse; /* pointer to service information entry */
+static unsigned short
+getGNUnetTCP6Port ()
+{
+ struct servent *pse; /* pointer to service information entry
*/
unsigned long long port;
- if (-1 == GC_get_configuration_value_number(cfg,
- "TCP6",
- "PORT",
- 1,
- 65535,
- 2086,
- &port)) {
- if ((pse = getservbyname("gnunet", "tcp6")))
- port = htons(pse->s_port);
- else
- port = 0;
- }
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "TCP6",
+ "PORT", 1, 65535, 2086, &port))
+ {
+ if ((pse = getservbyname ("gnunet", "tcp6")))
+ port = htons (pse->s_port);
+ else
+ port = 0;
+ }
return (unsigned short) port;
}
@@ -188,19 +192,20 @@
* (the signature/crc have been verified before)
* @return OK on success, SYSERR on error
*/
-static int verifyHello(const P2P_hello_MESSAGE * hello) {
- Host6Address * haddr;
+static int
+verifyHello (const P2P_hello_MESSAGE * hello)
+{
+ Host6Address *haddr;
- haddr = (Host6Address*) &hello[1];
- if ( (ntohs(hello->senderAddressSize) != sizeof(Host6Address)) ||
- (ntohs(hello->header.size) != P2P_hello_MESSAGE_size(hello)) ||
- (ntohs(hello->header.type) != p2p_PROTO_hello) ||
- (ntohs(hello->protocol) != TCP6_PROTOCOL_NUMBER) ||
- (YES == isBlacklisted(&haddr->ip,
- sizeof(IP6addr))) ||
- (YES != isWhitelisted(&haddr->ip,
- sizeof(IP6addr))) )
- return SYSERR; /* obviously invalid */
+ haddr = (Host6Address *) & hello[1];
+ if ((ntohs (hello->senderAddressSize) != sizeof (Host6Address)) ||
+ (ntohs (hello->header.size) != P2P_hello_MESSAGE_size (hello)) ||
+ (ntohs (hello->header.type) != p2p_PROTO_hello) ||
+ (ntohs (hello->protocol) != TCP6_PROTOCOL_NUMBER) ||
+ (YES == isBlacklisted (&haddr->ip,
+ sizeof (IP6addr))) ||
+ (YES != isWhitelisted (&haddr->ip, sizeof (IP6addr))))
+ return SYSERR; /* obviously invalid */
else
return OK;
}
@@ -212,37 +217,39 @@
*
* @return hello on success, NULL on error
*/
-static P2P_hello_MESSAGE * createhello() {
- P2P_hello_MESSAGE * msg;
- Host6Address * haddr;
+static P2P_hello_MESSAGE *
+createhello ()
+{
+ P2P_hello_MESSAGE *msg;
+ Host6Address *haddr;
unsigned short port;
- port = getGNUnetTCP6Port();
- if (0 == port) {
+ port = getGNUnetTCP6Port ();
+ if (0 == port)
+ {
#if DEBUG_TCP6
- GE_LOG(ectx,
- GE_DEBUG,
- "TCP6 port is 0, will only send using TCP6\n");
+ GE_LOG (ectx, GE_DEBUG, "TCP6 port is 0, will only send using TCP6\n");
#endif
- return NULL; /* TCP6 transport is configured SEND-only! */
- }
- msg = (P2P_hello_MESSAGE *) MALLOC(sizeof(P2P_hello_MESSAGE) +
sizeof(Host6Address));
- haddr = (Host6Address*) &msg[1];
+ return NULL; /* TCP6 transport is configured SEND-only! */
+ }
+ msg =
+ (P2P_hello_MESSAGE *) MALLOC (sizeof (P2P_hello_MESSAGE) +
+ sizeof (Host6Address));
+ haddr = (Host6Address *) & msg[1];
- if (SYSERR == getPublicIP6Address(cfg,
- ectx,
- &haddr->ip)) {
- FREE(msg);
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Could not determine my public IPv6 address.\n"));
- return NULL;
- }
- haddr->port = htons(port);
- haddr->reserved = htons(0);
- msg->senderAddressSize = htons(sizeof(Host6Address));
- msg->protocol = htons(TCP6_PROTOCOL_NUMBER);
- msg->MTU = htonl(tcp6API.mtu);
+ if (SYSERR == getPublicIP6Address (cfg, ectx, &haddr->ip))
+ {
+ FREE (msg);
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Could not determine my public IPv6 address.\n"));
+ return NULL;
+ }
+ haddr->port = htons (port);
+ haddr->reserved = htons (0);
+ msg->senderAddressSize = htons (sizeof (Host6Address));
+ msg->protocol = htons (TCP6_PROTOCOL_NUMBER);
+ msg->MTU = htonl (tcp6API.mtu);
return msg;
}
@@ -253,190 +260,170 @@
* @param tsessionPtr the session handle that is set
* @return OK on success, SYSERR if the operation failed
*/
-static int tcp6Connect(const P2P_hello_MESSAGE * hello,
- TSession ** tsessionPtr) {
+static int
+tcp6Connect (const P2P_hello_MESSAGE * hello, TSession ** tsessionPtr)
+{
int i;
- Host6Address * haddr;
+ Host6Address *haddr;
int sock;
char hostname[INET6_ADDRSTRLEN];
struct addrinfo hints, *res, *res0;
int rtn;
- struct SocketHandle * s;
- TCPSession * session;
+ struct SocketHandle *s;
+ TCPSession *session;
if (selector == NULL)
return SYSERR;
- MUTEX_LOCK(tcplock);
+ MUTEX_LOCK (tcplock);
session = sessions;
- while (session != NULL) {
- if (0 == memcmp(&session->sender,
- &hello->senderIdentity,
- sizeof(PeerIdentity))) {
- MUTEX_LOCK(session->lock);
- if (session->in_select) {
- session->users++;
- MUTEX_UNLOCK(session->lock);
- MUTEX_UNLOCK(tcplock);
- *tsessionPtr = session->tsession;
- return OK;
- }
- MUTEX_UNLOCK(session->lock);
+ while (session != NULL)
+ {
+ if (0 == memcmp (&session->sender,
+ &hello->senderIdentity, sizeof (PeerIdentity)))
+ {
+ MUTEX_LOCK (session->lock);
+ if (session->in_select)
+ {
+ session->users++;
+ MUTEX_UNLOCK (session->lock);
+ MUTEX_UNLOCK (tcplock);
+ *tsessionPtr = session->tsession;
+ return OK;
+ }
+ MUTEX_UNLOCK (session->lock);
+ }
+ session = session->next;
}
- session = session->next;
- }
- MUTEX_UNLOCK(tcplock);
- haddr = (Host6Address*) &hello[1];
- memset(&hints, 0, sizeof(hints));
+ MUTEX_UNLOCK (tcplock);
+ haddr = (Host6Address *) & hello[1];
+ memset (&hints, 0, sizeof (hints));
hints.ai_family = PF_INET6;
hints.ai_socktype = SOCK_STREAM;
- inet_ntop(AF_INET6,
- haddr,
- hostname,
- INET6_ADDRSTRLEN);
- rtn = getaddrinfo(hostname, NULL, &hints, &res0);
- if (rtn != 0) {
- GE_LOG(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- _("`%s': unknown service: %s\n"),
- __FUNCTION__,
- gai_strerror(rtn));
- return SYSERR;
- }
+ inet_ntop (AF_INET6, haddr, hostname, INET6_ADDRSTRLEN);
+ rtn = getaddrinfo (hostname, NULL, &hints, &res0);
+ if (rtn != 0)
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_ADMIN | GE_BULK,
+ _("`%s': unknown service: %s\n"),
+ __FUNCTION__, gai_strerror (rtn));
+ return SYSERR;
+ }
#if DEBUG_TCP6
- GE_LOG(ectx,
- GE_DEBUG,
- "Creating TCP6 connection to %s:%d\n",
- inet_ntop(AF_INET6,
- haddr,
- &hostname,
- INET6_ADDRSTRLEN),
- ntohs(haddr->port));
+ GE_LOG (ectx,
+ GE_DEBUG,
+ "Creating TCP6 connection to %s:%d\n",
+ inet_ntop (AF_INET6,
+ haddr,
+ &hostname, INET6_ADDRSTRLEN), ntohs (haddr->port));
#endif
sock = -1;
s = NULL;
- for (res=res0; res; res=res->ai_next) {
- if (res->ai_family != PF_INET6)
- continue;
- sock = SOCKET(res->ai_family,
- res->ai_socktype,
- res->ai_protocol);
- if (sock < 0) {
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "socket");
- sock = -1;
- continue;
+ for (res = res0; res; res = res->ai_next)
+ {
+ if (res->ai_family != PF_INET6)
+ continue;
+ sock = SOCKET (res->ai_family, res->ai_socktype, res->ai_protocol);
+ if (sock < 0)
+ {
+ GE_LOG_STRERROR (ectx, GE_WARNING | GE_ADMIN | GE_BULK, "socket");
+ sock = -1;
+ continue;
+ }
+ s = socket_create (ectx, coreAPI->load_monitor, sock);
+ if (-1 == socket_set_blocking (s, NO))
+ {
+ socket_destroy (s);
+ freeaddrinfo (res0);
+ return SYSERR;
+ }
+ ((struct sockaddr_in6 *) (res->ai_addr))->sin6_port = haddr->port;
+ i = CONNECT (sock, res->ai_addr, res->ai_addrlen);
+ if ((i < 0) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK))
+ {
+ GE_LOG_STRERROR (ectx, GE_WARNING | GE_ADMIN | GE_BULK, "connect");
+ socket_destroy (s);
+ s = NULL;
+ sock = -1;
+ continue;
+ }
+ break;
}
- s = socket_create(ectx,
- coreAPI->load_monitor,
- sock);
- if (-1 == socket_set_blocking(s, NO)) {
- socket_destroy(s);
- freeaddrinfo(res0);
- return SYSERR;
- }
- ((struct sockaddr_in6*)(res->ai_addr))->sin6_port = haddr->port;
- i = CONNECT(sock,
- res->ai_addr,
- res->ai_addrlen);
- if ( (i < 0) &&
- (errno != EINPROGRESS) && (errno != EWOULDBLOCK) ) {
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "connect");
- socket_destroy(s);
- s = NULL;
- sock = -1;
- continue;
- }
- break;
- }
- freeaddrinfo(res0);
+ freeaddrinfo (res0);
if (sock == -1)
return SYSERR;
- GE_ASSERT(ectx, s != NULL);
- return tcpConnectHelper(hello,
- s,
- tcp6API.protocolNumber,
- tsessionPtr);
+ GE_ASSERT (ectx, s != NULL);
+ return tcpConnectHelper (hello, s, tcp6API.protocolNumber, tsessionPtr);
}
/**
* Start the server process to receive inbound traffic.
* @return OK on success, SYSERR if the operation failed
*/
-static int startTransportServer() {
+static int
+startTransportServer ()
+{
struct sockaddr_in6 serverAddr;
const int on = 1;
unsigned short port;
int s;
- if (selector != NULL) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- port = getGNUnetTCP6Port();
- if (port != 0) {
- s = SOCKET(PF_INET6,
- SOCK_STREAM,
- 0);
- if (s < 0) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "socket");
+ if (selector != NULL)
+ {
+ GE_BREAK (ectx, 0);
return SYSERR;
}
- if (SETSOCKOPT(s,
- SOL_SOCKET,
- SO_REUSEADDR,
- &on,
- sizeof(on)) < 0 )
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "setsockopt");
- memset((char *) &serverAddr,
- 0,
- sizeof(serverAddr));
- serverAddr.sin6_family = AF_INET6;
- serverAddr.sin6_flowinfo = 0;
- serverAddr.sin6_addr = in6addr_any;
- serverAddr.sin6_port = htons(getGNUnetTCP6Port());
- if (BIND(s,
- (struct sockaddr *) &serverAddr,
- sizeof(serverAddr)) < 0) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_IMMEDIATE,
- "bind");
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_IMMEDIATE,
- _("Failed to start transport service on port %d.\n"),
- getGNUnetTCP6Port());
- if (0 != CLOSE(s))
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "close");
- return SYSERR;
+ port = getGNUnetTCP6Port ();
+ if (port != 0)
+ {
+ s = SOCKET (PF_INET6, SOCK_STREAM, 0);
+ if (s < 0)
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_ADMIN | GE_BULK, "socket");
+ return SYSERR;
+ }
+ if (SETSOCKOPT (s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0)
+ GE_DIE_STRERROR (ectx,
+ GE_FATAL | GE_ADMIN | GE_IMMEDIATE, "setsockopt");
+ memset ((char *) &serverAddr, 0, sizeof (serverAddr));
+ serverAddr.sin6_family = AF_INET6;
+ serverAddr.sin6_flowinfo = 0;
+ serverAddr.sin6_addr = in6addr_any;
+ serverAddr.sin6_port = htons (getGNUnetTCP6Port ());
+ if (BIND (s, (struct sockaddr *) &serverAddr, sizeof (serverAddr)) < 0)
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_ADMIN | GE_IMMEDIATE, "bind");
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_IMMEDIATE,
+ _("Failed to start transport service on port %d.\n"),
+ getGNUnetTCP6Port ());
+ if (0 != CLOSE (s))
+ GE_LOG_STRERROR (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "close");
+ return SYSERR;
+ }
}
- } else {
- s = -1;
- }
- selector = select_create("tcp6",
- NO,
- ectx,
- coreAPI->load_monitor,
- s,
- sizeof(IPaddr),
- TCP_FAST_TIMEOUT,
- &select_message_handler,
- NULL,
- &select_accept_handler,
- &isRejected,
- &select_close_handler,
- NULL,
- 128 * 1024 /* max memory */,
- 128 /* max sockets */);
+ else
+ {
+ s = -1;
+ }
+ selector = select_create ("tcp6",
+ NO,
+ ectx,
+ coreAPI->load_monitor,
+ s,
+ sizeof (IPaddr),
+ TCP_FAST_TIMEOUT,
+ &select_message_handler,
+ NULL,
+ &select_accept_handler,
+ &isRejected,
+ &select_close_handler,
+ NULL, 128 * 1024 /* max memory */ ,
+ 128 /* max sockets */ );
return OK;
}
@@ -444,39 +431,30 @@
* Reload the configuration. Should never fail (keep old
* configuration on error, syslog errors!)
*/
-static int reloadConfiguration(void * ctx,
- struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option) {
- char * ch;
+static int
+reloadConfiguration (void *ctx,
+ struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section, const char *option)
+{
+ char *ch;
- if (0 != strcmp(section, "TCP6"))
- return 0; /* fast path */
- MUTEX_LOCK(tcpblacklistlock);
- FREENONNULL(filteredNetworks_);
- FREENONNULL(allowedNetworks_);
- GC_get_configuration_value_string(cfg,
- "TCP6",
- "BLACKLIST",
- "",
- &ch);
- filteredNetworks_ = parse_ipv6_network_specification(ectx,
- ch);
- FREE(ch);
- GC_get_configuration_value_string(cfg,
- "TCP6",
- "WHITELIST",
- "",
- &ch);
- if (strlen(ch) > 0)
- allowedNetworks_ = parse_ipv6_network_specification(ectx,
- ch);
+ if (0 != strcmp (section, "TCP6"))
+ return 0; /* fast path */
+ MUTEX_LOCK (tcpblacklistlock);
+ FREENONNULL (filteredNetworks_);
+ FREENONNULL (allowedNetworks_);
+ GC_get_configuration_value_string (cfg, "TCP6", "BLACKLIST", "", &ch);
+ filteredNetworks_ = parse_ipv6_network_specification (ectx, ch);
+ FREE (ch);
+ GC_get_configuration_value_string (cfg, "TCP6", "WHITELIST", "", &ch);
+ if (strlen (ch) > 0)
+ allowedNetworks_ = parse_ipv6_network_specification (ectx, ch);
else
allowedNetworks_ = NULL;
- FREE(ch);
+ FREE (ch);
- MUTEX_UNLOCK(tcpblacklistlock);
+ MUTEX_UNLOCK (tcpblacklistlock);
return 0;
}
@@ -484,22 +462,18 @@
* Convert TCP6 hello to IPv6 address
*/
static int
-helloToAddress(const P2P_hello_MESSAGE * hello,
- void ** sa,
- unsigned int * sa_len) {
- const Host6Address * haddr = (const Host6Address*) &hello[1];
- struct sockaddr_in6 * serverAddr;
+helloToAddress (const P2P_hello_MESSAGE * hello,
+ void **sa, unsigned int *sa_len)
+{
+ const Host6Address *haddr = (const Host6Address *) &hello[1];
+ struct sockaddr_in6 *serverAddr;
- *sa_len = sizeof(struct sockaddr_in6);
- serverAddr = MALLOC(sizeof(struct sockaddr_in6));
+ *sa_len = sizeof (struct sockaddr_in6);
+ serverAddr = MALLOC (sizeof (struct sockaddr_in6));
*sa = serverAddr;
- memset(serverAddr,
- 0,
- sizeof(struct sockaddr_in6));
- serverAddr->sin6_family = AF_INET6;
- memcpy(&serverAddr->sin6_addr,
- haddr,
- sizeof(IP6addr));
+ memset (serverAddr, 0, sizeof (struct sockaddr_in6));
+ serverAddr->sin6_family = AF_INET6;
+ memcpy (&serverAddr->sin6_addr, haddr, sizeof (IP6addr));
serverAddr->sin6_port = haddr->port;
return OK;
}
@@ -511,56 +485,57 @@
* The exported method. Makes the core api available
* via a global and returns the udp transport API.
*/
-TransportAPI * inittransport_tcp6(CoreAPIForTransport * core) {
+TransportAPI *
+inittransport_tcp6 (CoreAPIForTransport * core)
+{
ectx = core->ectx;
cfg = core->cfg;
- tcplock = MUTEX_CREATE(YES);
- tcpblacklistlock = MUTEX_CREATE(YES);
- if (0 != GC_attach_change_listener(cfg,
- &reloadConfiguration,
- NULL)) {
- MUTEX_DESTROY(tcplock);
- MUTEX_DESTROY(tcpblacklistlock);
- tcplock = NULL;
- tcpblacklistlock = NULL;
- return NULL;
- }
+ tcplock = MUTEX_CREATE (YES);
+ tcpblacklistlock = MUTEX_CREATE (YES);
+ if (0 != GC_attach_change_listener (cfg, &reloadConfiguration, NULL))
+ {
+ MUTEX_DESTROY (tcplock);
+ MUTEX_DESTROY (tcpblacklistlock);
+ tcplock = NULL;
+ tcpblacklistlock = NULL;
+ return NULL;
+ }
coreAPI = core;
- stats = coreAPI->requestService("stats");
- if (stats != NULL) {
- stat_bytesReceived
- = stats->create(gettext_noop("# bytes received via TCP6"));
- stat_bytesSent
- = stats->create(gettext_noop("# bytes sent via TCP6"));
- stat_bytesDropped
- = stats->create(gettext_noop("# bytes dropped by TCP6 (outgoing)"));
- }
- tcp6API.protocolNumber = TCP6_PROTOCOL_NUMBER;
- tcp6API.mtu = 0;
- tcp6API.cost = 19950; /* about equal to udp6 */
- tcp6API.verifyHello = &verifyHello;
- tcp6API.createhello = &createhello;
- tcp6API.connect = &tcp6Connect;
- tcp6API.associate = &tcpAssociate;
- tcp6API.send = &tcpSend;
- tcp6API.disconnect = &tcpDisconnect;
+ stats = coreAPI->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_bytesReceived
+ = stats->create (gettext_noop ("# bytes received via TCP6"));
+ stat_bytesSent = stats->create (gettext_noop ("# bytes sent via TCP6"));
+ stat_bytesDropped
+ = stats->create (gettext_noop ("# bytes dropped by TCP6 (outgoing)"));
+ }
+ tcp6API.protocolNumber = TCP6_PROTOCOL_NUMBER;
+ tcp6API.mtu = 0;
+ tcp6API.cost = 19950; /* about equal to udp6 */
+ tcp6API.verifyHello = &verifyHello;
+ tcp6API.createhello = &createhello;
+ tcp6API.connect = &tcp6Connect;
+ tcp6API.associate = &tcpAssociate;
+ tcp6API.send = &tcpSend;
+ tcp6API.disconnect = &tcpDisconnect;
tcp6API.startTransportServer = &startTransportServer;
- tcp6API.stopTransportServer = &stopTransportServer;
- tcp6API.helloToAddress = &helloToAddress;
- tcp6API.testWouldTry = &tcpTestWouldTry;
+ tcp6API.stopTransportServer = &stopTransportServer;
+ tcp6API.helloToAddress = &helloToAddress;
+ tcp6API.testWouldTry = &tcpTestWouldTry;
return &tcp6API;
}
-void donetransport_tcp6() {
- GC_detach_change_listener(cfg,
- &reloadConfiguration,
- NULL);
- coreAPI->releaseService(stats);
+void
+donetransport_tcp6 ()
+{
+ GC_detach_change_listener (cfg, &reloadConfiguration, NULL);
+ coreAPI->releaseService (stats);
stats = NULL;
- FREENONNULL(filteredNetworks_);
- MUTEX_DESTROY(tcplock);
- MUTEX_DESTROY(tcpblacklistlock);
+ FREENONNULL (filteredNetworks_);
+ MUTEX_DESTROY (tcplock);
+ MUTEX_DESTROY (tcpblacklistlock);
}
/* end of tcp6.c */
Modified: GNUnet/src/transports/tcp_helper.c
===================================================================
--- GNUnet/src/transports/tcp_helper.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/tcp_helper.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -24,14 +24,14 @@
* @author Christian Grothoff
*/
-typedef int (*BlacklistedTester)(const void * addr,
- unsigned int addr_len);
+typedef int (*BlacklistedTester) (const void *addr, unsigned int addr_len);
/**
* Initial handshake message. Note that the beginning
* must match the CS_MESSAGE_HEADER since we are using tcpio.
*/
-typedef struct {
+typedef struct
+{
MESSAGE_HEADER header;
/**
@@ -43,24 +43,25 @@
/**
* Transport Session handle.
*/
-typedef struct TCPSession {
+typedef struct TCPSession
+{
- struct TCPSession * next;
+ struct TCPSession *next;
/**
* the tcp socket (used to identify this connection with selector)
*/
- struct SocketHandle * sock;
+ struct SocketHandle *sock;
/**
* Our tsession.
*/
- TSession * tsession;
+ TSession *tsession;
/**
* mutex for synchronized access to 'users'
*/
- struct MUTEX * lock;
+ struct MUTEX *lock;
/**
* To whom are we talking to (set to our identity
@@ -83,7 +84,7 @@
*/
int in_select;
- void * accept_addr;
+ void *accept_addr;
unsigned int addr_len;
@@ -94,9 +95,9 @@
/**
* apis (our advertised API and the core api )
*/
-static CoreAPIForTransport * coreAPI;
+static CoreAPIForTransport *coreAPI;
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static int stat_bytesReceived;
@@ -104,13 +105,13 @@
static int stat_bytesDropped;
-static struct SelectHandle * selector;
+static struct SelectHandle *selector;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct MUTEX * tcplock;
+static struct MUTEX *tcplock;
-static struct TCPSession * sessions;
+static struct TCPSession *sessions;
/**
@@ -118,57 +119,60 @@
* function (and should not hold the tcpsession's lock
* any more).
*/
-static void freeTCPSession(TCPSession * tcpsession) {
- TCPSession * pos;
- TCPSession * prev;
+static void
+freeTCPSession (TCPSession * tcpsession)
+{
+ TCPSession *pos;
+ TCPSession *prev;
- MUTEX_DESTROY(tcpsession->lock);
- FREENONNULL(tcpsession->accept_addr);
+ MUTEX_DESTROY (tcpsession->lock);
+ FREENONNULL (tcpsession->accept_addr);
pos = sessions;
prev = NULL;
- while (pos != NULL) {
- if (pos == tcpsession) {
- if (prev == NULL)
- sessions = pos->next;
- else
- prev->next = pos->next;
- break;
+ while (pos != NULL)
+ {
+ if (pos == tcpsession)
+ {
+ if (prev == NULL)
+ sessions = pos->next;
+ else
+ prev->next = pos->next;
+ break;
+ }
+ prev = pos;
+ pos = pos->next;
}
- prev = pos;
- pos = pos->next;
- }
- FREE(tcpsession->tsession);
- FREE(tcpsession);
+ FREE (tcpsession->tsession);
+ FREE (tcpsession);
}
-static int tcpDisconnect(TSession * tsession) {
- TCPSession * tcpsession = tsession->internal;
+static int
+tcpDisconnect (TSession * tsession)
+{
+ TCPSession *tcpsession = tsession->internal;
- GE_ASSERT(ectx, selector != NULL);
- MUTEX_LOCK(tcplock);
- MUTEX_LOCK(tcpsession->lock);
- GE_ASSERT(ectx, tcpsession->users > 0);
+ GE_ASSERT (ectx, selector != NULL);
+ MUTEX_LOCK (tcplock);
+ MUTEX_LOCK (tcpsession->lock);
+ GE_ASSERT (ectx, tcpsession->users > 0);
tcpsession->users--;
- if ( (tcpsession->users > 0) ||
- (tcpsession->in_select == YES) ) {
- if (tcpsession->users == 0)
- select_change_timeout(selector,
- tcpsession->sock,
- TCP_FAST_TIMEOUT);
- MUTEX_UNLOCK(tcpsession->lock);
- MUTEX_UNLOCK(tcplock);
- return OK;
- }
+ if ((tcpsession->users > 0) || (tcpsession->in_select == YES))
+ {
+ if (tcpsession->users == 0)
+ select_change_timeout (selector, tcpsession->sock, TCP_FAST_TIMEOUT);
+ MUTEX_UNLOCK (tcpsession->lock);
+ MUTEX_UNLOCK (tcplock);
+ return OK;
+ }
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "TCP disconnect closes socket session.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "TCP disconnect closes socket session.\n");
#endif
- select_disconnect(selector,
- tcpsession->sock);
- MUTEX_UNLOCK(tcpsession->lock);
- freeTCPSession(tcpsession);
- MUTEX_UNLOCK(tcplock);
+ select_disconnect (selector, tcpsession->sock);
+ MUTEX_UNLOCK (tcpsession->lock);
+ freeTCPSession (tcpsession);
+ MUTEX_UNLOCK (tcplock);
return OK;
}
@@ -191,20 +195,19 @@
* @return OK if the session could be associated,
* SYSERR if not.
*/
-static int tcpAssociate(TSession * tsession) {
- TCPSession * tcpSession;
+static int
+tcpAssociate (TSession * tsession)
+{
+ TCPSession *tcpSession;
- GE_ASSERT(ectx, tsession != NULL);
+ GE_ASSERT (ectx, tsession != NULL);
tcpSession = tsession->internal;
- MUTEX_LOCK(tcpSession->lock);
- if ( (tcpSession->users == 0) &&
- (tcpSession->in_select == YES) )
- select_change_timeout(selector,
- tcpSession->sock,
- TCP_TIMEOUT);
+ MUTEX_LOCK (tcpSession->lock);
+ if ((tcpSession->users == 0) && (tcpSession->in_select == YES))
+ select_change_timeout (selector, tcpSession->sock, TCP_TIMEOUT);
tcpSession->users++;
- MUTEX_UNLOCK(tcpSession->lock);
+ MUTEX_UNLOCK (tcpSession->lock);
return OK;
}
@@ -214,118 +217,120 @@
* This function may only be called if the tcplock is
* already held by the caller.
*/
-static int select_message_handler(void * mh_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * sock_ctx,
- const MESSAGE_HEADER * msg) {
- TSession * tsession = sock_ctx;
- TCPSession * tcpSession;
- TCPSession * pos;
+static int
+select_message_handler (void *mh_cls,
+ struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ void *sock_ctx, const MESSAGE_HEADER * msg)
+{
+ TSession *tsession = sock_ctx;
+ TCPSession *tcpSession;
+ TCPSession *pos;
unsigned int len;
- P2P_PACKET * mp;
- const TCPWelcome * welcome;
+ P2P_PACKET *mp;
+ const TCPWelcome *welcome;
- if (SYSERR == tcpAssociate(tsession)) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- len = ntohs(msg->size);
+ if (SYSERR == tcpAssociate (tsession))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ len = ntohs (msg->size);
if (stats != NULL)
- stats->change(stat_bytesReceived,
- len);
+ stats->change (stat_bytesReceived, len);
tcpSession = tsession->internal;
- if (YES == tcpSession->expectingWelcome) {
- /* at this point, we should be the only user! */
- GE_ASSERT(NULL,
- tcpSession->users == 1);
+ if (YES == tcpSession->expectingWelcome)
+ {
+ /* at this point, we should be the only user! */
+ GE_ASSERT (NULL, tcpSession->users == 1);
- welcome = (const TCPWelcome*) msg;
- if ( (ntohs(welcome->header.type) != 0) ||
- (len != sizeof(TCPWelcome)) ) {
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Received malformed message instead of welcome message. Closing.\n"));
- tcpDisconnect(tsession);
- return SYSERR;
- }
- tcpSession->expectingWelcome = NO;
- tcpSession->sender = welcome->clientIdentity;
- tsession->peer = welcome->clientIdentity;
- if (tcpSession->accept_addr != NULL)
- setIPaddressFromPID(&welcome->clientIdentity,
- tcpSession->accept_addr,
- tcpSession->addr_len);
- /* check that we do not already have
- a connection from this peer; if so,
- close the old one! */
- MUTEX_LOCK(tcplock);
- pos = sessions;
- while (pos != NULL) {
- if (pos == tcpSession) {
- pos = pos->next;
- continue;
- }
- if (0 == memcmp(&pos->sender,
- &tcpSession->sender,
- sizeof(PeerIdentity))) {
- /* replace existing socket in pos with
- the new socket in tcpSession; then
- delete the new tcpSession -- we have
- the old one! */
- MUTEX_LOCK(pos->lock);
- if (SYSERR == tcpAssociate(pos->tsession)) {
- GE_BREAK(ectx, 0);
- MUTEX_UNLOCK(pos->lock);
- MUTEX_UNLOCK(tcplock);
- return SYSERR;
- }
- if (pos->in_select)
- select_disconnect(sh,
- pos->sock);
- pos->in_select = YES;
- pos->sock = tcpSession->sock;
- select_update_closure(sh,
- pos->sock,
- tsession,
- pos->tsession);
- FREENONNULL(pos->accept_addr);
- pos->accept_addr = tcpSession->accept_addr;
- pos->addr_len = tcpSession->addr_len;
- tcpSession->accept_addr = NULL;
- tcpSession->addr_len = 0;
- tcpDisconnect(tsession);
- tcpSession->in_select = NO;
- freeTCPSession(tcpSession);
- tcpSession = pos;
- tsession = pos->tsession;
- MUTEX_UNLOCK(pos->lock);
- break;
- }
- pos = pos->next;
- }
- MUTEX_UNLOCK(tcplock);
+ welcome = (const TCPWelcome *) msg;
+ if ((ntohs (welcome->header.type) != 0) || (len != sizeof (TCPWelcome)))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _
+ ("Received malformed message instead of welcome message.
Closing.\n"));
+ tcpDisconnect (tsession);
+ return SYSERR;
+ }
+ tcpSession->expectingWelcome = NO;
+ tcpSession->sender = welcome->clientIdentity;
+ tsession->peer = welcome->clientIdentity;
+ if (tcpSession->accept_addr != NULL)
+ setIPaddressFromPID (&welcome->clientIdentity,
+ tcpSession->accept_addr, tcpSession->addr_len);
+ /* check that we do not already have
+ a connection from this peer; if so,
+ close the old one! */
+ MUTEX_LOCK (tcplock);
+ pos = sessions;
+ while (pos != NULL)
+ {
+ if (pos == tcpSession)
+ {
+ pos = pos->next;
+ continue;
+ }
+ if (0 == memcmp (&pos->sender,
+ &tcpSession->sender, sizeof (PeerIdentity)))
+ {
+ /* replace existing socket in pos with
+ the new socket in tcpSession; then
+ delete the new tcpSession -- we have
+ the old one! */
+ MUTEX_LOCK (pos->lock);
+ if (SYSERR == tcpAssociate (pos->tsession))
+ {
+ GE_BREAK (ectx, 0);
+ MUTEX_UNLOCK (pos->lock);
+ MUTEX_UNLOCK (tcplock);
+ return SYSERR;
+ }
+ if (pos->in_select)
+ select_disconnect (sh, pos->sock);
+ pos->in_select = YES;
+ pos->sock = tcpSession->sock;
+ select_update_closure (sh, pos->sock, tsession, pos->tsession);
+ FREENONNULL (pos->accept_addr);
+ pos->accept_addr = tcpSession->accept_addr;
+ pos->addr_len = tcpSession->addr_len;
+ tcpSession->accept_addr = NULL;
+ tcpSession->addr_len = 0;
+ tcpDisconnect (tsession);
+ tcpSession->in_select = NO;
+ freeTCPSession (tcpSession);
+ tcpSession = pos;
+ tsession = pos->tsession;
+ MUTEX_UNLOCK (pos->lock);
+ break;
+ }
+ pos = pos->next;
+ }
+ MUTEX_UNLOCK (tcplock);
- } else {
- /* send msg to core! */
- if (len <= sizeof(MESSAGE_HEADER)) {
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Received malformed message from tcp-peer connection. Closing.\n"));
- tcpDisconnect(tsession);
- return SYSERR;
}
- mp = MALLOC(sizeof(P2P_PACKET));
- mp->msg = MALLOC(len - sizeof(MESSAGE_HEADER));
- memcpy(mp->msg,
- &msg[1],
- len - sizeof(MESSAGE_HEADER));
- mp->sender = tcpSession->sender;
- mp->size = len - sizeof(MESSAGE_HEADER);
- mp->tsession = tsession;
- coreAPI->receive(mp);
- }
- tcpDisconnect(tsession);
+ else
+ {
+ /* send msg to core! */
+ if (len <= sizeof (MESSAGE_HEADER))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _
+ ("Received malformed message from tcp-peer connection.
Closing.\n"));
+ tcpDisconnect (tsession);
+ return SYSERR;
+ }
+ mp = MALLOC (sizeof (P2P_PACKET));
+ mp->msg = MALLOC (len - sizeof (MESSAGE_HEADER));
+ memcpy (mp->msg, &msg[1], len - sizeof (MESSAGE_HEADER));
+ mp->sender = tcpSession->sender;
+ mp->size = len - sizeof (MESSAGE_HEADER);
+ mp->tsession = tsession;
+ coreAPI->receive (mp);
+ }
+ tcpDisconnect (tsession);
return OK;
}
@@ -335,90 +340,94 @@
* socket. Adds the session to the array of sessions watched
* by the select thread.
*/
-static void * select_accept_handler(void * ah_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- const void * addr,
- unsigned int addr_len) {
+static void *
+select_accept_handler (void *ah_cls,
+ struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ const void *addr, unsigned int addr_len)
+{
BlacklistedTester blt = ah_cls;
- TSession * tsession;
- TCPSession * tcpSession;
+ TSession *tsession;
+ TCPSession *tcpSession;
- if (NO != blt(addr, addr_len)) {
+ if (NO != blt (addr, addr_len))
+ {
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Rejecting TCP connection (blacklisted).\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "Rejecting TCP connection (blacklisted).\n");
#endif
- return NULL;
- }
+ return NULL;
+ }
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Accepting TCP connection.\n");
+ GE_LOG (ectx, GE_DEBUG | GE_USER | GE_BULK, "Accepting TCP connection.\n");
#endif
- tcpSession = MALLOC(sizeof(TCPSession));
+ tcpSession = MALLOC (sizeof (TCPSession));
tcpSession->sock = sock;
/* fill in placeholder identity to mark that we
are waiting for the welcome message */
tcpSession->sender = *(coreAPI->myIdentity);
tcpSession->expectingWelcome = YES;
- tcpSession->lock = MUTEX_CREATE(YES);
+ tcpSession->lock = MUTEX_CREATE (YES);
tcpSession->users = 0;
tcpSession->in_select = YES;
- tsession = MALLOC(sizeof(TSession));
+ tsession = MALLOC (sizeof (TSession));
tsession->ttype = TCP_PROTOCOL_NUMBER;
tsession->internal = tcpSession;
tcpSession->tsession = tsession;
tsession->peer = *(coreAPI->myIdentity);
- if (addr_len > sizeof(IPaddr)) {
- tcpSession->accept_addr = MALLOC(addr_len);
- memcpy(tcpSession->accept_addr,
- (struct sockaddr_in*) addr,
- sizeof(struct sockaddr_in));
- tcpSession->addr_len = addr_len;
- } else {
- GE_BREAK(NULL, 0);
- tcpSession->addr_len = 0;
- tcpSession->accept_addr = NULL;
- }
- MUTEX_LOCK(tcplock);
+ if (addr_len > sizeof (IPaddr))
+ {
+ tcpSession->accept_addr = MALLOC (addr_len);
+ memcpy (tcpSession->accept_addr,
+ (struct sockaddr_in *) addr, sizeof (struct sockaddr_in));
+ tcpSession->addr_len = addr_len;
+ }
+ else
+ {
+ GE_BREAK (NULL, 0);
+ tcpSession->addr_len = 0;
+ tcpSession->accept_addr = NULL;
+ }
+ MUTEX_LOCK (tcplock);
tcpSession->next = sessions;
sessions = tcpSession;
- MUTEX_UNLOCK(tcplock);
+ MUTEX_UNLOCK (tcplock);
return tsession;
-}
+}
-static void select_close_handler(void * ch_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * sock_ctx) {
- TSession * tsession = sock_ctx;
- TCPSession * tcpSession = tsession->internal;
+static void
+select_close_handler (void *ch_cls,
+ struct SelectHandle *sh,
+ struct SocketHandle *sock, void *sock_ctx)
+{
+ TSession *tsession = sock_ctx;
+ TCPSession *tcpSession = tsession->internal;
#if DEBUG_TCP
EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- hash2enc(&tcpSession->sender.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Closed TCP socket of `%s'.\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ hash2enc (&tcpSession->sender.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Closed TCP socket of `%s'.\n", &enc);
#endif
- MUTEX_LOCK(tcplock);
- MUTEX_LOCK(tcpSession->lock);
+ MUTEX_LOCK (tcplock);
+ MUTEX_LOCK (tcpSession->lock);
tcpSession->in_select = NO;
- if (tcpSession->users == 0) {
- MUTEX_UNLOCK(tcpSession->lock);
- freeTCPSession(tcpSession);
- } else {
- MUTEX_UNLOCK(tcpSession->lock);
- }
- MUTEX_UNLOCK(tcplock);
+ if (tcpSession->users == 0)
+ {
+ MUTEX_UNLOCK (tcpSession->lock);
+ freeTCPSession (tcpSession);
+ }
+ else
+ {
+ MUTEX_UNLOCK (tcpSession->lock);
+ }
+ MUTEX_UNLOCK (tcplock);
}
/**
@@ -429,83 +438,76 @@
* @param size the size of the message
* @return SYSERR on error, OK on success
*/
-static int tcpSend(TSession * tsession,
- const void * msg,
- unsigned int size,
- int important) {
- TCPSession * tcpSession;
- MESSAGE_HEADER * mp;
+static int
+tcpSend (TSession * tsession,
+ const void *msg, unsigned int size, int important)
+{
+ TCPSession *tcpSession;
+ MESSAGE_HEADER *mp;
int ok;
tcpSession = tsession->internal;
- if (size >= MAX_BUFFER_SIZE - sizeof(MESSAGE_HEADER)) {
- GE_BREAK(ectx, 0);
- return SYSERR; /* too big */
- }
- if (tcpSession->in_select == NO) {
+ if (size >= MAX_BUFFER_SIZE - sizeof (MESSAGE_HEADER))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR; /* too big */
+ }
+ if (tcpSession->in_select == NO)
+ {
#if DEBUG_TCP
- EncName enc;
+ EncName enc;
- IF_GELOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- hash2enc(&tcpSession->sender.hashPubKey,
- &enc));
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Cannot send message - TCP socket of `%s' already closed!\n",
- &enc);
+ IF_GELOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ hash2enc (&tcpSession->sender.hashPubKey, &enc));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Cannot send message - TCP socket of `%s' already closed!\n",
+ &enc);
#endif
- return SYSERR;
- }
- if (selector == NULL) {
- if (stats != NULL)
- stats->change(stat_bytesDropped,
- size);
+ return SYSERR;
+ }
+ if (selector == NULL)
+ {
+ if (stats != NULL)
+ stats->change (stat_bytesDropped, size);
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Could not sent TCP message -- tcp transport is down.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "Could not sent TCP message -- tcp transport is down.\n");
#endif
- return SYSERR;
- }
- if (size == 0) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- if (tcpSession->sock == NULL) {
- if (stats != NULL)
- stats->change(stat_bytesDropped,
- size);
+ return SYSERR;
+ }
+ if (size == 0)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ if (tcpSession->sock == NULL)
+ {
+ if (stats != NULL)
+ stats->change (stat_bytesDropped, size);
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Could not sent TCP message -- other side closed connection.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "Could not sent TCP message -- other side closed connection.\n");
#endif
- return SYSERR; /* other side closed connection */
- }
- mp = MALLOC(sizeof(MESSAGE_HEADER) + size);
- mp->size = htons(size + sizeof(MESSAGE_HEADER));
+ return SYSERR; /* other side closed connection */
+ }
+ mp = MALLOC (sizeof (MESSAGE_HEADER) + size);
+ mp->size = htons (size + sizeof (MESSAGE_HEADER));
mp->type = 0;
- memcpy(&mp[1],
- msg,
- size);
+ memcpy (&mp[1], msg, size);
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Transport asks select to queue message of size %u\n",
- size);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Transport asks select to queue message of size %u\n", size);
#endif
- ok = select_write(selector,
- tcpSession->sock,
- mp,
- NO,
- important);
- if ( (OK == ok) &&
- (stats != NULL) )
- stats->change(stat_bytesSent,
- size + sizeof(MESSAGE_HEADER));
+ ok = select_write (selector, tcpSession->sock, mp, NO, important);
+ if ((OK == ok) && (stats != NULL))
+ stats->change (stat_bytesSent, size + sizeof (MESSAGE_HEADER));
- FREE(mp);
+ FREE (mp);
return ok;
}
@@ -522,28 +524,26 @@
* NO if the transport would just drop the message,
* SYSERR if the size/session is invalid
*/
-static int tcpTestWouldTry(TSession * tsession,
- const unsigned int size,
- int important) {
- TCPSession * tcpSession = tsession->internal;
+static int
+tcpTestWouldTry (TSession * tsession, const unsigned int size, int important)
+{
+ TCPSession *tcpSession = tsession->internal;
- if (size >= MAX_BUFFER_SIZE - sizeof(MESSAGE_HEADER)) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ if (size >= MAX_BUFFER_SIZE - sizeof (MESSAGE_HEADER))
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
if (selector == NULL)
return SYSERR;
- if (size == 0) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
+ if (size == 0)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
if (tcpSession->sock == NULL)
- return SYSERR; /* other side closed connection */
- return select_would_try(selector,
- tcpSession->sock,
- size,
- NO,
- important);
+ return SYSERR; /* other side closed connection */
+ return select_would_try (selector, tcpSession->sock, size, NO, important);
}
@@ -554,63 +554,55 @@
* @param tsessionPtr the session handle that is set
* @return OK on success, SYSERR if the operation failed
*/
-static int tcpConnectHelper(const P2P_hello_MESSAGE * hello,
- struct SocketHandle * s,
- unsigned int protocolNumber,
- TSession ** tsessionPtr) {
+static int
+tcpConnectHelper (const P2P_hello_MESSAGE * hello,
+ struct SocketHandle *s,
+ unsigned int protocolNumber, TSession ** tsessionPtr)
+{
TCPWelcome welcome;
- TSession * tsession;
- TCPSession * tcpSession;
+ TSession *tsession;
+ TCPSession *tcpSession;
- tcpSession = MALLOC(sizeof(TCPSession));
+ tcpSession = MALLOC (sizeof (TCPSession));
tcpSession->addr_len = 0;
tcpSession->accept_addr = NULL;
tcpSession->sock = s;
- tsession = MALLOC(sizeof(TSession));
+ tsession = MALLOC (sizeof (TSession));
tsession->internal = tcpSession;
tsession->ttype = protocolNumber;
tsession->peer = hello->senderIdentity;
tcpSession->tsession = tsession;
- tcpSession->lock = MUTEX_CREATE(YES);
- tcpSession->users = 1; /* caller */
+ tcpSession->lock = MUTEX_CREATE (YES);
+ tcpSession->users = 1; /* caller */
tcpSession->in_select = NO;
tcpSession->sender = hello->senderIdentity;
tcpSession->expectingWelcome = NO;
- MUTEX_LOCK(tcplock);
- if (OK ==
- select_connect(selector,
- tcpSession->sock,
- tsession))
+ MUTEX_LOCK (tcplock);
+ if (OK == select_connect (selector, tcpSession->sock, tsession))
tcpSession->in_select = YES;
/* send our node identity to the other side to fully establish the
connection! */
- welcome.header.size
- = htons(sizeof(TCPWelcome));
- welcome.header.type
- = htons(0);
- welcome.clientIdentity
- = *(coreAPI->myIdentity);
- if (OK != select_write(selector,
- s,
- &welcome.header,
- NO,
- YES)) {
+ welcome.header.size = htons (sizeof (TCPWelcome));
+ welcome.header.type = htons (0);
+ welcome.clientIdentity = *(coreAPI->myIdentity);
+ if (OK != select_write (selector, s, &welcome.header, NO, YES))
+ {
#if DEBUG_TCP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Could not sent TCP welcome message, closing connection.\n");
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "Could not sent TCP welcome message, closing connection.\n");
#endif
- /* disconnect caller -- error! */
- tcpDisconnect(tsession);
- MUTEX_UNLOCK(tcplock);
- return SYSERR;
- } else if (stats != NULL)
- stats->change(stat_bytesSent,
- sizeof(TCPWelcome));
+ /* disconnect caller -- error! */
+ tcpDisconnect (tsession);
+ MUTEX_UNLOCK (tcplock);
+ return SYSERR;
+ }
+ else if (stats != NULL)
+ stats->change (stat_bytesSent, sizeof (TCPWelcome));
tcpSession->next = sessions;
sessions = tcpSession;
- MUTEX_UNLOCK(tcplock);
+ MUTEX_UNLOCK (tcplock);
*tsessionPtr = tsession;
return OK;
}
@@ -619,11 +611,14 @@
* Shutdown the server process (stop receiving inbound
* traffic). Maybe restarted later!
*/
-static int stopTransportServer() {
- if (selector != NULL) {
- select_destroy(selector);
- selector = NULL;
- }
+static int
+stopTransportServer ()
+{
+ if (selector != NULL)
+ {
+ select_destroy (selector);
+ selector = NULL;
+ }
return OK;
}
Modified: GNUnet/src/transports/udp.c
===================================================================
--- GNUnet/src/transports/udp.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/udp.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -34,14 +34,15 @@
#define DEBUG_UDP NO
-static UPnP_ServiceAPI * upnp;
+static UPnP_ServiceAPI *upnp;
#include "udp_helper.c"
/**
* Host-Address in a UDP network.
*/
-typedef struct {
+typedef struct
+{
/**
* claimed IP of the sender, network byte order
*/
@@ -59,15 +60,15 @@
} HostAddress;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static struct LoadMonitor * load_monitor;
+static struct LoadMonitor *load_monitor;
-static struct CIDRNetwork * filteredNetworks_;
+static struct CIDRNetwork *filteredNetworks_;
-static struct CIDRNetwork * allowedNetworks_;
+static struct CIDRNetwork *allowedNetworks_;
-static struct MUTEX * configLock;
+static struct MUTEX *configLock;
/**
* Get the GNUnet UDP port from the configuration, or from
@@ -75,72 +76,60 @@
*
* @return the port in host byte order
*/
-static unsigned short getGNUnetUDPPort() {
- struct servent * pse; /* pointer to service information entry */
+static unsigned short
+getGNUnetUDPPort ()
+{
+ struct servent *pse; /* pointer to service information entry
*/
unsigned long long port;
- if (-1 == GC_get_configuration_value_number(cfg,
- "UDP",
- "PORT",
- 1,
- 65535,
- 2086,
- &port)) {
- if ((pse = getservbyname("gnunet", "udp")))
- port = htons(pse->s_port);
- else
- port = 0;
- }
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "UDP",
+ "PORT", 1, 65535, 2086, &port))
+ {
+ if ((pse = getservbyname ("gnunet", "udp")))
+ port = htons (pse->s_port);
+ else
+ port = 0;
+ }
return (unsigned short) port;
}
/**
* Allocate and bind a server socket for the UDP transport.
*/
-static int listensock(unsigned short port) {
+static int
+listensock (unsigned short port)
+{
struct sockaddr_in sin;
int sock;
const int on = 1;
- sock = SOCKET(PF_INET, SOCK_DGRAM, 17);
- if (sock < 0) {
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "socket");
- return -1;
- }
- if ( SETSOCKOPT(sock,
- SOL_SOCKET,
- SO_REUSEADDR,
- &on,
- sizeof(on)) < 0 ) {
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "setsockopt");
- return -1;
- }
- GE_ASSERT(NULL, port != 0);
- memset(&sin,
- 0,
- sizeof(sin));
- sin.sin_family = AF_INET;
+ sock = SOCKET (PF_INET, SOCK_DGRAM, 17);
+ if (sock < 0)
+ {
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_ADMIN | GE_IMMEDIATE, "socket");
+ return -1;
+ }
+ if (SETSOCKOPT (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0)
+ {
+ GE_DIE_STRERROR (ectx,
+ GE_FATAL | GE_ADMIN | GE_IMMEDIATE, "setsockopt");
+ return -1;
+ }
+ GE_ASSERT (NULL, port != 0);
+ memset (&sin, 0, sizeof (sin));
+ sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
- sin.sin_port = htons(port);
- if (BIND(sock,
- (struct sockaddr *)&sin,
- sizeof(sin)) < 0) {
- GE_LOG_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "bind");
- GE_LOG(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- _("Failed to bind to UDP port %d.\n"),
- port);
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_USER | GE_IMMEDIATE,
- "bind");
- return -1;
- }
+ sin.sin_port = htons (port);
+ if (BIND (sock, (struct sockaddr *) &sin, sizeof (sin)) < 0)
+ {
+ GE_LOG_STRERROR (ectx, GE_FATAL | GE_ADMIN | GE_IMMEDIATE, "bind");
+ GE_LOG (ectx,
+ GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
+ _("Failed to bind to UDP port %d.\n"), port);
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_USER | GE_IMMEDIATE, "bind");
+ return -1;
+ }
/* do not bind if port == 0, then we use
send-only! */
return sock;
@@ -149,71 +138,74 @@
/**
* Check if we are explicitly forbidden to communicate with this IP.
*/
-static int isBlacklisted(const void * addr,
- unsigned int addr_len) {
+static int
+isBlacklisted (const void *addr, unsigned int addr_len)
+{
IPaddr ip;
int ret;
- if (addr_len == sizeof(struct sockaddr_in)) {
- memcpy(&ip,
- &((struct sockaddr_in*) addr)->sin_addr,
- sizeof(IPaddr));
- } else if (addr_len == sizeof(IPaddr)) {
- memcpy(&ip,
- addr,
- addr_len);
- } else {
- return SYSERR;
- }
- MUTEX_LOCK(configLock);
- ret = check_ipv4_listed(filteredNetworks_,
- ip);
- MUTEX_UNLOCK(configLock);
+ if (addr_len == sizeof (struct sockaddr_in))
+ {
+ memcpy (&ip, &((struct sockaddr_in *) addr)->sin_addr, sizeof (IPaddr));
+ }
+ else if (addr_len == sizeof (IPaddr))
+ {
+ memcpy (&ip, addr, addr_len);
+ }
+ else
+ {
+ return SYSERR;
+ }
+ MUTEX_LOCK (configLock);
+ ret = check_ipv4_listed (filteredNetworks_, ip);
+ MUTEX_UNLOCK (configLock);
return ret;
}
/**
* Check if we are allowed to connect to the given IP.
*/
-static int isWhitelisted(const void * addr,
- unsigned int addr_len) {
+static int
+isWhitelisted (const void *addr, unsigned int addr_len)
+{
IPaddr ip;
int ret;
- if (addr_len == sizeof(struct sockaddr_in)) {
- memcpy(&ip,
- &((struct sockaddr_in*) addr)->sin_addr,
- sizeof(IPaddr));
- } else if (addr_len == sizeof(IPaddr)) {
- memcpy(&ip,
- addr,
- addr_len);
- } else {
- return SYSERR;
- }
+ if (addr_len == sizeof (struct sockaddr_in))
+ {
+ memcpy (&ip, &((struct sockaddr_in *) addr)->sin_addr, sizeof (IPaddr));
+ }
+ else if (addr_len == sizeof (IPaddr))
+ {
+ memcpy (&ip, addr, addr_len);
+ }
+ else
+ {
+ return SYSERR;
+ }
ret = OK;
- MUTEX_LOCK(configLock);
+ MUTEX_LOCK (configLock);
if (allowedNetworks_ != NULL)
- ret = check_ipv4_listed(allowedNetworks_,
- ip);
- MUTEX_UNLOCK(configLock);
+ ret = check_ipv4_listed (allowedNetworks_, ip);
+ MUTEX_UNLOCK (configLock);
return ret;
}
-static int isRejected(const void * addr,
- unsigned int addr_len) {
- if ((YES == isBlacklisted(addr,
- addr_len)) ||
- (YES != isWhitelisted(addr,
- addr_len))) {
+static int
+isRejected (const void *addr, unsigned int addr_len)
+{
+ if ((YES == isBlacklisted (addr,
+ addr_len)) ||
+ (YES != isWhitelisted (addr, addr_len)))
+ {
#if DEBUG_UDP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Rejecting traffic from %u.%u.%u.%u.\n",
- PRIP(ntohl(*(int*)addr)));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "Rejecting traffic from %u.%u.%u.%u.\n",
+ PRIP (ntohl (*(int *) addr)));
#endif
- return YES;
- }
+ return YES;
+ }
return NO;
}
@@ -227,35 +219,36 @@
* (the signature/crc have been verified before)
* @return OK on success, SYSERR on failure
*/
-static int verifyHello(const P2P_hello_MESSAGE * hello) {
- const HostAddress * haddr;
+static int
+verifyHello (const P2P_hello_MESSAGE * hello)
+{
+ const HostAddress *haddr;
- haddr = (const HostAddress*) &hello[1];
- if ( (ntohs(hello->senderAddressSize) != sizeof(HostAddress)) ||
- (ntohs(hello->header.size) != P2P_hello_MESSAGE_size(hello)) ||
- (ntohs(hello->header.type) != p2p_PROTO_hello) ) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- if ( (YES == isBlacklisted(&haddr->ip,
- sizeof(IPaddr))) ||
- (YES != isWhitelisted(&haddr->ip,
- sizeof(IPaddr))) ) {
+ haddr = (const HostAddress *) &hello[1];
+ if ((ntohs (hello->senderAddressSize) != sizeof (HostAddress)) ||
+ (ntohs (hello->header.size) != P2P_hello_MESSAGE_size (hello)) ||
+ (ntohs (hello->header.type) != p2p_PROTO_hello))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ if ((YES == isBlacklisted (&haddr->ip,
+ sizeof (IPaddr))) ||
+ (YES != isWhitelisted (&haddr->ip, sizeof (IPaddr))))
+ {
#if DEBUG_UDP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Rejecting UDP HELLO from %u.%u.%u.%u:%u due to configuration.\n",
- PRIP(ntohl(*(int*)&haddr->ip.addr)),
- ntohs(haddr->port));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "Rejecting UDP HELLO from %u.%u.%u.%u:%u due to
configuration.\n",
+ PRIP (ntohl (*(int *) &haddr->ip.addr)), ntohs (haddr->port));
#endif
- return SYSERR; /* obviously invalid */
- }
+ return SYSERR; /* obviously invalid */
+ }
#if DEBUG_UDP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Verified UDP HELLO from %u.%u.%u.%u:%u.\n",
- PRIP(ntohl(*(int*)&haddr->ip.addr)),
- ntohs(haddr->port));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "Verified UDP HELLO from %u.%u.%u.%u:%u.\n",
+ PRIP (ntohl (*(int *) &haddr->ip.addr)), ntohs (haddr->port));
#endif
return OK;
}
@@ -267,41 +260,42 @@
*
* @return hello on success, NULL on error
*/
-static P2P_hello_MESSAGE * createhello() {
- P2P_hello_MESSAGE * msg;
- HostAddress * haddr;
+static P2P_hello_MESSAGE *
+createhello ()
+{
+ P2P_hello_MESSAGE *msg;
+ HostAddress *haddr;
unsigned short port;
- port = getGNUnetUDPPort();
+ port = getGNUnetUDPPort ();
if (port == 0)
- return NULL; /* UDP transport configured send-only */
+ return NULL; /* UDP transport configured send-only */
- msg = MALLOC(sizeof(P2P_hello_MESSAGE) + sizeof(HostAddress));
- haddr = (HostAddress*) &msg[1];
+ msg = MALLOC (sizeof (P2P_hello_MESSAGE) + sizeof (HostAddress));
+ haddr = (HostAddress *) & msg[1];
- if (! ( ( (upnp != NULL) &&
- (OK == upnp->get_ip(port,
- "UDP",
- &haddr->ip)) ) ||
- (SYSERR != getPublicIPAddress(cfg,
- ectx,
- &haddr->ip)) ) ) {
- FREE(msg);
- GE_LOG(ectx,
- GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
- _("UDP: Could not determine my public IP address.\n"));
- return NULL;
- }
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "UDP uses IP address %u.%u.%u.%u.\n",
- PRIP(ntohl(*(int*)&haddr->ip)));
- haddr->port = htons(port);
- haddr->reserved = htons(0);
- msg->senderAddressSize = htons(sizeof(HostAddress));
- msg->protocol = htons(UDP_PROTOCOL_NUMBER);
- msg->MTU = htonl(udpAPI.mtu);
+ if (!(((upnp != NULL) &&
+ (OK == upnp->get_ip (port,
+ "UDP",
+ &haddr->ip))) ||
+ (SYSERR != getPublicIPAddress (cfg, ectx, &haddr->ip))))
+ {
+ FREE (msg);
+ GE_LOG (ectx,
+ GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
+ _("UDP: Could not determine my public IP address.\n"));
+ return NULL;
+ }
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "UDP uses IP address %u.%u.%u.%u.\n",
+ PRIP (ntohl (*(int *) &haddr->ip)));
+ haddr->port = htons (port);
+ haddr->reserved = htons (0);
+ msg->senderAddressSize = htons (sizeof (HostAddress));
+ msg->protocol = htons (UDP_PROTOCOL_NUMBER);
+ msg->MTU = htonl (udpAPI.mtu);
return msg;
}
@@ -313,88 +307,81 @@
* @param size the size of the message
* @return SYSERR on error, OK on success
*/
-static int udpSend(TSession * tsession,
- const void * message,
- const unsigned int size,
- int important) {
- UDPMessage * mp;
- P2P_hello_MESSAGE * hello;
- HostAddress * haddr;
- struct sockaddr_in sin; /* an Internet endpoint address */
+static int
+udpSend (TSession * tsession,
+ const void *message, const unsigned int size, int important)
+{
+ UDPMessage *mp;
+ P2P_hello_MESSAGE *hello;
+ HostAddress *haddr;
+ struct sockaddr_in sin; /* an Internet endpoint address */
int ok;
int ssize;
size_t sent;
if (udp_sock == NULL)
return SYSERR;
- if (size == 0) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- if (size > udpAPI.mtu) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- hello = (P2P_hello_MESSAGE*)tsession->internal;
+ if (size == 0)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ if (size > udpAPI.mtu)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ hello = (P2P_hello_MESSAGE *) tsession->internal;
if (hello == NULL)
return SYSERR;
- haddr = (HostAddress*) &hello[1];
- ssize = size + sizeof(UDPMessage);
- mp = MALLOC(ssize);
- mp->header.size = htons(ssize);
+ haddr = (HostAddress *) & hello[1];
+ ssize = size + sizeof (UDPMessage);
+ mp = MALLOC (ssize);
+ mp->header.size = htons (ssize);
mp->header.type = 0;
mp->sender = *(coreAPI->myIdentity);
- memcpy(&mp[1],
- message,
- size);
+ memcpy (&mp[1], message, size);
ok = SYSERR;
- memset(&sin, 0, sizeof(sin));
+ memset (&sin, 0, sizeof (sin));
sin.sin_family = AF_INET;
sin.sin_port = haddr->port;
- GE_ASSERT(ectx, sizeof(struct in_addr) == sizeof(IPaddr));
- memcpy(&sin.sin_addr,
- &haddr->ip,
- sizeof(IPaddr));
+ GE_ASSERT (ectx, sizeof (struct in_addr) == sizeof (IPaddr));
+ memcpy (&sin.sin_addr, &haddr->ip, sizeof (IPaddr));
#if DEBUG_UDP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Sending message of %d bytes via UDP to %u.%u.%u.%u:%u.\n",
- ssize,
- PRIP(ntohl(*(int*)&sin.sin_addr)),
- ntohs(sin.sin_port));
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK,
+ "Sending message of %d bytes via UDP to %u.%u.%u.%u:%u.\n",
+ ssize, PRIP (ntohl (*(int *) &sin.sin_addr)), ntohs (sin.sin_port));
#endif
#ifndef MINGW
- if (YES == socket_send_to(udp_sock,
- NC_Nonblocking,
- mp,
- ssize,
- &sent,
- (const char *) &sin,
- sizeof(sin)))
+ if (YES == socket_send_to (udp_sock,
+ NC_Nonblocking,
+ mp,
+ ssize, &sent, (const char *) &sin, sizeof (sin)))
#else
- sent = win_ols_sendto(udp_sock, mp, ssize, (const char *) &sin, sizeof(sin));
+ sent =
+ win_ols_sendto (udp_sock, mp, ssize, (const char *) &sin, sizeof (sin));
if (sent != SOCKET_ERROR)
#endif
- {
- ok = OK;
- if (stats != NULL)
- stats->change(stat_bytesSent,
- sent);
- } else {
- GE_LOG(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- _("Failed to send message of size %d via UDP to %u.%u.%u.%u:%u: %s\n"),
- ssize,
- PRIP(ntohl(*(int*)&sin.sin_addr)),
- ntohs(sin.sin_port),
- STRERROR(errno));
- if (stats != NULL)
- stats->change(stat_bytesDropped,
- ssize);
- }
- FREE(mp);
+ {
+ ok = OK;
+ if (stats != NULL)
+ stats->change (stat_bytesSent, sent);
+ }
+ else
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_ADMIN | GE_BULK,
+ _
+ ("Failed to send message of size %d via UDP to %u.%u.%u.%u:%u:
%s\n"),
+ ssize, PRIP (ntohl (*(int *) &sin.sin_addr)),
+ ntohs (sin.sin_port), STRERROR (errno));
+ if (stats != NULL)
+ stats->change (stat_bytesDropped, ssize);
+ }
+ FREE (mp);
return ok;
}
@@ -403,86 +390,70 @@
*
* @return OK on success, SYSERR if the operation failed
*/
-static int startTransportServer() {
+static int
+startTransportServer ()
+{
int sock;
unsigned short port;
- GE_ASSERT(ectx, selector == NULL);
- /* initialize UDP network */
- port = getGNUnetUDPPort();
- if (port != 0) {
- sock = listensock(port);
- if (sock == -1)
- return SYSERR;
- selector = select_create("udp",
- YES,
- ectx,
- load_monitor,
- sock,
- sizeof(struct sockaddr_in),
- 0, /* timeout */
- &select_message_handler,
- NULL,
- &select_accept_handler,
- &isRejected,
- &select_close_handler,
- NULL,
- 64 * 1024,
- 16 /* max sockets */);
- if (selector == NULL)
- return SYSERR;
- }
+ GE_ASSERT (ectx, selector == NULL);
+ /* initialize UDP network */
+ port = getGNUnetUDPPort ();
+ if (port != 0)
+ {
+ sock = listensock (port);
+ if (sock == -1)
+ return SYSERR;
+ selector = select_create ("udp", YES, ectx, load_monitor, sock, sizeof
(struct sockaddr_in), 0, /* timeout */
+ &select_message_handler,
+ NULL,
+ &select_accept_handler,
+ &isRejected,
+ &select_close_handler,
+ NULL, 64 * 1024, 16 /* max sockets */ );
+ if (selector == NULL)
+ return SYSERR;
+ }
#ifndef MINGW
- sock = SOCKET(PF_INET, SOCK_DGRAM, 17);
+ sock = SOCKET (PF_INET, SOCK_DGRAM, 17);
#else
- sock = win_ols_socket(PF_INET, SOCK_DGRAM, 17);
+ sock = win_ols_socket (PF_INET, SOCK_DGRAM, 17);
#endif
- if (sock == -1) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "socket");
- select_destroy(selector);
- selector = NULL;
- return SYSERR;
- }
- udp_sock = socket_create(ectx,
- load_monitor,
- sock);
- GE_ASSERT(ectx, udp_sock != NULL);
+ if (sock == -1)
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_ADMIN | GE_BULK, "socket");
+ select_destroy (selector);
+ selector = NULL;
+ return SYSERR;
+ }
+ udp_sock = socket_create (ectx, load_monitor, sock);
+ GE_ASSERT (ectx, udp_sock != NULL);
return OK;
}
/**
* Reload the configuration. Should never fail.
*/
-static int reloadConfiguration() {
- char * ch;
+static int
+reloadConfiguration ()
+{
+ char *ch;
- MUTEX_LOCK(configLock);
- FREENONNULL(filteredNetworks_);
- FREENONNULL(allowedNetworks_);
+ MUTEX_LOCK (configLock);
+ FREENONNULL (filteredNetworks_);
+ FREENONNULL (allowedNetworks_);
ch = NULL;
- GC_get_configuration_value_string(cfg,
- "UDP",
- "BLACKLIST",
- "",
- &ch);
- filteredNetworks_ = parse_ipv4_network_specification(ectx,
- ch);
- FREE(ch);
+ GC_get_configuration_value_string (cfg, "UDP", "BLACKLIST", "", &ch);
+ filteredNetworks_ = parse_ipv4_network_specification (ectx, ch);
+ FREE (ch);
ch = NULL;
- GC_get_configuration_value_string(cfg,
- "UDP",
- "WHITELIST",
- "",
- &ch);
- if (strlen(ch) > 0)
- allowedNetworks_ = parse_ipv4_network_specification(ectx,
- ch);
+ GC_get_configuration_value_string (cfg, "UDP", "WHITELIST", "", &ch);
+ if (strlen (ch) > 0)
+ allowedNetworks_ = parse_ipv4_network_specification (ectx, ch);
else
allowedNetworks_ = NULL;
- FREE(ch);
- MUTEX_UNLOCK(configLock);
+ FREE (ch);
+ MUTEX_UNLOCK (configLock);
return 0;
}
@@ -490,22 +461,18 @@
* Convert UDP hello to IP address
*/
static int
-helloToAddress(const P2P_hello_MESSAGE * hello,
- void ** sa,
- unsigned int * sa_len) {
- const HostAddress * haddr = (const HostAddress*) &hello[1];
- struct sockaddr_in * serverAddr;
+helloToAddress (const P2P_hello_MESSAGE * hello,
+ void **sa, unsigned int *sa_len)
+{
+ const HostAddress *haddr = (const HostAddress *) &hello[1];
+ struct sockaddr_in *serverAddr;
- *sa_len = sizeof(struct sockaddr_in);
- serverAddr = MALLOC(sizeof(struct sockaddr_in));
+ *sa_len = sizeof (struct sockaddr_in);
+ serverAddr = MALLOC (sizeof (struct sockaddr_in));
*sa = serverAddr;
- memset(serverAddr,
- 0,
- sizeof(struct sockaddr_in));
- serverAddr->sin_family = AF_INET;
- memcpy(&serverAddr->sin_addr,
- haddr,
- sizeof(IPaddr));
+ memset (serverAddr, 0, sizeof (struct sockaddr_in));
+ serverAddr->sin_family = AF_INET;
+ memcpy (&serverAddr->sin_addr, haddr, sizeof (IPaddr));
serverAddr->sin_port = haddr->port;
return OK;
}
@@ -521,84 +488,84 @@
* returns the udp transport API.
*/
TransportAPI *
-inittransport_udp(CoreAPIForTransport * core) {
+inittransport_udp (CoreAPIForTransport * core)
+{
unsigned long long mtu;
ectx = core->ectx;
cfg = core->cfg;
load_monitor = core->load_monitor;
- GE_ASSERT(ectx, sizeof(HostAddress) == 8);
- GE_ASSERT(ectx, sizeof(UDPMessage) == 68);
+ GE_ASSERT (ectx, sizeof (HostAddress) == 8);
+ GE_ASSERT (ectx, sizeof (UDPMessage) == 68);
coreAPI = core;
- if (-1 == GC_get_configuration_value_number(cfg,
- "UDP",
- "MTU",
- sizeof(UDPMessage)
- + P2P_MESSAGE_OVERHEAD
- + sizeof(MESSAGE_HEADER) + 32,
- 65500,
- MESSAGE_SIZE,
- &mtu)) {
- return NULL;
- }
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "UDP",
+ "MTU",
+ sizeof (UDPMessage)
+ + P2P_MESSAGE_OVERHEAD
+ + sizeof (MESSAGE_HEADER) + 32,
+ 65500, MESSAGE_SIZE, &mtu))
+ {
+ return NULL;
+ }
if (mtu < 1200)
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("MTU %llu for `%s' is probably too low!\n"),
- mtu,
- "UDP");
- if (GC_get_configuration_value_yesno(cfg,
- "UDP",
- "UPNP",
- YES) == YES) {
- upnp = coreAPI->requestService("upnp");
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _("MTU %llu for `%s' is probably too low!\n"), mtu, "UDP");
+ if (GC_get_configuration_value_yesno (cfg, "UDP", "UPNP", YES) == YES)
+ {
+ upnp = coreAPI->requestService ("upnp");
- if (upnp == NULL)
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- "The UPnP service could not be loaded. To disable UPnP, set the
" \
- "configuration option \"UPNP\" in section \"UDP\" to
\"NO\"\n");
- }
- stats = coreAPI->requestService("stats");
- if (stats != NULL) {
- stat_bytesReceived
- = stats->create(gettext_noop("# bytes received via UDP"));
- stat_bytesSent
- = stats->create(gettext_noop("# bytes sent via UDP"));
- stat_bytesDropped
- = stats->create(gettext_noop("# bytes dropped by UDP (outgoing)"));
- }
- configLock = MUTEX_CREATE(NO);
- reloadConfiguration();
- udpAPI.protocolNumber = UDP_PROTOCOL_NUMBER;
- udpAPI.mtu = mtu - sizeof(UDPMessage);
- udpAPI.cost = 20000;
- udpAPI.verifyHello = &verifyHello;
- udpAPI.createhello = &createhello;
- udpAPI.connect = &udpConnect;
- udpAPI.send = &udpSend;
- udpAPI.associate = &udpAssociate;
- udpAPI.disconnect = &udpDisconnect;
+ if (upnp == NULL)
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ "The UPnP service could not be loaded. To disable UPnP, set
the "
+ "configuration option \"UPNP\" in section \"UDP\" to
\"NO\"\n");
+ }
+ stats = coreAPI->requestService ("stats");
+ if (stats != NULL)
+ {
+ stat_bytesReceived
+ = stats->create (gettext_noop ("# bytes received via UDP"));
+ stat_bytesSent = stats->create (gettext_noop ("# bytes sent via UDP"));
+ stat_bytesDropped
+ = stats->create (gettext_noop ("# bytes dropped by UDP (outgoing)"));
+ }
+ configLock = MUTEX_CREATE (NO);
+ reloadConfiguration ();
+ udpAPI.protocolNumber = UDP_PROTOCOL_NUMBER;
+ udpAPI.mtu = mtu - sizeof (UDPMessage);
+ udpAPI.cost = 20000;
+ udpAPI.verifyHello = &verifyHello;
+ udpAPI.createhello = &createhello;
+ udpAPI.connect = &udpConnect;
+ udpAPI.send = &udpSend;
+ udpAPI.associate = &udpAssociate;
+ udpAPI.disconnect = &udpDisconnect;
udpAPI.startTransportServer = &startTransportServer;
- udpAPI.stopTransportServer = &stopTransportServer;
- udpAPI.helloToAddress = &helloToAddress;
- udpAPI.testWouldTry = &testWouldTry;
+ udpAPI.stopTransportServer = &stopTransportServer;
+ udpAPI.helloToAddress = &helloToAddress;
+ udpAPI.testWouldTry = &testWouldTry;
return &udpAPI;
}
-void donetransport_udp() {
- if (stats != NULL) {
- coreAPI->releaseService(stats);
- stats = NULL;
- }
- if (upnp != NULL) {
- coreAPI->releaseService(upnp);
- upnp = NULL;
- }
- MUTEX_DESTROY(configLock);
+void
+donetransport_udp ()
+{
+ if (stats != NULL)
+ {
+ coreAPI->releaseService (stats);
+ stats = NULL;
+ }
+ if (upnp != NULL)
+ {
+ coreAPI->releaseService (upnp);
+ upnp = NULL;
+ }
+ MUTEX_DESTROY (configLock);
configLock = NULL;
- FREENONNULL(filteredNetworks_);
+ FREENONNULL (filteredNetworks_);
coreAPI = NULL;
}
Modified: GNUnet/src/transports/udp6.c
===================================================================
--- GNUnet/src/transports/udp6.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/udp6.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -39,7 +39,8 @@
/**
* Host-Address in a UDP6 network.
*/
-typedef struct {
+typedef struct
+{
/**
* claimed IP of the sender, network byte order
*/
@@ -59,15 +60,15 @@
/* *********** globals ************* */
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static struct LoadMonitor * load_monitor;
+static struct LoadMonitor *load_monitor;
-static struct CIDR6Network * filteredNetworks_;
+static struct CIDR6Network *filteredNetworks_;
-static struct CIDR6Network * allowedNetworks_;
+static struct CIDR6Network *allowedNetworks_;
-static struct MUTEX * configLock;
+static struct MUTEX *configLock;
/**
* Get the GNUnet UDP6 port from the configuration, or from
@@ -75,128 +76,122 @@
*
* @return the port in host byte order
*/
-static unsigned short getGNUnetUDP6Port() {
- struct servent * pse; /* pointer to service information entry */
+static unsigned short
+getGNUnetUDP6Port ()
+{
+ struct servent *pse; /* pointer to service information entry
*/
unsigned long long port;
- if (-1 == GC_get_configuration_value_number(cfg,
- "UDP6",
- "PORT",
- 1,
- 65535,
- 2086,
- &port)) {
- if ((pse = getservbyname("gnunet", "udp")))
- port = htons(pse->s_port);
- else
- port = 0;
- }
- return (unsigned short) port;
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "UDP6",
+ "PORT", 1, 65535, 2086, &port))
+ {
+ if ((pse = getservbyname ("gnunet", "udp")))
+ port = htons (pse->s_port);
+ else
+ port = 0;
+ }
+ return (unsigned short) port;
}
/**
* Allocate and bind a server socket for the UDP6 transport.
*/
-static int passivesock(unsigned short port) {
+static int
+passivesock (unsigned short port)
+{
struct sockaddr_in6 sin;
int sock;
const int on = 1;
- sock = SOCKET(PF_INET6,
- SOCK_DGRAM,
- 17);
+ sock = SOCKET (PF_INET6, SOCK_DGRAM, 17);
if (sock < 0)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "socket");
- if ( SETSOCKOPT(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0 )
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "setsockopt");
- if (port != 0) {
- memset(&sin, 0, sizeof(sin));
- sin.sin6_family = AF_INET6;
- sin.sin6_port = htons(port);
- memcpy(&sin.sin6_addr,
- &in6addr_any,
- sizeof(IP6addr));
- if (BIND(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
- GE_LOG_STRERROR(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- "bind");
- GE_LOG(ectx,
- GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
- _("Failed to bind to UDP port %d.\n"),
- port);
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_USER | GE_IMMEDIATE,
- "bind");
- }
- } /* do not bind if port == 0, then we use send-only! */
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_ADMIN | GE_IMMEDIATE, "socket");
+ if (SETSOCKOPT (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0)
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_ADMIN | GE_IMMEDIATE, "setsockopt");
+ if (port != 0)
+ {
+ memset (&sin, 0, sizeof (sin));
+ sin.sin6_family = AF_INET6;
+ sin.sin6_port = htons (port);
+ memcpy (&sin.sin6_addr, &in6addr_any, sizeof (IP6addr));
+ if (BIND (sock, (struct sockaddr *) &sin, sizeof (sin)) < 0)
+ {
+ GE_LOG_STRERROR (ectx, GE_FATAL | GE_ADMIN | GE_IMMEDIATE, "bind");
+ GE_LOG (ectx,
+ GE_FATAL | GE_ADMIN | GE_IMMEDIATE,
+ _("Failed to bind to UDP port %d.\n"), port);
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_USER | GE_IMMEDIATE, "bind");
+ }
+ } /* do not bind if port == 0, then we use
send-only! */
return sock;
}
/**
* Check if we are explicitly forbidden to communicate with this IP.
*/
-static int isBlacklisted(const void * addr,
- unsigned int addr_len) {
+static int
+isBlacklisted (const void *addr, unsigned int addr_len)
+{
IP6addr ip;
int ret;
- if (addr_len == sizeof(IP6addr)) {
- memcpy(&ip,
- addr,
- sizeof(IP6addr));
- } else if (addr_len == sizeof(struct sockaddr_in6)) {
- memcpy(&ip,
- &((struct sockaddr_in6*) addr)->sin6_addr,
- sizeof(IP6addr));
- } else {
- return SYSERR;
- }
- MUTEX_LOCK(configLock);
- ret = check_ipv6_listed(filteredNetworks_,
- ip);
- MUTEX_UNLOCK(configLock);
+ if (addr_len == sizeof (IP6addr))
+ {
+ memcpy (&ip, addr, sizeof (IP6addr));
+ }
+ else if (addr_len == sizeof (struct sockaddr_in6))
+ {
+ memcpy (&ip,
+ &((struct sockaddr_in6 *) addr)->sin6_addr, sizeof (IP6addr));
+ }
+ else
+ {
+ return SYSERR;
+ }
+ MUTEX_LOCK (configLock);
+ ret = check_ipv6_listed (filteredNetworks_, ip);
+ MUTEX_UNLOCK (configLock);
return ret;
}
/**
* Check if we are allowed to connect to the given IP.
*/
-static int isWhitelisted(const void * addr,
- unsigned int addr_len) {
+static int
+isWhitelisted (const void *addr, unsigned int addr_len)
+{
IP6addr ip;
int ret;
- if (addr_len == sizeof(IP6addr)) {
- memcpy(&ip,
- addr,
- sizeof(IP6addr));
- } else if (addr_len == sizeof(struct sockaddr_in6)) {
- memcpy(&ip,
- &((struct sockaddr_in6*) addr)->sin6_addr,
- sizeof(IP6addr));
- } else {
- return SYSERR;
- }
+ if (addr_len == sizeof (IP6addr))
+ {
+ memcpy (&ip, addr, sizeof (IP6addr));
+ }
+ else if (addr_len == sizeof (struct sockaddr_in6))
+ {
+ memcpy (&ip,
+ &((struct sockaddr_in6 *) addr)->sin6_addr, sizeof (IP6addr));
+ }
+ else
+ {
+ return SYSERR;
+ }
ret = OK;
- MUTEX_LOCK(configLock);
+ MUTEX_LOCK (configLock);
if (allowedNetworks_ != NULL)
- ret = check_ipv6_listed(filteredNetworks_,
- ip);
- MUTEX_UNLOCK(configLock);
+ ret = check_ipv6_listed (filteredNetworks_, ip);
+ MUTEX_UNLOCK (configLock);
return ret;
}
-static int isRejected(const void * addr,
- unsigned int addr_len) {
- if ((YES == isBlacklisted(addr,
- addr_len)) ||
- (YES != isWhitelisted(addr,
- addr_len)))
+static int
+isRejected (const void *addr, unsigned int addr_len)
+{
+ if ((YES == isBlacklisted (addr,
+ addr_len)) ||
+ (YES != isWhitelisted (addr, addr_len)))
return YES;
return NO;
}
@@ -213,31 +208,31 @@
* (the signature/crc have been verified before)
* @return OK on success, SYSERR on failure
*/
-static int verifyHello(const P2P_hello_MESSAGE * hello) {
- Host6Address * haddr;
+static int
+verifyHello (const P2P_hello_MESSAGE * hello)
+{
+ Host6Address *haddr;
- haddr = (Host6Address*) &hello[1];
- if ( (ntohs(hello->senderAddressSize) != sizeof(Host6Address)) ||
- (ntohs(hello->header.size) != P2P_hello_MESSAGE_size(hello)) ||
- (ntohs(hello->header.type) != p2p_PROTO_hello) ||
- (YES == isBlacklisted(&haddr->ip,
- sizeof(IP6addr))) ||
- (YES != isWhitelisted(&haddr->ip,
- sizeof(IP6addr))) )
- return SYSERR; /* obviously invalid */
- else {
+ haddr = (Host6Address *) & hello[1];
+ if ((ntohs (hello->senderAddressSize) != sizeof (Host6Address)) ||
+ (ntohs (hello->header.size) != P2P_hello_MESSAGE_size (hello)) ||
+ (ntohs (hello->header.type) != p2p_PROTO_hello) ||
+ (YES == isBlacklisted (&haddr->ip,
+ sizeof (IP6addr))) ||
+ (YES != isWhitelisted (&haddr->ip, sizeof (IP6addr))))
+ return SYSERR; /* obviously invalid */
+ else
+ {
#if DEBUG_UDP6
- char inet6[INET6_ADDRSTRLEN];
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- "Verified UDP6 hello from %u.%u.%u.%u:%u.\n",
- inet_ntop(AF_INET6,
- &haddr->ip,
- inet6,
- INET6_ADDRSTRLEN),
- ntohs(haddr->port));
+ char inet6[INET6_ADDRSTRLEN];
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ "Verified UDP6 hello from %u.%u.%u.%u:%u.\n",
+ inet_ntop (AF_INET6,
+ &haddr->ip,
+ inet6, INET6_ADDRSTRLEN), ntohs (haddr->port));
#endif
- return OK;
- }
+ return OK;
+ }
}
/**
@@ -247,32 +242,33 @@
*
* @return hello on success, NULL on error
*/
-static P2P_hello_MESSAGE * createhello() {
- P2P_hello_MESSAGE * msg;
- Host6Address * haddr;
+static P2P_hello_MESSAGE *
+createhello ()
+{
+ P2P_hello_MESSAGE *msg;
+ Host6Address *haddr;
unsigned short port;
- port = getGNUnetUDP6Port();
+ port = getGNUnetUDP6Port ();
if (port == 0)
- return NULL; /* UDP6 transport configured send-only */
+ return NULL; /* UDP6 transport configured send-only */
- msg = MALLOC(sizeof(P2P_hello_MESSAGE) + sizeof(Host6Address));
- haddr = (Host6Address*) &msg[1];
+ msg = MALLOC (sizeof (P2P_hello_MESSAGE) + sizeof (Host6Address));
+ haddr = (Host6Address *) & msg[1];
- if (SYSERR == getPublicIP6Address(cfg,
- ectx,
- &haddr->ip)) {
- FREE(msg);
- GE_LOG(ectx,
- GE_WARNING,
- _("UDP6: Could not determine my public IPv6 address.\n"));
- return NULL;
- }
- haddr->port = htons(port);
- haddr->reserved = htons(0);
- msg->senderAddressSize = htons(sizeof(Host6Address));
- msg->protocol = htons(UDP6_PROTOCOL_NUMBER);
- msg->MTU = htonl(udpAPI.mtu);
+ if (SYSERR == getPublicIP6Address (cfg, ectx, &haddr->ip))
+ {
+ FREE (msg);
+ GE_LOG (ectx,
+ GE_WARNING,
+ _("UDP6: Could not determine my public IPv6 address.\n"));
+ return NULL;
+ }
+ haddr->port = htons (port);
+ haddr->reserved = htons (0);
+ msg->senderAddressSize = htons (sizeof (Host6Address));
+ msg->protocol = htons (UDP6_PROTOCOL_NUMBER);
+ msg->MTU = htonl (udpAPI.mtu);
return msg;
}
@@ -284,14 +280,14 @@
* @param size the size of the message
* @return SYSERR on error, OK on success
*/
-static int udp6Send(TSession * tsession,
- const void * message,
- const unsigned int size,
- int importance) {
- UDPMessage * mp;
- P2P_hello_MESSAGE * hello;
- Host6Address * haddr;
- struct sockaddr_in6 sin; /* an Internet endpoint address */
+static int
+udp6Send (TSession * tsession,
+ const void *message, const unsigned int size, int importance)
+{
+ UDPMessage *mp;
+ P2P_hello_MESSAGE *hello;
+ Host6Address *haddr;
+ struct sockaddr_in6 sin; /* an Internet endpoint address */
int ok;
size_t ssize;
#if DEBUG_UDP6
@@ -300,65 +296,57 @@
if (udp_sock == NULL)
return SYSERR;
- if (size == 0) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- if (size > udpAPI.mtu) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- hello = (P2P_hello_MESSAGE*)tsession->internal;
+ if (size == 0)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ if (size > udpAPI.mtu)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ hello = (P2P_hello_MESSAGE *) tsession->internal;
if (hello == NULL)
return SYSERR;
- haddr = (Host6Address*) &hello[1];
- ssize = size + sizeof(UDPMessage);
- mp = MALLOC(ssize);
- mp->header.size = htons(ssize);
+ haddr = (Host6Address *) & hello[1];
+ ssize = size + sizeof (UDPMessage);
+ mp = MALLOC (ssize);
+ mp->header.size = htons (ssize);
mp->header.type = 0;
- mp->sender = *coreAPI->myIdentity;
- memcpy(&mp[1],
- message,
- size);
+ mp->sender = *coreAPI->myIdentity;
+ memcpy (&mp[1], message, size);
ok = SYSERR;
- memset(&sin, 0, sizeof(sin));
+ memset (&sin, 0, sizeof (sin));
sin.sin6_family = AF_INET6;
sin.sin6_port = haddr->port;
- memcpy(&sin.sin6_addr,
- &haddr->ip.addr,
- sizeof(IP6addr));
+ memcpy (&sin.sin6_addr, &haddr->ip.addr, sizeof (IP6addr));
#if DEBUG_UDP6
- GE_LOG(ectx,
- GE_DEBUG,
- "Sending message of %u bytes via UDP6 to %s:%d..\n",
- ssize,
- inet_ntop(AF_INET6,
- &sin,
- inet6,
- INET6_ADDRSTRLEN),
- ntohs(sin.sin_port));
+ GE_LOG (ectx,
+ GE_DEBUG,
+ "Sending message of %u bytes via UDP6 to %s:%d..\n",
+ ssize,
+ inet_ntop (AF_INET6,
+ &sin, inet6, INET6_ADDRSTRLEN), ntohs (sin.sin_port));
#endif
- if (YES == socket_send_to(udp_sock,
- NC_Nonblocking,
- mp,
- ssize,
- &ssize,
- (const char*) &sin,
- sizeof(sin))) {
- ok = OK;
- if (stats != NULL)
- stats->change(stat_bytesSent,
- ssize);
- } else {
- GE_LOG_STRERROR(ectx,
- GE_WARNING,
- "sendto");
- if (stats != NULL)
- stats->change(stat_bytesDropped,
- ssize);
- }
- FREE(mp);
+ if (YES == socket_send_to (udp_sock,
+ NC_Nonblocking,
+ mp,
+ ssize,
+ &ssize, (const char *) &sin, sizeof (sin)))
+ {
+ ok = OK;
+ if (stats != NULL)
+ stats->change (stat_bytesSent, ssize);
+ }
+ else
+ {
+ GE_LOG_STRERROR (ectx, GE_WARNING, "sendto");
+ if (stats != NULL)
+ stats->change (stat_bytesDropped, ssize);
+ }
+ FREE (mp);
return ok;
}
@@ -367,77 +355,61 @@
*
* @return OK on success, SYSERR if the operation failed
*/
-static int startTransportServer() {
+static int
+startTransportServer ()
+{
int sock;
unsigned short port;
- /* initialize UDP6 network */
- port = getGNUnetUDP6Port();
- if (port != 0) {
- sock = passivesock(port);
- if (sock == -1)
+ /* initialize UDP6 network */
+ port = getGNUnetUDP6Port ();
+ if (port != 0)
+ {
+ sock = passivesock (port);
+ if (sock == -1)
+ return SYSERR;
+ selector = select_create ("udp6", YES, ectx, load_monitor, sock, sizeof
(struct sockaddr_in6), 0, /* timeout */
+ &select_message_handler,
+ NULL,
+ &select_accept_handler,
+ &isRejected,
+ &select_close_handler,
+ NULL, 64 * 1024, 16 /* max sockets */ );
+ if (selector == NULL)
+ return SYSERR;
+ }
+ sock = SOCKET (PF_INET, SOCK_DGRAM, 17);
+ if (sock == -1)
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_ADMIN | GE_BULK, "socket");
+ select_destroy (selector);
+ selector = NULL;
return SYSERR;
- selector = select_create("udp6",
- YES,
- ectx,
- load_monitor,
- sock,
- sizeof(struct sockaddr_in6),
- 0, /* timeout */
- &select_message_handler,
- NULL,
- &select_accept_handler,
- &isRejected,
- &select_close_handler,
- NULL,
- 64 * 1024,
- 16 /* max sockets */);
- if (selector == NULL)
- return SYSERR;
- }
- sock = SOCKET(PF_INET, SOCK_DGRAM, 17);
- if (sock == -1) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "socket");
- select_destroy(selector);
- selector = NULL;
- return SYSERR;
- }
- udp_sock = socket_create(ectx,
- load_monitor,
- sock);
+ }
+ udp_sock = socket_create (ectx, load_monitor, sock);
return OK;
}
/**
* Reload the configuration. Should never fail.
*/
-static int reloadConfiguration() {
- char * ch;
+static int
+reloadConfiguration ()
+{
+ char *ch;
- MUTEX_LOCK(configLock);
- FREENONNULL(filteredNetworks_);
- GC_get_configuration_value_string(cfg,
- "UDP6",
- "BLACKLIST",
- "",
- &ch);
- filteredNetworks_ = parse_ipv6_network_specification(ectx,
- ch);
- FREE(ch);
- GC_get_configuration_value_string(cfg,
- "UDP6",
- "WHITELIST",
- "",
- &ch);
- if (strlen(ch) > 0)
- allowedNetworks_ = parse_ipv6_network_specification(ectx,
- ch);
+ MUTEX_LOCK (configLock);
+ FREENONNULL (filteredNetworks_);
+ GC_get_configuration_value_string (cfg, "UDP6", "BLACKLIST", "", &ch);
+ filteredNetworks_ = parse_ipv6_network_specification (ectx, ch);
+ FREE (ch);
+ GC_get_configuration_value_string (cfg, "UDP6", "WHITELIST", "", &ch);
+ if (strlen (ch) > 0)
+ allowedNetworks_ = parse_ipv6_network_specification (ectx, ch);
else
allowedNetworks_ = NULL;
- FREE(ch);
- MUTEX_UNLOCK(configLock);
+ FREE (ch);
+ MUTEX_UNLOCK (configLock);
return 0;
}
@@ -445,22 +417,18 @@
* Convert UDP6 hello to IPv6 address
*/
static int
-helloToAddress(const P2P_hello_MESSAGE * hello,
- void ** sa,
- unsigned int * sa_len) {
- const Host6Address * haddr = (const Host6Address*) &hello[1];
- struct sockaddr_in6 * serverAddr;
+helloToAddress (const P2P_hello_MESSAGE * hello,
+ void **sa, unsigned int *sa_len)
+{
+ const Host6Address *haddr = (const Host6Address *) &hello[1];
+ struct sockaddr_in6 *serverAddr;
- *sa_len = sizeof(struct sockaddr_in6);
- serverAddr = MALLOC(sizeof(struct sockaddr_in6));
+ *sa_len = sizeof (struct sockaddr_in6);
+ serverAddr = MALLOC (sizeof (struct sockaddr_in6));
*sa = serverAddr;
- memset(serverAddr,
- 0,
- sizeof(struct sockaddr_in6));
- serverAddr->sin6_family = AF_INET6;
- memcpy(&serverAddr->sin6_addr,
- haddr,
- sizeof(IP6addr));
+ memset (serverAddr, 0, sizeof (struct sockaddr_in6));
+ serverAddr->sin6_family = AF_INET6;
+ memcpy (&serverAddr->sin6_addr, haddr, sizeof (IP6addr));
serverAddr->sin6_port = haddr->port;
return OK;
}
@@ -475,52 +443,55 @@
* The exported method. Makes the core api available via a global and
* returns the udp6 transport API.
*/
-TransportAPI * inittransport_udp6(CoreAPIForTransport * core) {
+TransportAPI *
+inittransport_udp6 (CoreAPIForTransport * core)
+{
unsigned long long mtu;
- GE_ASSERT(ectx, sizeof(UDPMessage) == 68);
+ GE_ASSERT (ectx, sizeof (UDPMessage) == 68);
coreAPI = core;
ectx = core->ectx;
cfg = core->cfg;
- configLock = MUTEX_CREATE(NO);
+ configLock = MUTEX_CREATE (NO);
- reloadConfiguration();
- if (-1 == GC_get_configuration_value_number(cfg,
- "UDP6",
- "MTU",
- sizeof(UDPMessage) + P2P_MESSAGE_OVERHEAD
+ sizeof(MESSAGE_HEADER) + 32,
- 65500,
- MESSAGE_SIZE,
- &mtu)) {
- return NULL;
- }
+ reloadConfiguration ();
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "UDP6",
+ "MTU",
+ sizeof (UDPMessage) +
+ P2P_MESSAGE_OVERHEAD +
+ sizeof (MESSAGE_HEADER) + 32,
+ 65500, MESSAGE_SIZE, &mtu))
+ {
+ return NULL;
+ }
if (mtu < 1200)
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("MTU %llu for `%s' is probably too low!\n"),
- mtu,
- "UDP6");
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _("MTU %llu for `%s' is probably too low!\n"), mtu, "UDP6");
- udpAPI.protocolNumber = UDP6_PROTOCOL_NUMBER;
- udpAPI.mtu = mtu - sizeof(UDPMessage);
- udpAPI.cost = 19950;
- udpAPI.verifyHello = &verifyHello;
- udpAPI.createhello = &createhello;
- udpAPI.connect = &udpConnect;
- udpAPI.send = &udp6Send;
- udpAPI.associate = &udpAssociate;
- udpAPI.disconnect = &udpDisconnect;
+ udpAPI.protocolNumber = UDP6_PROTOCOL_NUMBER;
+ udpAPI.mtu = mtu - sizeof (UDPMessage);
+ udpAPI.cost = 19950;
+ udpAPI.verifyHello = &verifyHello;
+ udpAPI.createhello = &createhello;
+ udpAPI.connect = &udpConnect;
+ udpAPI.send = &udp6Send;
+ udpAPI.associate = &udpAssociate;
+ udpAPI.disconnect = &udpDisconnect;
udpAPI.startTransportServer = &startTransportServer;
- udpAPI.stopTransportServer = &stopTransportServer;
- udpAPI.helloToAddress = &helloToAddress;
- udpAPI.testWouldTry = &testWouldTry;
+ udpAPI.stopTransportServer = &stopTransportServer;
+ udpAPI.helloToAddress = &helloToAddress;
+ udpAPI.testWouldTry = &testWouldTry;
return &udpAPI;
}
-void donetransport_udp6() {
- MUTEX_DESTROY(configLock);
- FREENONNULL(filteredNetworks_);
+void
+donetransport_udp6 ()
+{
+ MUTEX_DESTROY (configLock);
+ FREENONNULL (filteredNetworks_);
}
/* end of udp6.c */
Modified: GNUnet/src/transports/udp_helper.c
===================================================================
--- GNUnet/src/transports/udp_helper.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/udp_helper.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -24,13 +24,13 @@
* @author Christian Grothoff
*/
-typedef int (*BlacklistedTester)(const void * addr,
- unsigned int addr_len);
+typedef int (*BlacklistedTester) (const void *addr, unsigned int addr_len);
/**
* Message-Packet header.
*/
-typedef struct {
+typedef struct
+{
/**
* size of the message, in bytes, including this header.
*/
@@ -45,11 +45,11 @@
/* *********** globals ************* */
-static CoreAPIForTransport * coreAPI;
+static CoreAPIForTransport *coreAPI;
static TransportAPI udpAPI;
-static Stats_ServiceAPI * stats;
+static Stats_ServiceAPI *stats;
static int stat_bytesReceived;
@@ -57,17 +57,17 @@
static int stat_bytesDropped;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
/**
* thread that listens for inbound messages
*/
-static struct SelectHandle * selector;
+static struct SelectHandle *selector;
/**
* the socket that we transmit all data with
*/
-static struct SocketHandle * udp_sock;
+static struct SocketHandle *udp_sock;
/**
* The socket of session has data waiting, process!
@@ -75,53 +75,51 @@
* This function may only be called if the tcplock is
* already held by the caller.
*/
-static int select_message_handler(void * mh_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * sock_ctx,
- const MESSAGE_HEADER * msg) {
+static int
+select_message_handler (void *mh_cls,
+ struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ void *sock_ctx, const MESSAGE_HEADER * msg)
+{
unsigned int len;
- P2P_PACKET * mp;
- const UDPMessage * um;
+ P2P_PACKET *mp;
+ const UDPMessage *um;
- len = ntohs(msg->size);
- if (len <= sizeof(UDPMessage)) {
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Received malformed message from udp-peer connection. Closing.\n"));
- return SYSERR;
- }
+ len = ntohs (msg->size);
+ if (len <= sizeof (UDPMessage))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _
+ ("Received malformed message from udp-peer connection.
Closing.\n"));
+ return SYSERR;
+ }
#if DEBUG_UDP
- GE_LOG(ectx,
- GE_DEBUG | GE_USER | GE_BULK,
- "Received %d bytes via UDP\n",
- len);
+ GE_LOG (ectx,
+ GE_DEBUG | GE_USER | GE_BULK, "Received %d bytes via UDP\n", len);
#endif
- um = (const UDPMessage*) msg;
- mp = MALLOC(sizeof(P2P_PACKET));
- mp->msg = MALLOC(len - sizeof(UDPMessage));
- memcpy(mp->msg,
- &um[1],
- len - sizeof(UDPMessage));
+ um = (const UDPMessage *) msg;
+ mp = MALLOC (sizeof (P2P_PACKET));
+ mp->msg = MALLOC (len - sizeof (UDPMessage));
+ memcpy (mp->msg, &um[1], len - sizeof (UDPMessage));
mp->sender = um->sender;
- mp->size = len - sizeof(UDPMessage);
+ mp->size = len - sizeof (UDPMessage);
mp->tsession = NULL;
- coreAPI->receive(mp);
+ coreAPI->receive (mp);
if (stats != NULL)
- stats->change(stat_bytesReceived,
- len);
+ stats->change (stat_bytesReceived, len);
return OK;
}
-static void * select_accept_handler(void * ah_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- const void * addr,
- unsigned int addr_len) {
+static void *
+select_accept_handler (void *ah_cls,
+ struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ const void *addr, unsigned int addr_len)
+{
static int nonnullpointer;
BlacklistedTester blt = ah_cls;
- if (NO != blt(addr,
- addr_len))
+ if (NO != blt (addr, addr_len))
return NULL;
return &nonnullpointer;
}
@@ -130,10 +128,11 @@
* Select has been forced to close a connection.
* Free the associated context.
*/
-static void select_close_handler(void * ch_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * sock_ctx) {
+static void
+select_close_handler (void *ch_cls,
+ struct SelectHandle *sh,
+ struct SocketHandle *sock, void *sock_ctx)
+{
/* do nothing */
}
@@ -144,15 +143,14 @@
* @param tsessionPtr the session handle that is to be set
* @return OK on success, SYSERR if the operation failed
*/
-static int udpConnect(const P2P_hello_MESSAGE * hello,
- TSession ** tsessionPtr) {
- TSession * tsession;
+static int
+udpConnect (const P2P_hello_MESSAGE * hello, TSession ** tsessionPtr)
+{
+ TSession *tsession;
- tsession = MALLOC(sizeof(TSession));
- tsession->internal = MALLOC(P2P_hello_MESSAGE_size(hello));
- memcpy(tsession->internal,
- hello,
- P2P_hello_MESSAGE_size(hello));
+ tsession = MALLOC (sizeof (TSession));
+ tsession->internal = MALLOC (P2P_hello_MESSAGE_size (hello));
+ memcpy (tsession->internal, hello, P2P_hello_MESSAGE_size (hello));
tsession->ttype = udpAPI.protocolNumber;
tsession->peer = hello->senderIdentity;
*tsessionPtr = tsession;
@@ -170,8 +168,10 @@
* @return OK if the session could be associated,
* SYSERR if not.
*/
-int udpAssociate(TSession * tsession) {
- return SYSERR; /* UDP connections can never be associated */
+int
+udpAssociate (TSession * tsession)
+{
+ return SYSERR; /* UDP connections can never be associated */
}
/**
@@ -180,12 +180,15 @@
* @param tsession the session that is closed
* @return OK on success, SYSERR if the operation failed
*/
-static int udpDisconnect(TSession * tsession) {
- if (tsession != NULL) {
- if (tsession->internal != NULL)
- FREE(tsession->internal);
- FREE(tsession);
- }
+static int
+udpDisconnect (TSession * tsession)
+{
+ if (tsession != NULL)
+ {
+ if (tsession->internal != NULL)
+ FREE (tsession->internal);
+ FREE (tsession);
+ }
return OK;
}
@@ -193,13 +196,16 @@
* Shutdown the server process (stop receiving inbound traffic). Maybe
* restarted later!
*/
-static int stopTransportServer() {
- GE_ASSERT(ectx, udp_sock != NULL);
- if (selector != NULL) {
- select_destroy(selector);
- selector = NULL;
- }
- socket_destroy(udp_sock);
+static int
+stopTransportServer ()
+{
+ GE_ASSERT (ectx, udp_sock != NULL);
+ if (selector != NULL)
+ {
+ select_destroy (selector);
+ selector = NULL;
+ }
+ socket_destroy (udp_sock);
udp_sock = NULL;
return OK;
}
@@ -217,22 +223,24 @@
* NO if the transport would just drop the message,
* SYSERR if the size/session is invalid
*/
-static int testWouldTry(TSession * tsession,
- unsigned int size,
- int important) {
- const P2P_hello_MESSAGE * hello;
+static int
+testWouldTry (TSession * tsession, unsigned int size, int important)
+{
+ const P2P_hello_MESSAGE *hello;
if (udp_sock == NULL)
return SYSERR;
- if (size == 0) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- if (size > udpAPI.mtu) {
- GE_BREAK(ectx, 0);
- return SYSERR;
- }
- hello = (const P2P_hello_MESSAGE*)tsession->internal;
+ if (size == 0)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ if (size > udpAPI.mtu)
+ {
+ GE_BREAK (ectx, 0);
+ return SYSERR;
+ }
+ hello = (const P2P_hello_MESSAGE *) tsession->internal;
if (hello == NULL)
return SYSERR;
return YES;
Modified: GNUnet/src/transports/upnp/error.c
===================================================================
--- GNUnet/src/transports/upnp/error.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/upnp/error.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -4,26 +4,19 @@
/**
* Map gaim logger to GNUnet logger.
*/
-void gaim_debug_error(char * facility,
- char * format,
- ...) {
- GE_LOG(NULL,
- GE_WARNING | GE_DEVELOPER | GE_ADMIN | GE_BULK,
- "%s: %s\n",
- facility,
- format);
+void
+gaim_debug_error (char *facility, char *format, ...)
+{
+ GE_LOG (NULL,
+ GE_WARNING | GE_DEVELOPER | GE_ADMIN | GE_BULK,
+ "%s: %s\n", facility, format);
}
/**
* Map gaim logger to GNUnet logger.
*/
-void gaim_debug_info(char * facility,
- char * format,
- ...) {
- GE_LOG(NULL,
- GE_INFO | GE_ADMIN | GE_BULK,
- "%s: %s\n",
- facility,
- format);
+void
+gaim_debug_info (char *facility, char *format, ...)
+{
+ GE_LOG (NULL, GE_INFO | GE_ADMIN | GE_BULK, "%s: %s\n", facility, format);
}
-
Modified: GNUnet/src/transports/upnp/error.h
===================================================================
--- GNUnet/src/transports/upnp/error.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/upnp/error.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -5,14 +5,10 @@
/**
* Map gaim logger to GNUnet logger.
*/
-void gaim_debug_error(char * facility,
- char * format,
- ...);
+void gaim_debug_error (char *facility, char *format, ...);
/**
* Map gaim logger to GNUnet logger.
*/
-void gaim_debug_info(char * facility,
- char * format,
- ...);
+void gaim_debug_info (char *facility, char *format, ...);
Modified: GNUnet/src/transports/upnp/init.c
===================================================================
--- GNUnet/src/transports/upnp/init.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/upnp/init.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -31,24 +31,25 @@
#include "gnunet_upnp_service.h"
#include "gnunet_core.h"
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static struct CronManager * cron;
+static struct CronManager *cron;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-typedef struct {
+typedef struct
+{
unsigned short port;
- const char * proto;
+ const char *proto;
} PMap;
-static PMap * maps;
+static PMap *maps;
static unsigned int maps_size;
-static struct PTHREAD * discovery;
+static struct PTHREAD *discovery;
static int discovery_socket;
@@ -57,60 +58,64 @@
*
* @return SYSERR on error, OK on success
*/
-static int gnunet_upnp_get_public_ip(IPaddr * address) {
- const char * ip;
+static int
+gnunet_upnp_get_public_ip (IPaddr * address)
+{
+ const char *ip;
- ip = gaim_upnp_get_public_ip();
+ ip = gaim_upnp_get_public_ip ();
if (ip == NULL)
return SYSERR;
- return get_host_by_name(ectx,
- ip,
- address);
+ return get_host_by_name (ectx, ip, address);
}
-static void kill_discovery() {
- void * unused;
+static void
+kill_discovery ()
+{
+ void *unused;
- if (discovery != NULL) {
- SHUTDOWN(discovery_socket, SHUT_RDWR);
- CLOSE(discovery_socket);
- PTHREAD_JOIN(discovery, &unused);
- discovery = NULL;
- }
+ if (discovery != NULL)
+ {
+ SHUTDOWN (discovery_socket, SHUT_RDWR);
+ CLOSE (discovery_socket);
+ PTHREAD_JOIN (discovery, &unused);
+ discovery = NULL;
+ }
}
-static void * discover_thread() {
- gaim_upnp_discover(ectx, cfg, discovery_socket);
+static void *
+discover_thread ()
+{
+ gaim_upnp_discover (ectx, cfg, discovery_socket);
return NULL;
}
/**
* Periodically try to (re)discover UPnP access points.
*/
-static void discover(void * unused) {
- kill_discovery();
- discovery_socket = SOCKET(AF_INET, SOCK_DGRAM, 0);
+static void
+discover (void *unused)
+{
+ kill_discovery ();
+ discovery_socket = SOCKET (AF_INET, SOCK_DGRAM, 0);
if (discovery_socket == -1)
return;
- discovery = PTHREAD_CREATE(&discover_thread,
- NULL,
- 1024 * 128);
+ discovery = PTHREAD_CREATE (&discover_thread, NULL, 1024 * 128);
}
/**
* Periodically repeat our requests for port mappings.
*/
-static void portmap(void * unused) {
+static void
+portmap (void *unused)
+{
unsigned int i;
- MUTEX_LOCK(lock);
- for (i=0;i<maps_size;i++)
- gaim_upnp_change_port_mapping(ectx,
- cfg,
- NO,
- maps[i].port,
- maps[i].proto);
- MUTEX_UNLOCK(lock);
+ MUTEX_LOCK (lock);
+ for (i = 0; i < maps_size; i++)
+ gaim_upnp_change_port_mapping (ectx,
+ cfg, NO, maps[i].port, maps[i].proto);
+ MUTEX_UNLOCK (lock);
}
@@ -119,31 +124,26 @@
*
* @return SYSERR on error, OK on success
*/
-static int gnunet_upnp_get_ip(unsigned short port,
- const char * protocol,
- IPaddr * address) {
+static int
+gnunet_upnp_get_ip (unsigned short port,
+ const char *protocol, IPaddr * address)
+{
unsigned int i;
- MUTEX_LOCK(lock);
- for (i=0;i<maps_size;i++)
- if ( (0 == strcmp(maps[i].proto, protocol)) &&
- (maps[i].port == port) )
+ MUTEX_LOCK (lock);
+ for (i = 0; i < maps_size; i++)
+ if ((0 == strcmp (maps[i].proto, protocol)) && (maps[i].port == port))
break;
- if (i == maps_size) {
- /* new entry! */
- GROW(maps,
- maps_size,
- maps_size + 1);
- maps[i].proto = protocol;
- maps[i].port = port;
- gaim_upnp_change_port_mapping(ectx,
- cfg,
- YES,
- port,
- protocol);
- }
- MUTEX_UNLOCK(lock);
- return gnunet_upnp_get_public_ip(address);
+ if (i == maps_size)
+ {
+ /* new entry! */
+ GROW (maps, maps_size, maps_size + 1);
+ maps[i].proto = protocol;
+ maps[i].port = port;
+ gaim_upnp_change_port_mapping (ectx, cfg, YES, port, protocol);
+ }
+ MUTEX_UNLOCK (lock);
+ return gnunet_upnp_get_public_ip (address);
}
@@ -151,24 +151,17 @@
* Get the external IP address for the local machine.
*/
UPnP_ServiceAPI *
-provide_module_upnp(CoreAPIForApplication * capi) {
+provide_module_upnp (CoreAPIForApplication * capi)
+{
static UPnP_ServiceAPI api;
ectx = capi->ectx;
cfg = capi->cfg;
- cron = cron_create(ectx);
- lock = MUTEX_CREATE(NO);
- cron_start(cron);
- cron_add_job(cron,
- &discover,
- 0,
- 5 * cronMINUTES,
- NULL);
- cron_add_job(cron,
- &portmap,
- 150 * cronSECONDS,
- 5 * cronMINUTES,
- NULL);
+ cron = cron_create (ectx);
+ lock = MUTEX_CREATE (NO);
+ cron_start (cron);
+ cron_add_job (cron, &discover, 0, 5 * cronMINUTES, NULL);
+ cron_add_job (cron, &portmap, 150 * cronSECONDS, 5 * cronMINUTES, NULL);
api.get_ip = gnunet_upnp_get_ip;
return &api;
}
@@ -176,34 +169,25 @@
/**
* Shutdown UPNP.
*/
-int release_module_upnp() {
+int
+release_module_upnp ()
+{
unsigned int i;
if (cron == NULL)
- return SYSERR; /* not loaded! */
- for (i=0;i<maps_size;i++)
- gaim_upnp_change_port_mapping(ectx,
- cfg,
- NO,
- maps[i].port,
- maps[i].proto);
- cron_stop(cron);
- cron_del_job(cron,
- &discover,
- 5 * cronMINUTES,
- NULL);
- cron_del_job(cron,
- &portmap,
- 5 * cronMINUTES,
- NULL);
- cron_destroy(cron);
- kill_discovery();
+ return SYSERR; /* not loaded! */
+ for (i = 0; i < maps_size; i++)
+ gaim_upnp_change_port_mapping (ectx,
+ cfg, NO, maps[i].port, maps[i].proto);
+ cron_stop (cron);
+ cron_del_job (cron, &discover, 5 * cronMINUTES, NULL);
+ cron_del_job (cron, &portmap, 5 * cronMINUTES, NULL);
+ cron_destroy (cron);
+ kill_discovery ();
cron = NULL;
- MUTEX_DESTROY(lock);
+ MUTEX_DESTROY (lock);
lock = NULL;
- GROW(maps,
- maps_size,
- 0);
+ GROW (maps, maps_size, 0);
ectx = NULL;
cfg = NULL;
return OK;
Modified: GNUnet/src/transports/upnp/ip.c
===================================================================
--- GNUnet/src/transports/upnp/ip.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/upnp/ip.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -34,13 +34,13 @@
* Get the IP address for the local machine.
* @return NULL on error
*/
-char * gaim_upnp_get_internal_ip(struct GC_Configuration * cfg,
- struct GE_Context * ectx) {
+char *
+gaim_upnp_get_internal_ip (struct GC_Configuration *cfg,
+ struct GE_Context *ectx)
+{
IPaddr address;
- return network_get_local_ip(cfg,
- ectx,
- &address);
+ return network_get_local_ip (cfg, ectx, &address);
}
Modified: GNUnet/src/transports/upnp/ip.h
===================================================================
--- GNUnet/src/transports/upnp/ip.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/upnp/ip.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,8 +33,8 @@
* Get the IP address for the local machine.
* @return NULL on error
*/
-char * gaim_upnp_get_internal_ip(struct GC_Configuration * cfg,
- struct GE_Context * ectx);
+char *gaim_upnp_get_internal_ip (struct GC_Configuration *cfg,
+ struct GE_Context *ectx);
#endif
Modified: GNUnet/src/transports/upnp/upnp.c
===================================================================
--- GNUnet/src/transports/upnp/upnp.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/upnp/upnp.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -84,24 +84,27 @@
"<NewExternalPort>%i</NewExternalPort>\r\n" \
"<NewProtocol>%s</NewProtocol>\r\n"
-typedef enum {
+typedef enum
+{
GAIM_UPNP_STATUS_UNDISCOVERED = -1,
GAIM_UPNP_STATUS_UNABLE_TO_DISCOVER,
GAIM_UPNP_STATUS_DISCOVERING,
GAIM_UPNP_STATUS_DISCOVERED
} GaimUPnPStatus;
-typedef struct {
+typedef struct
+{
GaimUPnPStatus status;
- char* control_url;
- const char * service_type;
+ char *control_url;
+ const char *service_type;
char publicip[16];
} GaimUPnPControlInfo;
-typedef struct {
- const char * service_type;
- char * full_url;
- char * buf;
+typedef struct
+{
+ const char *service_type;
+ char *full_url;
+ char *buf;
unsigned int buf_len;
int sock;
} UPnPDiscoveryData;
@@ -117,16 +120,15 @@
* This is the signature used for functions that act as a callback
* to CURL.
*/
-typedef size_t (*GaimUtilFetchUrlCallback)(void *url_data,
- size_t size,
- size_t nmemb,
- void * user_data);
+typedef size_t (*GaimUtilFetchUrlCallback) (void *url_data,
+ size_t size,
+ size_t nmemb, void *user_data);
-static char * g_strstr_len (const char *haystack,
- int haystack_len,
- const char *needle) {
+static char *
+g_strstr_len (const char *haystack, int haystack_len, const char *needle)
+{
int i;
g_return_val_if_fail (haystack != NULL, NULL);
@@ -141,193 +143,212 @@
const char *end = haystack + haystack_len - needle_len;
if (needle_len == 0)
- return (char *)haystack;
+ return (char *) haystack;
while (*p && p <= end)
- {
- for (i = 0; i < needle_len; i++)
- if (p[i] != needle[i])
- goto next;
+ {
+ for (i = 0; i < needle_len; i++)
+ if (p[i] != needle[i])
+ goto next;
- return (char *)p;
+ return (char *) p;
- next:
- p++;
- }
+ next:
+ p++;
+ }
}
return NULL;
}
static int
-gaim_upnp_compare_device(const xmlnode* device,
- const char* deviceType) {
- xmlnode * deviceTypeNode = xmlnode_get_child(device, "deviceType");
- char * tmp;
+gaim_upnp_compare_device (const xmlnode * device, const char *deviceType)
+{
+ xmlnode *deviceTypeNode = xmlnode_get_child (device, "deviceType");
+ char *tmp;
int ret;
if (deviceTypeNode == NULL)
return FALSE;
- tmp = xmlnode_get_data(deviceTypeNode);
- ret = !strcasecmp(tmp, deviceType);
- FREE(tmp);
+ tmp = xmlnode_get_data (deviceTypeNode);
+ ret = !strcasecmp (tmp, deviceType);
+ FREE (tmp);
return ret;
}
static int
-gaim_upnp_compare_service(const xmlnode* service,
- const char* serviceType) {
- xmlnode * serviceTypeNode;
+gaim_upnp_compare_service (const xmlnode * service, const char *serviceType)
+{
+ xmlnode *serviceTypeNode;
char *tmp;
int ret;
if (service == NULL)
return FALSE;
- serviceTypeNode = xmlnode_get_child(service, "serviceType");
- if(serviceTypeNode == NULL)
+ serviceTypeNode = xmlnode_get_child (service, "serviceType");
+ if (serviceTypeNode == NULL)
return FALSE;
- tmp = xmlnode_get_data(serviceTypeNode);
- ret = !strcasecmp(tmp, serviceType);
- FREE(tmp);
+ tmp = xmlnode_get_data (serviceTypeNode);
+ ret = !strcasecmp (tmp, serviceType);
+ FREE (tmp);
return ret;
}
-static char*
-gaim_upnp_parse_description_response(const char* httpResponse,
- size_t len,
- const char* httpURL,
- const char* serviceType) {
+static char *
+gaim_upnp_parse_description_response (const char *httpResponse,
+ size_t len,
+ const char *httpURL,
+ const char *serviceType)
+{
char *xmlRoot, *baseURL, *controlURL, *service;
xmlnode *xmlRootNode, *serviceTypeNode, *controlURLNode, *baseURLNode;
char *tmp;
/* find the root of the xml document */
- xmlRoot = g_strstr_len(httpResponse, len, "<root");
+ xmlRoot = g_strstr_len (httpResponse, len, "<root");
if (xmlRoot == NULL)
return NULL;
- if (g_strstr_len(httpResponse, len, "</root") == NULL)
+ if (g_strstr_len (httpResponse, len, "</root") == NULL)
return NULL;
/* create the xml root node */
- xmlRootNode = xmlnode_from_str(xmlRoot,
- len - (xmlRoot - httpResponse));
+ xmlRootNode = xmlnode_from_str (xmlRoot, len - (xmlRoot - httpResponse));
if (xmlRootNode == NULL)
return NULL;
/* get the baseURL of the device */
- baseURLNode = xmlnode_get_child(xmlRootNode, "URLBase");
- if (baseURLNode != NULL) {
- baseURL = xmlnode_get_data(baseURLNode);
- } else {
- baseURL = STRDUP(httpURL);
- }
+ baseURLNode = xmlnode_get_child (xmlRootNode, "URLBase");
+ if (baseURLNode != NULL)
+ {
+ baseURL = xmlnode_get_data (baseURLNode);
+ }
+ else
+ {
+ baseURL = STRDUP (httpURL);
+ }
/* get the serviceType child that has the service type as its data */
/* get urn:schemas-upnp-org:device:InternetGatewayDevice:1 and its
devicelist */
- serviceTypeNode = xmlnode_get_child(xmlRootNode, "device");
- while(!gaim_upnp_compare_device(serviceTypeNode,
-
"urn:schemas-upnp-org:device:InternetGatewayDevice:1") &&
- serviceTypeNode != NULL) {
- serviceTypeNode = xmlnode_get_next_twin(serviceTypeNode);
- }
- if(serviceTypeNode == NULL) {
- FREE(baseURL);
- xmlnode_free(xmlRootNode);
- return NULL;
- }
- serviceTypeNode = xmlnode_get_child(serviceTypeNode, "deviceList");
- if(serviceTypeNode == NULL) {
- FREE(baseURL);
- xmlnode_free(xmlRootNode);
- return NULL;
- }
+ serviceTypeNode = xmlnode_get_child (xmlRootNode, "device");
+ while (!gaim_upnp_compare_device (serviceTypeNode,
+
"urn:schemas-upnp-org:device:InternetGatewayDevice:1")
+ && serviceTypeNode != NULL)
+ {
+ serviceTypeNode = xmlnode_get_next_twin (serviceTypeNode);
+ }
+ if (serviceTypeNode == NULL)
+ {
+ FREE (baseURL);
+ xmlnode_free (xmlRootNode);
+ return NULL;
+ }
+ serviceTypeNode = xmlnode_get_child (serviceTypeNode, "deviceList");
+ if (serviceTypeNode == NULL)
+ {
+ FREE (baseURL);
+ xmlnode_free (xmlRootNode);
+ return NULL;
+ }
/* get urn:schemas-upnp-org:device:WANDevice:1 and its devicelist */
- serviceTypeNode = xmlnode_get_child(serviceTypeNode, "device");
- while(!gaim_upnp_compare_device(serviceTypeNode,
- "urn:schemas-upnp-org:device:WANDevice:1") &&
- serviceTypeNode != NULL) {
- serviceTypeNode = xmlnode_get_next_twin(serviceTypeNode);
- }
- if(serviceTypeNode == NULL) {
- FREE(baseURL);
- xmlnode_free(xmlRootNode);
- return NULL;
- }
- serviceTypeNode = xmlnode_get_child(serviceTypeNode, "deviceList");
- if(serviceTypeNode == NULL) {
- FREE(baseURL);
- xmlnode_free(xmlRootNode);
- return NULL;
- }
+ serviceTypeNode = xmlnode_get_child (serviceTypeNode, "device");
+ while (!gaim_upnp_compare_device (serviceTypeNode,
+ "urn:schemas-upnp-org:device:WANDevice:1")
+ && serviceTypeNode != NULL)
+ {
+ serviceTypeNode = xmlnode_get_next_twin (serviceTypeNode);
+ }
+ if (serviceTypeNode == NULL)
+ {
+ FREE (baseURL);
+ xmlnode_free (xmlRootNode);
+ return NULL;
+ }
+ serviceTypeNode = xmlnode_get_child (serviceTypeNode, "deviceList");
+ if (serviceTypeNode == NULL)
+ {
+ FREE (baseURL);
+ xmlnode_free (xmlRootNode);
+ return NULL;
+ }
/* get urn:schemas-upnp-org:device:WANConnectionDevice:1 and its servicelist
*/
- serviceTypeNode = xmlnode_get_child(serviceTypeNode, "device");
- while(serviceTypeNode && !gaim_upnp_compare_device(serviceTypeNode,
-
"urn:schemas-upnp-org:device:WANConnectionDevice:1")) {
- serviceTypeNode = xmlnode_get_next_twin(serviceTypeNode);
- }
- if(serviceTypeNode == NULL) {
- FREE(baseURL);
- xmlnode_free(xmlRootNode);
- return NULL;
- }
- serviceTypeNode = xmlnode_get_child(serviceTypeNode, "serviceList");
- if(serviceTypeNode == NULL) {
- FREE(baseURL);
- xmlnode_free(xmlRootNode);
- return NULL;
- }
+ serviceTypeNode = xmlnode_get_child (serviceTypeNode, "device");
+ while (serviceTypeNode && !gaim_upnp_compare_device (serviceTypeNode,
+
"urn:schemas-upnp-org:device:WANConnectionDevice:1"))
+ {
+ serviceTypeNode = xmlnode_get_next_twin (serviceTypeNode);
+ }
+ if (serviceTypeNode == NULL)
+ {
+ FREE (baseURL);
+ xmlnode_free (xmlRootNode);
+ return NULL;
+ }
+ serviceTypeNode = xmlnode_get_child (serviceTypeNode, "serviceList");
+ if (serviceTypeNode == NULL)
+ {
+ FREE (baseURL);
+ xmlnode_free (xmlRootNode);
+ return NULL;
+ }
/* get the serviceType variable passed to this function */
- service = g_strdup_printf(SEARCH_REQUEST_DEVICE, serviceType);
- serviceTypeNode = xmlnode_get_child(serviceTypeNode, "service");
- while(!gaim_upnp_compare_service(serviceTypeNode, service) &&
- serviceTypeNode != NULL) {
- serviceTypeNode = xmlnode_get_next_twin(serviceTypeNode);
- }
+ service = g_strdup_printf (SEARCH_REQUEST_DEVICE, serviceType);
+ serviceTypeNode = xmlnode_get_child (serviceTypeNode, "service");
+ while (!gaim_upnp_compare_service (serviceTypeNode, service) &&
+ serviceTypeNode != NULL)
+ {
+ serviceTypeNode = xmlnode_get_next_twin (serviceTypeNode);
+ }
- FREE(service);
- if (serviceTypeNode == NULL) {
- FREE(baseURL);
- xmlnode_free(xmlRootNode);
- return NULL;
- }
+ FREE (service);
+ if (serviceTypeNode == NULL)
+ {
+ FREE (baseURL);
+ xmlnode_free (xmlRootNode);
+ return NULL;
+ }
/* get the controlURL of the service */
- if ((controlURLNode = xmlnode_get_child(serviceTypeNode,
- "controlURL")) == NULL) {
- FREE(baseURL);
- xmlnode_free(xmlRootNode);
- return NULL;
- }
+ if ((controlURLNode = xmlnode_get_child (serviceTypeNode,
+ "controlURL")) == NULL)
+ {
+ FREE (baseURL);
+ xmlnode_free (xmlRootNode);
+ return NULL;
+ }
- tmp = xmlnode_get_data(controlURLNode);
- if (baseURL && !gaim_str_has_prefix(tmp, "http://") &&
- !gaim_str_has_prefix(tmp, "HTTP://")) {
- if (tmp[0] == '/') {
- size_t len;
- const char * end;
- /* absolute path */
- end = strstr(&baseURL[strlen("http://")],
- "/");
- if (end == NULL)
- len = strlen(&baseURL[strlen("http://")]);
+ tmp = xmlnode_get_data (controlURLNode);
+ if (baseURL && !gaim_str_has_prefix (tmp, "http://") &&
+ !gaim_str_has_prefix (tmp, "HTTP://"))
+ {
+ if (tmp[0] == '/')
+ {
+ size_t len;
+ const char *end;
+ /* absolute path */
+ end = strstr (&baseURL[strlen ("http://")], "/");
+ if (end == NULL)
+ len = strlen (&baseURL[strlen ("http://")]);
+ else
+ len = end - &baseURL[strlen ("http://")];
+ controlURL = g_strdup_printf ("http://%.*s%s",
+ len,
+ &baseURL[strlen ("http://")], tmp);
+ }
else
- len = end - &baseURL[strlen("http://")];
- controlURL = g_strdup_printf("http://%.*s%s",
- len,
- &baseURL[strlen("http://")],
- tmp);
- } else {
- controlURL = g_strdup_printf("%s%s", baseURL, tmp);
+ {
+ controlURL = g_strdup_printf ("%s%s", baseURL, tmp);
+ }
+ FREE (tmp);
}
- FREE(tmp);
- } else{
- controlURL = tmp;
- }
- FREE(baseURL);
- xmlnode_free(xmlRootNode);
+ else
+ {
+ controlURL = tmp;
+ }
+ FREE (baseURL);
+ xmlnode_free (xmlRootNode);
return controlURL;
}
@@ -337,123 +358,85 @@
/**
* Do the generic curl setup.
*/
-static int setup_curl(const char * proxy,
- CURL * curl) {
+static int
+setup_curl (const char *proxy, CURL * curl)
+{
int ret;
- CURL_EASY_SETOPT(curl,
- CURLOPT_FAILONERROR,
- 1);
- if (strlen(proxy) > 0)
- CURL_EASY_SETOPT(curl,
- CURLOPT_PROXY,
- proxy);
- CURL_EASY_SETOPT(curl,
- CURLOPT_BUFFERSIZE,
- 1024); /* a bit more than one HELLO */
- CURL_EASY_SETOPT(curl,
- CURLOPT_CONNECTTIMEOUT,
- 150L);
+ CURL_EASY_SETOPT (curl, CURLOPT_FAILONERROR, 1);
+ if (strlen (proxy) > 0)
+ CURL_EASY_SETOPT (curl, CURLOPT_PROXY, proxy);
+ CURL_EASY_SETOPT (curl, CURLOPT_BUFFERSIZE, 1024); /* a bit more than one
HELLO */
+ CURL_EASY_SETOPT (curl, CURLOPT_CONNECTTIMEOUT, 150L);
/* NOTE: use of CONNECTTIMEOUT without also
setting NOSIGNAL results in really weird
crashes on my system! */
- CURL_EASY_SETOPT(curl,
- CURLOPT_NOSIGNAL,
- 1);
+ CURL_EASY_SETOPT (curl, CURLOPT_NOSIGNAL, 1);
return OK;
}
static int
-gaim_upnp_generate_action_message_and_send(const char * proxy,
- const char* actionName,
- const char* actionParams,
- GaimUtilFetchUrlCallback cb,
- void * cb_data) {
- CURL * curl;
+gaim_upnp_generate_action_message_and_send (const char *proxy,
+ const char *actionName,
+ const char *actionParams,
+ GaimUtilFetchUrlCallback cb,
+ void *cb_data)
+{
+ CURL *curl;
int ret;
- char * soapHeader;
- char * sizeHeader;
- char * soapMessage;
- struct curl_slist * headers = NULL;
+ char *soapHeader;
+ char *sizeHeader;
+ char *soapMessage;
+ struct curl_slist *headers = NULL;
- GE_ASSERT(NULL, cb != NULL);
- if (0 != curl_global_init(CURL_GLOBAL_WIN32))
+ GE_ASSERT (NULL, cb != NULL);
+ if (0 != curl_global_init (CURL_GLOBAL_WIN32))
return SYSERR;
/* set the soap message */
- soapMessage = g_strdup_printf(SOAP_ACTION,
- actionName,
- control_info.service_type,
- actionParams,
- actionName);
- soapHeader = g_strdup_printf(HTTP_POST_SOAP_HEADER,
- control_info.service_type,
- actionName);
- sizeHeader = g_strdup_printf(HTTP_POST_SIZE_HEADER,
- strlen(soapMessage));
- curl = curl_easy_init();
- setup_curl(proxy, curl);
- CURL_EASY_SETOPT(curl,
- CURLOPT_URL,
- control_info.control_url);
- CURL_EASY_SETOPT(curl,
- CURLOPT_WRITEFUNCTION,
- cb);
- CURL_EASY_SETOPT(curl,
- CURLOPT_WRITEDATA,
- cb_data);
- CURL_EASY_SETOPT(curl,
- CURLOPT_POST,
- 1);
- headers = curl_slist_append(headers,
- "CONTENT-TYPE: text/xml ; charset=\"utf-8\"");
- headers = curl_slist_append(headers,
- soapHeader);
- headers = curl_slist_append(headers,
- sizeHeader);
- CURL_EASY_SETOPT(curl,
- CURLOPT_HTTPHEADER,
- headers);
- CURL_EASY_SETOPT(curl,
- CURLOPT_POSTFIELDS,
- soapMessage);
- CURL_EASY_SETOPT(curl,
- CURLOPT_POSTFIELDSIZE,
- strlen(soapMessage));
- CURL_EASY_SETOPT(curl,
- CURLOPT_MAXREDIRS,
- 1L);
- CURL_EASY_SETOPT(curl,
- CURLOPT_CONNECTTIMEOUT,
- 1L);
- CURL_EASY_SETOPT(curl,
- CURLOPT_TIMEOUT,
- 2L);
+ soapMessage = g_strdup_printf (SOAP_ACTION,
+ actionName,
+ control_info.service_type,
+ actionParams, actionName);
+ soapHeader = g_strdup_printf (HTTP_POST_SOAP_HEADER,
+ control_info.service_type, actionName);
+ sizeHeader = g_strdup_printf (HTTP_POST_SIZE_HEADER, strlen (soapMessage));
+ curl = curl_easy_init ();
+ setup_curl (proxy, curl);
+ CURL_EASY_SETOPT (curl, CURLOPT_URL, control_info.control_url);
+ CURL_EASY_SETOPT (curl, CURLOPT_WRITEFUNCTION, cb);
+ CURL_EASY_SETOPT (curl, CURLOPT_WRITEDATA, cb_data);
+ CURL_EASY_SETOPT (curl, CURLOPT_POST, 1);
+ headers = curl_slist_append (headers,
+ "CONTENT-TYPE: text/xml ; charset=\"utf-8\"");
+ headers = curl_slist_append (headers, soapHeader);
+ headers = curl_slist_append (headers, sizeHeader);
+ CURL_EASY_SETOPT (curl, CURLOPT_HTTPHEADER, headers);
+ CURL_EASY_SETOPT (curl, CURLOPT_POSTFIELDS, soapMessage);
+ CURL_EASY_SETOPT (curl, CURLOPT_POSTFIELDSIZE, strlen (soapMessage));
+ CURL_EASY_SETOPT (curl, CURLOPT_MAXREDIRS, 1L);
+ CURL_EASY_SETOPT (curl, CURLOPT_CONNECTTIMEOUT, 1L);
+ CURL_EASY_SETOPT (curl, CURLOPT_TIMEOUT, 2L);
/* NOTE: use of CONNECTTIMEOUT without also
setting NOSIGNAL results in really weird
crashes on my system! */
- CURL_EASY_SETOPT(curl,
- CURLOPT_NOSIGNAL,
- 1);
- if (ret == CURLE_OK)
- ret = curl_easy_perform(curl);
+ CURL_EASY_SETOPT (curl, CURLOPT_NOSIGNAL, 1);
+ if (ret == CURLE_OK)
+ ret = curl_easy_perform (curl);
#if 0
if (ret != CURLE_OK)
- GE_LOG(NULL,
- GE_ERROR | GE_ADMIN | GE_DEVELOPER | GE_BULK,
- _("%s failed for url `%s' and post-data `%s' at %s:%d: `%s'\n"),
- "curl_easy_perform",
- control_info.control_url,
- soapMessage,
- __FILE__,
- __LINE__,
- curl_easy_strerror(ret));
+ GE_LOG (NULL,
+ GE_ERROR | GE_ADMIN | GE_DEVELOPER | GE_BULK,
+ _("%s failed for url `%s' and post-data `%s' at %s:%d: `%s'\n"),
+ "curl_easy_perform",
+ control_info.control_url,
+ soapMessage, __FILE__, __LINE__, curl_easy_strerror (ret));
#endif
- curl_slist_free_all(headers);
- curl_easy_cleanup(curl);
- curl_global_cleanup();
- FREE(sizeHeader);
- FREE(soapMessage);
- FREE(soapHeader);
+ curl_slist_free_all (headers);
+ curl_easy_cleanup (curl);
+ curl_global_cleanup ();
+ FREE (sizeHeader);
+ FREE (soapMessage);
+ FREE (soapHeader);
if (ret != CURLE_OK)
return SYSERR;
return OK;
@@ -461,57 +444,42 @@
static size_t
-looked_up_public_ip_cb(void *url_data,
- size_t size,
- size_t nmemb,
- void * user_data) {
- UPnPDiscoveryData * dd = user_data;
+looked_up_public_ip_cb (void *url_data,
+ size_t size, size_t nmemb, void *user_data)
+{
+ UPnPDiscoveryData *dd = user_data;
size_t len = size * nmemb;
- const char * temp;
- const char * temp2;
+ const char *temp;
+ const char *temp2;
if (len + dd->buf_len > 1024 * 1024 * 4)
- return 0; /* refuse to process - too big! */
- GROW(dd->buf,
- dd->buf_len,
- dd->buf_len + len);
- memcpy(&dd->buf[dd->buf_len - len],
- url_data,
- len);
+ return 0; /* refuse to process - too big! */
+ GROW (dd->buf, dd->buf_len, dd->buf_len + len);
+ memcpy (&dd->buf[dd->buf_len - len], url_data, len);
if (dd->buf_len == 0)
return len;
/* extract the ip, or see if there is an error */
- if ((temp = g_strstr_len(dd->buf,
- dd->buf_len,
- "<NewExternalIPAddress")) == NULL)
+ if ((temp = g_strstr_len (dd->buf,
+ dd->buf_len, "<NewExternalIPAddress")) == NULL)
return len;
- if (!(temp = g_strstr_len(temp,
- dd->buf_len - (temp - dd->buf), ">")))
+ if (!(temp = g_strstr_len (temp, dd->buf_len - (temp - dd->buf), ">")))
return len;
- if (!(temp2 = g_strstr_len(temp,
- dd->buf_len - (temp - dd->buf), "<")))
+ if (!(temp2 = g_strstr_len (temp, dd->buf_len - (temp - dd->buf), "<")))
return len;
- memset(control_info.publicip,
- 0,
- sizeof(control_info.publicip));
- if (temp2 - temp >= sizeof(control_info.publicip))
- temp2 = temp + sizeof(control_info.publicip) - 1;
- memcpy(control_info.publicip,
- temp + 1,
- temp2 - (temp + 1));
- GE_LOG(NULL,
- GE_INFO | GE_USER | GE_BULK,
- _("upnp: NAT Returned IP: %s\n"),
- control_info.publicip);
+ memset (control_info.publicip, 0, sizeof (control_info.publicip));
+ if (temp2 - temp >= sizeof (control_info.publicip))
+ temp2 = temp + sizeof (control_info.publicip) - 1;
+ memcpy (control_info.publicip, temp + 1, temp2 - (temp + 1));
+ GE_LOG (NULL,
+ GE_INFO | GE_USER | GE_BULK,
+ _("upnp: NAT Returned IP: %s\n"), control_info.publicip);
return len;
}
static size_t
-ignore_response(void *url_data,
- size_t size,
- size_t nmemb,
- void * user_data) {
+ignore_response (void *url_data, size_t size, size_t nmemb, void *user_data)
+{
return size * nmemb;
}
@@ -519,274 +487,239 @@
* Process downloaded bits of service description.
*/
static size_t
-upnp_parse_description_cb(void * httpResponse,
- size_t size,
- size_t nmemb,
- void * user_data) {
- UPnPDiscoveryData * dd = user_data;
+upnp_parse_description_cb (void *httpResponse,
+ size_t size, size_t nmemb, void *user_data)
+{
+ UPnPDiscoveryData *dd = user_data;
size_t len = size * nmemb;
- char * control_url = NULL;
+ char *control_url = NULL;
if (len + dd->buf_len > 1024 * 1024 * 4)
- return len; /* refuse to process - too big! */
- GROW(dd->buf,
- dd->buf_len,
- dd->buf_len + len);
- memcpy(&dd->buf[dd->buf_len - len],
- httpResponse,
- len);
+ return len; /* refuse to process - too big! */
+ GROW (dd->buf, dd->buf_len, dd->buf_len + len);
+ memcpy (&dd->buf[dd->buf_len - len], httpResponse, len);
if (dd->buf_len > 0)
- control_url = gaim_upnp_parse_description_response(dd->buf,
- dd->buf_len,
- dd->full_url,
- dd->service_type);
+ control_url = gaim_upnp_parse_description_response (dd->buf,
+ dd->buf_len,
+ dd->full_url,
+ dd->service_type);
control_info.status = control_url ? GAIM_UPNP_STATUS_DISCOVERED
: GAIM_UPNP_STATUS_UNABLE_TO_DISCOVER;
- FREENONNULL(control_info.control_url);
+ FREENONNULL (control_info.control_url);
control_info.control_url = control_url;
control_info.service_type = dd->service_type;
return len;
}
static int
-gaim_upnp_parse_description(char * proxy,
- UPnPDiscoveryData * dd) {
- CURL * curl;
+gaim_upnp_parse_description (char *proxy, UPnPDiscoveryData * dd)
+{
+ CURL *curl;
int ret;
- if (0 != curl_global_init(CURL_GLOBAL_WIN32))
+ if (0 != curl_global_init (CURL_GLOBAL_WIN32))
return SYSERR;
- curl = curl_easy_init();
- setup_curl(proxy, curl);
+ curl = curl_easy_init ();
+ setup_curl (proxy, curl);
ret = CURLE_OK;
- CURL_EASY_SETOPT(curl,
- CURLOPT_URL,
- dd->full_url);
- CURL_EASY_SETOPT(curl,
- CURLOPT_WRITEFUNCTION,
- &upnp_parse_description_cb);
- CURL_EASY_SETOPT(curl,
- CURLOPT_WRITEDATA,
- dd);
- CURL_EASY_SETOPT(curl,
- CURLOPT_MAXREDIRS,
- 1L);
- CURL_EASY_SETOPT(curl,
- CURLOPT_CONNECTTIMEOUT,
- 1L);
- CURL_EASY_SETOPT(curl,
- CURLOPT_TIMEOUT,
- 2L);
+ CURL_EASY_SETOPT (curl, CURLOPT_URL, dd->full_url);
+ CURL_EASY_SETOPT (curl, CURLOPT_WRITEFUNCTION, &upnp_parse_description_cb);
+ CURL_EASY_SETOPT (curl, CURLOPT_WRITEDATA, dd);
+ CURL_EASY_SETOPT (curl, CURLOPT_MAXREDIRS, 1L);
+ CURL_EASY_SETOPT (curl, CURLOPT_CONNECTTIMEOUT, 1L);
+ CURL_EASY_SETOPT (curl, CURLOPT_TIMEOUT, 2L);
/* NOTE: use of CONNECTTIMEOUT without also
setting NOSIGNAL results in really weird
crashes on my system! */
- CURL_EASY_SETOPT(curl,
- CURLOPT_NOSIGNAL,
- 1);
- ret = curl_easy_perform(curl);
+ CURL_EASY_SETOPT (curl, CURLOPT_NOSIGNAL, 1);
+ ret = curl_easy_perform (curl);
if (ret != CURLE_OK)
- GE_LOG(NULL,
- GE_ERROR | GE_ADMIN | GE_DEVELOPER | GE_BULK,
- _("%s failed at %s:%d: `%s'\n"),
- "curl_easy_perform",
- __FILE__,
- __LINE__,
- curl_easy_strerror(ret));
- curl_easy_cleanup(curl);
- curl_global_cleanup();
+ GE_LOG (NULL,
+ GE_ERROR | GE_ADMIN | GE_DEVELOPER | GE_BULK,
+ _("%s failed at %s:%d: `%s'\n"),
+ "curl_easy_perform",
+ __FILE__, __LINE__, curl_easy_strerror (ret));
+ curl_easy_cleanup (curl);
+ curl_global_cleanup ();
if (control_info.control_url == NULL)
return SYSERR;
return OK;
}
int
-gaim_upnp_discover(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- int sock) {
- char * proxy;
- struct hostent* hp;
+gaim_upnp_discover (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, int sock)
+{
+ char *proxy;
+ struct hostent *hp;
struct sockaddr_in server;
int retry_count;
- char * sendMessage;
+ char *sendMessage;
size_t totalSize;
int sentSuccess;
char buf[65536];
int buf_len;
- const char * startDescURL;
- const char * endDescURL;
+ const char *startDescURL;
+ const char *endDescURL;
int ret;
UPnPDiscoveryData dd;
- memset(&dd,
- 0,
- sizeof(UPnPDiscoveryData));
+ memset (&dd, 0, sizeof (UPnPDiscoveryData));
if (control_info.status == GAIM_UPNP_STATUS_DISCOVERING)
return NO;
dd.sock = sock;
- hp = gethostbyname(HTTPMU_HOST_ADDRESS);
- if (hp == NULL) {
- CLOSE(dd.sock);
- return SYSERR;
- }
- memset(&server,
- 0,
- sizeof(struct sockaddr));
+ hp = gethostbyname (HTTPMU_HOST_ADDRESS);
+ if (hp == NULL)
+ {
+ CLOSE (dd.sock);
+ return SYSERR;
+ }
+ memset (&server, 0, sizeof (struct sockaddr));
server.sin_family = AF_INET;
- memcpy(&server.sin_addr,
- hp->h_addr_list[0],
- hp->h_length);
- server.sin_port = htons(HTTPMU_HOST_PORT);
+ memcpy (&server.sin_addr, hp->h_addr_list[0], hp->h_length);
+ server.sin_port = htons (HTTPMU_HOST_PORT);
control_info.status = GAIM_UPNP_STATUS_DISCOVERING;
/* because we are sending over UDP, if there is a failure
we should retry the send NUM_UDP_ATTEMPTS times. Also,
- try different requests for WANIPConnection and WANPPPConnection*/
- for (retry_count=0;retry_count<NUM_UDP_ATTEMPTS;retry_count++) {
- sentSuccess = FALSE;
- if((retry_count % 2) == 0)
- dd.service_type = WAN_IP_CONN_SERVICE;
- else
- dd.service_type = WAN_PPP_CONN_SERVICE;
- sendMessage = g_strdup_printf(SEARCH_REQUEST_STRING,
- dd.service_type);
- totalSize = strlen(sendMessage);
- do {
- if (SENDTO(dd.sock,
- sendMessage,
- totalSize,
- 0,
- (struct sockaddr*) &server,
- sizeof(struct sockaddr_in)) == totalSize) {
- sentSuccess = TRUE;
- break;
- }
- } while ( ((errno == EINTR) || (errno == EAGAIN)) &&
- (GNUNET_SHUTDOWN_TEST() == NO));
- FREE(sendMessage);
- if (sentSuccess)
- break;
- }
+ try different requests for WANIPConnection and WANPPPConnection */
+ for (retry_count = 0; retry_count < NUM_UDP_ATTEMPTS; retry_count++)
+ {
+ sentSuccess = FALSE;
+ if ((retry_count % 2) == 0)
+ dd.service_type = WAN_IP_CONN_SERVICE;
+ else
+ dd.service_type = WAN_PPP_CONN_SERVICE;
+ sendMessage = g_strdup_printf (SEARCH_REQUEST_STRING, dd.service_type);
+ totalSize = strlen (sendMessage);
+ do
+ {
+ if (SENDTO (dd.sock,
+ sendMessage,
+ totalSize,
+ 0,
+ (struct sockaddr *) &server,
+ sizeof (struct sockaddr_in)) == totalSize)
+ {
+ sentSuccess = TRUE;
+ break;
+ }
+ }
+ while (((errno == EINTR) || (errno == EAGAIN)) &&
+ (GNUNET_SHUTDOWN_TEST () == NO));
+ FREE (sendMessage);
+ if (sentSuccess)
+ break;
+ }
if (sentSuccess == FALSE)
return SYSERR;
/* try to read response */
- do {
- buf_len = recv(dd.sock,
- buf,
- sizeof(buf) - 1,
- 0);
- if (buf_len > 0) {
- buf[buf_len] = '\0';
- break;
- } else if (errno != EINTR) {
- continue;
+ do
+ {
+ buf_len = recv (dd.sock, buf, sizeof (buf) - 1, 0);
+ if (buf_len > 0)
+ {
+ buf[buf_len] = '\0';
+ break;
+ }
+ else if (errno != EINTR)
+ {
+ continue;
+ }
}
- } while ( (errno == EINTR) &&
- (GNUNET_SHUTDOWN_TEST() == NO) );
+ while ((errno == EINTR) && (GNUNET_SHUTDOWN_TEST () == NO));
/* parse the response, and see if it was a success */
- if (g_strstr_len(buf, buf_len, HTTP_OK) == NULL)
+ if (g_strstr_len (buf, buf_len, HTTP_OK) == NULL)
return SYSERR;
- if ( (startDescURL = g_strstr_len(buf, buf_len, "http://")) == NULL)
+ if ((startDescURL = g_strstr_len (buf, buf_len, "http://")) == NULL)
return SYSERR;
- endDescURL = g_strstr_len(startDescURL,
- buf_len - (startDescURL - buf),
- "\r");
+ endDescURL = g_strstr_len (startDescURL,
+ buf_len - (startDescURL - buf), "\r");
if (endDescURL == NULL)
- endDescURL = g_strstr_len(startDescURL,
- buf_len - (startDescURL - buf), "\n");
- if(endDescURL == NULL)
+ endDescURL = g_strstr_len (startDescURL,
+ buf_len - (startDescURL - buf), "\n");
+ if (endDescURL == NULL)
return SYSERR;
if (endDescURL == startDescURL)
return SYSERR;
- dd.full_url = STRNDUP(startDescURL,
- endDescURL - startDescURL);
+ dd.full_url = STRNDUP (startDescURL, endDescURL - startDescURL);
proxy = NULL;
- GC_get_configuration_value_string(cfg,
- "GNUNETD",
- "HTTP-PROXY",
- "",
- &proxy);
- ret = gaim_upnp_parse_description(proxy,
- &dd);
- FREE(dd.full_url);
- GROW(dd.buf,
- dd.buf_len,
- 0);
- if (ret == OK) {
- ret = gaim_upnp_generate_action_message_and_send(proxy,
- "GetExternalIPAddress",
- "",
- looked_up_public_ip_cb,
- &dd);
- GROW(dd.buf,
- dd.buf_len,
- 0);
- }
- FREE(proxy);
+ GC_get_configuration_value_string (cfg,
+ "GNUNETD", "HTTP-PROXY", "", &proxy);
+ ret = gaim_upnp_parse_description (proxy, &dd);
+ FREE (dd.full_url);
+ GROW (dd.buf, dd.buf_len, 0);
+ if (ret == OK)
+ {
+ ret = gaim_upnp_generate_action_message_and_send (proxy,
+ "GetExternalIPAddress",
+ "",
+ looked_up_public_ip_cb,
+ &dd);
+ GROW (dd.buf, dd.buf_len, 0);
+ }
+ FREE (proxy);
return ret;
}
const char *
-gaim_upnp_get_public_ip() {
+gaim_upnp_get_public_ip ()
+{
if (control_info.status == GAIM_UPNP_STATUS_DISCOVERED
- && control_info.publicip
- && strlen(control_info.publicip) > 0)
+ && control_info.publicip && strlen (control_info.publicip) > 0)
return control_info.publicip;
return NULL;
}
int
-gaim_upnp_change_port_mapping(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- int do_add,
- unsigned short portmap,
- const char* protocol) {
- const char * action_name;
- char * action_params;
- char * internal_ip;
- char * proxy;
+gaim_upnp_change_port_mapping (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ int do_add,
+ unsigned short portmap, const char *protocol)
+{
+ const char *action_name;
+ char *action_params;
+ char *internal_ip;
+ char *proxy;
int ret;
if (control_info.status != GAIM_UPNP_STATUS_DISCOVERED)
return NO;
- if (do_add) {
- internal_ip = gaim_upnp_get_internal_ip(cfg,
- ectx);
- if (internal_ip == NULL) {
- gaim_debug_error("upnp",
- "gaim_upnp_set_port_mapping(): couldn't get local ip\n");
- return NO;
+ if (do_add)
+ {
+ internal_ip = gaim_upnp_get_internal_ip (cfg, ectx);
+ if (internal_ip == NULL)
+ {
+ gaim_debug_error ("upnp",
+ "gaim_upnp_set_port_mapping(): couldn't get local
ip\n");
+ return NO;
+ }
+ action_name = "AddPortMapping";
+ action_params = g_strdup_printf (ADD_PORT_MAPPING_PARAMS,
+ portmap,
+ protocol, portmap, internal_ip);
+ FREE (internal_ip);
}
- action_name = "AddPortMapping";
- action_params = g_strdup_printf(ADD_PORT_MAPPING_PARAMS,
- portmap,
- protocol,
- portmap,
- internal_ip);
- FREE(internal_ip);
- } else {
- action_name = "DeletePortMapping";
- action_params = g_strdup_printf(DELETE_PORT_MAPPING_PARAMS,
- portmap,
- protocol);
- }
+ else
+ {
+ action_name = "DeletePortMapping";
+ action_params = g_strdup_printf (DELETE_PORT_MAPPING_PARAMS,
+ portmap, protocol);
+ }
proxy = NULL;
- GC_get_configuration_value_string(cfg,
- "GNUNETD",
- "HTTP-PROXY",
- "",
- &proxy);
- ret = gaim_upnp_generate_action_message_and_send(proxy,
- action_name,
- action_params,
- &ignore_response,
- NULL);
+ GC_get_configuration_value_string (cfg,
+ "GNUNETD", "HTTP-PROXY", "", &proxy);
+ ret = gaim_upnp_generate_action_message_and_send (proxy,
+ action_name,
+ action_params,
+ &ignore_response, NULL);
- FREE(action_params);
- FREE(proxy);
+ FREE (action_params);
+ FREE (proxy);
return ret;
}
Modified: GNUnet/src/transports/upnp/upnp.h
===================================================================
--- GNUnet/src/transports/upnp/upnp.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/upnp/upnp.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -32,8 +32,9 @@
#include "gnunet_util_cron.h"
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -44,9 +45,8 @@
* public IP address of the IGD, and control it for forwarding ports.
* The result will be cached for further use.
*/
-int gaim_upnp_discover(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- int sock);
+int gaim_upnp_discover (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, int sock);
/**
* Gets the IP address from a UPnP enabled IGD that sits on the local
@@ -56,7 +56,7 @@
*
* @return The IP address of the network, or NULL if something went wrong
*/
-const char * gaim_upnp_get_public_ip(void);
+const char *gaim_upnp_get_public_ip (void);
/**
* Maps Ports in a UPnP enabled IGD that sits on the local network to
@@ -70,13 +70,13 @@
* addition is complete
* @param cb_data Extra data to be passed to the callback
*/
-int gaim_upnp_change_port_mapping(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- int do_add,
- unsigned short portmap,
- const char* protocol);
+int gaim_upnp_change_port_mapping (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ int do_add,
+ unsigned short portmap,
+ const char *protocol);
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/transports/upnp/upnptest.c
===================================================================
--- GNUnet/src/transports/upnp/upnptest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/transports/upnp/upnptest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -32,74 +32,76 @@
-int main(int argc,
- const char *argv[]) {
+int
+main (int argc, const char *argv[])
+{
static CoreAPIForApplication capi;
- struct GE_Context * ectx;
- struct GC_Configuration * cfg;
+ struct GE_Context *ectx;
+ struct GC_Configuration *cfg;
IPaddr addr;
int i;
- UPnP_ServiceAPI * upnp;
- struct PluginHandle * plug;
+ UPnP_ServiceAPI *upnp;
+ struct PluginHandle *plug;
ServiceInitMethod init;
ServiceDoneMethod done;
- ectx = GE_create_context_stderr(NO,
- GE_WARNING | GE_ERROR | GE_FATAL |
- GE_USER | GE_ADMIN | GE_DEVELOPER |
- GE_IMMEDIATE | GE_BULK);
- GE_setDefaultContext(ectx);
- cfg = GC_create_C_impl();
- GE_ASSERT(ectx, cfg != NULL);
- os_init(ectx);
+ ectx = GE_create_context_stderr (NO,
+ GE_WARNING | GE_ERROR | GE_FATAL |
+ GE_USER | GE_ADMIN | GE_DEVELOPER |
+ GE_IMMEDIATE | GE_BULK);
+ GE_setDefaultContext (ectx);
+ cfg = GC_create_C_impl ();
+ GE_ASSERT (ectx, cfg != NULL);
+ os_init (ectx);
capi.ectx = ectx;
capi.cfg = cfg;
- plug = os_plugin_load(ectx, "libgnunet", "module_upnp");
- if (plug == NULL) {
- GC_free(cfg);
- GE_free_context(ectx);
- return 1;
- }
- init = os_plugin_resolve_function(plug,
- "provide_",
- YES);
- if (init == NULL) {
- os_plugin_unload(plug);
- GC_free(cfg);
- GE_free_context(ectx);
- return 1;
- }
- upnp = init(&capi);
- if (upnp == NULL) {
- os_plugin_unload(plug);
- GC_free(cfg);
- GE_free_context(ectx);
- return 1;
- }
- for (i=0;i<10;i++) {
- if (GNUNET_SHUTDOWN_TEST() != NO)
- break;
- if (OK == upnp->get_ip(2086,
- "TCP",
- &addr)) {
- printf("UPnP returned external IP %u.%u.%u.%u\n",
- PRIP(ntohl(*(int*)&addr)));
- } else {
- /* we cannot be sure that there is a UPnP-capable
- NAT-box out there, so test should not fail
- just because of this! */
- printf("No UPnP response (yet).\n");
+ plug = os_plugin_load (ectx, "libgnunet", "module_upnp");
+ if (plug == NULL)
+ {
+ GC_free (cfg);
+ GE_free_context (ectx);
+ return 1;
}
- PTHREAD_SLEEP(2 * cronSECONDS);
- }
- done = os_plugin_resolve_function(plug,
- "release_",
- YES);
+ init = os_plugin_resolve_function (plug, "provide_", YES);
+ if (init == NULL)
+ {
+ os_plugin_unload (plug);
+ GC_free (cfg);
+ GE_free_context (ectx);
+ return 1;
+ }
+ upnp = init (&capi);
+ if (upnp == NULL)
+ {
+ os_plugin_unload (plug);
+ GC_free (cfg);
+ GE_free_context (ectx);
+ return 1;
+ }
+ for (i = 0; i < 10; i++)
+ {
+ if (GNUNET_SHUTDOWN_TEST () != NO)
+ break;
+ if (OK == upnp->get_ip (2086, "TCP", &addr))
+ {
+ printf ("UPnP returned external IP %u.%u.%u.%u\n",
+ PRIP (ntohl (*(int *) &addr)));
+ }
+ else
+ {
+ /* we cannot be sure that there is a UPnP-capable
+ NAT-box out there, so test should not fail
+ just because of this! */
+ printf ("No UPnP response (yet).\n");
+ }
+ PTHREAD_SLEEP (2 * cronSECONDS);
+ }
+ done = os_plugin_resolve_function (plug, "release_", YES);
if (done != NULL)
- done();
- os_plugin_unload(plug);
- GC_free(cfg);
- GE_free_context(ectx);
+ done ();
+ os_plugin_unload (plug);
+ GC_free (cfg);
+ GE_free_context (ectx);
return 0;
}
Modified: GNUnet/src/transports/upnp/util.c
===================================================================
--- GNUnet/src/transports/upnp/util.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/upnp/util.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -28,8 +28,8 @@
/* Returns a NULL-terminated string after unescaping an entity
* (eg. &, < & etc.) starting at s. Returns NULL on failure.*/
static char *
-detect_entity(const char *text,
- int *length) {
+detect_entity (const char *text, int *length)
+{
const char *pln;
int len;
int pound;
@@ -39,102 +39,114 @@
#define IS_ENTITY(s) (!strncasecmp(text, s, (len = sizeof(s) - 1)))
- if(IS_ENTITY("&"))
+ if (IS_ENTITY ("&"))
pln = "&";
- else if(IS_ENTITY("<"))
+ else if (IS_ENTITY ("<"))
pln = "<";
- else if(IS_ENTITY(">"))
+ else if (IS_ENTITY (">"))
pln = ">";
- else if(IS_ENTITY(" "))
+ else if (IS_ENTITY (" "))
pln = " ";
- else if(IS_ENTITY("©"))
- pln = "\302\251"; /* or use g_unichar_to_utf8(0xa9); */
- else if(IS_ENTITY("""))
+ else if (IS_ENTITY ("©"))
+ pln = "\302\251"; /* or use g_unichar_to_utf8(0xa9); */
+ else if (IS_ENTITY ("""))
pln = "\"";
- else if(IS_ENTITY("®"))
- pln = "\302\256"; /* or use g_unichar_to_utf8(0xae); */
- else if(IS_ENTITY("'"))
+ else if (IS_ENTITY ("®"))
+ pln = "\302\256"; /* or use g_unichar_to_utf8(0xae); */
+ else if (IS_ENTITY ("'"))
pln = "\'";
- else if(*(text+1) == '#' && (sscanf(text, "&#%u;", £) == 1) &&
- pound != 0 && *(text+3+(int)log10(pound)) == ';') {
- char b[7];
- char * buf = string_convertToUtf8(NULL,
- (const char*) £,
- 2,
- "UNICODE");
- if (strlen(buf) > 6)
- buf[6] = '\0';
- strcpy(b, buf);
- pln = b;
- FREE(buf);
- len = 2;
- while (isdigit((int) text[len]))
- len++;
- if (text[len] == ';') len++;
- } else
+ else if (*(text + 1) == '#' && (sscanf (text, "&#%u;", £) == 1) &&
+ pound != 0 && *(text + 3 + (int) log10 (pound)) == ';')
+ {
+ char b[7];
+ char *buf = string_convertToUtf8 (NULL,
+ (const char *) £,
+ 2,
+ "UNICODE");
+ if (strlen (buf) > 6)
+ buf[6] = '\0';
+ strcpy (b, buf);
+ pln = b;
+ FREE (buf);
+ len = 2;
+ while (isdigit ((int) text[len]))
+ len++;
+ if (text[len] == ';')
+ len++;
+ }
+ else
return NULL;
if (length)
*length = len;
- return STRDUP(pln);
+ return STRDUP (pln);
}
char *
-g_strdup_printf(const char * fmt,
- ...) {
+g_strdup_printf (const char *fmt, ...)
+{
size_t size;
- char * buf;
+ char *buf;
va_list va;
- va_start(va, fmt);
- size = VSNPRINTF(NULL, 0, fmt, va) + 1;
- va_end(va);
- buf = malloc(size);
- va_start(va, fmt);
- VSNPRINTF(buf, size, fmt, va);
- va_end(va);
+ va_start (va, fmt);
+ size = VSNPRINTF (NULL, 0, fmt, va) + 1;
+ va_end (va);
+ buf = malloc (size);
+ va_start (va, fmt);
+ VSNPRINTF (buf, size, fmt, va);
+ va_end (va);
return buf;
}
char *
-gaim_unescape_html(const char *html) {
- if (html != NULL) {
- const char *c = html;
- char *ret = STRDUP("");
- char *app;
- while (*c) {
- int len;
- char *ent;
+gaim_unescape_html (const char *html)
+{
+ if (html != NULL)
+ {
+ const char *c = html;
+ char *ret = STRDUP ("");
+ char *app;
+ while (*c)
+ {
+ int len;
+ char *ent;
- if ((ent = detect_entity(c, &len)) != NULL) {
- app = g_strdup_printf("%s%s", ret, ent);
- FREE(ret);
- ret = app;
- c += len;
- FREE(ent);
- } else if (!strncmp(c, "<br>", 4)) {
- app = g_strdup_printf("%s%s", ret, "\n");
- FREE(ret);
- ret = app;
- c += 4;
- } else {
- app = g_strdup_printf("%s%c", ret, *c);
- FREE(ret);
- ret = app;
- c++;
- }
+ if ((ent = detect_entity (c, &len)) != NULL)
+ {
+ app = g_strdup_printf ("%s%s", ret, ent);
+ FREE (ret);
+ ret = app;
+ c += len;
+ FREE (ent);
+ }
+ else if (!strncmp (c, "<br>", 4))
+ {
+ app = g_strdup_printf ("%s%s", ret, "\n");
+ FREE (ret);
+ ret = app;
+ c += 4;
+ }
+ else
+ {
+ app = g_strdup_printf ("%s%c", ret, *c);
+ FREE (ret);
+ ret = app;
+ c++;
+ }
+ }
+ return ret;
}
- return ret;
- }
return NULL;
}
int
-gaim_str_has_prefix(const char *s, const char *p) {
- if ( (s == NULL) || (p == NULL) )
+gaim_str_has_prefix (const char *s, const char *p)
+{
+ if ((s == NULL) || (p == NULL))
return 0;
- return ! strncmp(s, p, strlen(p));
+ return !strncmp (s, p, strlen (p));
}
/* end of util.c */
Modified: GNUnet/src/transports/upnp/util.h
===================================================================
--- GNUnet/src/transports/upnp/util.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/transports/upnp/util.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -32,7 +32,8 @@
#include <string.h>
#ifdef __cplusplus
-extern "C" {
+extern "C"
+{
#endif
/**
@@ -45,7 +46,7 @@
*
* @return the text with HTML entities literalized
*/
-char *gaim_unescape_html(const char *html);
+ char *gaim_unescape_html (const char *html);
/**
* Compares two strings to see if the first contains the second as
@@ -56,10 +57,9 @@
*
* @return TRUE if p is a prefix of s, otherwise FALSE.
*/
-int gaim_str_has_prefix(const char *s, const char *p);
+ int gaim_str_has_prefix (const char *s, const char *p);
-char * g_strdup_printf(const char * fmt,
- ...);
+ char *g_strdup_printf (const char *fmt, ...);
#ifdef __cplusplus
}
Modified: GNUnet/src/transports/upnp/xmlnode.c
===================================================================
--- GNUnet/src/transports/upnp/xmlnode.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/transports/upnp/xmlnode.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -52,91 +52,87 @@
/**
* The valid types for an xmlnode
*/
-typedef enum _XMLNodeType {
- XMLNODE_TYPE_TAG, /**< Just a tag */
- XMLNODE_TYPE_ATTRIB, /**< Has attributes */
- XMLNODE_TYPE_DATA /**< Has data */
+typedef enum _XMLNodeType
+{
+ XMLNODE_TYPE_TAG, /**< Just a tag */
+ XMLNODE_TYPE_ATTRIB, /**< Has attributes */
+ XMLNODE_TYPE_DATA /**< Has data */
} XMLNodeType;
-typedef struct {
- xmlnode * current;
- xmlnode ** nodes;
+typedef struct
+{
+ xmlnode *current;
+ xmlnode **nodes;
unsigned int pos;
unsigned int size;
} XMLNodePool;
-struct _xmlnode {
- char *name; /**< The name of the node. */
- char *xmlns; /**< The namespace of the node */
- XMLNodeType type; /**< The type of the node. */
- char *data; /**< The data for the node. */
- size_t data_sz; /**< The size of the data. */
+struct _xmlnode
+{
+ char *name; /**< The name of the node. */
+ char *xmlns; /**< The namespace of the node */
+ XMLNodeType type; /**< The type of the node. */
+ char *data; /**< The data for the node. */
+ size_t data_sz; /**< The size of the data. */
struct _xmlnode *parent; /**< The parent node or @c NULL.*/
- struct _xmlnode *child; /**< The child node or @c NULL.*/
+ struct _xmlnode *child; /**< The child node or @c NULL.*/
struct _xmlnode *lastchild; /**< The last child node or @c NULL.*/
- struct _xmlnode *next; /**< The next node or @c NULL. */
- XMLNodePool * pool;
- int free_pool; /* set to YES for the root node, which must free the pool */
+ struct _xmlnode *next; /**< The next node or @c NULL. */
+ XMLNodePool *pool;
+ int free_pool; /* set to YES for the root node, which must
free the pool */
};
-static void * g_memdup(const void * data,
- size_t s) {
- void * ret;
+static void *
+g_memdup (const void *data, size_t s)
+{
+ void *ret;
- ret = MALLOC(s);
- memcpy(ret, data, s);
+ ret = MALLOC (s);
+ memcpy (ret, data, s);
return ret;
}
-static char * g_string_append_len(char * prefix,
- const void * data,
- size_t s) {
- char * ret;
+static char *
+g_string_append_len (char *prefix, const void *data, size_t s)
+{
+ char *ret;
- ret = g_strdup_printf("%s%.*s",
- prefix,
- s,
- data);
- FREE(prefix);
+ ret = g_strdup_printf ("%s%.*s", prefix, s, data);
+ FREE (prefix);
return ret;
}
-static xmlnode*
-new_node(const char *name,
- XMLNodeType type,
- void * user_data) {
- xmlnode *node = MALLOC(sizeof(xmlnode));
+static xmlnode *
+new_node (const char *name, XMLNodeType type, void *user_data)
+{
+ xmlnode *node = MALLOC (sizeof (xmlnode));
- node->name = name == NULL ? NULL : STRDUP(name);
+ node->name = name == NULL ? NULL : STRDUP (name);
node->type = type;
node->pool = user_data;
if (node->pool->size == node->pool->pos)
- GROW(node->pool->nodes,
- node->pool->size,
- node->pool->size * 2 + 64);
+ GROW (node->pool->nodes, node->pool->size, node->pool->size * 2 + 64);
node->pool->nodes[node->pool->pos++] = node;
node->free_pool = 0;
return node;
}
-static xmlnode*
-xmlnode_new(const char *name,
- void * user_data) {
- g_return_val_if_fail(name != NULL, NULL);
- return new_node(name,
- XMLNODE_TYPE_TAG,
- user_data);
+static xmlnode *
+xmlnode_new (const char *name, void *user_data)
+{
+ g_return_val_if_fail (name != NULL, NULL);
+ return new_node (name, XMLNODE_TYPE_TAG, user_data);
}
static void
-xmlnode_insert_child(xmlnode *parent,
- xmlnode *child) {
- g_return_if_fail(parent != NULL);
- g_return_if_fail(child != NULL);
+xmlnode_insert_child (xmlnode * parent, xmlnode * child)
+{
+ g_return_if_fail (parent != NULL);
+ g_return_if_fail (child != NULL);
child->parent = parent;
- if(parent->lastchild)
+ if (parent->lastchild)
parent->lastchild->next = child;
else
parent->child = child;
@@ -144,120 +140,127 @@
}
static xmlnode *
-xmlnode_new_child(xmlnode *parent,
- const char *name,
- void * user_data) {
+xmlnode_new_child (xmlnode * parent, const char *name, void *user_data)
+{
xmlnode *node;
- g_return_val_if_fail(parent != NULL, NULL);
- g_return_val_if_fail(name != NULL, NULL);
- node = new_node(name, XMLNODE_TYPE_TAG, user_data);
- xmlnode_insert_child(parent, node);
+ g_return_val_if_fail (parent != NULL, NULL);
+ g_return_val_if_fail (name != NULL, NULL);
+ node = new_node (name, XMLNODE_TYPE_TAG, user_data);
+ xmlnode_insert_child (parent, node);
return node;
}
static void
-xmlnode_insert_data(xmlnode *node,
- const char *data,
- int size,
- void * user_data) {
+xmlnode_insert_data (xmlnode * node,
+ const char *data, int size, void *user_data)
+{
xmlnode *child;
size_t real_size;
- g_return_if_fail(node != NULL);
- g_return_if_fail(data != NULL);
- g_return_if_fail(size != 0);
- real_size = size == -1 ? strlen(data) : size;
- child = new_node(NULL, XMLNODE_TYPE_DATA, user_data);
- child->data = g_memdup(data, real_size);
+ g_return_if_fail (node != NULL);
+ g_return_if_fail (data != NULL);
+ g_return_if_fail (size != 0);
+ real_size = size == -1 ? strlen (data) : size;
+ child = new_node (NULL, XMLNODE_TYPE_DATA, user_data);
+ child->data = g_memdup (data, real_size);
child->data_sz = real_size;
- xmlnode_insert_child(node, child);
+ xmlnode_insert_child (node, child);
}
static void
-xmlnode_remove_attrib(xmlnode *node,
- const char *attr) {
+xmlnode_remove_attrib (xmlnode * node, const char *attr)
+{
xmlnode *attr_node, *sibling = NULL;
- g_return_if_fail(node != NULL);
- g_return_if_fail(attr != NULL);
+ g_return_if_fail (node != NULL);
+ g_return_if_fail (attr != NULL);
- for(attr_node = node->child; attr_node; attr_node = attr_node->next) {
- if(attr_node->type == XMLNODE_TYPE_ATTRIB &&
- !strcmp(attr_node->name, attr)) {
- if(node->child == attr_node) {
- node->child = attr_node->next;
- } else {
- sibling->next = attr_node->next;
- }
- if (node->lastchild == attr_node) {
- node->lastchild = sibling;
- }
- xmlnode_free(attr_node);
- return;
+ for (attr_node = node->child; attr_node; attr_node = attr_node->next)
+ {
+ if (attr_node->type == XMLNODE_TYPE_ATTRIB &&
+ !strcmp (attr_node->name, attr))
+ {
+ if (node->child == attr_node)
+ {
+ node->child = attr_node->next;
+ }
+ else
+ {
+ sibling->next = attr_node->next;
+ }
+ if (node->lastchild == attr_node)
+ {
+ node->lastchild = sibling;
+ }
+ xmlnode_free (attr_node);
+ return;
+ }
+ sibling = attr_node;
}
- sibling = attr_node;
- }
}
static void
-xmlnode_set_attrib(xmlnode *node,
- const char *attr,
- const char *value,
- void * user_data) {
+xmlnode_set_attrib (xmlnode * node,
+ const char *attr, const char *value, void *user_data)
+{
xmlnode *attrib_node;
- g_return_if_fail(node != NULL);
- g_return_if_fail(attr != NULL);
- g_return_if_fail(value != NULL);
- xmlnode_remove_attrib(node, attr);
- attrib_node = new_node(attr, XMLNODE_TYPE_ATTRIB, user_data);
- attrib_node->data = STRDUP(value);
- xmlnode_insert_child(node, attrib_node);
+ g_return_if_fail (node != NULL);
+ g_return_if_fail (attr != NULL);
+ g_return_if_fail (value != NULL);
+ xmlnode_remove_attrib (node, attr);
+ attrib_node = new_node (attr, XMLNODE_TYPE_ATTRIB, user_data);
+ attrib_node->data = STRDUP (value);
+ xmlnode_insert_child (node, attrib_node);
}
-static void xmlnode_set_namespace(xmlnode *node,
- const char *xmlns) {
- g_return_if_fail(node != NULL);
- FREENONNULL(node->xmlns);
- node->xmlns = STRDUP(xmlns);
+static void
+xmlnode_set_namespace (xmlnode * node, const char *xmlns)
+{
+ g_return_if_fail (node != NULL);
+ FREENONNULL (node->xmlns);
+ node->xmlns = STRDUP (xmlns);
}
-static const char *xmlnode_get_namespace(xmlnode *node) {
- g_return_val_if_fail(node != NULL, NULL);
+static const char *
+xmlnode_get_namespace (xmlnode * node)
+{
+ g_return_val_if_fail (node != NULL, NULL);
return node->xmlns;
}
static void
-freePool(XMLNodePool * pool) {
+freePool (XMLNodePool * pool)
+{
unsigned int i;
- xmlnode * x;
+ xmlnode *x;
- for (i=0;i<pool->pos;i++) {
- x = pool->nodes[i];
- FREENONNULL(x->name);
- FREENONNULL(x->data);
- FREENONNULL(x->xmlns);
- FREE(x);
- }
- GROW(pool->nodes,
- pool->size,
- 0);
- FREE(pool);
+ for (i = 0; i < pool->pos; i++)
+ {
+ x = pool->nodes[i];
+ FREENONNULL (x->name);
+ FREENONNULL (x->data);
+ FREENONNULL (x->xmlns);
+ FREE (x);
+ }
+ GROW (pool->nodes, pool->size, 0);
+ FREE (pool);
}
void
-xmlnode_free(xmlnode *node) {
- g_return_if_fail(node != NULL);
+xmlnode_free (xmlnode * node)
+{
+ g_return_if_fail (node != NULL);
if (node->free_pool != YES)
return;
- freePool(node->pool);
+ freePool (node->pool);
}
static xmlnode *
-xmlnode_get_child_with_namespace(const xmlnode *parent,
- const char *name,
- const char *ns) {
+xmlnode_get_child_with_namespace (const xmlnode * parent,
+ const char *name, const char *ns)
+{
xmlnode *x;
xmlnode *ret = NULL;
char *parent_name;
@@ -268,54 +271,60 @@
if (name == NULL)
return NULL;
- parent_name = STRDUP(name);
- child_name = strstr(parent_name, "/");
- if (child_name != NULL) {
- child_name[0] = '\0';
- child_name++;
- }
+ parent_name = STRDUP (name);
+ child_name = strstr (parent_name, "/");
+ if (child_name != NULL)
+ {
+ child_name[0] = '\0';
+ child_name++;
+ }
- for(x = parent->child; x; x = x->next) {
- const char *xmlns = NULL;
- if(ns)
- xmlns = xmlnode_get_namespace(x);
+ for (x = parent->child; x; x = x->next)
+ {
+ const char *xmlns = NULL;
+ if (ns)
+ xmlns = xmlnode_get_namespace (x);
- if(x->type == XMLNODE_TYPE_TAG && name && !strcmp(parent_name, x->name)
- && (!ns || (xmlns && !strcmp(ns, xmlns)))) {
- ret = x;
- break;
+ if (x->type == XMLNODE_TYPE_TAG && name
+ && !strcmp (parent_name, x->name) && (!ns
+ || (xmlns
+ && !strcmp (ns, xmlns))))
+ {
+ ret = x;
+ break;
+ }
}
- }
if (child_name && ret)
- ret = xmlnode_get_child(ret, child_name);
+ ret = xmlnode_get_child (ret, child_name);
- FREE(parent_name);
+ FREE (parent_name);
return ret;
}
-xmlnode*
-xmlnode_get_child(const xmlnode *parent,
- const char *name) {
- return xmlnode_get_child_with_namespace(parent,
- name,
- NULL);
+xmlnode *
+xmlnode_get_child (const xmlnode * parent, const char *name)
+{
+ return xmlnode_get_child_with_namespace (parent, name, NULL);
}
char *
-xmlnode_get_data(xmlnode *node) {
+xmlnode_get_data (xmlnode * node)
+{
char *str = NULL;
xmlnode *c;
if (node == NULL)
return NULL;
- for(c = node->child; c; c = c->next) {
- if(c->type == XMLNODE_TYPE_DATA) {
- if(!str)
- str = STRDUP("");
- str = g_string_append_len(str, c->data, c->data_sz);
+ for (c = node->child; c; c = c->next)
+ {
+ if (c->type == XMLNODE_TYPE_DATA)
+ {
+ if (!str)
+ str = STRDUP ("");
+ str = g_string_append_len (str, c->data, c->data_sz);
+ }
}
- }
if (str == NULL)
return NULL;
@@ -323,15 +332,16 @@
}
static void
-xmlnode_parser_element_start_libxml(void *user_data,
- const xmlChar *element_name,
- const xmlChar *prefix,
- const xmlChar *xmlns,
- int nb_namespaces,
- const xmlChar **namespaces,
- int nb_attributes,
- int nb_defaulted,
- const xmlChar **attributes) {
+xmlnode_parser_element_start_libxml (void *user_data,
+ const xmlChar * element_name,
+ const xmlChar * prefix,
+ const xmlChar * xmlns,
+ int nb_namespaces,
+ const xmlChar ** namespaces,
+ int nb_attributes,
+ int nb_defaulted,
+ const xmlChar ** attributes)
+{
XMLNodePool *xpd = user_data;
xmlnode *node;
int i;
@@ -339,133 +349,138 @@
if (!element_name)
return;
if (xpd->current)
- node = xmlnode_new_child(xpd->current, (const char*) element_name,
user_data);
+ node =
+ xmlnode_new_child (xpd->current, (const char *) element_name,
+ user_data);
else
- node = xmlnode_new((const char *) element_name, user_data);
+ node = xmlnode_new ((const char *) element_name, user_data);
- xmlnode_set_namespace(node, (const char *) xmlns);
+ xmlnode_set_namespace (node, (const char *) xmlns);
- for(i=0; i < nb_attributes * 5; i+=5) {
- char *txt;
- int attrib_len = attributes[i+4] - attributes[i+3];
- char *attrib = MALLOC(attrib_len + 1);
- memcpy(attrib, attributes[i+3], attrib_len);
- attrib[attrib_len] = '\0';
- txt = attrib;
- attrib = gaim_unescape_html(txt);
- FREE(txt);
- xmlnode_set_attrib(node, (const char*) attributes[i], attrib, user_data);
- FREE(attrib);
- }
+ for (i = 0; i < nb_attributes * 5; i += 5)
+ {
+ char *txt;
+ int attrib_len = attributes[i + 4] - attributes[i + 3];
+ char *attrib = MALLOC (attrib_len + 1);
+ memcpy (attrib, attributes[i + 3], attrib_len);
+ attrib[attrib_len] = '\0';
+ txt = attrib;
+ attrib = gaim_unescape_html (txt);
+ FREE (txt);
+ xmlnode_set_attrib (node, (const char *) attributes[i], attrib,
+ user_data);
+ FREE (attrib);
+ }
xpd->current = node;
}
static void
-xmlnode_parser_element_end_libxml(void *user_data,
- const xmlChar *element_name,
- const xmlChar *prefix,
- const xmlChar *xmlns) {
+xmlnode_parser_element_end_libxml (void *user_data,
+ const xmlChar * element_name,
+ const xmlChar * prefix,
+ const xmlChar * xmlns)
+{
XMLNodePool *xpd = user_data;
- if(!element_name || !xpd->current)
+ if (!element_name || !xpd->current)
return;
- if(xpd->current->parent) {
- if(!xmlStrcmp((xmlChar*) xpd->current->name, element_name))
- xpd->current = xpd->current->parent;
- }
+ if (xpd->current->parent)
+ {
+ if (!xmlStrcmp ((xmlChar *) xpd->current->name, element_name))
+ xpd->current = xpd->current->parent;
+ }
}
static void
-xmlnode_parser_element_text_libxml(void *user_data,
- const xmlChar *text,
- int text_len) {
+xmlnode_parser_element_text_libxml (void *user_data,
+ const xmlChar * text, int text_len)
+{
XMLNodePool *xpd = user_data;
if (!xpd->current || !text || !text_len)
return;
- xmlnode_insert_data(xpd->current,
- (const char*) text,
- text_len,
- user_data);
+ xmlnode_insert_data (xpd->current,
+ (const char *) text, text_len, user_data);
}
static xmlSAXHandler xmlnode_parser_libxml = {
- .internalSubset = NULL,
- .isStandalone = NULL,
- .hasInternalSubset = NULL,
- .hasExternalSubset = NULL,
- .resolveEntity = NULL,
- .getEntity = NULL,
- .entityDecl = NULL,
- .notationDecl = NULL,
- .attributeDecl = NULL,
- .elementDecl = NULL,
- .unparsedEntityDecl = NULL,
- .setDocumentLocator = NULL,
- .startDocument = NULL,
- .endDocument = NULL,
- .startElement = NULL,
- .endElement = NULL,
- .reference = NULL,
- .characters = xmlnode_parser_element_text_libxml,
- .ignorableWhitespace = NULL,
- .processingInstruction = NULL,
- .comment = NULL,
- .warning = NULL,
- .error = NULL,
- .fatalError = NULL,
- .getParameterEntity = NULL,
- .cdataBlock = NULL,
- .externalSubset = NULL,
- .initialized = XML_SAX2_MAGIC,
- ._private = NULL,
- .startElementNs = xmlnode_parser_element_start_libxml,
- .endElementNs = xmlnode_parser_element_end_libxml,
- .serror = NULL
+ .internalSubset = NULL,
+ .isStandalone = NULL,
+ .hasInternalSubset = NULL,
+ .hasExternalSubset = NULL,
+ .resolveEntity = NULL,
+ .getEntity = NULL,
+ .entityDecl = NULL,
+ .notationDecl = NULL,
+ .attributeDecl = NULL,
+ .elementDecl = NULL,
+ .unparsedEntityDecl = NULL,
+ .setDocumentLocator = NULL,
+ .startDocument = NULL,
+ .endDocument = NULL,
+ .startElement = NULL,
+ .endElement = NULL,
+ .reference = NULL,
+ .characters = xmlnode_parser_element_text_libxml,
+ .ignorableWhitespace = NULL,
+ .processingInstruction = NULL,
+ .comment = NULL,
+ .warning = NULL,
+ .error = NULL,
+ .fatalError = NULL,
+ .getParameterEntity = NULL,
+ .cdataBlock = NULL,
+ .externalSubset = NULL,
+ .initialized = XML_SAX2_MAGIC,
+ ._private = NULL,
+ .startElementNs = xmlnode_parser_element_start_libxml,
+ .endElementNs = xmlnode_parser_element_end_libxml,
+ .serror = NULL
};
xmlnode *
-xmlnode_from_str(const char *str,
- int size) {
+xmlnode_from_str (const char *str, int size)
+{
XMLNodePool *xpd;
xmlnode *ret;
size_t real_size;
- g_return_val_if_fail(str != NULL, NULL);
+ g_return_val_if_fail (str != NULL, NULL);
- real_size = size < 0 ? strlen(str) : size;
- xpd = MALLOC(sizeof(XMLNodePool));
- memset(xpd,
- 0,
- sizeof(XMLNodePool));
- if (xmlSAXUserParseMemory(&xmlnode_parser_libxml,
- xpd,
- str,
- real_size) < 0) {
- freePool(xpd);
- return NULL;
- }
+ real_size = size < 0 ? strlen (str) : size;
+ xpd = MALLOC (sizeof (XMLNodePool));
+ memset (xpd, 0, sizeof (XMLNodePool));
+ if (xmlSAXUserParseMemory (&xmlnode_parser_libxml, xpd, str, real_size) < 0)
+ {
+ freePool (xpd);
+ return NULL;
+ }
ret = xpd->current;
ret->free_pool = YES;
return ret;
}
xmlnode *
-xmlnode_get_next_twin(xmlnode *node) {
+xmlnode_get_next_twin (xmlnode * node)
+{
xmlnode *sibling;
- const char *ns = xmlnode_get_namespace(node);
+ const char *ns = xmlnode_get_namespace (node);
- g_return_val_if_fail(node != NULL, NULL);
- g_return_val_if_fail(node->type == XMLNODE_TYPE_TAG, NULL);
+ g_return_val_if_fail (node != NULL, NULL);
+ g_return_val_if_fail (node->type == XMLNODE_TYPE_TAG, NULL);
- for(sibling = node->next; sibling; sibling = sibling->next) {
- const char *xmlns = NULL;
- if(ns)
- xmlns = xmlnode_get_namespace(sibling);
+ for (sibling = node->next; sibling; sibling = sibling->next)
+ {
+ const char *xmlns = NULL;
+ if (ns)
+ xmlns = xmlnode_get_namespace (sibling);
- if(sibling->type == XMLNODE_TYPE_TAG && !strcmp(node->name, sibling->name)
&&
- (!ns || (xmlns && !strcmp(ns, xmlns))))
- return sibling;
- }
+ if (sibling->type == XMLNODE_TYPE_TAG
+ && !strcmp (node->name, sibling->name) && (!ns
+ || (xmlns
+ && !strcmp (ns,
+ xmlns))))
+ return sibling;
+ }
return NULL;
}
Modified: GNUnet/src/transports/upnp/xmlnode.h
===================================================================
--- GNUnet/src/transports/upnp/xmlnode.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/transports/upnp/xmlnode.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -27,13 +27,14 @@
#ifdef __cplusplus
-extern "C" {
+extern "C"
+{
#endif
/**
* An xmlnode.
*/
-typedef struct _xmlnode xmlnode;
+ typedef struct _xmlnode xmlnode;
/**
* Gets a child node named name.
@@ -43,8 +44,7 @@
*
* @return The child or NULL.
*/
-xmlnode * xmlnode_get_child(const xmlnode *parent,
- const char *name);
+ xmlnode *xmlnode_get_child (const xmlnode * parent, const char *name);
/**
* Gets the next node with the same name as node.
@@ -53,7 +53,7 @@
*
* @return The twin of node or NULL.
*/
-xmlnode *xmlnode_get_next_twin(xmlnode *node);
+ xmlnode *xmlnode_get_next_twin (xmlnode * node);
/**
* Gets data from a node.
@@ -63,7 +63,7 @@
* @return The data from the node. You must g_free
* this string when finished using it.
*/
-char *xmlnode_get_data(xmlnode *node);
+ char *xmlnode_get_data (xmlnode * node);
/**
* Creates a node from a string of XML. Calling this on the
@@ -76,18 +76,17 @@
*
* @return The new node.
*/
-xmlnode *xmlnode_from_str(const char *str,
- int size);
+ xmlnode *xmlnode_from_str (const char *str, int size);
/**
* Frees a node and all of it's children.
*
* @param node The node to free.
*/
-void xmlnode_free(xmlnode *node);
+ void xmlnode_free (xmlnode * node);
#ifdef __cplusplus
}
#endif
-#endif /* _GAIM_XMLNODE_H_ */
+#endif /* _GAIM_XMLNODE_H_ */
Modified: GNUnet/src/util/boot/startup.c
===================================================================
--- GNUnet/src/util/boot/startup.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/boot/startup.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -31,21 +31,22 @@
#include "platform.h"
static GE_KIND
-convertLogLevel(const char * level) {
+convertLogLevel (const char *level)
+{
GE_KIND ret;
ret = 0;
- if (ret || (0 == strcasecmp("debug", level)))
+ if (ret || (0 == strcasecmp ("debug", level)))
ret |= GE_DEBUG;
- if (ret || (0 == strcasecmp("status", level)))
+ if (ret || (0 == strcasecmp ("status", level)))
ret |= GE_STATUS;
- if (ret || (0 == strcasecmp("info", level)))
+ if (ret || (0 == strcasecmp ("info", level)))
ret |= GE_INFO;
- if (ret || (0 == strcasecmp("warning", level)))
+ if (ret || (0 == strcasecmp ("warning", level)))
ret |= GE_WARNING;
- if (ret || (0 == strcasecmp("error", level)))
+ if (ret || (0 == strcasecmp ("error", level)))
ret |= GE_ERROR;
- if (ret || (0 == strcasecmp("fatal", level)))
+ if (ret || (0 == strcasecmp ("fatal", level)))
ret = ret | GE_FATAL;
return ret;
}
@@ -56,15 +57,16 @@
*
* @return 0 on success, 1 on error
*/
-static int configure_logging(struct GE_Context ** ectx,
- struct GC_Configuration * cfg) {
- char * admin_log_file;
- char * admin_log_level;
- char * user_log_level;
+static int
+configure_logging (struct GE_Context **ectx, struct GC_Configuration *cfg)
+{
+ char *admin_log_file;
+ char *admin_log_level;
+ char *user_log_level;
GE_KIND all;
GE_KIND ull;
- struct GE_Context * nctx;
- struct GE_Context * tetx;
+ struct GE_Context *nctx;
+ struct GE_Context *tetx;
unsigned long long logrotate;
int dev;
@@ -73,68 +75,58 @@
admin_log_level = NULL;
user_log_level = NULL;
logrotate = 7;
- if (-1 == GC_get_configuration_value_number(cfg,
- "GNUNETD",
- "KEEPLOG",
- 0,
- 36500,
- 3,
- &logrotate))
- return 1; /* error! */
- GC_get_configuration_value_filename(cfg,
- "GNUNETD",
- "LOGFILE",
- VAR_DAEMON_DIRECTORY "/logs",
- &admin_log_file);
- disk_directory_create_for_file(*ectx,
- admin_log_file);
- GC_get_configuration_value_string(cfg,
- "LOGGING",
- "ADMIN-LEVEL",
- "WARNING",
- &admin_log_level);
- GC_get_configuration_value_string(cfg,
- "LOGGING",
- "USER-LEVEL",
- "WARNING",
- &user_log_level);
- dev = GC_get_configuration_value_yesno(cfg,
- "LOGGING",
- "DEVELOPER",
- NO);
- all = convertLogLevel(admin_log_level);
- ull = convertLogLevel(user_log_level);
- if (dev == YES) {
- all |= GE_DEVELOPER | GE_REQUEST;
- ull |= GE_DEVELOPER | GE_REQUEST;
- }
- FREE(admin_log_level);
- FREE(user_log_level);
- if (all != 0) {
- nctx = GE_create_context_logfile(NULL,
- all
- | GE_ADMIN
- | GE_BULK
- | GE_IMMEDIATE,
- admin_log_file,
- YES,
- (int) logrotate);
- }
- FREE(admin_log_file);
- if (ull != 0) {
- tetx = GE_create_context_stderr(YES,
- ull
- | GE_USERKIND
- | GE_BULK
- | GE_IMMEDIATE);
- if (nctx == NULL)
- nctx = tetx;
- else
- nctx = GE_create_context_multiplexer(nctx,
- tetx);
- }
- GE_setDefaultContext(nctx);
- GE_free_context(*ectx);
+ if (-1 == GC_get_configuration_value_number (cfg,
+ "GNUNETD",
+ "KEEPLOG",
+ 0, 36500, 3, &logrotate))
+ return 1; /* error! */
+ GC_get_configuration_value_filename (cfg,
+ "GNUNETD",
+ "LOGFILE",
+ VAR_DAEMON_DIRECTORY "/logs",
+ &admin_log_file);
+ disk_directory_create_for_file (*ectx, admin_log_file);
+ GC_get_configuration_value_string (cfg,
+ "LOGGING",
+ "ADMIN-LEVEL",
+ "WARNING", &admin_log_level);
+ GC_get_configuration_value_string (cfg,
+ "LOGGING",
+ "USER-LEVEL",
+ "WARNING", &user_log_level);
+ dev = GC_get_configuration_value_yesno (cfg, "LOGGING", "DEVELOPER", NO);
+ all = convertLogLevel (admin_log_level);
+ ull = convertLogLevel (user_log_level);
+ if (dev == YES)
+ {
+ all |= GE_DEVELOPER | GE_REQUEST;
+ ull |= GE_DEVELOPER | GE_REQUEST;
+ }
+ FREE (admin_log_level);
+ FREE (user_log_level);
+ if (all != 0)
+ {
+ nctx = GE_create_context_logfile (NULL,
+ all
+ | GE_ADMIN
+ | GE_BULK
+ | GE_IMMEDIATE,
+ admin_log_file, YES, (int) logrotate);
+ }
+ FREE (admin_log_file);
+ if (ull != 0)
+ {
+ tetx = GE_create_context_stderr (YES,
+ ull
+ | GE_USERKIND
+ | GE_BULK | GE_IMMEDIATE);
+ if (nctx == NULL)
+ nctx = tetx;
+ else
+ nctx = GE_create_context_multiplexer (nctx, tetx);
+ }
+ GE_setDefaultContext (nctx);
+ GE_free_context (*ectx);
*ectx = nctx;
return 0;
}
@@ -148,91 +140,80 @@
* command-line argument to be processed in argv
* otherwise
*/
-int GNUNET_init(int argc,
- char * const * argv,
- const char * binaryName,
- char ** cfgFileName,
- const struct CommandLineOption * options,
- struct GE_Context ** ectx,
- struct GC_Configuration ** cfg) {
+int
+GNUNET_init (int argc,
+ char *const *argv,
+ const char *binaryName,
+ char **cfgFileName,
+ const struct CommandLineOption *options,
+ struct GE_Context **ectx, struct GC_Configuration **cfg)
+{
int i;
- char * path;
+ char *path;
int is_daemon;
int ret;
- os_init(NULL);
+ os_init (NULL);
#if ENABLE_NLS
setlocale (LC_ALL, "");
- path = os_get_installation_path(IPK_LOCALEDIR);
- BINDTEXTDOMAIN("GNUnet", path);
- FREE(path);
- textdomain("GNUnet");
+ path = os_get_installation_path (IPK_LOCALEDIR);
+ BINDTEXTDOMAIN ("GNUnet", path);
+ FREE (path);
+ textdomain ("GNUnet");
#endif
- is_daemon = 0 == strcmp(DEFAULT_DAEMON_CONFIG_FILE, *cfgFileName);
+ is_daemon = 0 == strcmp (DEFAULT_DAEMON_CONFIG_FILE, *cfgFileName);
/* during startup, log all warnings and higher
for anybody to stderr */
- *ectx = GE_create_context_stderr(YES,
- GE_WARNING | GE_ERROR | GE_FATAL |
- GE_USER | GE_ADMIN | GE_DEVELOPER |
- GE_IMMEDIATE | GE_BULK);
- GE_setDefaultContext(*ectx);
- os_init(*ectx);
- *cfg = GC_create_C_impl();
- GE_ASSERT(*ectx, *cfg != NULL);
- i = gnunet_parse_options(binaryName,
- *ectx,
- *cfg,
- options,
- (unsigned int) argc,
- argv);
+ *ectx = GE_create_context_stderr (YES,
+ GE_WARNING | GE_ERROR | GE_FATAL |
+ GE_USER | GE_ADMIN | GE_DEVELOPER |
+ GE_IMMEDIATE | GE_BULK);
+ GE_setDefaultContext (*ectx);
+ os_init (*ectx);
+ *cfg = GC_create_C_impl ();
+ GE_ASSERT (*ectx, *cfg != NULL);
+ i = gnunet_parse_options (binaryName,
+ *ectx, *cfg, options, (unsigned int) argc, argv);
if (i == -1)
return -1;
- if ( (YES != disk_file_test(*ectx,
- *cfgFileName)) &&
- (! is_daemon) ) {
- char * run;
- char * bindir;
- size_t max;
+ if ((YES != disk_file_test (*ectx, *cfgFileName)) && (!is_daemon))
+ {
+ char *run;
+ char *bindir;
+ size_t max;
- bindir = os_get_installation_path(IPK_BINDIR);
- max = 128 + strlen(*cfgFileName) + strlen(bindir);
- run = MALLOC(max);
- SNPRINTF(run,
- max,
- "%sgnunet-setup -c %s generate-defaults",
- bindir,
- *cfgFileName);
- FREE(bindir);
- ret = system(run);
- if (0 != ret)
- GE_LOG(*ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("Failed to run %s: %s %d\n"),
- run,
- strerror(errno),
- WEXITSTATUS(ret));
- FREE(run);
- }
- if (0 != GC_parse_configuration(*cfg,
- *cfgFileName))
+ bindir = os_get_installation_path (IPK_BINDIR);
+ max = 128 + strlen (*cfgFileName) + strlen (bindir);
+ run = MALLOC (max);
+ SNPRINTF (run,
+ max,
+ "%sgnunet-setup -c %s generate-defaults",
+ bindir, *cfgFileName);
+ FREE (bindir);
+ ret = system (run);
+ if (0 != ret)
+ GE_LOG (*ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _("Failed to run %s: %s %d\n"),
+ run, strerror (errno), WEXITSTATUS (ret));
+ FREE (run);
+ }
+ if (0 != GC_parse_configuration (*cfg, *cfgFileName))
return -1;
/* if PATHS/GNUNETD_HOME is not set, set it to
the default value! */
- GC_get_configuration_value_string(*cfg,
- "PATHS",
- "GNUNETD_HOME",
- "/var/lib/gnunet",
- &path);
- FREE(path);
- GC_get_configuration_value_string(*cfg,
- "PATHS",
- "GNUNET_HOME",
- "~/.gnunet",
- &path);
- FREE(path);
- if (configure_logging(ectx, *cfg) != 0)
+ GC_get_configuration_value_string (*cfg,
+ "PATHS",
+ "GNUNETD_HOME",
+ "/var/lib/gnunet", &path);
+ FREE (path);
+ GC_get_configuration_value_string (*cfg,
+ "PATHS",
+ "GNUNET_HOME", "~/.gnunet", &path);
+ FREE (path);
+ if (configure_logging (ectx, *cfg) != 0)
return -1;
return i;
}
@@ -240,11 +221,12 @@
/**
* Free resources allocated during GNUnet_init.
*/
-void GNUNET_fini(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- GC_free(cfg);
- GE_setDefaultContext(NULL);
- GE_free_context(ectx);
+void
+GNUNET_fini (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ GC_free (cfg);
+ GE_setDefaultContext (NULL);
+ GE_free_context (ectx);
}
-
+
/* end of startup.c */
Modified: GNUnet/src/util/config/config.c
===================================================================
--- GNUnet/src/util/config/config.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/config/config.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -28,8 +28,10 @@
#include "gnunet_util_config_impl.h"
#include "platform.h"
-void GC_free(struct GC_Configuration * cfg) {
- cfg->free(cfg);
+void
+GC_free (struct GC_Configuration *cfg)
+{
+ cfg->free (cfg);
}
/**
@@ -44,9 +46,10 @@
* @parm ectx maybe NULL, in that case errors will no longer
* be reported
*/
-void GC_set_error_context(struct GC_Configuration * cfg,
- struct GE_Context * ectx) {
- cfg->set_error_context(cfg, ectx);
+void
+GC_set_error_context (struct GC_Configuration *cfg, struct GE_Context *ectx)
+{
+ cfg->set_error_context (cfg, ectx);
}
/**
@@ -54,9 +57,10 @@
* file to the configuration environment.
* @return 0 on success, -1 on error
*/
-int GC_parse_configuration(struct GC_Configuration * cfg,
- const char * filename) {
- return cfg->parse_configuration(cfg, filename);
+int
+GC_parse_configuration (struct GC_Configuration *cfg, const char *filename)
+{
+ return cfg->parse_configuration (cfg, filename);
}
/**
@@ -64,8 +68,10 @@
* changed since the last save.
* @return 0 if clean, 1 if dirty, -1 on error (i.e. last save failed)
*/
-int GC_test_dirty(struct GC_Configuration * cfg) {
- return cfg->test_dirty(cfg);
+int
+GC_test_dirty (struct GC_Configuration *cfg)
+{
+ return cfg->test_dirty (cfg);
}
@@ -73,9 +79,10 @@
* Write configuration file.
* @return 0 on success, -1 on error
*/
-int GC_write_configuration(struct GC_Configuration * cfg,
- const char * filename) {
- return cfg->write_configuration(cfg, filename);
+int
+GC_write_configuration (struct GC_Configuration *cfg, const char *filename)
+{
+ return cfg->write_configuration (cfg, filename);
}
@@ -87,20 +94,20 @@
* will NOT be aliased, maybe NULL)
* @return YES, NO or SYSERR
*/
-int GC_get_configuration_value_yesno(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- int def) {
- static const char * yesno[] = { "YES" , "NO", NULL };
- const char * val;
+int
+GC_get_configuration_value_yesno (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option, int def)
+{
+ static const char *yesno[] = { "YES", "NO", NULL };
+ const char *val;
int ret;
- ret = GC_get_configuration_value_choice(cfg,
- section,
- option,
- yesno,
- def == YES ? "YES" : "NO",
- &val);
+ ret = GC_get_configuration_value_choice (cfg,
+ section,
+ option,
+ yesno,
+ def == YES ? "YES" : "NO", &val);
if (ret == -1)
return SYSERR;
if (val == yesno[0])
@@ -116,9 +123,10 @@
* @param old string to $-expand (will be freed!)
* @return $-expanded string
*/
-char * GC_configuration_expand_dollar(struct GC_Configuration * cfg,
- char * old) {
- return cfg->configuration_expand_dollar(cfg, old);
+char *
+GC_configuration_expand_dollar (struct GC_Configuration *cfg, char *old)
+{
+ return cfg->configuration_expand_dollar (cfg, old);
}
/**
@@ -128,14 +136,17 @@
* @param def default value (use indicated by return value)
* @return 0 on success, -1 on error, 1 for default
*/
-int GC_get_configuration_value_number(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- unsigned long long min,
- unsigned long long max,
- unsigned long long def,
- unsigned long long * number) {
- return cfg->get_configuration_value_number(cfg, section, option, min, max,
def, number);
+int
+GC_get_configuration_value_number (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ unsigned long long min,
+ unsigned long long max,
+ unsigned long long def,
+ unsigned long long *number)
+{
+ return cfg->get_configuration_value_number (cfg, section, option, min, max,
+ def, number);
}
@@ -147,20 +158,24 @@
* value, or NULL if option is not specified and no default given
* @return 0 on success, -1 on error, 1 for default
*/
-int GC_get_configuration_value_string(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char * def,
- char ** value) {
- return cfg->get_configuration_value_string(cfg, section, option, def, value);
+int
+GC_get_configuration_value_string (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ const char *def, char **value)
+{
+ return cfg->get_configuration_value_string (cfg, section, option, def,
+ value);
}
-int GC_get_configuration_value_filename(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char * def,
- char ** value) {
- return cfg->get_configuration_value_filename(cfg, section, option, def,
value);
+int
+GC_get_configuration_value_filename (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ const char *def, char **value)
+{
+ return cfg->get_configuration_value_filename (cfg, section, option, def,
+ value);
}
/**
@@ -174,13 +189,15 @@
* or NULL if option is not specified and no default given
* @return 0 on success, -1 on error, 1 for default
*/
-int GC_get_configuration_value_choice(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char ** choices,
- const char * def,
- const char ** value) {
- return cfg->get_configuration_value_choice(cfg, section, option, choices,
def, value);
+int
+GC_get_configuration_value_choice (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ const char **choices,
+ const char *def, const char **value)
+{
+ return cfg->get_configuration_value_choice (cfg, section, option, choices,
+ def, value);
}
/**
@@ -188,12 +205,15 @@
* @return 0 on success, -1 on error (i.e. out of memory,
* or update refused by registered callback)
*/
-int GC_set_configuration_value_number(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option,
- unsigned long long number) {
- return cfg->set_configuration_value_number(cfg, ectx, section, option,
number);
+int
+GC_set_configuration_value_number (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section,
+ const char *option,
+ unsigned long long number)
+{
+ return cfg->set_configuration_value_number (cfg, ectx, section, option,
+ number);
}
@@ -203,12 +223,14 @@
* @return 0 on success, -1 on error (i.e. out of memory,
* or update refused by registered callback)
*/
-int GC_set_configuration_value_string(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option,
- const char * value) {
- return cfg->set_configuration_value_string(cfg, ectx, section, option,
value);
+int
+GC_set_configuration_value_string (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section,
+ const char *option, const char *value)
+{
+ return cfg->set_configuration_value_string (cfg, ectx, section, option,
+ value);
}
/**
@@ -218,12 +240,14 @@
* @return 0 on success, -1 on error (i.e. out of memory,
* or update refused by registered callback)
*/
-int GC_set_configuration_value_choice(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option,
- const char * choice) {
- return cfg->set_configuration_value_choice(cfg, ectx, section, option,
choice);
+int
+GC_set_configuration_value_choice (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section,
+ const char *option, const char *choice)
+{
+ return cfg->set_configuration_value_choice (cfg, ectx, section, option,
+ choice);
}
/**
@@ -231,10 +255,11 @@
* configuration option changes.
* @return 0 on success, -1 on error
*/
-int GC_attach_change_listener(struct GC_Configuration * cfg,
- GC_ChangeListener callback,
- void * ctx) {
- return cfg->attach_change_listener(cfg, callback, ctx);
+int
+GC_attach_change_listener (struct GC_Configuration *cfg,
+ GC_ChangeListener callback, void *ctx)
+{
+ return cfg->attach_change_listener (cfg, callback, ctx);
}
/**
@@ -242,16 +267,16 @@
* configuration option changes.
* @return 0 on success, -1 on error, 1 for no such handler registered
*/
-int GC_detach_change_listener(struct GC_Configuration * cfg,
- GC_ChangeListener callback,
- void * ctx) {
- return cfg->detach_change_listener(cfg, callback, ctx);
+int
+GC_detach_change_listener (struct GC_Configuration *cfg,
+ GC_ChangeListener callback, void *ctx)
+{
+ return cfg->detach_change_listener (cfg, callback, ctx);
}
-int GC_have_configuration_value(struct GC_Configuration * cfg,
- const char * section,
- const char * option) {
- return cfg->have_configuration_value(cfg,
- section,
- option);
+int
+GC_have_configuration_value (struct GC_Configuration *cfg,
+ const char *section, const char *option)
+{
+ return cfg->have_configuration_value (cfg, section, option);
}
Modified: GNUnet/src/util/config_impl/configtest.c
===================================================================
--- GNUnet/src/util/config_impl/configtest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/config_impl/configtest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -28,65 +28,50 @@
#include "gnunet_util_config_impl.h"
#include "gnunet_util_error_loggers.h"
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static int testConfig() {
- char * c;
+static int
+testConfig ()
+{
+ char *c;
unsigned long long l;
- if (0 != GC_get_configuration_value_string(cfg,
- "test",
- "b",
- NULL,
- &c))
+ if (0 != GC_get_configuration_value_string (cfg, "test", "b", NULL, &c))
return 1;
- if (0 != strcmp("b",
- c))
+ if (0 != strcmp ("b", c))
return 1;
- FREE(c);
- if (0 != GC_get_configuration_value_number(cfg,
- "test",
- "five",
- 0,
- 10,
- 9,
- &l))
+ FREE (c);
+ if (0 != GC_get_configuration_value_number (cfg,
+ "test", "five", 0, 10, 9, &l))
return 1;
if (5 != l)
return 1;
- GC_set_configuration_value_string(cfg,
- NULL,
- "more",
- "c",
- "YES");
- if (NO == GC_get_configuration_value_yesno(cfg,
- "more",
- "c",
- NO))
+ GC_set_configuration_value_string (cfg, NULL, "more", "c", "YES");
+ if (NO == GC_get_configuration_value_yesno (cfg, "more", "c", NO))
return 1;
return 0;
}
-int main(int argc,
- char * argv[]) {
- struct GE_Context * ectx;
+int
+main (int argc, char *argv[])
+{
+ struct GE_Context *ectx;
int failureCount = 0;
- ectx = GE_create_context_stderr(NO,
- GE_WARNING | GE_ERROR | GE_FATAL |
- GE_USER | GE_ADMIN | GE_DEVELOPER |
- GE_IMMEDIATE | GE_BULK);
- GE_setDefaultContext(ectx);
- cfg = GC_create_C_impl();
- if (0 != GC_parse_configuration(cfg,
- "testconfig.conf")) {
- fprintf(stderr,
- "Failed to parse configuration file\n");
- return 1;
- }
- GE_ASSERT(ectx, cfg != NULL);
- os_init(ectx);
- failureCount += testConfig();
+ ectx = GE_create_context_stderr (NO,
+ GE_WARNING | GE_ERROR | GE_FATAL |
+ GE_USER | GE_ADMIN | GE_DEVELOPER |
+ GE_IMMEDIATE | GE_BULK);
+ GE_setDefaultContext (ectx);
+ cfg = GC_create_C_impl ();
+ if (0 != GC_parse_configuration (cfg, "testconfig.conf"))
+ {
+ fprintf (stderr, "Failed to parse configuration file\n");
+ return 1;
+ }
+ GE_ASSERT (ectx, cfg != NULL);
+ os_init (ectx);
+ failureCount += testConfig ();
if (failureCount != 0)
return 1;
Modified: GNUnet/src/util/config_impl/impl.c
===================================================================
--- GNUnet/src/util/config_impl/impl.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/config_impl/impl.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -32,33 +32,35 @@
/**
* @brief configuration entry
*/
-typedef struct GC_Entry {
+typedef struct GC_Entry
+{
/**
* key for this entry
*/
- char * key;
+ char *key;
/**
* current, commited value
*/
- char * val;
+ char *val;
/**
* non-null during uncommited update
*/
- char * dirty_val;
+ char *dirty_val;
} GC_Entry;
/**
* @brief configuration section
*/
-typedef struct GC_Section {
+typedef struct GC_Section
+{
/**
* name of the section
*/
- char * name;
+ char *name;
/**
* number of entries in section
@@ -68,13 +70,14 @@
/**
* entries in the section
*/
- GC_Entry * entries;
+ GC_Entry *entries;
} GC_Section;
/**
* @brief GC_ChangeListener and context
*/
-typedef struct GC_Listener {
+typedef struct GC_Listener
+{
/**
* Callback.
@@ -84,23 +87,24 @@
/**
* Context for callback.
*/
- void * ctx;
+ void *ctx;
} GC_Listener;
/**
* @brief configuration data
*/
-typedef struct GC_ConfigurationData {
+typedef struct GC_ConfigurationData
+{
/**
* Lock to access the data.
*/
- struct MUTEX * lock;
+ struct MUTEX *lock;
/**
* Context for logging errors, maybe NULL.
*/
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
/**
* Modification indication since last save
@@ -116,7 +120,7 @@
/**
* Array with "ssize" entries.
*/
- GC_Section * sections;
+ GC_Section *sections;
/**
* How many listeners do we have?
@@ -126,48 +130,47 @@
/**
* Array with "lsize" entries.
*/
- GC_Listener * listeners;
+ GC_Listener *listeners;
} GC_ConfigurationData;
-static void _free(struct GC_Configuration * cfg) {
- GC_Section * sec;
- GC_Entry * e;
+static void
+_free (struct GC_Configuration *cfg)
+{
+ GC_Section *sec;
+ GC_Entry *e;
int i;
int j;
- for (i=0;i<cfg->data->ssize;i++) {
- sec = &cfg->data->sections[i];
- for (j=0;j<sec->size;j++) {
- e = &sec->entries[j];
- FREE(e->key);
- FREENONNULL(e->val);
- GE_ASSERT(cfg->data->ectx,
- e->dirty_val == NULL);
+ for (i = 0; i < cfg->data->ssize; i++)
+ {
+ sec = &cfg->data->sections[i];
+ for (j = 0; j < sec->size; j++)
+ {
+ e = &sec->entries[j];
+ FREE (e->key);
+ FREENONNULL (e->val);
+ GE_ASSERT (cfg->data->ectx, e->dirty_val == NULL);
+ }
+ GROW (sec->entries, sec->size, 0);
+ FREE (sec->name);
}
- GROW(sec->entries,
- sec->size,
- 0);
- FREE(sec->name);
- }
- GROW(cfg->data->sections,
- cfg->data->ssize,
- 0);
- GE_ASSERT(cfg->data->ectx,
- cfg->data->listeners == 0);
- MUTEX_DESTROY(cfg->data->lock);
- FREE(cfg->data);
- FREE(cfg);
+ GROW (cfg->data->sections, cfg->data->ssize, 0);
+ GE_ASSERT (cfg->data->ectx, cfg->data->listeners == 0);
+ MUTEX_DESTROY (cfg->data->lock);
+ FREE (cfg->data);
+ FREE (cfg);
}
-static void _set_error_context(struct GC_Configuration * cfg,
- struct GE_Context * ectx) {
+static void
+_set_error_context (struct GC_Configuration *cfg, struct GE_Context *ectx)
+{
cfg->data->ectx = ectx;
}
static int
-_parse_configuration(struct GC_Configuration * cfg,
- const char * filename) {
+_parse_configuration (struct GC_Configuration *cfg, const char *filename)
+{
int dirty;
char line[256];
char tag[64];
@@ -177,231 +180,230 @@
int i;
int emptyline;
int ret;
- char * section;
- char * fn;
+ char *section;
+ char *fn;
- fn = string_expandFileName(NULL,
- filename);
- MUTEX_LOCK(cfg->data->lock);
- dirty = cfg->data->dirty; /* back up value! */
- if (NULL == (fp = FOPEN(fn, "r"))) {
- GE_LOG_STRERROR_FILE(cfg->data->ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE | GE_BULK | GE_REQUEST,
- "fopen",
- fn);
- MUTEX_UNLOCK(cfg->data->lock);
- FREE(fn);
- return -1;
- }
- FREE(fn);
+ fn = string_expandFileName (NULL, filename);
+ MUTEX_LOCK (cfg->data->lock);
+ dirty = cfg->data->dirty; /* back up value! */
+ if (NULL == (fp = FOPEN (fn, "r")))
+ {
+ GE_LOG_STRERROR_FILE (cfg->data->ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE | GE_BULK |
+ GE_REQUEST, "fopen", fn);
+ MUTEX_UNLOCK (cfg->data->lock);
+ FREE (fn);
+ return -1;
+ }
+ FREE (fn);
ret = 0;
- section = STRDUP("");
- memset(line,
- 0,
- 256);
+ section = STRDUP ("");
+ memset (line, 0, 256);
nr = 0;
- while (NULL != fgets(line, 255, fp)) {
- nr++;
- for (i=0;i<255;i++)
- if (line[i] == '\t')
- line[i] = ' ';
- if (line[0] == '\n' || line[0] == '#' || line[0] == '%' ||
- line[0] == '\r')
- continue;
- emptyline = 1;
- for (i=0;(i<255 && line[i] != 0);i++)
- if (line[i] != ' ' && line[i] != '\n' && line[i] != '\r')
- emptyline = 0;
- if (emptyline == 1)
- continue;
- /* remove tailing whitespace */
- for (i=strlen(line)-1;(i>=0) && (isspace(line[i]));i--)
- line[i] = '\0';
- if (1 == sscanf(line, "@INLINE@ %191[^\n]", value) ) {
- /* @INLINE@ value */
- char * expanded = string_expandFileName(cfg->data->ectx,
- value);
- if (0 != _parse_configuration(cfg,
- expanded))
- ret = -1; /* failed to parse included config */
- } else if (1 == sscanf(line,
- "[%99[^]]]",
- value)) {
- /* [value] */
- FREE(section);
- section = STRDUP(value);
- } else if (2 == sscanf(line,
- " %63[^= ] = %191[^\n]",
- tag,
- value)) {
- /* tag = value */
- /* Strip LF */
- i = strlen(value) - 1;
- while ((i >= 0) && (isspace(value[i])))
- value[i--] = '\0';
- /* remove quotes */
- i = 0;
- if (value[0] == '"') {
- i = 1;
- while ( (value[i] != '\0') &&
- (value[i] != '"') )
- i++;
- if (value[i] == '"') {
- value[i] = '\0';
- i = 1;
- } else
- i = 0;
- }
- /* first check if we have this value already;
- this could happen if the value was changed
- using a command-line option; only set it
- if we do not have a value already... */
- if ( (NO == GC_have_configuration_value(cfg,
- section,
- tag)) &&
- (0 != GC_set_configuration_value_string(cfg,
- cfg->data->ectx,
- section,
- tag,
- &value[i])) )
- ret = -1; /* could not set value */
- } else if (1 == sscanf(line,
- " %63[^= ] =[^\n]",
- tag)) {
- /* tag = */
- /* first check if we have this value already;
- this could happen if the value was changed
- using a command-line option; only set it
- if we do not have a value already... */
- if ( (NO == GC_have_configuration_value(cfg,
- section,
- tag)) &&
- (0 != GC_set_configuration_value_string(cfg,
- cfg->data->ectx,
- section,
- tag,
- "")) )
- ret = -1; /* could not set value */
- } else {
- /* parse error */
- GE_LOG(cfg->data->ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE | GE_BULK,
- _("Syntax error in configuration file `%s' at line %d.\n"),
- filename, nr);
+ while (NULL != fgets (line, 255, fp))
+ {
+ nr++;
+ for (i = 0; i < 255; i++)
+ if (line[i] == '\t')
+ line[i] = ' ';
+ if (line[0] == '\n' || line[0] == '#' || line[0] == '%' ||
+ line[0] == '\r')
+ continue;
+ emptyline = 1;
+ for (i = 0; (i < 255 && line[i] != 0); i++)
+ if (line[i] != ' ' && line[i] != '\n' && line[i] != '\r')
+ emptyline = 0;
+ if (emptyline == 1)
+ continue;
+ /* remove tailing whitespace */
+ for (i = strlen (line) - 1; (i >= 0) && (isspace (line[i])); i--)
+ line[i] = '\0';
+ if (1 == sscanf (line, "@INLINE@ %191[^\n]", value))
+ {
+ /* @INLINE@ value */
+ char *expanded = string_expandFileName (cfg->data->ectx,
+ value);
+ if (0 != _parse_configuration (cfg, expanded))
+ ret = -1; /* failed to parse included config */
+ }
+ else if (1 == sscanf (line, "[%99[^]]]", value))
+ {
+ /* [value] */
+ FREE (section);
+ section = STRDUP (value);
+ }
+ else if (2 == sscanf (line, " %63[^= ] = %191[^\n]", tag, value))
+ {
+ /* tag = value */
+ /* Strip LF */
+ i = strlen (value) - 1;
+ while ((i >= 0) && (isspace (value[i])))
+ value[i--] = '\0';
+ /* remove quotes */
+ i = 0;
+ if (value[0] == '"')
+ {
+ i = 1;
+ while ((value[i] != '\0') && (value[i] != '"'))
+ i++;
+ if (value[i] == '"')
+ {
+ value[i] = '\0';
+ i = 1;
+ }
+ else
+ i = 0;
+ }
+ /* first check if we have this value already;
+ this could happen if the value was changed
+ using a command-line option; only set it
+ if we do not have a value already... */
+ if ((NO == GC_have_configuration_value (cfg,
+ section,
+ tag)) &&
+ (0 != GC_set_configuration_value_string (cfg,
+ cfg->data->ectx,
+ section,
+ tag, &value[i])))
+ ret = -1; /* could not set value */
+ }
+ else if (1 == sscanf (line, " %63[^= ] =[^\n]", tag))
+ {
+ /* tag = */
+ /* first check if we have this value already;
+ this could happen if the value was changed
+ using a command-line option; only set it
+ if we do not have a value already... */
+ if ((NO == GC_have_configuration_value (cfg,
+ section,
+ tag)) &&
+ (0 != GC_set_configuration_value_string (cfg,
+ cfg->data->ectx,
+ section, tag, "")))
+ ret = -1; /* could not set value */
+ }
+ else
+ {
+ /* parse error */
+ GE_LOG (cfg->data->ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE | GE_BULK,
+ _("Syntax error in configuration file `%s' at line %d.\n"),
+ filename, nr);
+ ret = -1;
+ break;
+ }
+ }
+ if (0 != fclose (fp))
+ {
+ GE_LOG_STRERROR_FILE (cfg->data->ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE |
+ GE_BULK | GE_REQUEST, "fclose", filename);
ret = -1;
- break;
}
- }
- if (0 != fclose(fp)) {
- GE_LOG_STRERROR_FILE(cfg->data->ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE | GE_BULK |
GE_REQUEST,
- "fclose",
- filename);
- ret = -1;
- }
/* restore dirty flag - anything we set in the meantime
came from disk */
cfg->data->dirty = dirty;
- MUTEX_UNLOCK(cfg->data->lock);
- FREE(section);
+ MUTEX_UNLOCK (cfg->data->lock);
+ FREE (section);
return ret;
}
static int
-_test_dirty(struct GC_Configuration * cfg) {
+_test_dirty (struct GC_Configuration *cfg)
+{
return cfg->data->dirty;
}
static int
-_write_configuration(struct GC_Configuration * cfg,
- const char * filename) {
- GC_ConfigurationData * data;
- GC_Section * sec;
- GC_Entry * e;
+_write_configuration (struct GC_Configuration *cfg, const char *filename)
+{
+ GC_ConfigurationData *data;
+ GC_Section *sec;
+ GC_Entry *e;
int i;
int j;
FILE *fp;
int error;
int ret;
- char * fn;
- char * val;
- char * pos;
+ char *fn;
+ char *val;
+ char *pos;
- fn = string_expandFileName(NULL, filename);
- disk_directory_create_for_file(NULL, fn);
+ fn = string_expandFileName (NULL, filename);
+ disk_directory_create_for_file (NULL, fn);
data = cfg->data;
- if (NULL == (fp = FOPEN(fn, "w"))) {
- GE_LOG_STRERROR_FILE(data->ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- "fopen",
- fn);
- FREE(fn);
- return -1;
- }
- FREE(fn);
+ if (NULL == (fp = FOPEN (fn, "w")))
+ {
+ GE_LOG_STRERROR_FILE (data->ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE, "fopen", fn);
+ FREE (fn);
+ return -1;
+ }
+ FREE (fn);
error = 0;
ret = 0;
- MUTEX_LOCK(data->lock);
- for (i=0;i<data->ssize;i++) {
- sec = &data->sections[i];
- if (0 > fprintf(fp,
- "[%s]\n",
- sec->name)) {
+ MUTEX_LOCK (data->lock);
+ for (i = 0; i < data->ssize; i++)
+ {
+ sec = &data->sections[i];
+ if (0 > fprintf (fp, "[%s]\n", sec->name))
+ {
+ error = 1;
+ break;
+ }
+ for (j = 0; j < sec->size; j++)
+ {
+ e = &sec->entries[j];
+ GE_ASSERT (data->ectx, e->dirty_val == NULL);
+ if (e->val != NULL)
+ {
+ val = MALLOC (strlen (e->val) * 2 + 1);
+ strcpy (val, e->val);
+ while (NULL != (pos = strstr (val, "\n")))
+ {
+ memmove (&pos[2], &pos[1], strlen (&pos[1]));
+ pos[0] = '\\';
+ pos[1] = 'n';
+ }
+ if (0 > fprintf (fp, "%s = %s\n", e->key, val))
+ {
+ error = 1;
+ FREE (val);
+ break;
+ }
+ FREE (val);
+ }
+ }
+ if (error != 0)
+ break;
+ if (0 > fprintf (fp, "\n"))
+ {
+ error = 1;
+ break;
+ }
+ }
+ if (error != 0)
+ GE_LOG_STRERROR_FILE (data->ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE | GE_BULK |
+ GE_REQUEST, "fprintf", filename);
+ if (0 != fclose (fp))
+ {
+ GE_LOG_STRERROR_FILE (data->ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE |
+ GE_BULK | GE_REQUEST, "fclose", filename);
error = 1;
- break;
}
- for (j=0;j<sec->size;j++) {
- e = &sec->entries[j];
- GE_ASSERT(data->ectx,
- e->dirty_val == NULL);
- if (e->val != NULL) {
- val = MALLOC(strlen(e->val) * 2 + 1);
- strcpy(val, e->val);
- while (NULL != (pos = strstr(val, "\n"))) {
- memmove(&pos[2],
- &pos[1],
- strlen(&pos[1]));
- pos[0] = '\\';
- pos[1] = 'n';
- }
- if (0 > fprintf(fp,
- "%s = %s\n",
- e->key,
- val)) {
- error = 1;
- FREE(val);
- break;
- }
- FREE(val);
- }
+ if (error == 0)
+ {
+ ret = 0;
+ data->dirty = 0; /* last write succeeded */
}
- if (error != 0)
- break;
- if (0 > fprintf(fp, "\n")) {
- error = 1;
- break;
+ else
+ {
+ ret = -1;
+ data->dirty = -1; /* last write failed */
}
- }
- if (error != 0)
- GE_LOG_STRERROR_FILE(data->ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE | GE_BULK | GE_REQUEST,
- "fprintf",
- filename);
- if (0 != fclose(fp)) {
- GE_LOG_STRERROR_FILE(data->ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE | GE_BULK |
GE_REQUEST,
- "fclose",
- filename);
- error = 1;
- }
- if (error == 0) {
- ret = 0;
- data->dirty = 0; /* last write succeeded */
- } else {
- ret = -1;
- data->dirty = -1; /* last write failed */
- }
- MUTEX_UNLOCK(data->lock);
+ MUTEX_UNLOCK (data->lock);
return ret;
}
@@ -409,12 +411,11 @@
* Call only with lock held!
*/
static GC_Section *
-findSection(GC_ConfigurationData * data,
- const char * section) {
+findSection (GC_ConfigurationData * data, const char *section)
+{
int i;
- for (i=data->ssize-1;i>=0;i--)
- if (0 == strcmp(section,
- data->sections[i].name))
+ for (i = data->ssize - 1; i >= 0; i--)
+ if (0 == strcmp (section, data->sections[i].name))
return &data->sections[i];
return NULL;
}
@@ -423,278 +424,271 @@
* Call only with lock held!
*/
static GC_Entry *
-findEntry(GC_ConfigurationData * data,
- const char * section,
- const char * key) {
+findEntry (GC_ConfigurationData * data, const char *section, const char *key)
+{
int i;
- GC_Section * sec;
+ GC_Section *sec;
- sec = findSection(data, section);
+ sec = findSection (data, section);
if (sec == NULL)
return NULL;
- for (i=sec->size-1;i>=0;i--)
- if (0 == strcmp(key,
- sec->entries[i].key))
+ for (i = sec->size - 1; i >= 0; i--)
+ if (0 == strcmp (key, sec->entries[i].key))
return &sec->entries[i];
return NULL;
}
static int
-_set_configuration_value_string(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option,
- const char * value) {
- GC_ConfigurationData * data;
- GC_Section * sec;
+_set_configuration_value_string (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section,
+ const char *option, const char *value)
+{
+ GC_ConfigurationData *data;
+ GC_Section *sec;
GC_Section nsec;
- GC_Entry * e;
+ GC_Entry *e;
GC_Entry ne;
int ret;
int i;
data = cfg->data;
- MUTEX_LOCK(data->lock);
- e = findEntry(data, section, option);
- if (e == NULL) {
- sec = findSection(data, section);
- if (sec == NULL) {
- nsec.name = STRDUP(section);
- nsec.size = 0;
- nsec.entries = NULL;
- APPEND(data->sections,
- data->ssize,
- nsec);
- sec = findSection(data, section);
+ MUTEX_LOCK (data->lock);
+ e = findEntry (data, section, option);
+ if (e == NULL)
+ {
+ sec = findSection (data, section);
+ if (sec == NULL)
+ {
+ nsec.name = STRDUP (section);
+ nsec.size = 0;
+ nsec.entries = NULL;
+ APPEND (data->sections, data->ssize, nsec);
+ sec = findSection (data, section);
+ }
+ ne.key = STRDUP (option);
+ ne.val = NULL;
+ ne.dirty_val = NULL;
+ APPEND (sec->entries, sec->size, ne);
+ e = findEntry (data, section, option);
}
- ne.key = STRDUP(option);
- ne.val = NULL;
- ne.dirty_val = NULL;
- APPEND(sec->entries,
- sec->size,
- ne);
- e = findEntry(data, section, option);
- }
- if (e->dirty_val != NULL) {
- if (0 == strcmp(e->dirty_val,
- value)) {
- ret = 0;
- } else {
- /* recursive update to different value -- not allowed! */
- GE_BREAK(ectx, 0);
- ret = -1;
+ if (e->dirty_val != NULL)
+ {
+ if (0 == strcmp (e->dirty_val, value))
+ {
+ ret = 0;
+ }
+ else
+ {
+ /* recursive update to different value -- not allowed! */
+ GE_BREAK (ectx, 0);
+ ret = -1;
+ }
}
- } else {
- e->dirty_val = STRDUP(value);
- i = data->lsize - 1;
- while (i >= 0) {
- if (0 != data->listeners[i].listener(data->listeners[i].ctx,
- cfg,
- ectx,
- section,
- option))
- break; /* update refused */
- i--;
- e = findEntry(data, section, option); /* side-effects of callback are
possible! */
+ else
+ {
+ e->dirty_val = STRDUP (value);
+ i = data->lsize - 1;
+ while (i >= 0)
+ {
+ if (0 != data->listeners[i].listener (data->listeners[i].ctx,
+ cfg, ectx, section, option))
+ break; /* update refused */
+ i--;
+ e = findEntry (data, section, option); /* side-effects of
callback are possible! */
+ }
+ e = findEntry (data, section, option); /* side-effects of callback
are possible! */
+ if (i >= 0)
+ {
+ /* update refused, revert! */
+ FREE (e->dirty_val);
+ e->dirty_val = NULL;
+ i++; /* the callback that refused does not need
refreshing */
+ while (i < data->lsize)
+ {
+ if (0 != data->listeners[i].listener (data->listeners[i].ctx,
+ cfg,
+ ectx, section, option))
+ GE_ASSERT (ectx, 0); /* refused the refusal!? */
+ e = findEntry (data, section, option); /* side-effects of
callback are possible! */
+ i++;
+ }
+ ret = -1; /* error -- update refused */
+ }
+ else
+ {
+ /* all confirmed, commit! */
+ if ((e->val == NULL) || (0 != strcmp (e->val, e->dirty_val)))
+ data->dirty = 1;
+ FREENONNULL (e->val);
+ e->val = e->dirty_val;
+ e->dirty_val = NULL;
+ ret = 0;
+ }
}
- e = findEntry(data, section, option); /* side-effects of callback are
possible! */
- if (i >= 0) {
- /* update refused, revert! */
- FREE(e->dirty_val);
- e->dirty_val = NULL;
- i++; /* the callback that refused does not need refreshing */
- while (i < data->lsize) {
- if (0 != data->listeners[i].listener(data->listeners[i].ctx,
- cfg,
- ectx,
- section,
- option))
- GE_ASSERT(ectx, 0); /* refused the refusal!? */
- e = findEntry(data, section, option); /* side-effects of callback are
possible! */
- i++;
- }
- ret = -1; /* error -- update refused */
- } else {
- /* all confirmed, commit! */
- if ( (e->val == NULL) ||
- (0 != strcmp(e->val,
- e->dirty_val)) )
- data->dirty = 1;
- FREENONNULL(e->val);
- e->val = e->dirty_val;
- e->dirty_val = NULL;
- ret = 0;
- }
- }
if (ret == -1)
- GE_LOG(ectx,
- GE_USER | GE_BULK | GE_WARNING,
- _("Setting option `%s' in section `%s' to value `%s' was refused.\n"),
- option,
- section,
- value);
- MUTEX_UNLOCK(data->lock);
+ GE_LOG (ectx,
+ GE_USER | GE_BULK | GE_WARNING,
+ _
+ ("Setting option `%s' in section `%s' to value `%s' was
refused.\n"),
+ option, section, value);
+ MUTEX_UNLOCK (data->lock);
return ret;
}
static int
-_set_configuration_value_number(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option,
- unsigned long long number) {
+_set_configuration_value_number (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section,
+ const char *option,
+ unsigned long long number)
+{
char s[64];
- SNPRINTF(s, 64, "%llu", number);
- return _set_configuration_value_string(cfg, ectx, section, option, s);
+ SNPRINTF (s, 64, "%llu", number);
+ return _set_configuration_value_string (cfg, ectx, section, option, s);
}
static int
-_get_configuration_value_number(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- unsigned long long min,
- unsigned long long max,
- unsigned long long def,
- unsigned long long * number) {
- GC_Entry * e;
- const char * val;
+_get_configuration_value_number (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ unsigned long long min,
+ unsigned long long max,
+ unsigned long long def,
+ unsigned long long *number)
+{
+ GC_Entry *e;
+ const char *val;
int ret;
- MUTEX_LOCK(cfg->data->lock);
- e = findEntry(cfg->data,
- section,
- option);
- if (e != NULL) {
- val = (e->dirty_val != NULL) ? e->dirty_val : e->val;
- if (1 == SSCANF(val,
- "%llu",
- number)) {
- if ( (*number >= min) &&
- (*number <= max) ) {
- ret = 0;
- } else {
- GE_LOG(cfg->data->ectx,
- GE_ERROR | GE_USER | GE_BULK,
- _("Configuration value '%llu' for '%s' "
- "in section '%s' is out of legal bounds [%llu,%llu]\n"),
- *number,
- option,
- section,
- min,
- max);
- ret = -1; /* error */
- }
- } else {
- GE_LOG(cfg->data->ectx,
- GE_ERROR | GE_USER | GE_BULK,
- _("Configuration value '%s' for '%s'"
- " in section '%s' should be a number\n"),
- val,
- option,
- section,
- min,
- max);
- ret = -1; /* error */
+ MUTEX_LOCK (cfg->data->lock);
+ e = findEntry (cfg->data, section, option);
+ if (e != NULL)
+ {
+ val = (e->dirty_val != NULL) ? e->dirty_val : e->val;
+ if (1 == SSCANF (val, "%llu", number))
+ {
+ if ((*number >= min) && (*number <= max))
+ {
+ ret = 0;
+ }
+ else
+ {
+ GE_LOG (cfg->data->ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ _("Configuration value '%llu' for '%s' "
+ "in section '%s' is out of legal bounds
[%llu,%llu]\n"),
+ *number, option, section, min, max);
+ ret = -1; /* error */
+ }
+ }
+ else
+ {
+ GE_LOG (cfg->data->ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ _("Configuration value '%s' for '%s'"
+ " in section '%s' should be a number\n"),
+ val, option, section, min, max);
+ ret = -1; /* error */
+ }
}
- } else {
- *number = def;
- _set_configuration_value_number(cfg,
- cfg->data->ectx,
- section,
- option,
- def);
- ret = 1; /* default */
- }
- MUTEX_UNLOCK(cfg->data->lock);
+ else
+ {
+ *number = def;
+ _set_configuration_value_number (cfg,
+ cfg->data->ectx, section, option, def);
+ ret = 1; /* default */
+ }
+ MUTEX_UNLOCK (cfg->data->lock);
return ret;
}
static int
-_get_configuration_value_string(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char * def,
- char ** value) {
- GC_Entry * e;
- const char * val;
+_get_configuration_value_string (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ const char *def, char **value)
+{
+ GC_Entry *e;
+ const char *val;
int ret;
- MUTEX_LOCK(cfg->data->lock);
- e = findEntry(cfg->data,
- section,
- option);
- if (e != NULL) {
- val = (e->dirty_val != NULL) ? e->dirty_val : e->val;
- *value = STRDUP(val);
- ret = 0;
- } else {
- if (def == NULL) {
- MUTEX_UNLOCK(cfg->data->lock);
- GE_LOG(cfg->data->ectx,
- GE_USER | GE_IMMEDIATE | GE_ERROR,
- "Configuration value for option `%s' in section `%s' required.\n",
- option,
- section);
- return -1;
+ MUTEX_LOCK (cfg->data->lock);
+ e = findEntry (cfg->data, section, option);
+ if (e != NULL)
+ {
+ val = (e->dirty_val != NULL) ? e->dirty_val : e->val;
+ *value = STRDUP (val);
+ ret = 0;
}
- *value = STRDUP(def);
- _set_configuration_value_string(cfg,
- cfg->data->ectx,
- section,
- option,
- def);
- ret = 1; /* default */
- }
- MUTEX_UNLOCK(cfg->data->lock);
+ else
+ {
+ if (def == NULL)
+ {
+ MUTEX_UNLOCK (cfg->data->lock);
+ GE_LOG (cfg->data->ectx,
+ GE_USER | GE_IMMEDIATE | GE_ERROR,
+ "Configuration value for option `%s' in section `%s'
required.\n",
+ option, section);
+ return -1;
+ }
+ *value = STRDUP (def);
+ _set_configuration_value_string (cfg,
+ cfg->data->ectx, section, option, def);
+ ret = 1; /* default */
+ }
+ MUTEX_UNLOCK (cfg->data->lock);
return ret;
}
static int
-_get_configuration_value_choice(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char ** choices,
- const char * def,
- const char ** value) {
- GC_Entry * e;
- const char * val;
+_get_configuration_value_choice (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ const char **choices,
+ const char *def, const char **value)
+{
+ GC_Entry *e;
+ const char *val;
int i;
int ret;
- MUTEX_LOCK(cfg->data->lock);
- e = findEntry(cfg->data,
- section,
- option);
- if (e != NULL) {
- val = (e->dirty_val != NULL) ? e->dirty_val : e->val;
- i = 0;
- while (choices[i] != NULL) {
- if (0 == strcasecmp(choices[i],
- val))
- break;
- i++;
+ MUTEX_LOCK (cfg->data->lock);
+ e = findEntry (cfg->data, section, option);
+ if (e != NULL)
+ {
+ val = (e->dirty_val != NULL) ? e->dirty_val : e->val;
+ i = 0;
+ while (choices[i] != NULL)
+ {
+ if (0 == strcasecmp (choices[i], val))
+ break;
+ i++;
+ }
+ if (choices[i] == NULL)
+ {
+ GE_LOG (cfg->data->ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ _("Configuration value '%s' for '%s'"
+ " in section '%s' is not in set of legal choices\n"),
+ val, option, section);
+ ret = -1; /* error */
+ }
+ else
+ {
+ *value = choices[i];
+ ret = 0;
+ }
}
- if (choices[i] == NULL) {
- GE_LOG(cfg->data->ectx,
- GE_ERROR | GE_USER | GE_BULK,
- _("Configuration value '%s' for '%s'"
- " in section '%s' is not in set of legal choices\n"),
- val,
- option,
- section);
- ret = -1; /* error */
- } else {
- *value = choices[i];
- ret = 0;
+ else
+ {
+ *value = def;
+ if (def == NULL)
+ ret = -1;
+ else
+ ret = 1; /* default */
}
- } else {
- *value = def;
- if (def == NULL)
- ret = -1;
- else
- ret = 1; /* default */
- }
- MUTEX_UNLOCK(cfg->data->lock);
+ MUTEX_UNLOCK (cfg->data->lock);
return ret;
}
@@ -703,21 +697,19 @@
* @return YES if so, NO if not.
*/
static int
-_have_configuration_value(struct GC_Configuration * cfg,
- const char * section,
- const char * option) {
- GC_Entry * e;
+_have_configuration_value (struct GC_Configuration *cfg,
+ const char *section, const char *option)
+{
+ GC_Entry *e;
int ret;
- MUTEX_LOCK(cfg->data->lock);
- e = findEntry(cfg->data,
- section,
- option);
+ MUTEX_LOCK (cfg->data->lock);
+ e = findEntry (cfg->data, section, option);
if (e == NULL)
ret = NO;
else
ret = YES;
- MUTEX_UNLOCK(cfg->data->lock);
+ MUTEX_UNLOCK (cfg->data->lock);
return ret;
}
@@ -730,57 +722,60 @@
* @return $-expanded string
*/
static char *
-_configuration_expand_dollar(struct GC_Configuration * cfg,
- char * orig) {
+_configuration_expand_dollar (struct GC_Configuration *cfg, char *orig)
+{
int i;
- char * prefix;
- char * result;
- const char * post;
+ char *prefix;
+ char *result;
+ const char *post;
if (orig[0] != '$')
return orig;
i = 0;
- while ( (orig[i] != '/') &&
- (orig[i] != '\\') &&
- (orig[i] != '\0') )
+ while ((orig[i] != '/') && (orig[i] != '\\') && (orig[i] != '\0'))
i++;
- if (orig[i] == '\0') {
- post = "";
- } else {
- orig[i] = '\0';
- post = &orig[i+1];
- }
+ if (orig[i] == '\0')
+ {
+ post = "";
+ }
+ else
+ {
+ orig[i] = '\0';
+ post = &orig[i + 1];
+ }
prefix = NULL;
- if (YES == _have_configuration_value(cfg,
- "PATHS",
- &orig[1])) {
- if (0 != _get_configuration_value_string(cfg,
- "PATHS",
- &orig[1],
- NULL,
- &prefix)) {
- GE_BREAK(NULL, 0);
- return orig;
+ if (YES == _have_configuration_value (cfg, "PATHS", &orig[1]))
+ {
+ if (0 != _get_configuration_value_string (cfg,
+ "PATHS",
+ &orig[1], NULL, &prefix))
+ {
+ GE_BREAK (NULL, 0);
+ return orig;
+ }
}
- } else {
- const char * env = getenv(&orig[1]);
+ else
+ {
+ const char *env = getenv (&orig[1]);
- if (env != NULL) {
- prefix = STRDUP(env);
- } else {
- orig[i] = DIR_SEPARATOR;
- return orig;
+ if (env != NULL)
+ {
+ prefix = STRDUP (env);
+ }
+ else
+ {
+ orig[i] = DIR_SEPARATOR;
+ return orig;
+ }
}
- }
- result = MALLOC(strlen(prefix) +
- strlen(post) + 2);
- strcpy(result, prefix);
- if ( (strlen(prefix) == 0) ||
- (prefix[strlen(prefix)-1] != DIR_SEPARATOR) )
- strcat(result, DIR_SEPARATOR_STR);
- strcat(result, post);
- FREE(prefix);
- FREE(orig);
+ result = MALLOC (strlen (prefix) + strlen (post) + 2);
+ strcpy (result, prefix);
+ if ((strlen (prefix) == 0) ||
+ (prefix[strlen (prefix) - 1] != DIR_SEPARATOR))
+ strcat (result, DIR_SEPARATOR_STR);
+ strcat (result, post);
+ FREE (prefix);
+ FREE (orig);
return result;
}
@@ -793,98 +788,91 @@
* @return 0 on success, -1 on error, 1 for default
*/
static int
-_get_configuration_value_filename(struct GC_Configuration * cfg,
- const char * section,
- const char * option,
- const char * def,
- char ** value) {
- GC_ConfigurationData * data;
+_get_configuration_value_filename (struct GC_Configuration *cfg,
+ const char *section,
+ const char *option,
+ const char *def, char **value)
+{
+ GC_ConfigurationData *data;
int ret;
- char * tmp;
+ char *tmp;
data = cfg->data;
tmp = NULL;
- ret = _get_configuration_value_string(cfg,
- section,
- option,
- def,
- &tmp);
- if (tmp != NULL) {
- tmp = _configuration_expand_dollar(cfg,
- tmp);
- *value = string_expandFileName(data->ectx,
- tmp);
- FREE(tmp);
- } else {
- *value = NULL;
- }
+ ret = _get_configuration_value_string (cfg, section, option, def, &tmp);
+ if (tmp != NULL)
+ {
+ tmp = _configuration_expand_dollar (cfg, tmp);
+ *value = string_expandFileName (data->ectx, tmp);
+ FREE (tmp);
+ }
+ else
+ {
+ *value = NULL;
+ }
return ret;
}
static int
-_set_configuration_value_choice(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * section,
- const char * option,
- const char * choice) {
- return _set_configuration_value_string(cfg, ectx, section, option, choice);
+_set_configuration_value_choice (struct GC_Configuration *cfg,
+ struct GE_Context *ectx,
+ const char *section,
+ const char *option, const char *choice)
+{
+ return _set_configuration_value_string (cfg, ectx, section, option, choice);
}
static int
-_attach_change_listener(struct GC_Configuration * cfg,
- GC_ChangeListener callback,
- void * ctx) {
+_attach_change_listener (struct GC_Configuration *cfg,
+ GC_ChangeListener callback, void *ctx)
+{
GC_Listener l;
int i;
int j;
- MUTEX_LOCK(cfg->data->lock);
- for (i=0;i<cfg->data->ssize;i++) {
- GC_Section * s = &cfg->data->sections[i];
- for (j=0;j<s->size;j++) {
- GC_Entry * e = &s->entries[j];
- if (0 != callback(ctx,
- cfg,
- cfg->data->ectx,
- s->name,
- e->key)) {
- MUTEX_UNLOCK(cfg->data->lock);
- return -1;
- }
- s = &cfg->data->sections[i]; /* side-effects of callback are possible! */
+ MUTEX_LOCK (cfg->data->lock);
+ for (i = 0; i < cfg->data->ssize; i++)
+ {
+ GC_Section *s = &cfg->data->sections[i];
+ for (j = 0; j < s->size; j++)
+ {
+ GC_Entry *e = &s->entries[j];
+ if (0 != callback (ctx, cfg, cfg->data->ectx, s->name, e->key))
+ {
+ MUTEX_UNLOCK (cfg->data->lock);
+ return -1;
+ }
+ s = &cfg->data->sections[i]; /* side-effects of callback are
possible! */
+ }
}
- }
l.listener = callback;
l.ctx = ctx;
- APPEND(cfg->data->listeners,
- cfg->data->lsize,
- l);
- MUTEX_UNLOCK(cfg->data->lock);
+ APPEND (cfg->data->listeners, cfg->data->lsize, l);
+ MUTEX_UNLOCK (cfg->data->lock);
return 0;
}
static int
-_detach_change_listener(struct GC_Configuration * cfg,
- GC_ChangeListener callback,
- void * ctx) {
+_detach_change_listener (struct GC_Configuration *cfg,
+ GC_ChangeListener callback, void *ctx)
+{
int i;
- GC_Listener * l;
+ GC_Listener *l;
- MUTEX_LOCK(cfg->data->lock);
- for (i=cfg->data->lsize-1;i>=0;i--) {
- l = &cfg->data->listeners[i];
- if ( (l->listener == callback) &&
- (l->ctx == ctx) ) {
- cfg->data->listeners[i]
- = cfg->data->listeners[cfg->data->lsize-1];
- GROW(cfg->data->listeners,
- cfg->data->lsize,
- cfg->data->lsize-1);
- MUTEX_UNLOCK(cfg->data->lock);
- return 0;
+ MUTEX_LOCK (cfg->data->lock);
+ for (i = cfg->data->lsize - 1; i >= 0; i--)
+ {
+ l = &cfg->data->listeners[i];
+ if ((l->listener == callback) && (l->ctx == ctx))
+ {
+ cfg->data->listeners[i]
+ = cfg->data->listeners[cfg->data->lsize - 1];
+ GROW (cfg->data->listeners, cfg->data->lsize, cfg->data->lsize - 1);
+ MUTEX_UNLOCK (cfg->data->lock);
+ return 0;
+ }
}
- }
- MUTEX_UNLOCK(cfg->data->lock);
+ MUTEX_UNLOCK (cfg->data->lock);
return -1;
}
@@ -892,13 +880,14 @@
* Create a GC_Configuration (C implementation).
*/
GC_Configuration *
-GC_create_C_impl() {
- GC_Configuration * ret;
+GC_create_C_impl ()
+{
+ GC_Configuration *ret;
- ret = MALLOC(sizeof(GC_Configuration));
- ret->data = MALLOC(sizeof(GC_ConfigurationData));
- memset(ret->data, 0, sizeof(GC_ConfigurationData));
- ret->data->lock = MUTEX_CREATE(YES);
+ ret = MALLOC (sizeof (GC_Configuration));
+ ret->data = MALLOC (sizeof (GC_ConfigurationData));
+ memset (ret->data, 0, sizeof (GC_ConfigurationData));
+ ret->data->lock = MUTEX_CREATE (YES);
ret->free = &_free;
ret->set_error_context = &_set_error_context;
ret->parse_configuration = &_parse_configuration;
@@ -917,4 +906,3 @@
ret->have_configuration_value = &_have_configuration_value;
return ret;
}
-
Modified: GNUnet/src/util/containers/bloomfilter.c
===================================================================
--- GNUnet/src/util/containers/bloomfilter.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/containers/bloomfilter.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -43,27 +43,28 @@
#include "gnunet_util_containers.h"
#include "platform.h"
-typedef struct Bloomfilter {
+typedef struct Bloomfilter
+{
/**
* Concurrency control
*/
- struct MUTEX * lock;
+ struct MUTEX *lock;
/**
* The actual bloomfilter bit array
*/
- char * bitArray;
+ char *bitArray;
/**
* For error handling.
*/
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
/**
* Filename of the filter
*/
- char * filename;
+ char *filename;
/**
* The bit counter file on disk
@@ -90,8 +91,9 @@
* @param bitArray memory area to set the bit in
* @param bitIdx which bit to set
*/
-static void setBit(char * bitArray,
- unsigned int bitIdx) {
+static void
+setBit (char *bitArray, unsigned int bitIdx)
+{
unsigned int arraySlot;
unsigned int targetBit;
@@ -107,8 +109,9 @@
* @param bitArray memory area to set the bit in
* @param bitIdx which bit to unset
*/
-static void clearBit(char * bitArray,
- unsigned int bitIdx) {
+static void
+clearBit (char *bitArray, unsigned int bitIdx)
+{
unsigned int slot;
unsigned int targetBit;
@@ -124,8 +127,9 @@
* @param bitIdx which bit to test
* @return YES if the bit is set, NO if not.
*/
-static int testBit(char * bitArray,
- unsigned int bitIdx) {
+static int
+testBit (char *bitArray, unsigned int bitIdx)
+{
unsigned int slot;
unsigned int targetBit;
@@ -146,50 +150,48 @@
* @param bitIdx which bit to test
* @param fd A file to keep the 4 bit address usage counters in
*/
-static void incrementBit(char * bitArray,
- unsigned int bitIdx,
- int fd) {
+static void
+incrementBit (char *bitArray, unsigned int bitIdx, int fd)
+{
unsigned int fileSlot;
unsigned char value;
unsigned int high;
unsigned int low;
unsigned int targetLoc;
- setBit(bitArray, bitIdx);
+ setBit (bitArray, bitIdx);
if (fd == -1)
return;
/* Update the counter file on disk */
fileSlot = bitIdx / 2;
targetLoc = bitIdx % 2;
- if (fileSlot != (unsigned int) lseek(fd, fileSlot, SEEK_SET))
- GE_DIE_STRERROR(NULL,
- GE_ADMIN | GE_USER | GE_FATAL | GE_IMMEDIATE,
- "lseek");
+ if (fileSlot != (unsigned int) lseek (fd, fileSlot, SEEK_SET))
+ GE_DIE_STRERROR (NULL,
+ GE_ADMIN | GE_USER | GE_FATAL | GE_IMMEDIATE, "lseek");
value = 0;
- READ(fd,
- &value,
- 1);
+ READ (fd, &value, 1);
low = value & 0xF;
high = (value & (~0xF)) >> 4;
- if (targetLoc == 0) {
- if (low < 0xF)
- low++;
- } else {
- if (high < 0xF)
- high++;
- }
- value = ((high<<4) | low);
- if (fileSlot != (unsigned int) lseek(fd, fileSlot, SEEK_SET))
- GE_DIE_STRERROR(NULL,
- GE_ADMIN | GE_USER | GE_FATAL | GE_IMMEDIATE,
- "lseek");
- if (1 != WRITE(fd, &value, 1))
- GE_DIE_STRERROR(NULL,
- GE_ADMIN | GE_USER | GE_FATAL | GE_IMMEDIATE,
- "write");
+ if (targetLoc == 0)
+ {
+ if (low < 0xF)
+ low++;
+ }
+ else
+ {
+ if (high < 0xF)
+ high++;
+ }
+ value = ((high << 4) | low);
+ if (fileSlot != (unsigned int) lseek (fd, fileSlot, SEEK_SET))
+ GE_DIE_STRERROR (NULL,
+ GE_ADMIN | GE_USER | GE_FATAL | GE_IMMEDIATE, "lseek");
+ if (1 != WRITE (fd, &value, 1))
+ GE_DIE_STRERROR (NULL,
+ GE_ADMIN | GE_USER | GE_FATAL | GE_IMMEDIATE, "write");
}
@@ -201,9 +203,9 @@
* @param bitIdx which bit to test
* @param fd A file to keep the 4bit address usage counters in
*/
-static void decrementBit(char * bitArray,
- unsigned int bitIdx,
- int fd) {
+static void
+decrementBit (char *bitArray, unsigned int bitIdx, int fd)
+{
unsigned int fileSlot;
unsigned char value;
unsigned int high;
@@ -211,38 +213,42 @@
unsigned int targetLoc;
if (fd == -1)
- return; /* cannot decrement! */
- GE_ASSERT(NULL, fd != -1);
+ return; /* cannot decrement! */
+ GE_ASSERT (NULL, fd != -1);
/* Each char slot in the counter file holds two 4 bit counters */
fileSlot = bitIdx / 2;
targetLoc = bitIdx % 2;
- lseek(fd, fileSlot, SEEK_SET);
+ lseek (fd, fileSlot, SEEK_SET);
value = 0;
- READ(fd, &value, 1);
+ READ (fd, &value, 1);
- low = value & 0xF;
+ low = value & 0xF;
high = (value & 0xF0) >> 4;
/* decrement, but once we have reached the max, never go back! */
- if (targetLoc == 0) {
- if ( (low > 0) && (low < 0xF) )
- low--;
- if (low == 0) {
- clearBit(bitArray, bitIdx);
+ if (targetLoc == 0)
+ {
+ if ((low > 0) && (low < 0xF))
+ low--;
+ if (low == 0)
+ {
+ clearBit (bitArray, bitIdx);
+ }
}
- } else {
- if ( (high > 0) && (high < 0xF) )
- high--;
- if (high == 0) {
- clearBit(bitArray, bitIdx);
+ else
+ {
+ if ((high > 0) && (high < 0xF))
+ high--;
+ if (high == 0)
+ {
+ clearBit (bitArray, bitIdx);
+ }
}
- }
- value = ((high<<4) | low);
- lseek(fd, fileSlot, SEEK_SET);
- if (1 != WRITE(fd, &value, 1))
- GE_DIE_STRERROR(NULL,
- GE_ADMIN | GE_USER | GE_FATAL | GE_IMMEDIATE,
- "write");
+ value = ((high << 4) | low);
+ lseek (fd, fileSlot, SEEK_SET);
+ if (1 != WRITE (fd, &value, 1))
+ GE_DIE_STRERROR (NULL,
+ GE_ADMIN | GE_USER | GE_FATAL | GE_IMMEDIATE, "write");
}
#define BUFFSIZE 65536
@@ -254,35 +260,41 @@
* @param size the size of the file
* @return OK if created ok, SYSERR otherwise
*/
-static int makeEmptyFile(int fd,
- unsigned int size) {
- char * buffer;
- unsigned int bytesleft=size;
+static int
+makeEmptyFile (int fd, unsigned int size)
+{
+ char *buffer;
+ unsigned int bytesleft = size;
int res = 0;
if (fd == -1)
return SYSERR;
- buffer = MALLOC(BUFFSIZE);
- memset(buffer, 0, BUFFSIZE);
- lseek(fd, 0, SEEK_SET);
+ buffer = MALLOC (BUFFSIZE);
+ memset (buffer, 0, BUFFSIZE);
+ lseek (fd, 0, SEEK_SET);
- while (bytesleft > 0) {
- if (bytesleft>BUFFSIZE) {
- res = WRITE(fd, buffer, BUFFSIZE);
- bytesleft -= BUFFSIZE;
- } else {
- res = WRITE(fd, buffer, bytesleft);
- bytesleft = 0;
+ while (bytesleft > 0)
+ {
+ if (bytesleft > BUFFSIZE)
+ {
+ res = WRITE (fd, buffer, BUFFSIZE);
+ bytesleft -= BUFFSIZE;
+ }
+ else
+ {
+ res = WRITE (fd, buffer, bytesleft);
+ bytesleft = 0;
+ }
+ if (res == -1)
+ {
+ GE_DIE_STRERROR (NULL,
+ GE_ADMIN | GE_USER | GE_FATAL | GE_IMMEDIATE,
+ "write");
+ FREE (buffer);
+ return SYSERR;
+ }
}
- if(res == -1) {
- GE_DIE_STRERROR(NULL,
- GE_ADMIN | GE_USER | GE_FATAL | GE_IMMEDIATE,
- "write");
- FREE(buffer);
- return SYSERR;
- }
- }
- FREE(buffer);
+ FREE (buffer);
return OK;
}
@@ -297,10 +309,8 @@
* @param bit the current bit
* @param additional context specific argument
*/
-typedef void (*BitIterator)(Bloomfilter * bf,
- unsigned int bit,
- void * arg);
-
+typedef void (*BitIterator) (Bloomfilter * bf, unsigned int bit, void *arg);
+
/**
* Call an iterator for each bit that the bloomfilter
* must test or set for this element.
@@ -310,38 +320,37 @@
* @param arg extra argument to callback
* @param key the key for which we iterate over the BF bits
*/
-static void iterateBits(Bloomfilter * bf,
- BitIterator callback,
- void * arg,
- const HashCode512 * key) {
+static void
+iterateBits (Bloomfilter * bf,
+ BitIterator callback, void *arg, const HashCode512 * key)
+{
HashCode512 tmp[2];
int bitCount;
int round;
- unsigned int slot=0;
+ unsigned int slot = 0;
bitCount = bf->addressesPerElement;
- memcpy(&tmp[0],
- key,
- sizeof(HashCode512));
+ memcpy (&tmp[0], key, sizeof (HashCode512));
round = 0;
- while (bitCount > 0) {
- while (slot < (sizeof(HashCode512)/sizeof(unsigned int))) {
- callback(bf,
- (((unsigned int*)&tmp[round&1])[slot]) & ((bf->bitArraySize*8)-1),
- arg);
- slot++;
- bitCount--;
- if (bitCount == 0)
- break;
+ while (bitCount > 0)
+ {
+ while (slot < (sizeof (HashCode512) / sizeof (unsigned int)))
+ {
+ callback (bf,
+ (((unsigned int *) &tmp[round & 1])[slot]) &
+ ((bf->bitArraySize * 8) - 1), arg);
+ slot++;
+ bitCount--;
+ if (bitCount == 0)
+ break;
+ }
+ if (bitCount > 0)
+ {
+ hash (&tmp[round & 1], sizeof (HashCode512), &tmp[(round + 1) & 1]);
+ round++;
+ slot = 0;
+ }
}
- if (bitCount > 0) {
- hash(&tmp[round & 1],
- sizeof(HashCode512),
- &tmp[(round+1) & 1]);
- round++;
- slot = 0;
- }
- }
}
/**
@@ -351,12 +360,10 @@
* @param bit the bit to increment
* @param arg not used
*/
-static void incrementBitCallback(Bloomfilter * bf,
- unsigned int bit,
- void * arg) {
- incrementBit(bf->bitArray,
- bit,
- bf->fd);
+static void
+incrementBitCallback (Bloomfilter * bf, unsigned int bit, void *arg)
+{
+ incrementBit (bf->bitArray, bit, bf->fd);
}
/**
@@ -366,12 +373,10 @@
* @param bit the bit to decrement
* @param arg not used
*/
-static void decrementBitCallback(Bloomfilter * bf,
- unsigned int bit,
- void * arg) {
- decrementBit(bf->bitArray,
- bit,
- bf->fd);
+static void
+decrementBitCallback (Bloomfilter * bf, unsigned int bit, void *arg)
+{
+ decrementBit (bf->bitArray, bit, bf->fd);
}
/**
@@ -381,12 +386,11 @@
* @param bit the bit to test
* @param arg pointer set to NO if bit is not set
*/
-static void testBitCallback(Bloomfilter * bf,
- unsigned int bit,
- void * cls) {
- int * arg = cls;
- if (NO == testBit(bf->bitArray,
- bit))
+static void
+testBitCallback (Bloomfilter * bf, unsigned int bit, void *cls)
+{
+ int *arg = cls;
+ if (NO == testBit (bf->bitArray, bit))
*arg = NO;
}
@@ -402,85 +406,82 @@
* element (number of bits set per element in the set)
* @return the bloomfilter
*/
-Bloomfilter * loadBloomfilter(struct GE_Context * ectx,
- const char * filename,
- unsigned int size,
- unsigned int k) {
- Bloomfilter * bf;
- char * rbuff;
+Bloomfilter *
+loadBloomfilter (struct GE_Context *ectx,
+ const char *filename, unsigned int size, unsigned int k)
+{
+ Bloomfilter *bf;
+ char *rbuff;
unsigned int pos;
int i;
unsigned int ui;
- if ( (k==0) ||
- (size==0) )
+ if ((k == 0) || (size == 0))
return NULL;
if (size < BUFFSIZE)
size = BUFFSIZE;
ui = 1;
while (ui < size)
- ui*=2;
- size = ui; /* make sure it's a power of 2 */
+ ui *= 2;
+ size = ui; /* make sure it's a power of 2 */
- bf = MALLOC(sizeof(Bloomfilter));
+ bf = MALLOC (sizeof (Bloomfilter));
bf->ectx = ectx;
/* Try to open a bloomfilter file */
- if (filename != NULL) {
+ if (filename != NULL)
+ {
#ifndef _MSC_VER
- bf->fd = disk_file_open(ectx,
- filename,
- O_RDWR|O_CREAT,
- S_IRUSR|S_IWUSR);
+ bf->fd = disk_file_open (ectx,
+ filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
#else
- bf->fd = disk_file_open(ectx,
- filename,
- O_WRONLY|O_CREAT,
- S_IREAD|S_IWRITE);
+ bf->fd = disk_file_open (ectx,
+ filename,
+ O_WRONLY | O_CREAT, S_IREAD | S_IWRITE);
#endif
- if (-1 == bf->fd) {
- FREE(bf);
- return NULL;
+ if (-1 == bf->fd)
+ {
+ FREE (bf);
+ return NULL;
+ }
+ bf->filename = STRDUP (filename);
}
- bf->filename = STRDUP(filename);
- } else {
- bf->fd = -1;
- bf->filename = NULL;
- }
+ else
+ {
+ bf->fd = -1;
+ bf->filename = NULL;
+ }
/* Alloc block */
- bf->lock = MUTEX_CREATE(YES);
- bf->bitArray = MALLOC_LARGE(size);
+ bf->lock = MUTEX_CREATE (YES);
+ bf->bitArray = MALLOC_LARGE (size);
bf->bitArraySize = size;
bf->addressesPerElement = k;
- memset(bf->bitArray,
- 0,
- bf->bitArraySize);
+ memset (bf->bitArray, 0, bf->bitArraySize);
- if (bf->fd != -1) {
- /* Read from the file what bits we can */
- rbuff = MALLOC(BUFFSIZE);
- pos = 0;
- while (pos < size*8) {
- int res;
+ if (bf->fd != -1)
+ {
+ /* Read from the file what bits we can */
+ rbuff = MALLOC (BUFFSIZE);
+ pos = 0;
+ while (pos < size * 8)
+ {
+ int res;
- res = READ(bf->fd,
- rbuff,
- BUFFSIZE);
- if (res == 0)
- break; /* is ok! we just did not use that many bits yet */
- for (i=0;i<res;i++) {
- if ( (rbuff[i] & 0x0F) != 0)
- setBit(bf->bitArray,
- pos + i*2);
- if ( (rbuff[i] & 0xF0) != 0)
- setBit(bf->bitArray,
- pos + i*2 + 1);
- }
- if (res < BUFFSIZE)
- break;
- pos += BUFFSIZE * 2; /* 2 bits per byte in the buffer */
+ res = READ (bf->fd, rbuff, BUFFSIZE);
+ if (res == 0)
+ break; /* is ok! we just did not use that many bits
yet */
+ for (i = 0; i < res; i++)
+ {
+ if ((rbuff[i] & 0x0F) != 0)
+ setBit (bf->bitArray, pos + i * 2);
+ if ((rbuff[i] & 0xF0) != 0)
+ setBit (bf->bitArray, pos + i * 2 + 1);
+ }
+ if (res < BUFFSIZE)
+ break;
+ pos += BUFFSIZE * 2; /* 2 bits per byte in the buffer */
+ }
+ FREE (rbuff);
}
- FREE(rbuff);
- }
return bf;
}
@@ -491,17 +492,17 @@
*
* @param bf the filter
*/
-void freeBloomfilter(Bloomfilter * bf) {
+void
+freeBloomfilter (Bloomfilter * bf)
+{
if (NULL == bf)
return;
- MUTEX_DESTROY(bf->lock);
+ MUTEX_DESTROY (bf->lock);
if (bf->fd != -1)
- disk_file_close(bf->ectx,
- bf->filename,
- bf->fd);
- FREENONNULL(bf->filename);
- FREE(bf->bitArray);
- FREE(bf);
+ disk_file_close (bf->ectx, bf->filename, bf->fd);
+ FREENONNULL (bf->filename);
+ FREE (bf->bitArray);
+ FREE (bf);
}
/**
@@ -509,18 +510,17 @@
*
* @param bf the filter
*/
-void resetBloomfilter(Bloomfilter * bf) {
+void
+resetBloomfilter (Bloomfilter * bf)
+{
if (NULL == bf)
return;
- MUTEX_LOCK(bf->lock);
- memset(bf->bitArray,
- 0,
- bf->bitArraySize);
+ MUTEX_LOCK (bf->lock);
+ memset (bf->bitArray, 0, bf->bitArraySize);
if (bf->fd != -1)
- makeEmptyFile(bf->fd,
- bf->bitArraySize * 4);
- MUTEX_UNLOCK(bf->lock);
+ makeEmptyFile (bf->fd, bf->bitArraySize * 4);
+ MUTEX_UNLOCK (bf->lock);
}
@@ -531,19 +531,17 @@
* @param bf the filter
* @return YES if the element is in the filter, NO if not
*/
-int testBloomfilter(Bloomfilter * bf,
- const HashCode512 * e) {
+int
+testBloomfilter (Bloomfilter * bf, const HashCode512 * e)
+{
int res;
if (NULL == bf)
return YES;
- MUTEX_LOCK(bf->lock);
+ MUTEX_LOCK (bf->lock);
res = YES;
- iterateBits(bf,
- &testBitCallback,
- &res,
- e);
- MUTEX_UNLOCK(bf->lock);
+ iterateBits (bf, &testBitCallback, &res, e);
+ MUTEX_UNLOCK (bf->lock);
return res;
}
@@ -553,17 +551,15 @@
* @param bf the filter
* @param e the element
*/
-void addToBloomfilter(Bloomfilter * bf,
- const HashCode512 * e) {
+void
+addToBloomfilter (Bloomfilter * bf, const HashCode512 * e)
+{
if (NULL == bf)
return;
- MUTEX_LOCK(bf->lock);
- iterateBits(bf,
- &incrementBitCallback,
- NULL,
- e);
- MUTEX_UNLOCK(bf->lock);
+ MUTEX_LOCK (bf->lock);
+ iterateBits (bf, &incrementBitCallback, NULL, e);
+ MUTEX_UNLOCK (bf->lock);
}
/**
@@ -572,16 +568,14 @@
* @param bf the filter
* @param e the element to remove
*/
-void delFromBloomfilter(Bloomfilter * bf,
- const HashCode512 * e) {
- if(NULL == bf)
+void
+delFromBloomfilter (Bloomfilter * bf, const HashCode512 * e)
+{
+ if (NULL == bf)
return;
- MUTEX_LOCK(bf->lock);
- iterateBits(bf,
- &decrementBitCallback,
- NULL,
- e);
- MUTEX_UNLOCK(bf->lock);
+ MUTEX_LOCK (bf->lock);
+ iterateBits (bf, &decrementBitCallback, NULL, e);
+ MUTEX_UNLOCK (bf->lock);
}
/**
@@ -595,37 +589,34 @@
* @param size the new size for the filter
* @param k the new number of hash-function to apply per element
*/
-void resizeBloomfilter(Bloomfilter * bf,
- ElementIterator iterator,
- void * iterator_arg,
- unsigned int size,
- unsigned int k) {
- HashCode512 * e;
+void
+resizeBloomfilter (Bloomfilter * bf,
+ ElementIterator iterator,
+ void *iterator_arg, unsigned int size, unsigned int k)
+{
+ HashCode512 *e;
unsigned int i;
- MUTEX_LOCK(bf->lock);
- FREE(bf->bitArray);
+ MUTEX_LOCK (bf->lock);
+ FREE (bf->bitArray);
i = 1;
while (i < size)
- i*=2;
- size = i; /* make sure it's a power of 2 */
+ i *= 2;
+ size = i; /* make sure it's a power of 2 */
bf->bitArraySize = size;
- bf->bitArray = MALLOC(size);
- memset(bf->bitArray,
- 0,
- bf->bitArraySize);
+ bf->bitArray = MALLOC (size);
+ memset (bf->bitArray, 0, bf->bitArraySize);
if (bf->fd != -1)
- makeEmptyFile(bf->fd,
- bf->bitArraySize * 4);
- e = iterator(iterator_arg);
- while (e != NULL) {
- addToBloomfilter(bf,
- e);
- FREE(e);
- e = iterator(iterator_arg);
- }
- MUTEX_UNLOCK(bf->lock);
+ makeEmptyFile (bf->fd, bf->bitArraySize * 4);
+ e = iterator (iterator_arg);
+ while (e != NULL)
+ {
+ addToBloomfilter (bf, e);
+ FREE (e);
+ e = iterator (iterator_arg);
+ }
+ MUTEX_UNLOCK (bf->lock);
}
/* ******************** end of bloomfilter.c *********** */
Modified: GNUnet/src/util/containers/bloomtest.c
===================================================================
--- GNUnet/src/util/containers/bloomtest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/containers/bloomtest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -34,98 +34,100 @@
/**
* Generate a random hashcode.
*/
-static void nextHC(HashCode512 * hc) {
- makeRandomId(hc);
+static void
+nextHC (HashCode512 * hc)
+{
+ makeRandomId (hc);
}
-int main(int argc, char *argv[]) {
+int
+main (int argc, char *argv[])
+{
struct Bloomfilter *bf;
HashCode512 tmp;
int i;
int ok;
int falseok;
- srand(1);
- UNLINK("/tmp/bloomtest.dat");
- bf = loadBloomfilter(NULL,
- "/tmp/bloomtest.dat",
- SIZE,
- K);
+ srand (1);
+ UNLINK ("/tmp/bloomtest.dat");
+ bf = loadBloomfilter (NULL, "/tmp/bloomtest.dat", SIZE, K);
- for(i=0;i<200;i++) {
- nextHC(&tmp);
- addToBloomfilter(bf, &tmp);
- }
- srand(1);
- ok=0;
- for(i=0;i<200;i++) {
- nextHC(&tmp);
- if (testBloomfilter(bf, &tmp) == YES)
- ok++;
- }
- if (ok != 200) {
- printf(" Got %d elements out of"
- "200 expected after insertion.\n",
- ok);
- return -1;
- }
- freeBloomfilter(bf);
+ for (i = 0; i < 200; i++)
+ {
+ nextHC (&tmp);
+ addToBloomfilter (bf, &tmp);
+ }
+ srand (1);
+ ok = 0;
+ for (i = 0; i < 200; i++)
+ {
+ nextHC (&tmp);
+ if (testBloomfilter (bf, &tmp) == YES)
+ ok++;
+ }
+ if (ok != 200)
+ {
+ printf (" Got %d elements out of"
+ "200 expected after insertion.\n", ok);
+ return -1;
+ }
+ freeBloomfilter (bf);
- bf=loadBloomfilter(NULL,
- "/tmp/bloomtest.dat",
- SIZE,
- K);
+ bf = loadBloomfilter (NULL, "/tmp/bloomtest.dat", SIZE, K);
- srand(1);
- ok=0;
- for(i=0;i<200;i++) {
- nextHC(&tmp);
- if (testBloomfilter(bf, &tmp) == YES)
- ok++;
- }
- if (ok != 200) {
- printf(" Got %d elements out of 200"
- "expected after reloading.\n",
- ok);
- return -1;
- }
+ srand (1);
+ ok = 0;
+ for (i = 0; i < 200; i++)
+ {
+ nextHC (&tmp);
+ if (testBloomfilter (bf, &tmp) == YES)
+ ok++;
+ }
+ if (ok != 200)
+ {
+ printf (" Got %d elements out of 200"
+ "expected after reloading.\n", ok);
+ return -1;
+ }
- srand(1);
- for(i=0;i<100;i++) {
- nextHC(&tmp);
- delFromBloomfilter(bf, &tmp);
- }
+ srand (1);
+ for (i = 0; i < 100; i++)
+ {
+ nextHC (&tmp);
+ delFromBloomfilter (bf, &tmp);
+ }
- srand(1);
+ srand (1);
- ok=0;
- for(i=0;i<200;i++) {
- nextHC(&tmp);
- if(testBloomfilter(bf, &tmp) == YES)
- ok++;
- }
+ ok = 0;
+ for (i = 0; i < 200; i++)
+ {
+ nextHC (&tmp);
+ if (testBloomfilter (bf, &tmp) == YES)
+ ok++;
+ }
- if (ok != 100) {
- printf(" Expected 100 elements in filter"
- " after adding 200 and deleting 100, got %d\n",
- ok);
- return -1;
- }
+ if (ok != 100)
+ {
+ printf (" Expected 100 elements in filter"
+ " after adding 200 and deleting 100, got %d\n", ok);
+ return -1;
+ }
- srand(3);
+ srand (3);
- falseok=0;
- for(i=0;i<1000;i++) {
- nextHC(&tmp);
- if(testBloomfilter(bf, &tmp) == YES)
- falseok++;
- }
+ falseok = 0;
+ for (i = 0; i < 1000; i++)
+ {
+ nextHC (&tmp);
+ if (testBloomfilter (bf, &tmp) == YES)
+ falseok++;
+ }
- freeBloomfilter(bf);
+ freeBloomfilter (bf);
- UNLINK("/tmp/bloomtest.dat");
+ UNLINK ("/tmp/bloomtest.dat");
return 0;
}
-
-
Modified: GNUnet/src/util/containers/hashtable.c
===================================================================
--- GNUnet/src/util/containers/hashtable.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/containers/hashtable.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -32,7 +32,8 @@
#include "gnunet_util_containers.h"
#include "platform.h"
-typedef struct KeyValuePair {
+typedef struct KeyValuePair
+{
void *key;
unsigned long keylen;
void *value;
@@ -40,7 +41,8 @@
struct KeyValuePair *next;
} KeyValuePair;
-typedef struct HashTable {
+typedef struct HashTable
+{
long numOfBuckets;
long numOfElements;
KeyValuePair **bucketArray;
@@ -55,38 +57,45 @@
* @param n the size of z
* @return the hashcode
*/
-static unsigned long long weakHash(const char *z, int n){
+static unsigned long long
+weakHash (const char *z, int n)
+{
unsigned long long h = 0;
- while(n > 0) {
- h = (h << 3) ^ h ^ (unsigned char) *z++;
- n--;
- }
+ while (n > 0)
+ {
+ h = (h << 3) ^ h ^ (unsigned char) *z++;
+ n--;
+ }
return h;
}
-static int isProbablePrime(long oddNumber) {
+static int
+isProbablePrime (long oddNumber)
+{
long i;
- for (i=3; i<51; i+=2)
+ for (i = 3; i < 51; i += 2)
if (oddNumber == i)
return 1;
- else if (oddNumber%i == 0)
+ else if (oddNumber % i == 0)
return 0;
- return 1; /* maybe */
+ return 1; /* maybe */
}
-static long calculateIdealNumOfBuckets(const struct HashTable *hashTable) {
- long idealNumOfBuckets = hashTable->numOfElements / hashTable->idealRatio;
- if (idealNumOfBuckets < 5)
- idealNumOfBuckets = 5;
- else
- idealNumOfBuckets |= 0x01; /* make it an odd number */
- while (!isProbablePrime(idealNumOfBuckets))
- idealNumOfBuckets += 2;
+static long
+calculateIdealNumOfBuckets (const struct HashTable *hashTable)
+{
+ long idealNumOfBuckets = hashTable->numOfElements / hashTable->idealRatio;
+ if (idealNumOfBuckets < 5)
+ idealNumOfBuckets = 5;
+ else
+ idealNumOfBuckets |= 0x01; /* make it an odd number */
+ while (!isProbablePrime (idealNumOfBuckets))
+ idealNumOfBuckets += 2;
- return idealNumOfBuckets;
+ return idealNumOfBuckets;
}
@@ -107,57 +116,64 @@
* passes the thresholds set by ht_setIdealRatio().
* @return a new Hashtable, or NULL on error
*/
-struct HashTable *ht_create(long numOfBuckets) {
- struct HashTable *hashTable;
- int i;
+struct HashTable *
+ht_create (long numOfBuckets)
+{
+ struct HashTable *hashTable;
+ int i;
- if (numOfBuckets <= 0)
- return NULL;
+ if (numOfBuckets <= 0)
+ return NULL;
- hashTable = (struct HashTable *) MALLOC(sizeof(struct HashTable));
- if (hashTable == NULL)
- return NULL;
+ hashTable = (struct HashTable *) MALLOC (sizeof (struct HashTable));
+ if (hashTable == NULL)
+ return NULL;
- hashTable->bucketArray = (KeyValuePair **)
- MALLOC(numOfBuckets * sizeof(KeyValuePair *));
- if (hashTable->bucketArray == NULL) {
- FREE(hashTable);
- return NULL;
+ hashTable->bucketArray = (KeyValuePair **)
+ MALLOC (numOfBuckets * sizeof (KeyValuePair *));
+ if (hashTable->bucketArray == NULL)
+ {
+ FREE (hashTable);
+ return NULL;
}
- hashTable->numOfBuckets = numOfBuckets;
- hashTable->numOfElements = 0;
+ hashTable->numOfBuckets = numOfBuckets;
+ hashTable->numOfElements = 0;
- for (i=0; i<numOfBuckets; i++)
- hashTable->bucketArray[i] = NULL;
+ for (i = 0; i < numOfBuckets; i++)
+ hashTable->bucketArray[i] = NULL;
- hashTable->idealRatio = 3.0;
- hashTable->lowerRehashThreshold = 0.0;
- hashTable->upperRehashThreshold = 15.0;
+ hashTable->idealRatio = 3.0;
+ hashTable->lowerRehashThreshold = 0.0;
+ hashTable->upperRehashThreshold = 15.0;
- return hashTable;
+ return hashTable;
}
/**
* @brief destroys an existing HashTable
* @param hashTable the HashTable to destroy
*/
-void ht_destroy(struct HashTable *hashTable) {
- int i;
+void
+ht_destroy (struct HashTable *hashTable)
+{
+ int i;
- for (i=0; i < hashTable->numOfBuckets; i++) {
- KeyValuePair *pair = hashTable->bucketArray[i];
- while (pair != NULL) {
- KeyValuePair *nextPair = pair->next;
- FREE(pair->key);
- FREE(pair->value);
- FREE(pair);
- pair = nextPair;
+ for (i = 0; i < hashTable->numOfBuckets; i++)
+ {
+ KeyValuePair *pair = hashTable->bucketArray[i];
+ while (pair != NULL)
+ {
+ KeyValuePair *nextPair = pair->next;
+ FREE (pair->key);
+ FREE (pair->value);
+ FREE (pair);
+ pair = nextPair;
}
}
- FREE(hashTable->bucketArray);
- FREE(hashTable);
+ FREE (hashTable->bucketArray);
+ FREE (hashTable);
}
/**
@@ -167,13 +183,14 @@
* @return whether or not the specified HashTable contains the
* specified key
*/
-int ht_containsKey(const struct HashTable *hashTable,
- const void *key,
- const unsigned int keylen) {
- void *ret;
- unsigned int retlen;
+int
+ht_containsKey (const struct HashTable *hashTable,
+ const void *key, const unsigned int keylen)
+{
+ void *ret;
+ unsigned int retlen;
- return ht_get(hashTable, key, keylen, &ret, &retlen);
+ return ht_get (hashTable, key, keylen, &ret, &retlen);
}
/**
@@ -183,22 +200,25 @@
* @return whether or not the specified HashTable contains the
* specified value
*/
-int ht_containsValue(const struct HashTable *hashTable,
- const void *value,
- const unsigned int valuelen) {
- int i;
+int
+ht_containsValue (const struct HashTable *hashTable,
+ const void *value, const unsigned int valuelen)
+{
+ int i;
- for (i=0; i<hashTable->numOfBuckets; i++) {
- KeyValuePair *pair = hashTable->bucketArray[i];
- while (pair != NULL) {
- if ( (pair->valuelen == valuelen) &&
- (memcmp(value, pair->value, valuelen) == 0) )
- return 1;
- pair = pair->next;
+ for (i = 0; i < hashTable->numOfBuckets; i++)
+ {
+ KeyValuePair *pair = hashTable->bucketArray[i];
+ while (pair != NULL)
+ {
+ if ((pair->valuelen == valuelen) &&
+ (memcmp (value, pair->value, valuelen) == 0))
+ return 1;
+ pair = pair->next;
}
}
- return 0;
+ return 0;
}
/**
@@ -208,58 +228,62 @@
* @param value the value associated with the key
* @return YES if successful, NO if an error was encountered
*/
-int ht_put(struct HashTable *hashTable,
- const void *key,
- const unsigned int keylen,
- void *value,
- const unsigned int valuelen) {
- long hashValue;
- KeyValuePair *pair;
+int
+ht_put (struct HashTable *hashTable,
+ const void *key,
+ const unsigned int keylen, void *value, const unsigned int valuelen)
+{
+ long hashValue;
+ KeyValuePair *pair;
- if (key == NULL || value == NULL)
- return NO;
+ if (key == NULL || value == NULL)
+ return NO;
- hashValue = weakHash(key, keylen) % hashTable->numOfBuckets;
- pair = hashTable->bucketArray[hashValue];
+ hashValue = weakHash (key, keylen) % hashTable->numOfBuckets;
+ pair = hashTable->bucketArray[hashValue];
- while (pair != NULL && pair->keylen != keylen &&
- memcmp(key, pair->key, keylen) != 0)
- pair = pair->next;
+ while (pair != NULL && pair->keylen != keylen &&
+ memcmp (key, pair->key, keylen) != 0)
+ pair = pair->next;
- if (pair) {
- pair->key = REALLOC(pair->key, keylen);
- memcpy(pair->key, key, keylen);
- pair->keylen = keylen;
+ if (pair)
+ {
+ pair->key = REALLOC (pair->key, keylen);
+ memcpy (pair->key, key, keylen);
+ pair->keylen = keylen;
- pair->key = REALLOC(value, valuelen);
- memcpy(pair->value, value, valuelen);
- pair->valuelen = valuelen;
+ pair->key = REALLOC (value, valuelen);
+ memcpy (pair->value, value, valuelen);
+ pair->valuelen = valuelen;
}
- else {
- KeyValuePair *newPair = MALLOC(sizeof(KeyValuePair));
- if (newPair == NULL)
- return NO;
- else {
- newPair->key = MALLOC(keylen);
- memcpy(newPair->key, key, keylen);
- newPair->keylen = keylen;
- newPair->value = MALLOC(valuelen);
- memcpy(newPair->value, value, valuelen);
- newPair->valuelen = valuelen;
- newPair->next = hashTable->bucketArray[hashValue];
- hashTable->bucketArray[hashValue] = newPair;
- hashTable->numOfElements++;
+ else
+ {
+ KeyValuePair *newPair = MALLOC (sizeof (KeyValuePair));
+ if (newPair == NULL)
+ return NO;
+ else
+ {
+ newPair->key = MALLOC (keylen);
+ memcpy (newPair->key, key, keylen);
+ newPair->keylen = keylen;
+ newPair->value = MALLOC (valuelen);
+ memcpy (newPair->value, value, valuelen);
+ newPair->valuelen = valuelen;
+ newPair->next = hashTable->bucketArray[hashValue];
+ hashTable->bucketArray[hashValue] = newPair;
+ hashTable->numOfElements++;
- if (hashTable->upperRehashThreshold > hashTable->idealRatio) {
- float elementToBucketRatio = (float) hashTable->numOfElements /
- (float) hashTable->numOfBuckets;
- if (elementToBucketRatio > hashTable->upperRehashThreshold)
- ht_rehash(hashTable, 0);
+ if (hashTable->upperRehashThreshold > hashTable->idealRatio)
+ {
+ float elementToBucketRatio = (float) hashTable->numOfElements /
+ (float) hashTable->numOfBuckets;
+ if (elementToBucketRatio > hashTable->upperRehashThreshold)
+ ht_rehash (hashTable, 0);
}
}
}
- return YES;
+ return YES;
}
/**
@@ -270,24 +294,25 @@
* @param valuelen the length of the value
* @return YES if found, NO otherwise
*/
-int ht_get(const struct HashTable *hashTable,
- const void *key,
- const unsigned int keylen,
- void **value,
- unsigned int *valuelen) {
- long hashValue = weakHash(key, keylen) % hashTable->numOfBuckets;
- KeyValuePair *pair = hashTable->bucketArray[hashValue];
+int
+ht_get (const struct HashTable *hashTable,
+ const void *key,
+ const unsigned int keylen, void **value, unsigned int *valuelen)
+{
+ long hashValue = weakHash (key, keylen) % hashTable->numOfBuckets;
+ KeyValuePair *pair = hashTable->bucketArray[hashValue];
- while (pair != NULL && keylen != pair->keylen && memcmp(key, pair->key,
keylen) != 0)
- pair = pair->next;
+ while (pair != NULL && keylen != pair->keylen
+ && memcmp (key, pair->key, keylen) != 0)
+ pair = pair->next;
- if (pair != NULL)
+ if (pair != NULL)
{
*value = pair->value;
*valuelen = pair->valuelen;
}
- return pair != NULL;
+ return pair != NULL;
}
/**
@@ -295,34 +320,38 @@
* @param hashTable the HashTable to remove the key/value pair from
* @param key the key specifying the key/value pair to be removed
*/
-void ht_remove(struct HashTable *hashTable,
- const void *key,
- const unsigned int keylen) {
- long hashValue = weakHash(key, keylen) % hashTable->numOfBuckets;
- KeyValuePair *pair = hashTable->bucketArray[hashValue];
- KeyValuePair *previousPair = NULL;
+void
+ht_remove (struct HashTable *hashTable,
+ const void *key, const unsigned int keylen)
+{
+ long hashValue = weakHash (key, keylen) % hashTable->numOfBuckets;
+ KeyValuePair *pair = hashTable->bucketArray[hashValue];
+ KeyValuePair *previousPair = NULL;
- while (pair != NULL && pair->keylen != keylen &&
- memcmp(pair->key, key, keylen) != 0) {
- previousPair = pair;
- pair = pair->next;
+ while (pair != NULL && pair->keylen != keylen &&
+ memcmp (pair->key, key, keylen) != 0)
+ {
+ previousPair = pair;
+ pair = pair->next;
}
- if (pair != NULL) {
- FREE(pair->key);
- FREE(pair->value);
- if (previousPair != NULL)
- previousPair->next = pair->next;
- else
- hashTable->bucketArray[hashValue] = pair->next;
- FREE(pair);
- hashTable->numOfElements--;
+ if (pair != NULL)
+ {
+ FREE (pair->key);
+ FREE (pair->value);
+ if (previousPair != NULL)
+ previousPair->next = pair->next;
+ else
+ hashTable->bucketArray[hashValue] = pair->next;
+ FREE (pair);
+ hashTable->numOfElements--;
- if (hashTable->lowerRehashThreshold > 0.0) {
- float elementToBucketRatio = (float) hashTable->numOfElements /
- (float) hashTable->numOfBuckets;
- if (elementToBucketRatio < hashTable->lowerRehashThreshold)
- ht_rehash(hashTable, 0);
+ if (hashTable->lowerRehashThreshold > 0.0)
+ {
+ float elementToBucketRatio = (float) hashTable->numOfElements /
+ (float) hashTable->numOfBuckets;
+ if (elementToBucketRatio < hashTable->lowerRehashThreshold)
+ ht_rehash (hashTable, 0);
}
}
}
@@ -331,23 +360,27 @@
* @brief removes all key/value pairs from a HashTable
* @param hashTable the HashTable to remove all key/value pairs from
*/
-void ht_removeAll(struct HashTable *hashTable) {
- int i;
+void
+ht_removeAll (struct HashTable *hashTable)
+{
+ int i;
- for (i=0; i<hashTable->numOfBuckets; i++) {
- KeyValuePair *pair = hashTable->bucketArray[i];
- while (pair != NULL) {
- KeyValuePair *nextPair = pair->next;
- FREE(pair->key);
- FREE(pair->value);
- FREE(pair);
- pair = nextPair;
+ for (i = 0; i < hashTable->numOfBuckets; i++)
+ {
+ KeyValuePair *pair = hashTable->bucketArray[i];
+ while (pair != NULL)
+ {
+ KeyValuePair *nextPair = pair->next;
+ FREE (pair->key);
+ FREE (pair->value);
+ FREE (pair);
+ pair = nextPair;
}
- hashTable->bucketArray[i] = NULL;
+ hashTable->bucketArray[i] = NULL;
}
- hashTable->numOfElements = 0;
- ht_rehash(hashTable, 5);
+ hashTable->numOfElements = 0;
+ ht_rehash (hashTable, 5);
}
/**
@@ -356,8 +389,10 @@
* @return the number of key/value pairs that are present in
* the specified HashTable
*/
-long ht_size(const struct HashTable *hashTable) {
- return hashTable->numOfElements;
+long
+ht_size (const struct HashTable *hashTable)
+{
+ return hashTable->numOfElements;
}
/**
@@ -366,8 +401,10 @@
* @return the number of buckets that are in the specified
* HashTable
*/
-long ht_buckets(const struct HashTable *hashTable) {
- return hashTable->numOfBuckets;
+long
+ht_buckets (const struct HashTable *hashTable)
+{
+ return hashTable->numOfBuckets;
}
/**
@@ -382,41 +419,46 @@
* specified, an appropriate number of buckets is
* automatically calculated.
*/
-void ht_rehash(struct HashTable *hashTable, long numOfBuckets) {
- KeyValuePair **newBucketArray;
- int i;
+void
+ht_rehash (struct HashTable *hashTable, long numOfBuckets)
+{
+ KeyValuePair **newBucketArray;
+ int i;
- if (numOfBuckets == 0)
- numOfBuckets = calculateIdealNumOfBuckets(hashTable);
+ if (numOfBuckets == 0)
+ numOfBuckets = calculateIdealNumOfBuckets (hashTable);
- if (numOfBuckets == hashTable->numOfBuckets)
- return; /* already the right size! */
+ if (numOfBuckets == hashTable->numOfBuckets)
+ return; /* already the right size! */
- newBucketArray = (KeyValuePair **)
- MALLOC(numOfBuckets * sizeof(KeyValuePair *));
- if (newBucketArray == NULL) {
- /* Couldn't allocate memory for the new array. This isn't a fatal
- * error; we just can't perform the rehash. */
- return;
+ newBucketArray = (KeyValuePair **)
+ MALLOC (numOfBuckets * sizeof (KeyValuePair *));
+ if (newBucketArray == NULL)
+ {
+ /* Couldn't allocate memory for the new array. This isn't a fatal
+ * error; we just can't perform the rehash. */
+ return;
}
- for (i=0; i<numOfBuckets; i++)
- newBucketArray[i] = NULL;
+ for (i = 0; i < numOfBuckets; i++)
+ newBucketArray[i] = NULL;
- for (i=0; i<hashTable->numOfBuckets; i++) {
- KeyValuePair *pair = hashTable->bucketArray[i];
- while (pair != NULL) {
- KeyValuePair *nextPair = pair->next;
- long hashValue = weakHash(pair->key, pair->keylen) % numOfBuckets;
- pair->next = newBucketArray[hashValue];
- newBucketArray[hashValue] = pair;
- pair = nextPair;
+ for (i = 0; i < hashTable->numOfBuckets; i++)
+ {
+ KeyValuePair *pair = hashTable->bucketArray[i];
+ while (pair != NULL)
+ {
+ KeyValuePair *nextPair = pair->next;
+ long hashValue = weakHash (pair->key, pair->keylen) % numOfBuckets;
+ pair->next = newBucketArray[hashValue];
+ newBucketArray[hashValue] = pair;
+ pair = nextPair;
}
}
- FREE(hashTable->bucketArray);
- hashTable->bucketArray = newBucketArray;
- hashTable->numOfBuckets = numOfBuckets;
+ FREE (hashTable->bucketArray);
+ hashTable->bucketArray = newBucketArray;
+ hashTable->numOfBuckets = numOfBuckets;
}
/**
@@ -445,18 +487,19 @@
* is considered unacceptably high, a value of 0.0 can
* be specified.
*/
-void ht_setIdealRatio(struct HashTable *hashTable,
- float idealRatio,
- float lowerRehashThreshold,
- float upperRehashThreshold) {
+void
+ht_setIdealRatio (struct HashTable *hashTable,
+ float idealRatio,
+ float lowerRehashThreshold, float upperRehashThreshold)
+{
- if (idealRatio <= 0.0 || lowerRehashThreshold >= idealRatio ||
- (upperRehashThreshold != 0.0 || upperRehashThreshold <= idealRatio))
- return;
+ if (idealRatio <= 0.0 || lowerRehashThreshold >= idealRatio ||
+ (upperRehashThreshold != 0.0 || upperRehashThreshold <= idealRatio))
+ return;
- hashTable->idealRatio = idealRatio;
- hashTable->lowerRehashThreshold = lowerRehashThreshold;
- hashTable->upperRehashThreshold = upperRehashThreshold;
+ hashTable->idealRatio = idealRatio;
+ hashTable->lowerRehashThreshold = lowerRehashThreshold;
+ hashTable->upperRehashThreshold = upperRehashThreshold;
}
Modified: GNUnet/src/util/containers/hashtabletest.c
===================================================================
--- GNUnet/src/util/containers/hashtabletest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/containers/hashtabletest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -27,86 +27,89 @@
#include "gnunet_util_containers.h"
#include "platform.h"
-static int testHT()
+static int
+testHT ()
{
- struct HashTable *ht = ht_create(10);
+ struct HashTable *ht = ht_create (10);
void *val;
unsigned int vallen;
- if (HT_PUT(ht, "Sweden", "Stockholm") != YES ||
- HT_PUT(ht, "Germany", "Berlin") != YES ||
- HT_PUT(ht, "France", "Paris") != YES ||
- HT_PUT(ht, "Spain", "Madrid") != YES ||
- HT_PUT(ht, "Italy", "Rome") != YES ||
- HT_PUT(ht, "USA", "Washington") != YES)
- {
- puts("ht_put failed\n");
- ht_destroy(ht);
- return 1;
- }
+ if (HT_PUT (ht, "Sweden", "Stockholm") != YES ||
+ HT_PUT (ht, "Germany", "Berlin") != YES ||
+ HT_PUT (ht, "France", "Paris") != YES ||
+ HT_PUT (ht, "Spain", "Madrid") != YES ||
+ HT_PUT (ht, "Italy", "Rome") != YES ||
+ HT_PUT (ht, "USA", "Washington") != YES)
+ {
+ puts ("ht_put failed\n");
+ ht_destroy (ht);
+ return 1;
+ }
- if (HT_CONTAINS_KEY(ht, "France") != YES ||
- HT_CONTAINS_KEY(ht, "Iceland") != NO)
- {
- puts("ht_contains_key failed!\n");
- ht_destroy(ht);
- return 1;
- }
+ if (HT_CONTAINS_KEY (ht, "France") != YES ||
+ HT_CONTAINS_KEY (ht, "Iceland") != NO)
+ {
+ puts ("ht_contains_key failed!\n");
+ ht_destroy (ht);
+ return 1;
+ }
- if (HT_CONTAINS_VALUE(ht, "Paris") != YES ||
- HT_CONTAINS_VALUE(ht, "London") != NO)
- {
- puts("ht_contains_value failed!\n");
- ht_destroy(ht);
- return 1;
- }
+ if (HT_CONTAINS_VALUE (ht, "Paris") != YES ||
+ HT_CONTAINS_VALUE (ht, "London") != NO)
+ {
+ puts ("ht_contains_value failed!\n");
+ ht_destroy (ht);
+ return 1;
+ }
- if (HT_GET(ht, "USA", &val, &vallen) != YES)
- {
- puts("ht_get failed!\n");
- ht_destroy(ht);
- return 1;
- }
+ if (HT_GET (ht, "USA", &val, &vallen) != YES)
+ {
+ puts ("ht_get failed!\n");
+ ht_destroy (ht);
+ return 1;
+ }
- if (strcmp((char *) val, "Washington") != 0)
- {
- puts("ht_get result invalid!\n");
- ht_destroy(ht);
- return 1;
- }
+ if (strcmp ((char *) val, "Washington") != 0)
+ {
+ puts ("ht_get result invalid!\n");
+ ht_destroy (ht);
+ return 1;
+ }
- HT_REMOVE(ht, "Spain");
- if (HT_CONTAINS_KEY(ht, "Spain") != NO)
- {
- puts("ht_remove failed!\n");
- ht_destroy(ht);
- return 1;
- }
+ HT_REMOVE (ht, "Spain");
+ if (HT_CONTAINS_KEY (ht, "Spain") != NO)
+ {
+ puts ("ht_remove failed!\n");
+ ht_destroy (ht);
+ return 1;
+ }
- if (ht_size(ht) != 5)
- {
- puts("ht_size failed!\n");
- ht_destroy(ht);
- return 1;
- }
+ if (ht_size (ht) != 5)
+ {
+ puts ("ht_size failed!\n");
+ ht_destroy (ht);
+ return 1;
+ }
- ht_removeAll(ht);
- if (ht_size(ht) != 0)
- {
- puts("ht_size#2 failed!\n");
- ht_destroy(ht);
- return 1;
- }
+ ht_removeAll (ht);
+ if (ht_size (ht) != 0)
+ {
+ puts ("ht_size#2 failed!\n");
+ ht_destroy (ht);
+ return 1;
+ }
- ht_destroy(ht);
+ ht_destroy (ht);
return 0;
}
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
int ret = 0;
- ret = testHT();
+ ret = testHT ();
return ret;
}
Modified: GNUnet/src/util/containers/hashtest.c
===================================================================
--- GNUnet/src/util/containers/hashtest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/containers/hashtest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -9,43 +9,44 @@
/**
* Perform option parsing from the command line.
*/
-static int parseCommandLine(int argc,
- char * argv[]) {
+static int
+parseCommandLine (int argc, char *argv[])
+{
return OK;
}
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
HashCode512 hc;
- initUtil(argc, argv, &parseCommandLine);
- hash("TEST", 4, &hc);
- if ( (hc.bits[0] != ntohl(2080019878)) ||
- (hc.bits[1] != ntohl(-2003678137)) ||
- (hc.bits[2] != ntohl(-942529663)) ||
- (hc.bits[3] != ntohl(-234043098)) ||
- (hc.bits[4] != ntohl(-182141268)) ) {
- printf("Hash of TEST wrong (%d, %d, %d, %d, %d).\n",
- ntohl(hc.bits[0]),
- ntohl(hc.bits[1]),
- ntohl(hc.bits[2]),
- ntohl(hc.bits[3]),
- ntohl(hc.bits[4]));
- return -1;
- }
- hash(NULL, 0, &hc);
- if ( (hc.bits[0] != ntohl(-813440715)) ||
- (hc.bits[1] != ntohl(2129639613)) ||
- (hc.bits[2] != ntohl(-246142896)) ||
- (hc.bits[3] != ntohl(-697466873)) ||
- (hc.bits[4] != ntohl(-702487547)) ) {
- printf("Hash of nothing (0-size) wrong (%d, %d, %d, %d, %d).\n",
- ntohl(hc.bits[0]),
- ntohl(hc.bits[1]),
- ntohl(hc.bits[2]),
- ntohl(hc.bits[3]),
- ntohl(hc.bits[4]));
- return -1;
- }
- doneUtil();
+ initUtil (argc, argv, &parseCommandLine);
+ hash ("TEST", 4, &hc);
+ if ((hc.bits[0] != ntohl (2080019878)) ||
+ (hc.bits[1] != ntohl (-2003678137)) ||
+ (hc.bits[2] != ntohl (-942529663)) ||
+ (hc.bits[3] != ntohl (-234043098)) ||
+ (hc.bits[4] != ntohl (-182141268)))
+ {
+ printf ("Hash of TEST wrong (%d, %d, %d, %d, %d).\n",
+ ntohl (hc.bits[0]),
+ ntohl (hc.bits[1]),
+ ntohl (hc.bits[2]), ntohl (hc.bits[3]), ntohl (hc.bits[4]));
+ return -1;
+ }
+ hash (NULL, 0, &hc);
+ if ((hc.bits[0] != ntohl (-813440715)) ||
+ (hc.bits[1] != ntohl (2129639613)) ||
+ (hc.bits[2] != ntohl (-246142896)) ||
+ (hc.bits[3] != ntohl (-697466873)) ||
+ (hc.bits[4] != ntohl (-702487547)))
+ {
+ printf ("Hash of nothing (0-size) wrong (%d, %d, %d, %d, %d).\n",
+ ntohl (hc.bits[0]),
+ ntohl (hc.bits[1]),
+ ntohl (hc.bits[2]), ntohl (hc.bits[3]), ntohl (hc.bits[4]));
+ return -1;
+ }
+ doneUtil ();
return 0;
}
Modified: GNUnet/src/util/containers/vector.c
===================================================================
--- GNUnet/src/util/containers/vector.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/containers/vector.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -43,18 +43,20 @@
#include "gnunet_util.h"
#include "gnunet_util_containers.h"
-typedef struct Vector {
+typedef struct Vector
+{
unsigned int VECTOR_SEGMENT_SIZE;
- struct vector_segment_t * segmentsHead;
- struct vector_segment_t * segmentsTail;
- struct vector_segment_t * iteratorSegment;
+ struct vector_segment_t *segmentsHead;
+ struct vector_segment_t *segmentsTail;
+ struct vector_segment_t *iteratorSegment;
unsigned int iteratorIndex;
size_t size;
} Vector;
-typedef struct vector_segment_t {
- void ** data; /* always of size VECTOR_SEGMENT_SIZE */
+typedef struct vector_segment_t
+{
+ void **data; /* always of size VECTOR_SEGMENT_SIZE */
struct vector_segment_t *next;
struct vector_segment_t *previous;
size_t size;
@@ -64,86 +66,88 @@
* A debug function that traverses the linked list and prints the
* sizes of the segments. This currently isn't used.
*/
-void vectorDump(Vector *v) {
+void
+vectorDump (Vector * v)
+{
VectorSegment *vs;
int n;
unsigned int sum = 0;
- for (vs = v->segmentsHead; vs; vs = vs->next) {
- fprintf(stderr,
- "Segment-size: %3llu / %llu [%llu...%llu]: ",
- (unsigned long long) vs->size,
- (unsigned long long) v->VECTOR_SEGMENT_SIZE,
- (unsigned long long) sum,
- (unsigned long long) (sum + vs->size - 1));
- for (n=0;n<vs->size;n++) {
- fprintf(stderr,
- "%p, ",
- vs->data[n]);
+ for (vs = v->segmentsHead; vs; vs = vs->next)
+ {
+ fprintf (stderr,
+ "Segment-size: %3llu / %llu [%llu...%llu]: ",
+ (unsigned long long) vs->size,
+ (unsigned long long) v->VECTOR_SEGMENT_SIZE,
+ (unsigned long long) sum,
+ (unsigned long long) (sum + vs->size - 1));
+ for (n = 0; n < vs->size; n++)
+ {
+ fprintf (stderr, "%p, ", vs->data[n]);
+ }
+ fprintf (stderr, "\n");
+ sum += vs->size;
}
- fprintf(stderr, "\n");
- sum += vs->size;
- }
- fprintf(stderr,
- "Vector size: %u\n",
- sum);
+ fprintf (stderr, "Vector size: %u\n", sum);
}
/**
* Remove and return the element at given index in the segment's array. The
* trailing pointers in the array, if any, are moved backwards to fill the gap.
*/
-static void *vectorSegmentRemoveAtIndex(VectorSegment *vs,
- int index) {
- void *rvalue = vs->data[index];
+static void *
+vectorSegmentRemoveAtIndex (VectorSegment * vs, int index)
+{
+ void *rvalue = vs->data[index];
- while (index < vs->size) {
+ while (index < vs->size)
+ {
vs->data[index] = vs->data[index + 1];
index++;
- }
- return rvalue;
+ }
+ return rvalue;
}
/**
* Split the full segment vs into two half-full segments.
*/
-static void vectorSegmentSplit(Vector *v,
- VectorSegment *vs) {
- VectorSegment *oldNext;
- int moveCount;
+static void
+vectorSegmentSplit (Vector * v, VectorSegment * vs)
+{
+ VectorSegment *oldNext;
+ int moveCount;
- oldNext = vs->next;
- vs->next = MALLOC(sizeof(VectorSegment));
- vs->next->data = MALLOC(v->VECTOR_SEGMENT_SIZE * sizeof(void*));
- vs->next->previous = vs;
- vs->next->next = oldNext;
- if (NULL != oldNext)
- oldNext->previous = vs->next;
- else
- v->segmentsTail = vs->next;
- moveCount = vs->size / 2;
- memcpy(vs->next->data,
- vs->data + (vs->size - moveCount),
- moveCount * sizeof (void *));
- vs->next->size = moveCount;
- vs->size -= moveCount;
+ oldNext = vs->next;
+ vs->next = MALLOC (sizeof (VectorSegment));
+ vs->next->data = MALLOC (v->VECTOR_SEGMENT_SIZE * sizeof (void *));
+ vs->next->previous = vs;
+ vs->next->next = oldNext;
+ if (NULL != oldNext)
+ oldNext->previous = vs->next;
+ else
+ v->segmentsTail = vs->next;
+ moveCount = vs->size / 2;
+ memcpy (vs->next->data,
+ vs->data + (vs->size - moveCount), moveCount * sizeof (void *));
+ vs->next->size = moveCount;
+ vs->size -= moveCount;
}
/**
* Joins the given segment with the following segment. The first segment _must_
* be empty enough to store the data of both segments.
*/
-static void vectorSegmentJoin(Vector *v,
- VectorSegment *vs) {
+static void
+vectorSegmentJoin (Vector * v, VectorSegment * vs)
+{
VectorSegment *oldNext = vs->next->next;
- memcpy(vs->data + vs->size,
- vs->next->data,
- vs->next->size * sizeof (void *));
+ memcpy (vs->data + vs->size,
+ vs->next->data, vs->next->size * sizeof (void *));
vs->size += vs->next->size;
- FREE(vs->next->data);
- FREE(vs->next);
+ FREE (vs->next->data);
+ FREE (vs->next);
vs->next = oldNext;
if (oldNext != NULL)
vs->next->previous = vs;
@@ -154,10 +158,10 @@
/**
* Free an empty segment, _unless_ it is the only segment.
*/
-static void vectorSegmentRemove(Vector *v,
- VectorSegment *vs) {
- if ( (vs->previous == NULL) &&
- (vs->next == NULL) )
+static void
+vectorSegmentRemove (Vector * v, VectorSegment * vs)
+{
+ if ((vs->previous == NULL) && (vs->next == NULL))
return;
if (vs->previous != NULL)
vs->previous->next = vs->next;
@@ -167,8 +171,8 @@
vs->next->previous = vs->previous;
else
v->segmentsTail = vs->previous;
- FREE(vs->data);
- FREE(vs);
+ FREE (vs->data);
+ FREE (vs);
}
@@ -178,31 +182,37 @@
* If possible, an unused index at the end of a segment is returned, as this
* is also a requirement for adding data in an empty vector.
*/
-static int vectorFindNewIndex(Vector * v,
- unsigned int index,
- VectorSegment **vs) {
+static int
+vectorFindNewIndex (Vector * v, unsigned int index, VectorSegment ** vs)
+{
VectorSegment *segment;
int segmentStartIndex;
- if (index > v->size) {
- *vs = NULL;
- return -1;
- }
- if (index <= v->size / 2) { /* empty vector included */
- segment = v->segmentsHead;
- segmentStartIndex = 0;
- while (index > segmentStartIndex + segment->size) {
- segmentStartIndex += segment->size;
- segment = segment->next;
+ if (index > v->size)
+ {
+ *vs = NULL;
+ return -1;
}
- } else { /* reverse */
- segment = v->segmentsTail;
- segmentStartIndex = v->size - segment->size;
- while (index <= segmentStartIndex) {
- segment = segment->previous;
- segmentStartIndex -= segment->size;
+ if (index <= v->size / 2)
+ { /* empty vector included */
+ segment = v->segmentsHead;
+ segmentStartIndex = 0;
+ while (index > segmentStartIndex + segment->size)
+ {
+ segmentStartIndex += segment->size;
+ segment = segment->next;
+ }
}
- }
+ else
+ { /* reverse */
+ segment = v->segmentsTail;
+ segmentStartIndex = v->size - segment->size;
+ while (index <= segmentStartIndex)
+ {
+ segment = segment->previous;
+ segmentStartIndex -= segment->size;
+ }
+ }
*vs = segment;
return index - segmentStartIndex;
}
@@ -212,31 +222,37 @@
* Find the segment and segmentIndex of the element
* with the given index.
*/
-static int vectorFindIndex(Vector *v,
- unsigned int index,
- VectorSegment **vs) {
+static int
+vectorFindIndex (Vector * v, unsigned int index, VectorSegment ** vs)
+{
VectorSegment *segment;
int segmentStartIndex;
- if (index >= v->size) {
- *vs = NULL;
- return -1;
- }
- if (index < v->size / 2) {
- segment = v->segmentsHead;
- segmentStartIndex = 0;
- while (index >= segmentStartIndex + segment->size) {
- segmentStartIndex += segment->size;
- segment = segment->next;
+ if (index >= v->size)
+ {
+ *vs = NULL;
+ return -1;
}
- } else {
- segment = v->segmentsTail;
- segmentStartIndex = v->size - segment->size;
- while (index < segmentStartIndex) {
- segment = segment->previous;
- segmentStartIndex -= segment->size;
+ if (index < v->size / 2)
+ {
+ segment = v->segmentsHead;
+ segmentStartIndex = 0;
+ while (index >= segmentStartIndex + segment->size)
+ {
+ segmentStartIndex += segment->size;
+ segment = segment->next;
+ }
}
- }
+ else
+ {
+ segment = v->segmentsTail;
+ segmentStartIndex = v->size - segment->size;
+ while (index < segmentStartIndex)
+ {
+ segment = segment->previous;
+ segmentStartIndex -= segment->size;
+ }
+ }
*vs = segment;
return index - segmentStartIndex;
}
@@ -248,24 +264,27 @@
* to by segmentIndex to the object's index in the segment. If the object is
* not found, *vs is set to NULL.
*/
-static void vectorFindObject(Vector *v,
- void *object,
- VectorSegment **vs,
- int *segmentIndex) {
+static void
+vectorFindObject (Vector * v,
+ void *object, VectorSegment ** vs, int *segmentIndex)
+{
VectorSegment *segment;
int i;
segment = v->segmentsHead;
- while (NULL != segment) {
- for (i=0;i<segment->size;i++) {
- if (segment->data[i] == object) {
- *vs = segment;
- *segmentIndex = i;
- return;
- }
+ while (NULL != segment)
+ {
+ for (i = 0; i < segment->size; i++)
+ {
+ if (segment->data[i] == object)
+ {
+ *vs = segment;
+ *segmentIndex = i;
+ return;
+ }
+ }
+ segment = segment->next;
}
- segment = segment->next;
- }
*vs = NULL;
}
@@ -273,23 +292,25 @@
/**
* Allocate a new vector structure with a single empty data segment.
*/
-Vector * vectorNew(unsigned int vss) {
- Vector *rvalue;
+Vector *
+vectorNew (unsigned int vss)
+{
+ Vector *rvalue;
- if (vss < 2)
- return NULL; /* invalid! */
- rvalue = MALLOC(sizeof (Vector));
- rvalue->VECTOR_SEGMENT_SIZE = vss;
- rvalue->size = 0;
- rvalue->segmentsHead = MALLOC(sizeof(VectorSegment));
- rvalue->segmentsHead->data = MALLOC(sizeof(void*)*vss);
- rvalue->segmentsTail = rvalue->segmentsHead;
- rvalue->segmentsHead->next = NULL;
- rvalue->segmentsHead->previous = NULL;
- rvalue->segmentsHead->size = 0;
- rvalue->iteratorSegment = NULL;
- rvalue->iteratorIndex = 0;
- return rvalue;
+ if (vss < 2)
+ return NULL; /* invalid! */
+ rvalue = MALLOC (sizeof (Vector));
+ rvalue->VECTOR_SEGMENT_SIZE = vss;
+ rvalue->size = 0;
+ rvalue->segmentsHead = MALLOC (sizeof (VectorSegment));
+ rvalue->segmentsHead->data = MALLOC (sizeof (void *) * vss);
+ rvalue->segmentsTail = rvalue->segmentsHead;
+ rvalue->segmentsHead->next = NULL;
+ rvalue->segmentsHead->previous = NULL;
+ rvalue->segmentsHead->size = 0;
+ rvalue->iteratorSegment = NULL;
+ rvalue->iteratorIndex = 0;
+ return rvalue;
}
/**
@@ -297,34 +318,39 @@
* stored void pointers. It is the user's responsibility to empty the vector
* when necessary to avoid memory leakage.
*/
-void vectorFree(Vector *v) {
- VectorSegment * vs;
- VectorSegment * vsNext;
+void
+vectorFree (Vector * v)
+{
+ VectorSegment *vs;
+ VectorSegment *vsNext;
vs = v->segmentsHead;
- while (vs != NULL) {
- vsNext = vs->next;
- FREE(vs->data);
- FREE(vs);
- vs = vsNext;
- }
- FREE(v);
+ while (vs != NULL)
+ {
+ vsNext = vs->next;
+ FREE (vs->data);
+ FREE (vs);
+ vs = vsNext;
+ }
+ FREE (v);
}
/**
* Return the size of the vector.
*/
-size_t vectorSize(Vector *v) {
- return v->size;
+size_t
+vectorSize (Vector * v)
+{
+ return v->size;
}
/**
* Insert a new element in the vector at given index. The return value is
* OK on success, SYSERR if the index is out of bounds.
*/
-int vectorInsertAt(Vector *v,
- void *object,
- unsigned int index) {
+int
+vectorInsertAt (Vector * v, void *object, unsigned int index)
+{
VectorSegment *segment;
int segmentIndex;
int i;
@@ -332,7 +358,7 @@
if (index > v->size)
return SYSERR;
v->iteratorSegment = NULL;
- segmentIndex = vectorFindNewIndex(v, index, &segment);
+ segmentIndex = vectorFindNewIndex (v, index, &segment);
if (segmentIndex == -1)
return SYSERR;
for (i = segment->size; i > segmentIndex; i--)
@@ -341,18 +367,20 @@
v->size++;
segment->size++;
if (segment->size == v->VECTOR_SEGMENT_SIZE)
- vectorSegmentSplit(v, segment);
+ vectorSegmentSplit (v, segment);
return OK;
}
/**
* Insert a new element at the end of the vector.
*/
-void vectorInsertLast(Vector *v, void *object) {
+void
+vectorInsertLast (Vector * v, void *object)
+{
v->iteratorSegment = NULL;
v->segmentsTail->data[v->segmentsTail->size++] = object;
if (v->segmentsTail->size == v->VECTOR_SEGMENT_SIZE)
- vectorSegmentSplit(v, v->segmentsTail);
+ vectorSegmentSplit (v, v->segmentsTail);
v->size++;
}
@@ -360,14 +388,13 @@
* Return the element at given index in the vector or NULL if the index is out
* of bounds. The iterator is set to point to the returned element.
*/
-void * vectorGetAt(Vector *v,
- unsigned int index) {
+void *
+vectorGetAt (Vector * v, unsigned int index)
+{
int ret;
- if ( (index < 0) || (index >= v->size) )
+ if ((index < 0) || (index >= v->size))
return NULL;
- ret = vectorFindIndex(v,
- index,
- &v->iteratorSegment);
+ ret = vectorFindIndex (v, index, &v->iteratorSegment);
if (ret == -1)
return NULL;
v->iteratorIndex = ret;
@@ -379,7 +406,9 @@
* vector is empty. The iterator of the vector is set to point to the first
* element.
*/
-void * vectorGetFirst(Vector *v) {
+void *
+vectorGetFirst (Vector * v)
+{
if (v->size == 0)
return NULL;
v->iteratorSegment = v->segmentsHead;
@@ -391,11 +420,13 @@
* Return the last element in the vector or NULL if the vector is
* empty. The iterator of the vector is set to the last element.
*/
-void * vectorGetLast(Vector *v) {
+void *
+vectorGetLast (Vector * v)
+{
if (v->size == 0)
return NULL;
v->iteratorSegment = v->segmentsTail;
- v->iteratorIndex = v->segmentsTail->size-1;
+ v->iteratorIndex = v->segmentsTail->size - 1;
return v->segmentsTail->data[v->iteratorIndex];
}
@@ -404,18 +435,24 @@
* vector_get_first(). The return value is NULL if there are no more elements
* in the vector or if the iterator has not been set.
*/
-void * vectorGetNext(Vector *v) {
+void *
+vectorGetNext (Vector * v)
+{
if (v->iteratorSegment == NULL)
return NULL;
- if (++v->iteratorIndex >= v->iteratorSegment->size) {
- if (v->iteratorSegment == v->segmentsTail) {
- v->iteratorSegment = NULL;
- return NULL;
- } else {
- v->iteratorSegment = v->iteratorSegment->next;
- v->iteratorIndex = 0;
+ if (++v->iteratorIndex >= v->iteratorSegment->size)
+ {
+ if (v->iteratorSegment == v->segmentsTail)
+ {
+ v->iteratorSegment = NULL;
+ return NULL;
+ }
+ else
+ {
+ v->iteratorSegment = v->iteratorSegment->next;
+ v->iteratorIndex = 0;
+ }
}
- }
return v->iteratorSegment->data[v->iteratorIndex];
}
@@ -424,18 +461,24 @@
* or vector_get_last(). The return value is NULL if there are no more
* elements in the vector or if the iterator has not been set.
*/
-void * vectorGetPrevious(Vector * v) {
+void *
+vectorGetPrevious (Vector * v)
+{
if (v->iteratorSegment == NULL)
return NULL;
- if (--v->iteratorIndex == -1) {
- if (v->iteratorSegment == v->segmentsHead) {
- v->iteratorSegment = 0;
- return NULL;
- } else {
- v->iteratorSegment = v->iteratorSegment->previous;
- v->iteratorIndex = v->iteratorSegment->size - 1;
+ if (--v->iteratorIndex == -1)
+ {
+ if (v->iteratorSegment == v->segmentsHead)
+ {
+ v->iteratorSegment = 0;
+ return NULL;
+ }
+ else
+ {
+ v->iteratorSegment = v->iteratorSegment->previous;
+ v->iteratorIndex = v->iteratorSegment->size - 1;
+ }
}
- }
return v->iteratorSegment->data[v->iteratorIndex];
}
@@ -443,30 +486,30 @@
* Delete and return the element at given index. NULL is returned if index is
* out of bounds.
*/
-void * vectorRemoveAt(Vector *v,
- unsigned int index) {
- VectorSegment * segment;
+void *
+vectorRemoveAt (Vector * v, unsigned int index)
+{
+ VectorSegment *segment;
int segmentIndex;
void *rvalue;
if (index >= v->size)
- return NULL;
+ return NULL;
v->iteratorSegment = NULL;
- segmentIndex = vectorFindIndex(v, index, &segment);
+ segmentIndex = vectorFindIndex (v, index, &segment);
if (segmentIndex == -1)
return NULL;
- rvalue = vectorSegmentRemoveAtIndex(segment,
- segmentIndex);
+ rvalue = vectorSegmentRemoveAtIndex (segment, segmentIndex);
/* If the segment ends empty remove it, otherwise
try to join it with its neighbors. */
if (--segment->size == 0)
- vectorSegmentRemove(v, segment);
+ vectorSegmentRemove (v, segment);
else if (segment->next &&
- segment->size + segment->next->size < v->VECTOR_SEGMENT_SIZE)
- vectorSegmentJoin(v, segment);
+ segment->size + segment->next->size < v->VECTOR_SEGMENT_SIZE)
+ vectorSegmentJoin (v, segment);
else if (segment->previous &&
- segment->size + segment->previous->size < v->VECTOR_SEGMENT_SIZE)
- vectorSegmentJoin(v, segment->previous);
+ segment->size + segment->previous->size < v->VECTOR_SEGMENT_SIZE)
+ vectorSegmentJoin (v, segment->previous);
v->size--;
return rvalue;
}
@@ -475,7 +518,9 @@
* Delete and return the last element in the vector, or NULL if the vector
* is empty.
*/
-void *vectorRemoveLast (Vector *v) {
+void *
+vectorRemoveLast (Vector * v)
+{
void *rvalue;
if (v->size == 0)
@@ -484,10 +529,10 @@
rvalue = v->segmentsTail->data[v->segmentsTail->size - 1];
/* If the segment ends empty remove it, otherwise join it if necessary. */
if (--v->segmentsTail->size == 0)
- vectorSegmentRemove(v, v->segmentsTail);
- else if ( (v->segmentsTail->previous != NULL) &&
- (v->segmentsTail->size + v->segmentsTail->previous->size
- < v->VECTOR_SEGMENT_SIZE) )
+ vectorSegmentRemove (v, v->segmentsTail);
+ else if ((v->segmentsTail->previous != NULL) &&
+ (v->segmentsTail->size + v->segmentsTail->previous->size
+ < v->VECTOR_SEGMENT_SIZE))
vectorSegmentJoin (v, v->segmentsTail->previous);
v->size--;
return rvalue;
@@ -497,24 +542,26 @@
* Delete and return given object from the vector, or return NULL if the object
* is not found.
*/
-void * vectorRemoveObject(Vector *v, void *object) {
+void *
+vectorRemoveObject (Vector * v, void *object)
+{
VectorSegment *segment;
int segmentIndex;
- void * rvalue;
+ void *rvalue;
v->iteratorSegment = NULL;
- vectorFindObject(v, object, &segment, &segmentIndex);
+ vectorFindObject (v, object, &segment, &segmentIndex);
if (segment == NULL)
return NULL;
- rvalue = vectorSegmentRemoveAtIndex(segment, segmentIndex);
+ rvalue = vectorSegmentRemoveAtIndex (segment, segmentIndex);
/* If the segment ends empty remove it, otherwise join it if necessary. */
if (--segment->size == 0)
vectorSegmentRemove (v, segment);
- else if ( (segment->next != NULL) &&
- (segment->size + segment->next->size < v->VECTOR_SEGMENT_SIZE) )
+ else if ((segment->next != NULL) &&
+ (segment->size + segment->next->size < v->VECTOR_SEGMENT_SIZE))
vectorSegmentJoin (v, segment);
- else if ( (segment->previous != NULL) &&
- (segment->size + segment->previous->size < v->VECTOR_SEGMENT_SIZE) )
+ else if ((segment->previous != NULL) &&
+ (segment->size + segment->previous->size < v->VECTOR_SEGMENT_SIZE))
vectorSegmentJoin (v, segment->previous);
v->size--;
return rvalue;
@@ -524,9 +571,9 @@
* Set the given index in the vector. The old value of the index is
* returned, or NULL if the index is out of bounds.
*/
-void *vectorSetAt (Vector *v,
- void *object,
- unsigned int index) {
+void *
+vectorSetAt (Vector * v, void *object, unsigned int index)
+{
VectorSegment *segment;
int segmentIndex;
void *rvalue;
@@ -534,7 +581,7 @@
if (index >= v->size)
return NULL;
v->iteratorSegment = NULL;
- segmentIndex = vectorFindIndex(v, index, &segment);
+ segmentIndex = vectorFindIndex (v, index, &segment);
if (segmentIndex == -1)
return NULL;
rvalue = segment->data[segmentIndex];
@@ -547,9 +594,9 @@
* Set the index occupied by the given object to point to the new object.
* The old object is returned, or NULL if it's not found.
*/
-void *vectorSetObject(Vector *v,
- void *object,
- void *oldObject) {
+void *
+vectorSetObject (Vector * v, void *object, void *oldObject)
+{
VectorSegment *segment;
int segmentIndex;
void *rvalue;
@@ -568,23 +615,21 @@
* Swaps the contents of index1 and index2. Return value is OK
* on success, SYSERR if either index is out of bounds.
*/
-int vectorSwap(Vector *v,
- unsigned int index1,
- unsigned int index2) {
- VectorSegment * segment1;
- VectorSegment * segment2;
+int
+vectorSwap (Vector * v, unsigned int index1, unsigned int index2)
+{
+ VectorSegment *segment1;
+ VectorSegment *segment2;
int segmentIndex1;
int segmentIndex2;
void *temp;
- if ( (index1 >= v->size) ||
- (index2 >= v->size) )
+ if ((index1 >= v->size) || (index2 >= v->size))
return SYSERR;
- v->iteratorSegment= NULL;
- segmentIndex1 = vectorFindIndex(v, index1, &segment1);
- segmentIndex2 = vectorFindIndex(v, index2, &segment2);
- if( (segmentIndex1 == -1) ||
- (segmentIndex2 == -1) )
+ v->iteratorSegment = NULL;
+ segmentIndex1 = vectorFindIndex (v, index1, &segment1);
+ segmentIndex2 = vectorFindIndex (v, index2, &segment2);
+ if ((segmentIndex1 == -1) || (segmentIndex2 == -1))
return SYSERR;
temp = segment1->data[segmentIndex1];
segment1->data[segmentIndex1] = segment2->data[segmentIndex2];
@@ -595,21 +640,23 @@
/**
* Return the index of given element or -1 if the element is not found.
*/
-unsigned int vectorIndexOf(Vector *v,
- void *object) {
- VectorSegment * segment;
+unsigned int
+vectorIndexOf (Vector * v, void *object)
+{
+ VectorSegment *segment;
unsigned int i;
unsigned int segmentStartIndex;
segmentStartIndex = 0;
segment = v->segmentsHead;
- while (NULL != segment) {
- for (i = 0; i < segment->size; i++)
- if (segment->data[i] == object)
- return segmentStartIndex + i;
- segmentStartIndex += segment->size;
- segment = segment->next;
- }
+ while (NULL != segment)
+ {
+ for (i = 0; i < segment->size; i++)
+ if (segment->data[i] == object)
+ return segmentStartIndex + i;
+ segmentStartIndex += segment->size;
+ segment = segment->next;
+ }
return (unsigned int) -1;
}
@@ -620,18 +667,19 @@
* get_{at,first,last,next,previous} instead, unless you really need to access
* everything in the vector as fast as possible.
*/
-void ** vectorElements (Vector *v) {
+void **
+vectorElements (Vector * v)
+{
void **rvalue;
VectorSegment *vs;
size_t i = 0;
- rvalue = MALLOC_LARGE(v->size * sizeof (void *));
- for (vs = v->segmentsHead; vs; vs = vs->next) {
- memcpy (rvalue + i,
- vs->data,
- vs->size * sizeof (void *));
- i += vs->size;
- }
+ rvalue = MALLOC_LARGE (v->size * sizeof (void *));
+ for (vs = v->segmentsHead; vs; vs = vs->next)
+ {
+ memcpy (rvalue + i, vs->data, vs->size * sizeof (void *));
+ i += vs->size;
+ }
return rvalue;
}
Modified: GNUnet/src/util/containers/vectortest.c
===================================================================
--- GNUnet/src/util/containers/vectortest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/containers/vectortest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -28,119 +28,250 @@
#define DUMP(v) fprintf(stderr, "At %d: \n", __LINE__); vectorDump(v);
vectorFree(v);
-static int test(int size) {
- struct Vector * v;
+static int
+test (int size)
+{
+ struct Vector *v;
- v = vectorNew(size);
- if (0 != vectorSize(v))
- { DUMP(v); return 1; }
- if (OK != vectorInsertAt(v, "first", 0))
- { DUMP(v); return 1; }
- if (OK == vectorInsertAt(v, "not", 2))
- { DUMP(v); return 1; }
- if (OK != vectorInsertAt(v, "zero", 0))
- { DUMP(v); return 1; }
- if (OK != vectorInsertAt(v, "second", 2))
- { DUMP(v); return 1; }
- vectorInsertLast(v, "third");
- if (4 != vectorSize(v))
- { DUMP(v); return 1; }
- if (0 != strcmp(vectorGetAt(v, 1), "first"))
- { DUMP(v); return 1; }
- if (0 != strcmp(vectorGetAt(v, 3), "third"))
- { DUMP(v); return 1; }
- if (0 != strcmp(vectorGetAt(v, 0), "zero"))
- { DUMP(v); return 1; }
- if (0 != strcmp(vectorGetFirst(v), "zero"))
- { DUMP(v); return 1; }
- if (0 != strcmp(vectorGetLast(v), "third"))
- { DUMP(v); return 1; }
- if (0 != strcmp(vectorRemoveAt(v, 1), "first"))
- { DUMP(v); return 1; }
- if (0 != strcmp(vectorGetAt(v, 1), "second"))
- { DUMP(v); return 1; }
- if (NULL != vectorRemoveAt(v, 3))
- { DUMP(v); return 1; }
- if (3 != vectorSize(v))
- { DUMP(v); return 1; }
- if (0 != strcmp(vectorRemoveAt(v, 1), "second"))
- { DUMP(v); return 1; }
- if (0 != strcmp(vectorRemoveObject(v, "third"), "third"))
- { DUMP(v); return 1; }
- if (NULL != vectorRemoveObject(v, "third"))
- { DUMP(v); return 1; }
- if (0 != strcmp(vectorRemoveLast(v), "zero"))
- { DUMP(v); return 1; }
- if (0 != vectorSize(v))
- { DUMP(v); return 1; }
- if (NULL != vectorRemoveLast(v))
- { DUMP(v); return 1; }
- if (0 != vectorSize(v))
- { DUMP(v); return 1; }
- vectorFree(v);
+ v = vectorNew (size);
+ if (0 != vectorSize (v))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (OK != vectorInsertAt (v, "first", 0))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (OK == vectorInsertAt (v, "not", 2))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (OK != vectorInsertAt (v, "zero", 0))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (OK != vectorInsertAt (v, "second", 2))
+ {
+ DUMP (v);
+ return 1;
+ }
+ vectorInsertLast (v, "third");
+ if (4 != vectorSize (v))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (0 != strcmp (vectorGetAt (v, 1), "first"))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (0 != strcmp (vectorGetAt (v, 3), "third"))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (0 != strcmp (vectorGetAt (v, 0), "zero"))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (0 != strcmp (vectorGetFirst (v), "zero"))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (0 != strcmp (vectorGetLast (v), "third"))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (0 != strcmp (vectorRemoveAt (v, 1), "first"))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (0 != strcmp (vectorGetAt (v, 1), "second"))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (NULL != vectorRemoveAt (v, 3))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (3 != vectorSize (v))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (0 != strcmp (vectorRemoveAt (v, 1), "second"))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (0 != strcmp (vectorRemoveObject (v, "third"), "third"))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (NULL != vectorRemoveObject (v, "third"))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (0 != strcmp (vectorRemoveLast (v), "zero"))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (0 != vectorSize (v))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (NULL != vectorRemoveLast (v))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (0 != vectorSize (v))
+ {
+ DUMP (v);
+ return 1;
+ }
+ vectorFree (v);
return 0;
}
-static int test2(int size) {
+static int
+test2 (int size)
+{
long i;
- struct Vector * v;
+ struct Vector *v;
- v = vectorNew(size);
+ v = vectorNew (size);
- for (i=0;i<500;i++)
- if (OK != vectorInsertAt(v, (void*)i, 0))
- { DUMP(v); return 1; }
- if (500 != vectorSize(v))
- { DUMP(v); return 1; }
- for (i=0;i<500;i++)
- if (499 - i != (long) vectorGetAt(v, i))
- { DUMP(v); return 1; }
- if (499 != (long) vectorGetFirst(v))
- { DUMP(v); return 1; }
- for (i=498;i>=0;i--)
- if (i != (long) vectorGetNext(v))
- { DUMP(v); return 1; }
+ for (i = 0; i < 500; i++)
+ if (OK != vectorInsertAt (v, (void *) i, 0))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (500 != vectorSize (v))
+ {
+ DUMP (v);
+ return 1;
+ }
+ for (i = 0; i < 500; i++)
+ if (499 - i != (long) vectorGetAt (v, i))
+ {
+ DUMP (v);
+ return 1;
+ }
+ if (499 != (long) vectorGetFirst (v))
+ {
+ DUMP (v);
+ return 1;
+ }
+ for (i = 498; i >= 0; i--)
+ if (i != (long) vectorGetNext (v))
+ {
+ DUMP (v);
+ return 1;
+ }
- if (499 != (long) vectorGetFirst(v))
- { DUMP(v); return 1; }
- for (i=498;i>=250;i--)
- if (i != (long) vectorGetNext(v))
- { DUMP(v); return 1; }
- for (i=251;i<499;i++)
- if (i != (long) vectorGetPrevious(v))
- { DUMP(v); return 1; }
+ if (499 != (long) vectorGetFirst (v))
+ {
+ DUMP (v);
+ return 1;
+ }
+ for (i = 498; i >= 250; i--)
+ if (i != (long) vectorGetNext (v))
+ {
+ DUMP (v);
+ return 1;
+ }
+ for (i = 251; i < 499; i++)
+ if (i != (long) vectorGetPrevious (v))
+ {
+ DUMP (v);
+ return 1;
+ }
- vectorFree(v);
+ vectorFree (v);
return 0;
}
-int main(int argc,
- char * argv[]) {
- if (NULL != vectorNew(0))
- { printf("At %d\n", __LINE__); return 1; }
- if (NULL != vectorNew(1))
- { printf("At %d\n", __LINE__); return 1; }
- if (test(2) != 0)
- { printf("At %d\n", __LINE__); return 1; }
- if (test(3) != 0)
- { printf("At %d\n", __LINE__); return 1; }
- if (test(4) != 0)
- { printf("At %d\n", __LINE__); return 1; }
- if (test(128) != 0)
- { printf("At %d\n", __LINE__); return 1; }
- if (test(65536) != 0)
- { printf("At %d\n", __LINE__); return 1; }
- if (test(2*65536) != 0)
- { printf("At %d\n", __LINE__); return 1; }
+int
+main (int argc, char *argv[])
+{
+ if (NULL != vectorNew (0))
+ {
+ printf ("At %d\n", __LINE__);
+ return 1;
+ }
+ if (NULL != vectorNew (1))
+ {
+ printf ("At %d\n", __LINE__);
+ return 1;
+ }
+ if (test (2) != 0)
+ {
+ printf ("At %d\n", __LINE__);
+ return 1;
+ }
+ if (test (3) != 0)
+ {
+ printf ("At %d\n", __LINE__);
+ return 1;
+ }
+ if (test (4) != 0)
+ {
+ printf ("At %d\n", __LINE__);
+ return 1;
+ }
+ if (test (128) != 0)
+ {
+ printf ("At %d\n", __LINE__);
+ return 1;
+ }
+ if (test (65536) != 0)
+ {
+ printf ("At %d\n", __LINE__);
+ return 1;
+ }
+ if (test (2 * 65536) != 0)
+ {
+ printf ("At %d\n", __LINE__);
+ return 1;
+ }
- if (test2(2) != 0)
- { printf("At %d\n", __LINE__); return 1; }
- if (test2(3) != 0)
- { printf("At %d\n", __LINE__); return 1; }
- if (test2(4) != 0)
- { printf("At %d\n", __LINE__); return 1; }
- if (test2(128) != 0)
- { printf("At %d\n", __LINE__); return 1; }
+ if (test2 (2) != 0)
+ {
+ printf ("At %d\n", __LINE__);
+ return 1;
+ }
+ if (test2 (3) != 0)
+ {
+ printf ("At %d\n", __LINE__);
+ return 1;
+ }
+ if (test2 (4) != 0)
+ {
+ printf ("At %d\n", __LINE__);
+ return 1;
+ }
+ if (test2 (128) != 0)
+ {
+ printf ("At %d\n", __LINE__);
+ return 1;
+ }
return 0;
}
Modified: GNUnet/src/util/cron/cron.c
===================================================================
--- GNUnet/src/util/cron/cron.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/cron/cron.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -82,7 +82,8 @@
/**
* @brief The Delta-list for the cron jobs.
*/
-typedef struct {
+typedef struct
+{
/**
* The method to call at that point.
@@ -92,7 +93,7 @@
/**
* data ptr (argument to the method)
*/
- void * data;
+ void *data;
/**
* The start-time for this event (in milliseconds).
@@ -113,37 +114,38 @@
} UTIL_cron_DeltaListEntry;
-typedef struct CronManager {
+typedef struct CronManager
+{
/**
* The lock for the delta-list.
*/
- struct MUTEX * deltaListLock_;
+ struct MUTEX *deltaListLock_;
/**
* The delta-list of waiting tasks.
*/
- UTIL_cron_DeltaListEntry * deltaList_;
+ UTIL_cron_DeltaListEntry *deltaList_;
/**
* The currently running job.
*/
CronJob runningJob_;
- void * runningData_;
+ void *runningData_;
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
/**
* The cron thread.
*/
- struct PTHREAD * cron_handle;
+ struct PTHREAD *cron_handle;
- struct SEMAPHORE * cron_signal;
+ struct SEMAPHORE *cron_signal;
- struct SEMAPHORE * cron_signal_up;
+ struct SEMAPHORE *cron_signal_up;
- struct MUTEX * inBlockLock_;
+ struct MUTEX *inBlockLock_;
unsigned int runningRepeat_;
@@ -172,28 +174,30 @@
*/
int inBlock;
- struct SEMAPHORE * sig;
+ struct SEMAPHORE *sig;
} CronManager;
-struct CronManager * cron_create(struct GE_Context * ectx) {
- struct CronManager * cron;
+struct CronManager *
+cron_create (struct GE_Context *ectx)
+{
+ struct CronManager *cron;
unsigned int i;
- cron = MALLOC(sizeof(CronManager));
- memset(cron, 0, sizeof(CronManager));
+ cron = MALLOC (sizeof (CronManager));
+ memset (cron, 0, sizeof (CronManager));
cron->deltaListSize_ = INIT_CRON_JOBS;
cron->deltaList_
- = MALLOC(sizeof(UTIL_cron_DeltaListEntry) * cron->deltaListSize_);
- for (i=0;i<cron->deltaListSize_;i++)
- cron->deltaList_[i].next = i-1;
- cron->firstFree_ = cron->deltaListSize_-1;
- cron->deltaListLock_ = MUTEX_CREATE(YES);
- cron->inBlockLock_ = MUTEX_CREATE(NO);
+ = MALLOC (sizeof (UTIL_cron_DeltaListEntry) * cron->deltaListSize_);
+ for (i = 0; i < cron->deltaListSize_; i++)
+ cron->deltaList_[i].next = i - 1;
+ cron->firstFree_ = cron->deltaListSize_ - 1;
+ cron->deltaListLock_ = MUTEX_CREATE (YES);
+ cron->inBlockLock_ = MUTEX_CREATE (NO);
cron->runningJob_ = NULL;
- cron->firstUsed_ = -1;
- cron->cron_signal_up = SEMAPHORE_CREATE(0);
+ cron->firstUsed_ = -1;
+ cron->cron_signal_up = SEMAPHORE_CREATE (0);
cron->ectx = ectx;
cron->cron_shutdown = YES;
cron->sig = NULL;
@@ -201,36 +205,30 @@
}
-static void noJob(void * unused) {
+static void
+noJob (void *unused)
+{
#if DEBUG_CRON
- GE_LOG(NULL,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "In noJob.\n");
+ GE_LOG (NULL, GE_STATUS | GE_DEVELOPER | GE_BULK, "In noJob.\n");
#endif
}
-void cron_stop(struct CronManager * cron) {
- void * unused;
+void
+cron_stop (struct CronManager *cron)
+{
+ void *unused;
#if DEBUG_CRON
- GE_LOG(cron->ectx,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "Stopping cron\n");
+ GE_LOG (cron->ectx, GE_STATUS | GE_DEVELOPER | GE_BULK, "Stopping cron\n");
#endif
cron->cron_shutdown = YES;
- cron_add_job(cron,
- &noJob,
- 0,
- 0,
- NULL);
- SEMAPHORE_DOWN(cron->cron_signal, YES);
- SEMAPHORE_DESTROY(cron->cron_signal);
+ cron_add_job (cron, &noJob, 0, 0, NULL);
+ SEMAPHORE_DOWN (cron->cron_signal, YES);
+ SEMAPHORE_DESTROY (cron->cron_signal);
cron->cron_signal = NULL;
- PTHREAD_JOIN(cron->cron_handle, &unused);
+ PTHREAD_JOIN (cron->cron_handle, &unused);
#if DEBUG_CRON
- GE_LOG(NULL,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "Cron stopped\n");
+ GE_LOG (NULL, GE_STATUS | GE_DEVELOPER | GE_BULK, "Cron stopped\n");
#endif
}
@@ -238,66 +236,72 @@
* CronJob to suspend the cron thread
* until it is resumed.
*/
-static void block(void * cls) {
- struct CronManager * cron = cls;
+static void
+block (void *cls)
+{
+ struct CronManager *cron = cls;
int ok = SYSERR;
if (cron->sig != NULL)
- SEMAPHORE_UP(cron->sig);
- while (ok == SYSERR) {
- SEMAPHORE_DOWN(cron->cron_signal_up, YES);
- MUTEX_LOCK(cron->inBlockLock_);
- cron->inBlock--;
- if (cron->inBlock == 0)
- ok = OK;
- MUTEX_UNLOCK(cron->inBlockLock_);
- }
+ SEMAPHORE_UP (cron->sig);
+ while (ok == SYSERR)
+ {
+ SEMAPHORE_DOWN (cron->cron_signal_up, YES);
+ MUTEX_LOCK (cron->inBlockLock_);
+ cron->inBlock--;
+ if (cron->inBlock == 0)
+ ok = OK;
+ MUTEX_UNLOCK (cron->inBlockLock_);
+ }
}
-
-void cron_suspend(struct CronManager * cron,
- int checkSelf) {
- if ( (YES == checkSelf) &&
- (cron->cron_shutdown == NO) &&
- (NO != PTHREAD_TEST_SELF(cron->cron_handle)) )
+
+void
+cron_suspend (struct CronManager *cron, int checkSelf)
+{
+ if ((YES == checkSelf) &&
+ (cron->cron_shutdown == NO) &&
+ (NO != PTHREAD_TEST_SELF (cron->cron_handle)))
return;
- GE_ASSERT(NULL, NO == PTHREAD_TEST_SELF(cron->cron_handle));
- MUTEX_LOCK(cron->inBlockLock_);
+ GE_ASSERT (NULL, NO == PTHREAD_TEST_SELF (cron->cron_handle));
+ MUTEX_LOCK (cron->inBlockLock_);
cron->inBlock++;
- if (cron->inBlock == 1) {
- cron->sig = SEMAPHORE_CREATE(0);
- cron_add_job(cron,
- &block,
- 0,
- 0,
- cron);
- SEMAPHORE_DOWN(cron->sig, YES);
- SEMAPHORE_DESTROY(cron->sig);
- cron->sig = NULL;
- }
- MUTEX_UNLOCK(cron->inBlockLock_);
+ if (cron->inBlock == 1)
+ {
+ cron->sig = SEMAPHORE_CREATE (0);
+ cron_add_job (cron, &block, 0, 0, cron);
+ SEMAPHORE_DOWN (cron->sig, YES);
+ SEMAPHORE_DESTROY (cron->sig);
+ cron->sig = NULL;
+ }
+ MUTEX_UNLOCK (cron->inBlockLock_);
}
-int cron_test_running(struct CronManager * cron) {
- if ( (NO == cron->cron_shutdown) || (cron->inBlock > 0) )
+int
+cron_test_running (struct CronManager *cron)
+{
+ if ((NO == cron->cron_shutdown) || (cron->inBlock > 0))
return YES;
else
return NO;
}
-void cron_resume_jobs(struct CronManager * cron,
- int checkSelf) {
- if ( (YES == checkSelf) &&
- (cron->cron_shutdown == NO) &&
- (NO != PTHREAD_TEST_SELF(cron->cron_handle)) )
+void
+cron_resume_jobs (struct CronManager *cron, int checkSelf)
+{
+ if ((YES == checkSelf) &&
+ (cron->cron_shutdown == NO) &&
+ (NO != PTHREAD_TEST_SELF (cron->cron_handle)))
return;
- GE_ASSERT(NULL, cron->inBlock > 0);
- SEMAPHORE_UP(cron->cron_signal_up);
+ GE_ASSERT (NULL, cron->inBlock > 0);
+ SEMAPHORE_UP (cron->cron_signal_up);
}
-static void abortSleep(struct CronManager * cron) {
+static void
+abortSleep (struct CronManager *cron)
+{
if (cron->cron_signal == NULL)
- return; /* cron_handle not valid */
- PTHREAD_STOP_SLEEP(cron->cron_handle);
+ return; /* cron_handle not valid */
+ PTHREAD_STOP_SLEEP (cron->cron_handle);
}
@@ -305,171 +309,161 @@
/**
* Print the cron-tab.
*/
-void printCronTab(struct CronManager * cron) {
+void
+printCronTab (struct CronManager *cron)
+{
int jobId;
- UTIL_cron_DeltaListEntry * tab;
+ UTIL_cron_DeltaListEntry *tab;
cron_t now;
- now = get_time();
- MUTEX_LOCK(cron->deltaListLock_);
+ now = get_time ();
+ MUTEX_LOCK (cron->deltaListLock_);
jobId = cron->firstUsed_;
- while (jobId != -1) {
- tab = &cron->deltaList_[jobId];
- GE_LOG(NULL,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "%3u: delta %8lld CU --- method %p --- repeat %8u CU\n",
- jobId,
- tab->delta - now,
- (int)tab->method,
- tab->deltaRepeat);
- jobId = tab->next;
- }
- MUTEX_UNLOCK(cron->deltaListLock_);
+ while (jobId != -1)
+ {
+ tab = &cron->deltaList_[jobId];
+ GE_LOG (NULL,
+ GE_STATUS | GE_DEVELOPER | GE_BULK,
+ "%3u: delta %8lld CU --- method %p --- repeat %8u CU\n",
+ jobId, tab->delta - now, (int) tab->method, tab->deltaRepeat);
+ jobId = tab->next;
+ }
+ MUTEX_UNLOCK (cron->deltaListLock_);
}
#endif
-void cron_advance_job(struct CronManager * cron,
- CronJob method,
- unsigned int deltaRepeat,
- void * data) {
- UTIL_cron_DeltaListEntry * job;
- UTIL_cron_DeltaListEntry * last;
+void
+cron_advance_job (struct CronManager *cron,
+ CronJob method, unsigned int deltaRepeat, void *data)
+{
+ UTIL_cron_DeltaListEntry *job;
+ UTIL_cron_DeltaListEntry *last;
int jobId;
#if DEBUG_CRON
- GE_LOG(NULL,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "Advancing job %p-%p\n",
- method,
- data);
+ GE_LOG (NULL,
+ GE_STATUS | GE_DEVELOPER | GE_BULK,
+ "Advancing job %p-%p\n", method, data);
#endif
- MUTEX_LOCK(cron->deltaListLock_);
+ MUTEX_LOCK (cron->deltaListLock_);
jobId = cron->firstUsed_;
- if (jobId == -1) {
- /* not in queue - do nothing! */
- MUTEX_UNLOCK(cron->deltaListLock_);
- return;
- }
+ if (jobId == -1)
+ {
+ /* not in queue - do nothing! */
+ MUTEX_UNLOCK (cron->deltaListLock_);
+ return;
+ }
last = NULL;
job = &cron->deltaList_[jobId];
- while ( (job->method != method) ||
- (job->data != data) ||
- (job->deltaRepeat != deltaRepeat) ) {
- last = job;
- if (job->next == -1) {
- /* not in queue; add if not running */
- if ( (method != cron->runningJob_) ||
- (data != cron->runningData_) ||
- (deltaRepeat != cron->runningRepeat_) ) {
- cron_add_job(cron,
- method,
- 0,
- deltaRepeat,
- data);
- }
- MUTEX_UNLOCK(cron->deltaListLock_);
- return;
+ while ((job->method != method) ||
+ (job->data != data) || (job->deltaRepeat != deltaRepeat))
+ {
+ last = job;
+ if (job->next == -1)
+ {
+ /* not in queue; add if not running */
+ if ((method != cron->runningJob_) ||
+ (data != cron->runningData_) ||
+ (deltaRepeat != cron->runningRepeat_))
+ {
+ cron_add_job (cron, method, 0, deltaRepeat, data);
+ }
+ MUTEX_UNLOCK (cron->deltaListLock_);
+ return;
+ }
+ jobId = job->next;
+ job = &cron->deltaList_[jobId];
}
- jobId = job->next;
- job = &cron->deltaList_[jobId];
- }
/* ok, found it; remove, re-add with time 0 */
- cron_del_job(cron,
- method,
- deltaRepeat,
- data);
- cron_add_job(cron,
- method,
- 0,
- deltaRepeat,
- data);
- MUTEX_UNLOCK(cron->deltaListLock_);
+ cron_del_job (cron, method, deltaRepeat, data);
+ cron_add_job (cron, method, 0, deltaRepeat, data);
+ MUTEX_UNLOCK (cron->deltaListLock_);
}
-void cron_add_job(struct CronManager * cron,
- CronJob method,
- unsigned int delta,
- unsigned int deltaRepeat,
- void * data) {
- UTIL_cron_DeltaListEntry * entry;
- UTIL_cron_DeltaListEntry * pos;
+void
+cron_add_job (struct CronManager *cron,
+ CronJob method,
+ unsigned int delta, unsigned int deltaRepeat, void *data)
+{
+ UTIL_cron_DeltaListEntry *entry;
+ UTIL_cron_DeltaListEntry *pos;
int last;
int current;
#if DEBUG_CRON
- GE_LOG(cron->ectx,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "Adding job %p-%p to fire in %d CU\n",
- method,
- data,
- delta);
+ GE_LOG (cron->ectx,
+ GE_STATUS | GE_DEVELOPER | GE_BULK,
+ "Adding job %p-%p to fire in %d CU\n", method, data, delta);
#endif
- MUTEX_LOCK(cron->deltaListLock_);
- if (cron->firstFree_ == -1) { /* need to grow */
- unsigned int i;
+ MUTEX_LOCK (cron->deltaListLock_);
+ if (cron->firstFree_ == -1)
+ { /* need to grow */
+ unsigned int i;
- GROW(cron->deltaList_,
- cron->deltaListSize_,
- cron->deltaListSize_ * 2);
- for (i=cron->deltaListSize_/2;i<cron->deltaListSize_;i++)
- cron->deltaList_[i].next = i-1;
- cron->deltaList_[cron->deltaListSize_/2].next = -1;
- cron->firstFree_ = cron->deltaListSize_-1;
- }
+ GROW (cron->deltaList_, cron->deltaListSize_, cron->deltaListSize_ * 2);
+ for (i = cron->deltaListSize_ / 2; i < cron->deltaListSize_; i++)
+ cron->deltaList_[i].next = i - 1;
+ cron->deltaList_[cron->deltaListSize_ / 2].next = -1;
+ cron->firstFree_ = cron->deltaListSize_ - 1;
+ }
entry = &cron->deltaList_[cron->firstFree_];
entry->method = method;
entry->data = data;
entry->deltaRepeat = deltaRepeat;
- entry->delta = get_time() + delta;
- if (cron->firstUsed_ == -1) {
- cron->firstUsed_
- = cron->firstFree_;
- cron->firstFree_
- = entry->next;
- entry->next = -1; /* end of list */
- MUTEX_UNLOCK(cron->deltaListLock_);
- /* interrupt sleeping cron-thread! */
- abortSleep(cron);
- return;
- }
+ entry->delta = get_time () + delta;
+ if (cron->firstUsed_ == -1)
+ {
+ cron->firstUsed_ = cron->firstFree_;
+ cron->firstFree_ = entry->next;
+ entry->next = -1; /* end of list */
+ MUTEX_UNLOCK (cron->deltaListLock_);
+ /* interrupt sleeping cron-thread! */
+ abortSleep (cron);
+ return;
+ }
/* no, there are jobs waiting */
last = -1;
current = cron->firstUsed_;
pos = &cron->deltaList_[current];
- while (entry->delta > pos->delta) {
- if (pos->next != -1) {
- last = current;
- current = pos->next;
- pos = &cron->deltaList_[current];
- } else { /* append */
- pos->next = cron->firstFree_;
- cron->firstFree_
- = entry->next;
- entry->next = -1;
- MUTEX_UNLOCK(cron->deltaListLock_);
+ while (entry->delta > pos->delta)
+ {
+ if (pos->next != -1)
+ {
+ last = current;
+ current = pos->next;
+ pos = &cron->deltaList_[current];
+ }
+ else
+ { /* append */
+ pos->next = cron->firstFree_;
+ cron->firstFree_ = entry->next;
+ entry->next = -1;
+ MUTEX_UNLOCK (cron->deltaListLock_);
#if HAVE_PRINT_CRON_TAB
- printCronTab();
+ printCronTab ();
#endif
- return;
+ return;
+ }
}
- }
/* insert before pos */
- if (last == -1) {
- cron->firstUsed_ = cron->firstFree_;
- abortSleep(cron);
- } else {
- cron->deltaList_[last].next = cron->firstFree_;
+ if (last == -1)
+ {
+ cron->firstUsed_ = cron->firstFree_;
+ abortSleep (cron);
+ }
+ else
+ {
+ cron->deltaList_[last].next = cron->firstFree_;
#if HAVE_PRINT_CRON_TAB
- printCronTab();
+ printCronTab ();
#endif
- }
- cron->firstFree_
- = entry->next;
+ }
+ cron->firstFree_ = entry->next;
entry->next = current;
- MUTEX_UNLOCK(cron->deltaListLock_);
+ MUTEX_UNLOCK (cron->deltaListLock_);
}
/**
@@ -480,131 +474,122 @@
* where the job is running (the job to run may add other
* jobs!)
*/
-static void runJob(struct CronManager * cron) {
- UTIL_cron_DeltaListEntry * job;
+static void
+runJob (struct CronManager *cron)
+{
+ UTIL_cron_DeltaListEntry *job;
int jobId;
CronJob method;
- void * data;
+ void *data;
unsigned int repeat;
jobId = cron->firstUsed_;
if (jobId == -1)
- return; /* no job to be done */
- job = &cron->deltaList_[jobId];
+ return; /* no job to be done */
+ job = &cron->deltaList_[jobId];
method = job->method;
cron->runningJob_ = method;
- data = job->data;
+ data = job->data;
cron->runningData_ = data;
repeat = job->deltaRepeat;
cron->runningRepeat_ = repeat;
/* remove from queue */
- cron->firstUsed_
- = job->next;
- job->next
- = cron->firstFree_;
+ cron->firstUsed_ = job->next;
+ job->next = cron->firstFree_;
cron->firstFree_ = jobId;
- MUTEX_UNLOCK(cron->deltaListLock_);
+ MUTEX_UNLOCK (cron->deltaListLock_);
/* re-insert */
- if (repeat > 0) {
+ if (repeat > 0)
+ {
#if DEBUG_CRON
- GE_LOG(cron->ectx,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "adding periodic job %p-%p to run again in %u\n",
- method,
- data,
- repeat);
+ GE_LOG (cron->ectx,
+ GE_STATUS | GE_DEVELOPER | GE_BULK,
+ "adding periodic job %p-%p to run again in %u\n",
+ method, data, repeat);
#endif
- cron_add_job(cron,
- method,
- repeat,
- repeat,
- data);
- }
+ cron_add_job (cron, method, repeat, repeat, data);
+ }
/* run */
#if DEBUG_CRON
- GE_LOG(cron->ectx,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "running job %p-%p\n",
- method,
- data);
+ GE_LOG (cron->ectx,
+ GE_STATUS | GE_DEVELOPER | GE_BULK,
+ "running job %p-%p\n", method, data);
#endif
- method(data);
- MUTEX_LOCK(cron->deltaListLock_);
+ method (data);
+ MUTEX_LOCK (cron->deltaListLock_);
cron->runningJob_ = NULL;
#if DEBUG_CRON
- GE_LOG(cron->ectx,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "job %p-%p done\n",
- method,
- data);
+ GE_LOG (cron->ectx,
+ GE_STATUS | GE_DEVELOPER | GE_BULK,
+ "job %p-%p done\n", method, data);
#endif
}
/**
* The main-method of cron.
*/
-static void * cron_main_method(void * ctx) {
- struct CronManager * cron = ctx;
+static void *
+cron_main_method (void *ctx)
+{
+ struct CronManager *cron = ctx;
cron_t now;
cron_t next;
- while (cron->cron_shutdown == NO) {
+ while (cron->cron_shutdown == NO)
+ {
#if HAVE_PRINT_CRON_TAB
- printCronTab(cron);
+ printCronTab (cron);
#endif
- now = get_time();
- next = now + 0xFFFFFFFF;
- MUTEX_LOCK(cron->deltaListLock_);
- while ( (cron->cron_shutdown == NO) &&
- (cron->firstUsed_ != -1) ) {
- now = get_time();
- next = cron->deltaList_[cron->firstUsed_].delta;
- if (next <= now) {
+ now = get_time ();
+ next = now + 0xFFFFFFFF;
+ MUTEX_LOCK (cron->deltaListLock_);
+ while ((cron->cron_shutdown == NO) && (cron->firstUsed_ != -1))
+ {
+ now = get_time ();
+ next = cron->deltaList_[cron->firstUsed_].delta;
+ if (next <= now)
+ {
#if DEBUG_CRON
- GE_LOG(cron->ectx,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "running cron job, table is\n");
- printCronTab(cron);
+ GE_LOG (cron->ectx,
+ GE_STATUS | GE_DEVELOPER | GE_BULK,
+ "running cron job, table is\n");
+ printCronTab (cron);
#endif
- runJob(cron);
+ runJob (cron);
#if DEBUG_CRON
- GE_LOG(cron->ectx,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "job run, new table is\n");
- printCronTab(cron);
+ GE_LOG (cron->ectx,
+ GE_STATUS | GE_DEVELOPER | GE_BULK,
+ "job run, new table is\n");
+ printCronTab (cron);
#endif
- } else
- break;
- }
- MUTEX_UNLOCK(cron->deltaListLock_);
- next = next - now; /* how long to sleep */
+ }
+ else
+ break;
+ }
+ MUTEX_UNLOCK (cron->deltaListLock_);
+ next = next - now; /* how long to sleep */
#if DEBUG_CRON
- GE_LOG(cron->ectx,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "Sleeping at %llu for %llu CU (%llu s, %llu CU)\n",
- now,
- next,
- next / cronSECONDS,
- next);
+ GE_LOG (cron->ectx,
+ GE_STATUS | GE_DEVELOPER | GE_BULK,
+ "Sleeping at %llu for %llu CU (%llu s, %llu CU)\n",
+ now, next, next / cronSECONDS, next);
#endif
- if (next > MAXSLEEP)
- next = MAXSLEEP;
- if (cron->cron_shutdown == NO)
- PTHREAD_SLEEP(next);
+ if (next > MAXSLEEP)
+ next = MAXSLEEP;
+ if (cron->cron_shutdown == NO)
+ PTHREAD_SLEEP (next);
#if DEBUG_CRON
- GE_LOG(cron->ectx,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "woke up at %llu - %lld CS late\n",
- get_time(),
- get_time() - (now+next));
+ GE_LOG (cron->ectx,
+ GE_STATUS | GE_DEVELOPER | GE_BULK,
+ "woke up at %llu - %lld CS late\n",
+ get_time (), get_time () - (now + next));
#endif
- }
- SEMAPHORE_UP(cron->cron_signal);
+ }
+ SEMAPHORE_UP (cron->cron_signal);
#if DEBUG_CRON
- GE_LOG(cron->ectx,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "Cron thread exits.\n");
- printCronTab(cron);
+ GE_LOG (cron->ectx,
+ GE_STATUS | GE_DEVELOPER | GE_BULK, "Cron thread exits.\n");
+ printCronTab (cron);
#endif
return NULL;
}
@@ -613,87 +598,87 @@
/**
* Make sure to call stopCron before calling this method!
*/
-void cron_destroy(struct CronManager * cron) {
+void
+cron_destroy (struct CronManager *cron)
+{
int i;
- GE_ASSERT(cron->ectx,
- cron->cron_signal == NULL);
+ GE_ASSERT (cron->ectx, cron->cron_signal == NULL);
i = cron->firstUsed_;
- while (i != -1) {
- FREENONNULL(cron->deltaList_[i].data);
- i = cron->deltaList_[i].next;
- }
- MUTEX_DESTROY(cron->deltaListLock_);
- MUTEX_DESTROY(cron->inBlockLock_);
- FREE(cron->deltaList_);
- SEMAPHORE_DESTROY(cron->cron_signal_up);
- FREE(cron);
+ while (i != -1)
+ {
+ FREENONNULL (cron->deltaList_[i].data);
+ i = cron->deltaList_[i].next;
+ }
+ MUTEX_DESTROY (cron->deltaListLock_);
+ MUTEX_DESTROY (cron->inBlockLock_);
+ FREE (cron->deltaList_);
+ SEMAPHORE_DESTROY (cron->cron_signal_up);
+ FREE (cron);
}
/**
* Start the cron jobs.
*/
-void cron_start(struct CronManager * cron) {
- GE_ASSERT(cron->ectx,
- cron->cron_signal == NULL);
+void
+cron_start (struct CronManager *cron)
+{
+ GE_ASSERT (cron->ectx, cron->cron_signal == NULL);
cron->cron_shutdown = NO;
- cron->cron_signal = SEMAPHORE_CREATE(0);
+ cron->cron_signal = SEMAPHORE_CREATE (0);
/* large stack, we don't know for sure
what the cron jobs may be doing */
- cron->cron_handle = PTHREAD_CREATE(&cron_main_method,
- cron,
- 256 * 1024);
+ cron->cron_handle = PTHREAD_CREATE (&cron_main_method, cron, 256 * 1024);
if (cron->cron_handle == 0)
- GE_DIE_STRERROR(cron->ectx,
- GE_FATAL | GE_ADMIN | GE_USER | GE_BULK,
- "pthread_create");
+ GE_DIE_STRERROR (cron->ectx,
+ GE_FATAL | GE_ADMIN | GE_USER | GE_BULK,
+ "pthread_create");
}
-int cron_del_job(struct CronManager * cron,
- CronJob method,
- unsigned int repeat,
- void * data) {
- UTIL_cron_DeltaListEntry * job;
- UTIL_cron_DeltaListEntry * last;
+int
+cron_del_job (struct CronManager *cron,
+ CronJob method, unsigned int repeat, void *data)
+{
+ UTIL_cron_DeltaListEntry *job;
+ UTIL_cron_DeltaListEntry *last;
int jobId;
#if DEBUG_CRON
- GE_LOG(cron->ectx,
- GE_STATUS | GE_DEVELOPER | GE_BULK,
- "deleting job %p-%p\n",
- method,
- data);
+ GE_LOG (cron->ectx,
+ GE_STATUS | GE_DEVELOPER | GE_BULK,
+ "deleting job %p-%p\n", method, data);
#endif
- MUTEX_LOCK(cron->deltaListLock_);
+ MUTEX_LOCK (cron->deltaListLock_);
jobId = cron->firstUsed_;
- if (jobId == -1) {
- MUTEX_UNLOCK(cron->deltaListLock_);
- return 0;
- }
+ if (jobId == -1)
+ {
+ MUTEX_UNLOCK (cron->deltaListLock_);
+ return 0;
+ }
last = NULL;
job = &cron->deltaList_[jobId];
- while ( (job->method != method) ||
- (job->data != data) ||
- (job->deltaRepeat != repeat) ) {
- last = job;
- if (job->next == -1) {
- MUTEX_UNLOCK(cron->deltaListLock_);
- return 0;
+ while ((job->method != method) ||
+ (job->data != data) || (job->deltaRepeat != repeat))
+ {
+ last = job;
+ if (job->next == -1)
+ {
+ MUTEX_UNLOCK (cron->deltaListLock_);
+ return 0;
+ }
+ jobId = job->next;
+ job = &cron->deltaList_[jobId];
}
- jobId = job->next;
- job = &cron->deltaList_[jobId];
- }
if (last != NULL)
last->next = job->next;
else
cron->firstUsed_ = job->next;
- job->next
- = cron->firstFree_;
+ job->next = cron->firstFree_;
cron->firstFree_ = jobId;
job->method = NULL;
job->data = NULL;
job->deltaRepeat = 0;
- MUTEX_UNLOCK(cron->deltaListLock_);
+ MUTEX_UNLOCK (cron->deltaListLock_);
return 1;
}
Modified: GNUnet/src/util/cron/crontest.c
===================================================================
--- GNUnet/src/util/cron/crontest.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/cron/crontest.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -31,87 +31,97 @@
static int global2;
static int global3;
-static struct CronManager * cron;
+static struct CronManager *cron;
-static void cronJob(void * unused) {
- global++;
+static void
+cronJob (void *unused)
+{
+ global ++;
}
-static void cronJob2(void * unused) {
+static void
+cronJob2 (void *unused)
+{
global2++;
}
-static void cronJob3(void * unused) {
+static void
+cronJob3 (void *unused)
+{
global3++;
}
-static int testCron() {
+static int
+testCron ()
+{
int i;
global = -1;
global2 = -1;
global3 = -1;
- cron_add_job(cron,
- &cronJob, cronSECONDS*1, cronSECONDS*1, NULL);
- cron_add_job(cron,
- &cronJob2, cronSECONDS*4, cronSECONDS*4, NULL);
- cron_add_job(cron,
- &cronJob3, cronSECONDS*16, cronSECONDS*16, NULL);
- for (i=0;i<10;i++) {
- /* fprintf(stderr,"."); */
- sleep(1);
- if (((global-i) * (global-i)) > 9) {
- fprintf(stderr,"1: Expected %d got %d\n", i, global);
- return 1;
+ cron_add_job (cron, &cronJob, cronSECONDS * 1, cronSECONDS * 1, NULL);
+ cron_add_job (cron, &cronJob2, cronSECONDS * 4, cronSECONDS * 4, NULL);
+ cron_add_job (cron, &cronJob3, cronSECONDS * 16, cronSECONDS * 16, NULL);
+ for (i = 0; i < 10; i++)
+ {
+ /* fprintf(stderr,"."); */
+ sleep (1);
+ if (((global -i) *(global -i)) > 9)
+ {
+ fprintf (stderr, "1: Expected %d got %d\n", i, global);
+ return 1;
+ }
+ if (((global2 - (i >> 2)) * (global2 - (i >> 2))) > 9)
+ {
+ fprintf (stderr, "2: Expected %d got %d\n", i >> 2, global2);
+ return 1;
+ }
+ if (((global3 - (i >> 4)) * (global3 - (i >> 4))) > 9)
+ {
+ fprintf (stderr, "3: Expected %d got %d\n", i >> 4, global3);
+ return 1;
+ }
}
- if (((global2-(i>>2)) * (global2-(i>>2))) > 9) {
- fprintf(stderr,"2: Expected %d got %d\n", i>>2, global2);
- return 1;
- }
- if (((global3-(i>>4)) * (global3-(i>>4))) > 9) {
- fprintf(stderr,"3: Expected %d got %d\n", i>>4, global3);
- return 1;
- }
- }
- cron_del_job(cron,
- &cronJob, cronSECONDS*1, NULL);
- cron_del_job(cron,
- &cronJob2, cronSECONDS*4, NULL);
- cron_del_job(cron,
- &cronJob3, cronSECONDS*16, NULL);
+ cron_del_job (cron, &cronJob, cronSECONDS * 1, NULL);
+ cron_del_job (cron, &cronJob2, cronSECONDS * 4, NULL);
+ cron_del_job (cron, &cronJob3, cronSECONDS * 16, NULL);
return 0;
}
-static void delJob(void * unused) {
- cron_del_job(cron,
- &cronJob, 42, NULL);
+static void
+delJob (void *unused)
+{
+ cron_del_job (cron, &cronJob, 42, NULL);
}
-static int testDelCron() {
+static int
+testDelCron ()
+{
global = 0;
- cron_add_job(cron,
- &cronJob, cronSECONDS*1, 42, NULL);
- cron_add_job(cron,
- &delJob, 500 * cronMILLIS, 0, NULL);
- PTHREAD_SLEEP(1 * cronSECONDS);
- if (global != 0) {
- fprintf(stderr,
- "cron job was supposed to be deleted, but ran anyway!\n");
- return 1;
- }
+ cron_add_job (cron, &cronJob, cronSECONDS * 1, 42, NULL);
+ cron_add_job (cron, &delJob, 500 * cronMILLIS, 0, NULL);
+ PTHREAD_SLEEP (1 * cronSECONDS);
+ if (global !=0)
+ {
+ fprintf (stderr,
+ "cron job was supposed to be deleted, but ran anyway!\n");
+ return 1;
+ }
return 0;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
- cron = cron_create(NULL);
- cron_start(cron);
- failureCount += testCron();
- failureCount += testDelCron();
- cron_stop(cron);
- cron_destroy(cron);
+ cron = cron_create (NULL);
+ cron_start (cron);
+ failureCount += testCron ();
+ failureCount += testDelCron ();
+ cron_stop (cron);
+ cron_destroy (cron);
if (failureCount != 0)
return 1;
return 0;
-} /* end of main */
+} /* end of main */
Modified: GNUnet/src/util/cron/timertest.c
===================================================================
--- GNUnet/src/util/cron/timertest.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/cron/timertest.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -26,75 +26,73 @@
#include "gnunet_util_cron.h"
#include "platform.h"
-static void semaphore_up(void * ctx) {
- struct SEMAPHORE * sem = ctx;
- SEMAPHORE_UP(sem);
+static void
+semaphore_up (void *ctx)
+{
+ struct SEMAPHORE *sem = ctx;
+ SEMAPHORE_UP (sem);
}
-static struct CronManager * cron;
+static struct CronManager *cron;
-static int check() {
- struct SEMAPHORE * sem;
+static int
+check ()
+{
+ struct SEMAPHORE *sem;
unsigned long long cumDelta;
cron_t now;
cron_t last;
int i;
- sem = SEMAPHORE_CREATE(0);
+ sem = SEMAPHORE_CREATE (0);
cumDelta = 0;
#define MAXV2 1500
#define INCR2 113
- for (i=50;i<MAXV2+50;i+=INCR2) {
- last = get_time();
- cron_add_job(cron,
- &semaphore_up,
- i * cronMILLIS,
- 0,
- sem);
- SEMAPHORE_DOWN(sem, YES);
- now = get_time();
- if (now < last + i)
- now = last + i - now;
- else
- now = now - (last + i);
- cumDelta += now;
+ for (i = 50; i < MAXV2 + 50; i += INCR2)
+ {
+ last = get_time ();
+ cron_add_job (cron, &semaphore_up, i * cronMILLIS, 0, sem);
+ SEMAPHORE_DOWN (sem, YES);
+ now = get_time ();
+ if (now < last + i)
+ now = last + i - now;
+ else
+ now = now - (last + i);
+ cumDelta += now;
#if VERBOSE
- FPRINTF(stderr,
- "Sleep interrupted by signal within %llu ms of deadline (intended delay:
%d ms).\n",
- now,
- i);
+ FPRINTF (stderr,
+ "Sleep interrupted by signal within %llu ms of deadline
(intended delay: %d ms).\n",
+ now, i);
#endif
- }
- FPRINTF(stdout,
- "Sleep interrupt precision is %llums. ",
- cumDelta / (MAXV2/INCR2) );
+ }
+ FPRINTF (stdout,
+ "Sleep interrupt precision is %llums. ",
+ cumDelta / (MAXV2 / INCR2));
if (cumDelta <= 10 * cronMILLIS * MAXV2 / INCR2)
- fprintf(stdout,
- "Timer precision is excellent.\n");
+ fprintf (stdout, "Timer precision is excellent.\n");
else if (cumDelta <= 50 * cronMILLIS * MAXV2 / INCR2) /* 50ms average
deviation */
- fprintf(stdout,
- "Timer precision is good.\n");
+ fprintf (stdout, "Timer precision is good.\n");
else if (cumDelta > 250 * cronMILLIS * MAXV2 / INCR2)
- fprintf(stdout,
- "Timer precision is awful.\n");
+ fprintf (stdout, "Timer precision is awful.\n");
else
- fprintf(stdout,
- "Timer precision is acceptable.\n");
+ fprintf (stdout, "Timer precision is acceptable.\n");
- SEMAPHORE_DESTROY(sem);
+ SEMAPHORE_DESTROY (sem);
return 0;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
- cron = cron_create(NULL);
- cron_start(cron);
- failureCount += check();
- cron_stop(cron);
- cron_destroy(cron);
+ cron = cron_create (NULL);
+ cron_start (cron);
+ failureCount += check ();
+ cron_stop (cron);
+ cron_destroy (cron);
if (failureCount != 0)
return 1;
return 0;
Modified: GNUnet/src/util/crypto/crc32.c
===================================================================
--- GNUnet/src/util/crypto/crc32.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/crypto/crc32.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -34,11 +34,11 @@
/* Avoid wasting space on 8-byte longs. */
#if UINT_MAX >= 0xffffffff
- typedef unsigned int uLong;
+typedef unsigned int uLong;
#elif ULONG_MAX >= 0xffffffff
- typedef unsigned long uLong;
+typedef unsigned long uLong;
#else
- #error This compiler is not ANSI-compliant!
+#error This compiler is not ANSI-compliant!
#endif
#define Z_NULL 0
@@ -52,16 +52,18 @@
* with the ccorrect final value. Thus, it is safe to call
* even on a table that someone else is using concurrently.
*/
-void __attribute__ ((constructor)) crc32_init(void) {
+void __attribute__ ((constructor)) crc32_init (void)
+{
unsigned int i, j;
uLong h = 1;
crc_table[0] = 0;
- for (i = 128; i; i >>= 1) {
- h = (h >> 1) ^ ((h & 1) ? POLYNOMIAL : 0);
- /* h is now crc_table[i] */
- for (j = 0; j < 256; j += 2*i)
- crc_table[i+j] = crc_table[j] ^ h;
- }
+ for (i = 128; i; i >>= 1)
+ {
+ h = (h >> 1) ^ ((h & 1) ? POLYNOMIAL : 0);
+ /* h is now crc_table[i] */
+ for (j = 0; j < 256; j += 2 * i)
+ crc_table[i + j] = crc_table[j] ^ h;
+ }
}
/*
@@ -74,10 +76,10 @@
* to data in little-endian byte and bit order to preserve the
* property of detecting all burst errors of length 32 bits or less.
*/
-static uLong crc32(uLong crc,
- const char *buf,
- size_t len) {
- GE_ASSERT(NULL, crc_table[255] != 0);
+static uLong
+crc32 (uLong crc, const char *buf, size_t len)
+{
+ GE_ASSERT (NULL, crc_table[255] != 0);
crc ^= 0xffffffff;
while (len--)
crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
@@ -92,10 +94,12 @@
* @param len the length of the buffer
* @return the resulting CRC32 checksum
*/
-int crc32N(const void * buf, int len) {
+int
+crc32N (const void *buf, int len)
+{
uLong crc;
- crc = crc32(0L, Z_NULL, 0);
- crc = crc32(crc, (char*)buf, len);
+ crc = crc32 (0L, Z_NULL, 0);
+ crc = crc32 (crc, (char *) buf, len);
return crc;
}
Modified: GNUnet/src/util/crypto/crctest.c
===================================================================
--- GNUnet/src/util/crypto/crctest.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/crypto/crctest.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -32,17 +32,190 @@
#include "platform.h"
static int expected[] = {
--1223996378, 929797997, -1048047323, 1791081351, -425765913, 2138425902,
82584863, 1939615314, 1806463044, -1505003452, 1878277636, -997353517,
201238705, 1723258694, -1107452366, -344562561, -1102247383, 1973035265,
715213337, -1886586005, 2021214515, -1387332962, 593019378, -571088044,
1412577760, 412164558, -1626111170, 1556494863, -289796528, -850404775,
2066714587, -911838105, -1426027382, 499684507, -835420055, 1817119454,
-1221795958, 1516966784, -1038806877, -2115880691, 532627620, 1984437415,
-396341583, -1345366324, -590766745, -1801923449, 1752427988, -386896390,
453906317, 1552589433, -858925718, 1160445643, -740188079, -486609040,
1102529269, -515846212, -1614217202, 1572162207, 943558923, -467330358,
-1870764193, 1477005328, -793029208, -888983175, -696956020, 842706021,
1642390067, -805889494, 1284862057, 1562545388, 2091626273, 1852404553,
-2076508101, 370903003, 1186422975, 1936085227, 769358463, 180401058,
2032612572, -105461719, -1119935472, 617249831, 1169304728, 1771205256,
-2042554284, 653270859, -918610713, 336081663, -913685370, 1962213744,
-505406126, -838622649, -1141518710, 893143582, -1330296611, 122119483,
1111564496, 688811976, 1016241049, -1803438473, 359630107, 1034798954,
-581359286, 1590946527, -389997034, 2020318460, 1695967527, -464069727,
-862641495, -1405012109, -771244841, 738226150, -1035328134, -933945474,
1254965774, 1661863830, -884127998, 1800460481, 814702567, -1214068102,
-541120421, 1898656429, -236825530, 1505866267, 1252462132, -981007520,
1502096471, -2134644056, 483221797, 1276403836, 541133290, -1234093967,
350748780, 257941070, 1030457090, 434988890, -1098135432, -1000556640,
-577128022, 644806294, -787536281, -1288346343, 998079404, 1259353935,
955771631, -958377466, 1746756252, 451579658, 1913409243, -952026299,
-1556035958, -830279881, 834744289, -1878491428, 700000962, -1027245802,
1393574384, -1260409147, -841420884, 892132797, 1494730226, -1649181766,
1651097838, -1041807403, -1916675721, -1324525963, 157405899, -655788033,
-1943555237, -79747022, 339721623, -138341083, 1111902411, -435322914,
-533294200, -190220608, -1718346014, -1631301894, 1706265243, 745533899,
1351941230, 1803009594, -1218191958, 1467751062, 84368433, -711251880,
1699423788, -768792716, 846639904, 2103267723, -2095288070, -440571408,
-362144485, 2020468971, 352105963, -849211036, -1272592429, 1743440467,
2020667861, -1649992312, 172682343, 816705364, -1990206923, 902689869,
-298510060, 164207498, 190378213, 242531543, 113383268, 304810777, -1081099373,
819221134, -1100982926, -855941239, 1091308887, -934548124, 520508733,
-1381763773, -491593287, -2143492665, 700894653, -2049034808, -160942046,
-2009323577, 1464245054, 1584746011, -768646852, -993282698, 1265838699,
-1873820824, 575704373, -986682955, 1270688416, 88587481, -1723991633,
-409928242, 866669946, -483811323, -181759253, -963525431, -1686612238,
-1663460076, -1128449775, -1368922329, 122318131, 795862385, 528576131,
-19927090, 1369299478, 1285665642, -738964611, 1328292127, 552041252,
-1431494354, -1205275362, 42768297, -1329537238, -449177266, 943925221,
987016465, -945138414, -270064876, 1650366626, -369252552, 582030210,
-1229235374, 147901387, -517510506, -1609742888, -1086838308, 1391998445,
-313975512, -613392078, 855706229, 1475706341, -1112105406, 2032001400,
1565777625, 2030937777, 435522421, 1823527907, -691390605, -827253664,
1057171580, -314146639, -630099999, -1347514552, 478716232, -1533658804,
-1425371979, 761987780, 1560243817, -1945893959, 1205759225, -959343783,
-576742354, -154125407, -1158108776, 1183788580, 1354198127, -1534207721,
-823991517, -170534462, -912524170, 1858513573, 467072185, 2091040157,
-1765027018, -1659401643, -1173890143, -1912754057, -84568053, 2010781784,
-921970156, 944508352, -922040609, 1055102010, 1018688871, -1186761311,
-2012263648, 1311654161, 277659086, 2029602288, 1127061510, 1029452642,
285677123, -188521091, -641039012, 653836416, -805916340, -1644860596,
1352872213, 691634876, -1477113308, -748430369, 1030697363, -2007864449,
-1196662616, 1313997192, 177342476, -566676450, -1118618118, 1697953104,
344671484, -1489783116, -889507873, 1259591310, -716567168, 2116447062,
324368527, 1789366816, 1558930442, 1950250221, -785460151, 1174714258,
-430047304, -859487565, -580633932, 607732845, -1128150220, 1544355315,
1460298016, -1771194297, 1215703690, 277231808, -416020628, -418936577,
-1724839216, 404731389, 1058730508, -1508366681, 229883053, -572310243,
1883189553, 931286849, 1659300867, -94236383, -241524462, 548020458,
-302406981, 579986475, 73468197, -984957614, 1554382245, 2084807492,
-1456802798, -1105192593, 629440327, -16313961, -2102585261, 1873675206,
161035128, 1497033351, 1990150811, -499405222, 304019482, 41935663, -805987182,
-571699268, 1748462913, 2096239823, -116359807, -1871127553, -1074832534,
-1558866192, 231353861, 2122854560, -2102323721, -281462361, -343403210,
-673268171, 1776058383, 1581561150, 2059580579, 768848632, 1347190372,
-1701705879, 245282007, -563267886, -592558289, 1662399958, 1390406821,
-1522485580, -706446863, 2069516289, -301855859, -778346387, -1454093198,
1249083752, -1760506745, 262193320, 630751125, -1495939124, -29980580,
-1989626563, 659039376, -329477132, -1003507166, -1322549020, 358606508,
-2052572059, 1848014133, 1826958586, -1004948862, -1775370541, 2134177912,
-1739214473, 1892700918, 926629675, -1042761322, 2020075900, 606370962,
-1256609305, 117577265, -586848924, 191368285, 1653535275, -1329269701,
-375879127, -1089901406, 1206489978, 534223924, -1042752982, -1178316881,
-445594741, -1501682065, -1598136839, -467688289, 750784023, 1781080461,
1729380226, 16906088, 862168532, -2037752683, 1455274138, -1491220107,
1058323960, 1711530558, 1355062750, 227640096, 396568027, -173579098,
-408975801, -993618329, -1470751562, 371076647, 209563718, 2015405719,
-723460281, -1423934420, -2089643958, 353260489, 2084264341, -792676687,
701391030, -1440658244, 1479321011, 1907822880, 1232524257, -256712289,
401077577, 621808069, 868263613, 1244930119, 2020996902, 117483907, 1341376744,
-1936988014, -445200547, -843751811, -435291191, 1041695743, 476132726,
-1226874735, -1436046747, -297047422, 1739645396, 1948680937, -718144374,
1141983978, 1673650568, -197244350, 1604464002, 1424069853, -485626505,
1708710014, -849136541, 1573778103, 530360999, 1777767203, 1376958336,
-1088364352, 1826167753, 742735448, -1386211659, -1991323164, -444115655,
-443055378, -1586901006, -1741686587, 1925818034, -2118916824, 803890920,
-1481793154, 992278937, 1302616410, 444517030, 1393144770, -2025632978,
1902300505, -1683582981, 800654133, 873850324, -619580878, -2002070410,
-2024936385, 1978986634, 2012024264, 675768872, 389435615, -867217540,
231209167, -303917385, 1445676969, -1385982721, 1310476490, 580273453,
-160600202, -1330895874, 487110497, 1124384798, 227637416, -1829783306,
1014818058, -1336870683, -1042199518, -468525587, -1186267363, -472843891,
1215617600, -2056648329, -873216891, 156780951, -1883246047, -842549253,
-717684332, 760531638, 1074787431, 786267513, 814031289, -561255343,
-110302255, -1837376592, 989669060, -81350614, 546038730, 222899882,
1298746805, 1791615733, 1565630269, 1516024174, 421691479, 1860326051,
-1973359550, 1854393443, -1401468528, -158562295, 1509929255, -124024738,
-462937489, 259890715, -1515121317, -289511197, -913738664, 698079062,
-1631229382, -507275144, 1897739663, -1118192766, -1687033399, 61405556,
-1913606579, -473308896, -259107170, -576944609, -1689355510, 322156799,
545090192, 127425176, -1815211748, -2070235628, -1172529316, 599259550,
-910906653, 1797380363, -938649427, 142991392, 504559631, 1208867355,
-807699247, -616021271, -254935281, -57151221, -1095534993, 1998380318,
1772459584, 713271407, -1197898266, 808881935, -308133481, -1314455137,
284321772, -743117625, -1622364240, -1667535152, 118713606, 1053615347,
-2072876023, -178189072, -828319551, 2047304928, -1311435786, -1970672907,
-747972100, 86806159, -436088421, 1464645587, 735840899, 32600466, -190473426,
-735703440, 482872155, 475662392, -713681085, 1424078728, -150668609,
-1137197868, -1682762563, -48035649, 1143959866, -1542015129, 284920371,
-1587695586, -625236551, -753893357, -433976266, -1329796037, -1636712478,
1686783454, 27839146, 1748631474, -879528256, 2057796026, 773734654, 112269667,
-2011541314, 1517797297, -1943171794, 268166111, -1037010413, -1945824504,
-1672323792, 306260758, -692968628, -701704965, -462980996, 939188824,
553289792, 1790245000, 2093793129, -658085781, -186055037, -2130433650,
-1013235433, 1190870089, -2126586963, -1509655742, -1291895256, -1427857845,
309538950, 388316741, 259659733, -1895092434, 110126220, -170175575,
-419430224, -696234084, -832170948, -353431720, -797675726, -1644136054,
715163272, -1305904349, -145786463, -99586244, -695450446, -871327102,
-725496060, 952863853, -688441983, -1729929460, -103732092, 1059054528,
568873585, -982665223, -128672783, 2099418320, 1508239336, -2089480835,
-390935727, 664306522, -1607364342, -163246802, -1121295140, -128375779,
-615694409, -2079391797, 760542037, 677761593, -750117849, -1060525080,
2128437080, 525250908, 1987657172, 2032530557, -2011247936, 1942775263,
1681562788, 688229491, -803856505, 684707948, 1308988965, 1455480037,
790659611, 1557968784, -383203149, -361510986, -742575828, 558837193,
-1214977424, 1253274105, -119513513, -993964385, -33438767, -177452803,
1186928041, -2073533871, 1188528559, 1896514695, 1200128512, 1930588755,
-1914141443, 1534656032, -1192989829, -1848274656, -220848455, 1001806509,
1298797392, 1533031884, -1912322446, 1705583815, 1568094347, -1397640627,
807828512, -1852996497, -1529733505, -1575634185, -1280270160, -1567624159,
-1861904922, 1276738579, 1163432999, 626879833, 316942006, -1871138342,
1341039701, 1595907877, 1950911580, 1634717748, 1071476055, -809354290,
-1161553341, -2081621710, -2085557943, 19360224, 322135580, -698485151,
1267663094, -233890834, -126361189, -1426257522, 1094007921, 500179855,
-283548002, -1678987343, 1946999943, 1489410849, 2089571262, 1430799093,
1961848046, -99462663, -552833264, 1168700661, -1783882181, 2089196401,
1092839657, 914488673, 80263859, -2140947098, -726384741, -1022448237,
2113887675, 1485770846, -112922517, 1995461466, 774613726, 944068011,
1521975359, 289086919, -386920759, -1960513175, 358460021, -238698524,
-1913640563, -1000324864, 1731755224, -1271586254, -1917469655, 2134162829,
-828097534, -1089292503, -1514835999, 1682931514, -482307169, 2110243841,
115744834, -2038340170, 65889188, -539445712, -1713206408, -1842396726,
-1659545588, -909558923, 860164922, 1328713040, 1044007120, -2103807103,
-1073990344, -1312783785, -884980824, -705318011, -1263408788, -2032228692,
-1732844111, -1813827156, 1462566279, 1179250845, 1732421772, 604429013,
-92284336, -1192166516, 304654351, 1998552034, -1802461575, -1802704071,
-1704833934, -976264396, 1005840702, 2108843914, 1363909309, 843040834,
-1039625241, 1285007226, 91610001, 418426329, 678422358, -945360697,
-440008081, -1053091357, 425719777, -1372778676, 591912153, 1229089037,
-56663158, 2140251400, 830257037, 763914157, 175610373, -2105655963,
-1040826150, 1174443038, 339290593, 346618443, -180504100, -1363190515,
210620018, 1028894425, 573529714, 698460117, 136999397, 1015621712,
-1401813739, -297990684, -1820934845, -1299093313, 1299361369, -366522415,
91527707, 1113466178, -956229484, 22204763, -1394374195, -1912666711,
-1453789804, 1613408399, -169509567, 1350520309, 540761213, -2086682848,
1095131491, -812787911, 1860108594, -1121378737, -1667252487, -486084366,
166519760, 1609891237, 728218405, 291075010, 646168382, 108462277, -1616661910,
1016600360, 2099958568, 27934736, 183821196, 13660496, -805589719, 936068730,
-439037934, 1414622584, 215845485, -1352304469, -1817427526, -1318710977,
-110207199, 228524335, 1704746590, 998293651, -1521016702, -641956531,
-2089808167, 2094404052, -1446381065, -662186492, 1670154584, 9637833,
493925511, 660047318, 1197537103, 1696017374, -204994399, -1104145601,
-852330465, -1936369658, -829716674, -1255255217, 1264013799, 1642611772,
-652520861, 777247164, 2028895987, -1424241853, -54367829, -1940161761,
-1802831079, -449405299, 838242661, -323055438, 794295411, -136989378,
-446686673, -421252799, -16777216,
+ -1223996378, 929797997, -1048047323, 1791081351, -425765913, 2138425902,
+ 82584863, 1939615314, 1806463044, -1505003452, 1878277636, -997353517,
+ 201238705, 1723258694, -1107452366, -344562561, -1102247383, 1973035265,
+ 715213337, -1886586005, 2021214515, -1387332962, 593019378, -571088044,
+ 1412577760, 412164558, -1626111170, 1556494863, -289796528, -850404775,
+ 2066714587, -911838105, -1426027382, 499684507, -835420055, 1817119454,
+ -1221795958, 1516966784, -1038806877, -2115880691, 532627620, 1984437415,
+ -396341583, -1345366324, -590766745, -1801923449, 1752427988, -386896390,
+ 453906317, 1552589433, -858925718, 1160445643, -740188079, -486609040,
+ 1102529269, -515846212, -1614217202, 1572162207, 943558923, -467330358,
+ -1870764193, 1477005328, -793029208, -888983175, -696956020, 842706021,
+ 1642390067, -805889494, 1284862057, 1562545388, 2091626273, 1852404553,
+ -2076508101, 370903003, 1186422975, 1936085227, 769358463, 180401058,
+ 2032612572, -105461719, -1119935472, 617249831, 1169304728, 1771205256,
+ -2042554284, 653270859, -918610713, 336081663, -913685370, 1962213744,
+ -505406126, -838622649, -1141518710, 893143582, -1330296611, 122119483,
+ 1111564496, 688811976, 1016241049, -1803438473, 359630107, 1034798954,
+ -581359286, 1590946527, -389997034, 2020318460, 1695967527, -464069727,
+ -862641495, -1405012109, -771244841, 738226150, -1035328134, -933945474,
+ 1254965774, 1661863830, -884127998, 1800460481, 814702567, -1214068102,
+ -541120421, 1898656429, -236825530, 1505866267, 1252462132, -981007520,
+ 1502096471, -2134644056, 483221797, 1276403836, 541133290, -1234093967,
+ 350748780, 257941070, 1030457090, 434988890, -1098135432, -1000556640,
+ -577128022, 644806294, -787536281, -1288346343, 998079404, 1259353935,
+ 955771631, -958377466, 1746756252, 451579658, 1913409243, -952026299,
+ -1556035958, -830279881, 834744289, -1878491428, 700000962, -1027245802,
+ 1393574384, -1260409147, -841420884, 892132797, 1494730226, -1649181766,
+ 1651097838, -1041807403, -1916675721, -1324525963, 157405899, -655788033,
+ -1943555237, -79747022, 339721623, -138341083, 1111902411, -435322914,
+ -533294200, -190220608, -1718346014, -1631301894, 1706265243, 745533899,
+ 1351941230, 1803009594, -1218191958, 1467751062, 84368433, -711251880,
+ 1699423788, -768792716, 846639904, 2103267723, -2095288070, -440571408,
+ -362144485, 2020468971, 352105963, -849211036, -1272592429, 1743440467,
+ 2020667861, -1649992312, 172682343, 816705364, -1990206923, 902689869,
+ -298510060, 164207498, 190378213, 242531543, 113383268, 304810777,
+ -1081099373, 819221134, -1100982926, -855941239, 1091308887, -934548124,
+ 520508733, -1381763773, -491593287, -2143492665, 700894653, -2049034808,
+ -160942046, -2009323577, 1464245054, 1584746011, -768646852, -993282698,
+ 1265838699, -1873820824, 575704373, -986682955, 1270688416, 88587481,
+ -1723991633, -409928242, 866669946, -483811323, -181759253, -963525431,
+ -1686612238, -1663460076, -1128449775, -1368922329, 122318131, 795862385,
+ 528576131, -19927090, 1369299478, 1285665642, -738964611, 1328292127,
+ 552041252, -1431494354, -1205275362, 42768297, -1329537238, -449177266,
+ 943925221, 987016465, -945138414, -270064876, 1650366626, -369252552,
+ 582030210, -1229235374, 147901387, -517510506, -1609742888, -1086838308,
+ 1391998445, -313975512, -613392078, 855706229, 1475706341, -1112105406,
+ 2032001400, 1565777625, 2030937777, 435522421, 1823527907, -691390605,
+ -827253664, 1057171580, -314146639, -630099999, -1347514552, 478716232,
+ -1533658804, -1425371979, 761987780, 1560243817, -1945893959, 1205759225,
+ -959343783, -576742354, -154125407, -1158108776, 1183788580, 1354198127,
+ -1534207721, -823991517, -170534462, -912524170, 1858513573, 467072185,
+ 2091040157, -1765027018, -1659401643, -1173890143, -1912754057, -84568053,
+ 2010781784, -921970156, 944508352, -922040609, 1055102010, 1018688871,
+ -1186761311, -2012263648, 1311654161, 277659086, 2029602288, 1127061510,
+ 1029452642, 285677123, -188521091, -641039012, 653836416, -805916340,
+ -1644860596, 1352872213, 691634876, -1477113308, -748430369, 1030697363,
+ -2007864449, -1196662616, 1313997192, 177342476, -566676450, -1118618118,
+ 1697953104, 344671484, -1489783116, -889507873, 1259591310, -716567168,
+ 2116447062, 324368527, 1789366816, 1558930442, 1950250221, -785460151,
+ 1174714258, -430047304, -859487565, -580633932, 607732845, -1128150220,
+ 1544355315, 1460298016, -1771194297, 1215703690, 277231808, -416020628,
+ -418936577, -1724839216, 404731389, 1058730508, -1508366681, 229883053,
+ -572310243, 1883189553, 931286849, 1659300867, -94236383, -241524462,
+ 548020458, -302406981, 579986475, 73468197, -984957614, 1554382245,
+ 2084807492, -1456802798, -1105192593, 629440327, -16313961, -2102585261,
+ 1873675206, 161035128, 1497033351, 1990150811, -499405222, 304019482,
+ 41935663, -805987182, -571699268, 1748462913, 2096239823, -116359807,
+ -1871127553, -1074832534, -1558866192, 231353861, 2122854560, -2102323721,
+ -281462361, -343403210, -673268171, 1776058383, 1581561150, 2059580579,
+ 768848632, 1347190372, -1701705879, 245282007, -563267886, -592558289,
+ 1662399958, 1390406821, -1522485580, -706446863, 2069516289, -301855859,
+ -778346387, -1454093198, 1249083752, -1760506745, 262193320, 630751125,
+ -1495939124, -29980580, -1989626563, 659039376, -329477132, -1003507166,
+ -1322549020, 358606508, -2052572059, 1848014133, 1826958586, -1004948862,
+ -1775370541, 2134177912, -1739214473, 1892700918, 926629675, -1042761322,
+ 2020075900, 606370962, -1256609305, 117577265, -586848924, 191368285,
+ 1653535275, -1329269701, -375879127, -1089901406, 1206489978, 534223924,
+ -1042752982, -1178316881, -445594741, -1501682065, -1598136839,
+ -467688289, 750784023, 1781080461, 1729380226, 16906088, 862168532,
+ -2037752683, 1455274138, -1491220107, 1058323960, 1711530558, 1355062750,
+ 227640096, 396568027, -173579098, -408975801, -993618329, -1470751562,
+ 371076647, 209563718, 2015405719, -723460281, -1423934420, -2089643958,
+ 353260489, 2084264341, -792676687, 701391030, -1440658244, 1479321011,
+ 1907822880, 1232524257, -256712289, 401077577, 621808069, 868263613,
+ 1244930119, 2020996902, 117483907, 1341376744, -1936988014, -445200547,
+ -843751811, -435291191, 1041695743, 476132726, -1226874735, -1436046747,
+ -297047422, 1739645396, 1948680937, -718144374, 1141983978, 1673650568,
+ -197244350, 1604464002, 1424069853, -485626505, 1708710014, -849136541,
+ 1573778103, 530360999, 1777767203, 1376958336, -1088364352, 1826167753,
+ 742735448, -1386211659, -1991323164, -444115655, -443055378, -1586901006,
+ -1741686587, 1925818034, -2118916824, 803890920, -1481793154, 992278937,
+ 1302616410, 444517030, 1393144770, -2025632978, 1902300505, -1683582981,
+ 800654133, 873850324, -619580878, -2002070410, -2024936385, 1978986634,
+ 2012024264, 675768872, 389435615, -867217540, 231209167, -303917385,
+ 1445676969, -1385982721, 1310476490, 580273453, -160600202, -1330895874,
+ 487110497, 1124384798, 227637416, -1829783306, 1014818058, -1336870683,
+ -1042199518, -468525587, -1186267363, -472843891, 1215617600, -2056648329,
+ -873216891, 156780951, -1883246047, -842549253, -717684332, 760531638,
+ 1074787431, 786267513, 814031289, -561255343, -110302255, -1837376592,
+ 989669060, -81350614, 546038730, 222899882, 1298746805, 1791615733,
+ 1565630269, 1516024174, 421691479, 1860326051, -1973359550, 1854393443,
+ -1401468528, -158562295, 1509929255, -124024738, -462937489, 259890715,
+ -1515121317, -289511197, -913738664, 698079062, -1631229382, -507275144,
+ 1897739663, -1118192766, -1687033399, 61405556, -1913606579, -473308896,
+ -259107170, -576944609, -1689355510, 322156799, 545090192, 127425176,
+ -1815211748, -2070235628, -1172529316, 599259550, -910906653, 1797380363,
+ -938649427, 142991392, 504559631, 1208867355, -807699247, -616021271,
+ -254935281, -57151221, -1095534993, 1998380318, 1772459584, 713271407,
+ -1197898266, 808881935, -308133481, -1314455137, 284321772, -743117625,
+ -1622364240, -1667535152, 118713606, 1053615347, -2072876023, -178189072,
+ -828319551, 2047304928, -1311435786, -1970672907, -747972100, 86806159,
+ -436088421, 1464645587, 735840899, 32600466, -190473426, -735703440,
+ 482872155, 475662392, -713681085, 1424078728, -150668609, -1137197868,
+ -1682762563, -48035649, 1143959866, -1542015129, 284920371, -1587695586,
+ -625236551, -753893357, -433976266, -1329796037, -1636712478, 1686783454,
+ 27839146, 1748631474, -879528256, 2057796026, 773734654, 112269667,
+ -2011541314, 1517797297, -1943171794, 268166111, -1037010413, -1945824504,
+ -1672323792, 306260758, -692968628, -701704965, -462980996, 939188824,
+ 553289792, 1790245000, 2093793129, -658085781, -186055037, -2130433650,
+ -1013235433, 1190870089, -2126586963, -1509655742, -1291895256,
+ -1427857845, 309538950, 388316741, 259659733, -1895092434, 110126220,
+ -170175575, -419430224, -696234084, -832170948, -353431720, -797675726,
+ -1644136054, 715163272, -1305904349, -145786463, -99586244, -695450446,
+ -871327102, -725496060, 952863853, -688441983, -1729929460, -103732092,
+ 1059054528, 568873585, -982665223, -128672783, 2099418320, 1508239336,
+ -2089480835, -390935727, 664306522, -1607364342, -163246802, -1121295140,
+ -128375779, -615694409, -2079391797, 760542037, 677761593, -750117849,
+ -1060525080, 2128437080, 525250908, 1987657172, 2032530557, -2011247936,
+ 1942775263, 1681562788, 688229491, -803856505, 684707948, 1308988965,
+ 1455480037, 790659611, 1557968784, -383203149, -361510986, -742575828,
+ 558837193, -1214977424, 1253274105, -119513513, -993964385, -33438767,
+ -177452803, 1186928041, -2073533871, 1188528559, 1896514695, 1200128512,
+ 1930588755, -1914141443, 1534656032, -1192989829, -1848274656, -220848455,
+ 1001806509, 1298797392, 1533031884, -1912322446, 1705583815, 1568094347,
+ -1397640627, 807828512, -1852996497, -1529733505, -1575634185,
+ -1280270160, -1567624159, -1861904922, 1276738579, 1163432999, 626879833,
+ 316942006, -1871138342, 1341039701, 1595907877, 1950911580, 1634717748,
+ 1071476055, -809354290, -1161553341, -2081621710, -2085557943, 19360224,
+ 322135580, -698485151, 1267663094, -233890834, -126361189, -1426257522,
+ 1094007921, 500179855, -283548002, -1678987343, 1946999943, 1489410849,
+ 2089571262, 1430799093, 1961848046, -99462663, -552833264, 1168700661,
+ -1783882181, 2089196401, 1092839657, 914488673, 80263859, -2140947098,
+ -726384741, -1022448237, 2113887675, 1485770846, -112922517, 1995461466,
+ 774613726, 944068011, 1521975359, 289086919, -386920759, -1960513175,
+ 358460021, -238698524, -1913640563, -1000324864, 1731755224, -1271586254,
+ -1917469655, 2134162829, -828097534, -1089292503, -1514835999, 1682931514,
+ -482307169, 2110243841, 115744834, -2038340170, 65889188, -539445712,
+ -1713206408, -1842396726, -1659545588, -909558923, 860164922, 1328713040,
+ 1044007120, -2103807103, -1073990344, -1312783785, -884980824, -705318011,
+ -1263408788, -2032228692, -1732844111, -1813827156, 1462566279,
+ 1179250845, 1732421772, 604429013, -92284336, -1192166516, 304654351,
+ 1998552034, -1802461575, -1802704071, -1704833934, -976264396, 1005840702,
+ 2108843914, 1363909309, 843040834, -1039625241, 1285007226, 91610001,
+ 418426329, 678422358, -945360697, -440008081, -1053091357, 425719777,
+ -1372778676, 591912153, 1229089037, -56663158, 2140251400, 830257037,
+ 763914157, 175610373, -2105655963, -1040826150, 1174443038, 339290593,
+ 346618443, -180504100, -1363190515, 210620018, 1028894425, 573529714,
+ 698460117, 136999397, 1015621712, -1401813739, -297990684, -1820934845,
+ -1299093313, 1299361369, -366522415, 91527707, 1113466178, -956229484,
+ 22204763, -1394374195, -1912666711, -1453789804, 1613408399, -169509567,
+ 1350520309, 540761213, -2086682848, 1095131491, -812787911, 1860108594,
+ -1121378737, -1667252487, -486084366, 166519760, 1609891237, 728218405,
+ 291075010, 646168382, 108462277, -1616661910, 1016600360, 2099958568,
+ 27934736, 183821196, 13660496, -805589719, 936068730, -439037934,
+ 1414622584, 215845485, -1352304469, -1817427526, -1318710977, -110207199,
+ 228524335, 1704746590, 998293651, -1521016702, -641956531, -2089808167,
+ 2094404052, -1446381065, -662186492, 1670154584, 9637833, 493925511,
+ 660047318, 1197537103, 1696017374, -204994399, -1104145601, -852330465,
+ -1936369658, -829716674, -1255255217, 1264013799, 1642611772, -652520861,
+ 777247164, 2028895987, -1424241853, -54367829, -1940161761, -1802831079,
+ -449405299, 838242661, -323055438, 794295411, -136989378, -446686673,
+ -421252799, -16777216,
};
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
char buf[1024];
int i;
- for (i=0;i<1024;i++)
- buf[i] = (char)i;
- for (i=0;i<1024;i++)
- if (expected[i] != crc32N(&buf[i], 1024-i))
+ for (i = 0; i < 1024; i++)
+ buf[i] = (char) i;
+ for (i = 0; i < 1024; i++)
+ if (expected[i] != crc32N (&buf[i], 1024 - i))
return 1;
return 0;
}
Modified: GNUnet/src/util/crypto/hashing.c
===================================================================
--- GNUnet/src/util/crypto/hashing.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/crypto/hashing.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -36,26 +36,28 @@
#define SHA512_DIGEST_SIZE 64
#define SHA512_HMAC_BLOCK_SIZE 128
-struct sha512_ctx {
+struct sha512_ctx
+{
unsigned long long state[8];
unsigned int count[4];
unsigned char buf[128];
};
-static unsigned long long Ch(unsigned long long x,
- unsigned long long y,
- unsigned long long z) {
+static unsigned long long
+Ch (unsigned long long x, unsigned long long y, unsigned long long z)
+{
return z ^ (x & (y ^ z));
}
-static unsigned long long Maj(unsigned long long x,
- unsigned long long y,
- unsigned long long z) {
+static unsigned long long
+Maj (unsigned long long x, unsigned long long y, unsigned long long z)
+{
return (x & y) | (z & (x | y));
}
-static unsigned long long RORu64(unsigned long long x,
- unsigned long long y) {
+static unsigned long long
+RORu64 (unsigned long long x, unsigned long long y)
+{
return (x >> y) | (x << (64 - y));
}
@@ -137,56 +139,88 @@
W[I] = s1(W[I-2]) + W[I-7] + s0(W[I-15]) + W[I-16];
static void
-sha512_transform(unsigned long long *state,
- const unsigned char *input) {
+sha512_transform (unsigned long long *state, const unsigned char *input)
+{
unsigned long long a, b, c, d, e, f, g, h, t1, t2;
unsigned long long W[80];
unsigned long long t0;
int i;
/* load the input */
- for (i = 0; i < 16; i++) {
- LOAD_OP(t0, i, W, input);
- }
+ for (i = 0; i < 16; i++)
+ {
+ LOAD_OP (t0, i, W, input);
+ }
- for (i = 16; i < 80; i++) {
- BLEND_OP(i, W);
- }
+ for (i = 16; i < 80; i++)
+ {
+ BLEND_OP (i, W);
+ }
/* load the state into our registers */
- a=state[0]; b=state[1]; c=state[2]; d=state[3];
- e=state[4]; f=state[5]; g=state[6]; h=state[7];
+ a = state[0];
+ b = state[1];
+ c = state[2];
+ d = state[3];
+ e = state[4];
+ f = state[5];
+ g = state[6];
+ h = state[7];
/* now iterate */
- for (i=0; i<80; i+=8) {
- t1 = h + e1(e) + Ch(e,f,g) + sha512_K[i ] + W[i ];
- t2 = e0(a) + Maj(a,b,c); d+=t1; h=t1+t2;
- t1 = g + e1(d) + Ch(d,e,f) + sha512_K[i+1] + W[i+1];
- t2 = e0(h) + Maj(h,a,b); c+=t1; g=t1+t2;
- t1 = f + e1(c) + Ch(c,d,e) + sha512_K[i+2] + W[i+2];
- t2 = e0(g) + Maj(g,h,a); b+=t1; f=t1+t2;
- t1 = e + e1(b) + Ch(b,c,d) + sha512_K[i+3] + W[i+3];
- t2 = e0(f) + Maj(f,g,h); a+=t1; e=t1+t2;
- t1 = d + e1(a) + Ch(a,b,c) + sha512_K[i+4] + W[i+4];
- t2 = e0(e) + Maj(e,f,g); h+=t1; d=t1+t2;
- t1 = c + e1(h) + Ch(h,a,b) + sha512_K[i+5] + W[i+5];
- t2 = e0(d) + Maj(d,e,f); g+=t1; c=t1+t2;
- t1 = b + e1(g) + Ch(g,h,a) + sha512_K[i+6] + W[i+6];
- t2 = e0(c) + Maj(c,d,e); f+=t1; b=t1+t2;
- t1 = a + e1(f) + Ch(f,g,h) + sha512_K[i+7] + W[i+7];
- t2 = e0(b) + Maj(b,c,d); e+=t1; a=t1+t2;
- }
+ for (i = 0; i < 80; i += 8)
+ {
+ t1 = h + e1 (e) + Ch (e, f, g) + sha512_K[i] + W[i];
+ t2 = e0 (a) + Maj (a, b, c);
+ d += t1;
+ h = t1 + t2;
+ t1 = g + e1 (d) + Ch (d, e, f) + sha512_K[i + 1] + W[i + 1];
+ t2 = e0 (h) + Maj (h, a, b);
+ c += t1;
+ g = t1 + t2;
+ t1 = f + e1 (c) + Ch (c, d, e) + sha512_K[i + 2] + W[i + 2];
+ t2 = e0 (g) + Maj (g, h, a);
+ b += t1;
+ f = t1 + t2;
+ t1 = e + e1 (b) + Ch (b, c, d) + sha512_K[i + 3] + W[i + 3];
+ t2 = e0 (f) + Maj (f, g, h);
+ a += t1;
+ e = t1 + t2;
+ t1 = d + e1 (a) + Ch (a, b, c) + sha512_K[i + 4] + W[i + 4];
+ t2 = e0 (e) + Maj (e, f, g);
+ h += t1;
+ d = t1 + t2;
+ t1 = c + e1 (h) + Ch (h, a, b) + sha512_K[i + 5] + W[i + 5];
+ t2 = e0 (d) + Maj (d, e, f);
+ g += t1;
+ c = t1 + t2;
+ t1 = b + e1 (g) + Ch (g, h, a) + sha512_K[i + 6] + W[i + 6];
+ t2 = e0 (c) + Maj (c, d, e);
+ f += t1;
+ b = t1 + t2;
+ t1 = a + e1 (f) + Ch (f, g, h) + sha512_K[i + 7] + W[i + 7];
+ t2 = e0 (b) + Maj (b, c, d);
+ e += t1;
+ a = t1 + t2;
+ }
- state[0] += a; state[1] += b; state[2] += c; state[3] += d;
- state[4] += e; state[5] += f; state[6] += g; state[7] += h;
+ state[0] += a;
+ state[1] += b;
+ state[2] += c;
+ state[3] += d;
+ state[4] += e;
+ state[5] += f;
+ state[6] += g;
+ state[7] += h;
/* erase our data */
a = b = c = d = e = f = g = h = t1 = t2 = 0;
- memset(W, 0, 80 * sizeof(unsigned long long));
+ memset (W, 0, 80 * sizeof (unsigned long long));
}
static void
-sha512_init(struct sha512_ctx * sctx) {
+sha512_init (struct sha512_ctx *sctx)
+{
sctx->state[0] = H0;
sctx->state[1] = H1;
sctx->state[2] = H2;
@@ -196,48 +230,52 @@
sctx->state[6] = H6;
sctx->state[7] = H7;
sctx->count[0] = sctx->count[1] = sctx->count[2] = sctx->count[3] = 0;
- memset(sctx->buf, 0, sizeof(sctx->buf));
+ memset (sctx->buf, 0, sizeof (sctx->buf));
}
static void
-sha512_update(struct sha512_ctx * sctx,
- const unsigned char *data,
- unsigned int len) {
+sha512_update (struct sha512_ctx *sctx,
+ const unsigned char *data, unsigned int len)
+{
unsigned int i, index, part_len;
/* Compute number of bytes mod 128 */
- index = (unsigned int)((sctx->count[0] >> 3) & 0x7F);
+ index = (unsigned int) ((sctx->count[0] >> 3) & 0x7F);
/* Update number of bits */
- if ((sctx->count[0] += (len << 3)) < (len << 3)) {
- if ((sctx->count[1] += 1) < 1)
- if ((sctx->count[2] += 1) < 1)
- sctx->count[3]++;
- sctx->count[1] += (len >> 29);
- }
+ if ((sctx->count[0] += (len << 3)) < (len << 3))
+ {
+ if ((sctx->count[1] += 1) < 1)
+ if ((sctx->count[2] += 1) < 1)
+ sctx->count[3]++;
+ sctx->count[1] += (len >> 29);
+ }
part_len = 128 - index;
/* Transform as many times as possible. */
- if (len >= part_len) {
- memcpy(&sctx->buf[index], data, part_len);
- sha512_transform(sctx->state, sctx->buf);
+ if (len >= part_len)
+ {
+ memcpy (&sctx->buf[index], data, part_len);
+ sha512_transform (sctx->state, sctx->buf);
- for (i = part_len; i + 127 < len; i+=128)
- sha512_transform(sctx->state, &data[i]);
+ for (i = part_len; i + 127 < len; i += 128)
+ sha512_transform (sctx->state, &data[i]);
- index = 0;
- } else {
- i = 0;
- }
+ index = 0;
+ }
+ else
+ {
+ i = 0;
+ }
/* Buffer remaining input */
- memcpy(&sctx->buf[index], &data[i], len - i);
+ memcpy (&sctx->buf[index], &data[i], len - i);
}
static void
-sha512_final(struct sha512_ctx * sctx,
- unsigned char *hash) {
+sha512_final (struct sha512_ctx *sctx, unsigned char *hash)
+{
static unsigned char padding[128] = { 0x80, };
unsigned int t;
@@ -251,49 +289,69 @@
/* Save number of bits */
t = sctx->count[0];
- bits[15] = t; t>>=8;
- bits[14] = t; t>>=8;
- bits[13] = t; t>>=8;
+ bits[15] = t;
+ t >>= 8;
+ bits[14] = t;
+ t >>= 8;
+ bits[13] = t;
+ t >>= 8;
bits[12] = t;
t = sctx->count[1];
- bits[11] = t; t>>=8;
- bits[10] = t; t>>=8;
- bits[9 ] = t; t>>=8;
- bits[8 ] = t;
+ bits[11] = t;
+ t >>= 8;
+ bits[10] = t;
+ t >>= 8;
+ bits[9] = t;
+ t >>= 8;
+ bits[8] = t;
t = sctx->count[2];
- bits[7 ] = t; t>>=8;
- bits[6 ] = t; t>>=8;
- bits[5 ] = t; t>>=8;
- bits[4 ] = t;
+ bits[7] = t;
+ t >>= 8;
+ bits[6] = t;
+ t >>= 8;
+ bits[5] = t;
+ t >>= 8;
+ bits[4] = t;
t = sctx->count[3];
- bits[3 ] = t; t>>=8;
- bits[2 ] = t; t>>=8;
- bits[1 ] = t; t>>=8;
- bits[0 ] = t;
+ bits[3] = t;
+ t >>= 8;
+ bits[2] = t;
+ t >>= 8;
+ bits[1] = t;
+ t >>= 8;
+ bits[0] = t;
/* Pad out to 112 mod 128. */
index = (sctx->count[0] >> 3) & 0x7f;
- pad_len = (index < 112) ? (112 - index) : ((128+112) - index);
- sha512_update(sctx, padding, pad_len);
+ pad_len = (index < 112) ? (112 - index) : ((128 + 112) - index);
+ sha512_update (sctx, padding, pad_len);
/* Append length (before padding) */
- sha512_update(sctx, bits, 16);
+ sha512_update (sctx, bits, 16);
/* Store state in digest */
- for (i = j = 0; i < 8; i++, j += 8) {
- t2 = sctx->state[i];
- hash[j+7] = (char)t2 & 0xff; t2>>=8;
- hash[j+6] = (char)t2 & 0xff; t2>>=8;
- hash[j+5] = (char)t2 & 0xff; t2>>=8;
- hash[j+4] = (char)t2 & 0xff; t2>>=8;
- hash[j+3] = (char)t2 & 0xff; t2>>=8;
- hash[j+2] = (char)t2 & 0xff; t2>>=8;
- hash[j+1] = (char)t2 & 0xff; t2>>=8;
- hash[j ] = (char)t2 & 0xff;
- }
+ for (i = j = 0; i < 8; i++, j += 8)
+ {
+ t2 = sctx->state[i];
+ hash[j + 7] = (char) t2 & 0xff;
+ t2 >>= 8;
+ hash[j + 6] = (char) t2 & 0xff;
+ t2 >>= 8;
+ hash[j + 5] = (char) t2 & 0xff;
+ t2 >>= 8;
+ hash[j + 4] = (char) t2 & 0xff;
+ t2 >>= 8;
+ hash[j + 3] = (char) t2 & 0xff;
+ t2 >>= 8;
+ hash[j + 2] = (char) t2 & 0xff;
+ t2 >>= 8;
+ hash[j + 1] = (char) t2 & 0xff;
+ t2 >>= 8;
+ hash[j] = (char) t2 & 0xff;
+ }
/* Zeroize sensitive information. */
- memset(sctx, 0, sizeof(struct sha512_ctx));
+ memset (sctx, 0, sizeof (struct sha512_ctx));
}
/**
@@ -303,14 +361,14 @@
* @param size the length of the data to hash
* @param ret pointer to where to write the hashcode
*/
-void hash(const void * block,
- unsigned int size,
- HashCode512 * ret) {
+void
+hash (const void *block, unsigned int size, HashCode512 * ret)
+{
struct sha512_ctx ctx;
- sha512_init(&ctx);
- sha512_update(&ctx, block, size);
- sha512_final(&ctx, (unsigned char*) ret);
+ sha512_init (&ctx);
+ sha512_update (&ctx, block, size);
+ sha512_final (&ctx, (unsigned char *) ret);
}
/**
@@ -320,72 +378,60 @@
*
* @return OK on success, SYSERR on error
*/
-int getFileHash(struct GE_Context * ectx,
- const char * filename,
- HashCode512 * ret) {
- unsigned char * buf;
+int
+getFileHash (struct GE_Context *ectx, const char *filename, HashCode512 * ret)
+{
+ unsigned char *buf;
unsigned long long len;
unsigned long long pos;
unsigned int delta;
int fh;
struct sha512_ctx ctx;
- if (OK != disk_file_test(ectx,
- filename))
+ if (OK != disk_file_test (ectx, filename))
return SYSERR;
- if (OK != disk_file_size(ectx,
- filename,
- &len,
- NO))
+ if (OK != disk_file_size (ectx, filename, &len, NO))
return SYSERR;
- fh = disk_file_open(ectx,
- filename,
- O_RDONLY | O_LARGEFILE);
- if (fh == -1) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_REQUEST,
- "open",
- filename);
- return SYSERR;
- }
- sha512_init(&ctx);
- pos = 0;
- buf = MALLOC(65536);
- while (pos < len) {
- delta = 65536;
- if (len - pos < delta)
- delta = len-pos;
- if (delta != READ(fh,
- buf,
- delta)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "read",
- filename);
- if (0 != CLOSE(fh))
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "close",
- filename);
- FREE(buf);
+ fh = disk_file_open (ectx, filename, O_RDONLY | O_LARGEFILE);
+ if (fh == -1)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_REQUEST,
+ "open", filename);
return SYSERR;
}
- sha512_update(&ctx,
- buf,
- delta);
- if (pos + delta > pos)
- pos += delta;
- else
- break;
- }
- if (0 != CLOSE(fh))
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "close",
- filename);
- sha512_final(&ctx,
- (unsigned char*) ret);
- FREE(buf);
+ sha512_init (&ctx);
+ pos = 0;
+ buf = MALLOC (65536);
+ while (pos < len)
+ {
+ delta = 65536;
+ if (len - pos < delta)
+ delta = len - pos;
+ if (delta != READ (fh, buf, delta))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "read", filename);
+ if (0 != CLOSE (fh))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "close", filename);
+ FREE (buf);
+ return SYSERR;
+ }
+ sha512_update (&ctx, buf, delta);
+ if (pos + delta > pos)
+ pos += delta;
+ else
+ break;
+ }
+ if (0 != CLOSE (fh))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "close", filename);
+ sha512_final (&ctx, (unsigned char *) ret);
+ FREE (buf);
return OK;
}
@@ -395,12 +441,14 @@
/**
* 32 characters for encoding (hash => 32 characters)
*/
-static char * encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
+static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
-static unsigned int getValue__(unsigned char a) {
- if ( (a >= '0') && (a <= '9') )
+static unsigned int
+getValue__ (unsigned char a)
+{
+ if ((a >= '0') && (a <= '9'))
return a - '0';
- if ( (a >= 'A') && (a <= 'V') )
+ if ((a >= 'A') && (a <= 'V'))
return (a - 'A' + 10);
return -1;
}
@@ -416,37 +464,39 @@
* @param result where to store the encoding (EncName can be
* safely cast to char*, a '\0' termination is set).
*/
-void hash2enc(const HashCode512 * block,
- EncName * result) {
+void
+hash2enc (const HashCode512 * block, EncName * result)
+{
unsigned int wpos;
unsigned int rpos;
unsigned int bits;
unsigned int vbit;
- GE_ASSERT(NULL, block != NULL);
- GE_ASSERT(NULL, result != NULL);
+ GE_ASSERT (NULL, block != NULL);
+ GE_ASSERT (NULL, result != NULL);
vbit = 0;
wpos = 0;
rpos = 0;
bits = 0;
- while ( (rpos < sizeof(HashCode512)) ||
- (vbit > 0) ) {
- if ( (rpos < sizeof(HashCode512)) &&
- (vbit < 5) ) {
- bits = (bits << 8) | ((unsigned char*)block)[rpos++]; /* eat 8 more bits
*/
- vbit += 8;
+ while ((rpos < sizeof (HashCode512)) || (vbit > 0))
+ {
+ if ((rpos < sizeof (HashCode512)) && (vbit < 5))
+ {
+ bits = (bits << 8) | ((unsigned char *) block)[rpos++]; /* eat
8 more bits */
+ vbit += 8;
+ }
+ if (vbit < 5)
+ {
+ bits <<= (5 - vbit); /* zero-padding */
+ GE_ASSERT (NULL, vbit == 2); /* padding by 3: 512+3 mod 5 == 0 */
+ vbit = 5;
+ }
+ GE_ASSERT (NULL, wpos < sizeof (EncName) - 1);
+ result->encoding[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
+ vbit -= 5;
}
- if (vbit < 5) {
- bits <<= (5 - vbit); /* zero-padding */
- GE_ASSERT(NULL, vbit == 2); /* padding by 3: 512+3 mod 5 == 0 */
- vbit = 5;
- }
- GE_ASSERT(NULL, wpos < sizeof(EncName)-1);
- result->encoding[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
- vbit -= 5;
- }
- GE_ASSERT(NULL, wpos == sizeof(EncName)-1);
- GE_ASSERT(NULL, vbit == 0);
+ GE_ASSERT (NULL, wpos == sizeof (EncName) - 1);
+ GE_ASSERT (NULL, vbit == 0);
result->encoding[wpos] = '\0';
}
@@ -457,33 +507,35 @@
* @param result where to store the hash code
* @return OK on success, SYSERR if result has the wrong encoding
*/
-int enc2hash(const char * enc,
- HashCode512 * result) {
+int
+enc2hash (const char *enc, HashCode512 * result)
+{
unsigned int rpos;
unsigned int wpos;
unsigned int bits;
unsigned int vbit;
- if (strlen(enc) != sizeof(EncName)-1)
+ if (strlen (enc) != sizeof (EncName) - 1)
return SYSERR;
- vbit = 2; /* padding! */
- wpos = sizeof(HashCode512);
- rpos = sizeof(EncName)-1;
- bits = getValue__(enc[--rpos]) >> 3;
- while (wpos > 0) {
- GE_ASSERT(NULL, rpos > 0);
- bits = (getValue__(enc[--rpos]) << vbit) | bits;
- vbit += 5;
- if (vbit >= 8) {
- ((unsigned char*)result)[--wpos]
- = (unsigned char) bits;
- bits >>= 8;
- vbit -= 8;
+ vbit = 2; /* padding! */
+ wpos = sizeof (HashCode512);
+ rpos = sizeof (EncName) - 1;
+ bits = getValue__ (enc[--rpos]) >> 3;
+ while (wpos > 0)
+ {
+ GE_ASSERT (NULL, rpos > 0);
+ bits = (getValue__ (enc[--rpos]) << vbit) | bits;
+ vbit += 5;
+ if (vbit >= 8)
+ {
+ ((unsigned char *) result)[--wpos] = (unsigned char) bits;
+ bits >>= 8;
+ vbit -= 8;
+ }
}
- }
- GE_ASSERT(NULL, rpos == 0);
- GE_ASSERT(NULL, vbit == 0);
+ GE_ASSERT (NULL, rpos == 0);
+ GE_ASSERT (NULL, vbit == 0);
return OK;
}
@@ -496,69 +548,68 @@
* @returns a positive number which is a measure for
* hashcode proximity.
*/
-unsigned int distanceHashCode512(const HashCode512 * a,
- const HashCode512 * b) {
- unsigned int x = (a->bits[1] - b->bits[1])>>16;
- return ((x*x)>>16);
+unsigned int
+distanceHashCode512 (const HashCode512 * a, const HashCode512 * b)
+{
+ unsigned int x = (a->bits[1] - b->bits[1]) >> 16;
+ return ((x * x) >> 16);
}
/**
* Compare two hashcodes.
* @return 1 if they are equal, 0 if not.
*/
-int equalsHashCode512(const HashCode512 * a,
- const HashCode512 * b) {
- return (0 == memcmp(a,b,sizeof(HashCode512)));
+int
+equalsHashCode512 (const HashCode512 * a, const HashCode512 * b)
+{
+ return (0 == memcmp (a, b, sizeof (HashCode512)));
}
-void makeRandomId(HashCode512 * result) {
+void
+makeRandomId (HashCode512 * result)
+{
int i;
- for (i=(sizeof(HashCode512)/sizeof(unsigned int))-1;i>=0;i--)
- result->bits[i] = rand();
+ for (i = (sizeof (HashCode512) / sizeof (unsigned int)) - 1; i >= 0; i--)
+ result->bits[i] = rand ();
}
-void deltaId(const HashCode512 * a,
- const HashCode512 * b,
- HashCode512 * result) {
+void
+deltaId (const HashCode512 * a, const HashCode512 * b, HashCode512 * result)
+{
int i;
- for (i=(sizeof(HashCode512)/sizeof(unsigned int))-1;i>=0;i--)
+ for (i = (sizeof (HashCode512) / sizeof (unsigned int)) - 1; i >= 0; i--)
result->bits[i] = b->bits[i] - a->bits[i];
}
-void addHashCodes(const HashCode512 * a,
- const HashCode512 * delta,
- HashCode512 * result) {
+void
+addHashCodes (const HashCode512 * a,
+ const HashCode512 * delta, HashCode512 * result)
+{
int i;
- for (i=(sizeof(HashCode512)/sizeof(unsigned int))-1;i>=0;i--)
+ for (i = (sizeof (HashCode512) / sizeof (unsigned int)) - 1; i >= 0; i--)
result->bits[i] = delta->bits[i] + a->bits[i];
}
-void xorHashCodes(const HashCode512 * a,
- const HashCode512 * b,
- HashCode512 * result) {
+void
+xorHashCodes (const HashCode512 * a,
+ const HashCode512 * b, HashCode512 * result)
+{
int i;
- for (i=(sizeof(HashCode512)/sizeof(unsigned int))-1;i>=0;i--)
+ for (i = (sizeof (HashCode512) / sizeof (unsigned int)) - 1; i >= 0; i--)
result->bits[i] = a->bits[i] ^ b->bits[i];
}
/**
* Convert a hashcode into a key.
*/
-void hashToKey(const HashCode512 * hc,
- SESSIONKEY * skey,
- INITVECTOR * iv) {
- GE_ASSERT(NULL,
- sizeof(HashCode512) >=
- SESSIONKEY_LEN +
- sizeof(INITVECTOR));
- memcpy(skey,
- hc,
- SESSIONKEY_LEN);
- skey->crc32 = htonl(crc32N(skey,
- SESSIONKEY_LEN));
- memcpy(iv,
- &((char *)hc)[SESSIONKEY_LEN],
- sizeof(INITVECTOR));
+void
+hashToKey (const HashCode512 * hc, SESSIONKEY * skey, INITVECTOR * iv)
+{
+ GE_ASSERT (NULL,
+ sizeof (HashCode512) >= SESSIONKEY_LEN + sizeof (INITVECTOR));
+ memcpy (skey, hc, SESSIONKEY_LEN);
+ skey->crc32 = htonl (crc32N (skey, SESSIONKEY_LEN));
+ memcpy (iv, &((char *) hc)[SESSIONKEY_LEN], sizeof (INITVECTOR));
}
/**
@@ -567,14 +618,15 @@
* @param bit index into the hashcode, [0...511]
* @return Bit \a bit from hashcode \a code, -1 for invalid index
*/
-int getHashCodeBit(const HashCode512 * code,
- unsigned int bit) {
- if (bit >= 8 * sizeof(HashCode512)) {
- GE_ASSERT(NULL,
- 0);
- return -1; /* error */
- }
- return (((unsigned char*)code)[bit >> 3] & (1 << bit & 7)) > 0;
+int
+getHashCodeBit (const HashCode512 * code, unsigned int bit)
+{
+ if (bit >= 8 * sizeof (HashCode512))
+ {
+ GE_ASSERT (NULL, 0);
+ return -1; /* error */
+ }
+ return (((unsigned char *) code)[bit >> 3] & (1 << bit & 7)) > 0;
}
/**
@@ -582,20 +634,22 @@
* of all hashcodes.
* @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
*/
-int hashCodeCompare(const HashCode512 * h1,
- const HashCode512 * h2) {
- unsigned int * i1;
- unsigned int * i2;
+int
+hashCodeCompare (const HashCode512 * h1, const HashCode512 * h2)
+{
+ unsigned int *i1;
+ unsigned int *i2;
int i;
- i1 = (unsigned int*) h1;
- i2 = (unsigned int*) h2;
- for (i=(sizeof(HashCode512) / sizeof(unsigned int))-1;i>=0;i--) {
- if (i1[i] > i2[i])
- return 1;
- if (i1[i] < i2[i])
- return -1;
- }
+ i1 = (unsigned int *) h1;
+ i2 = (unsigned int *) h2;
+ for (i = (sizeof (HashCode512) / sizeof (unsigned int)) - 1; i >= 0; i--)
+ {
+ if (i1[i] > i2[i])
+ return 1;
+ if (i1[i] < i2[i])
+ return -1;
+ }
return 0;
}
@@ -604,21 +658,23 @@
* in the XOR metric (Kademlia).
* @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
*/
-int hashCodeCompareDistance(const HashCode512 * h1,
- const HashCode512 * h2,
- const HashCode512 * target) {
+int
+hashCodeCompareDistance (const HashCode512 * h1,
+ const HashCode512 * h2, const HashCode512 * target)
+{
int i;
unsigned int d1;
unsigned int d2;
- for (i=sizeof(HashCode512)/sizeof(unsigned int)-1;i>=0;i--) {
- d1 = ((unsigned int*)h1)[i] ^ ((unsigned int*)target)[i];
- d2 = ((unsigned int*)h2)[i] ^ ((unsigned int*)target)[i];
- if (d1 > d2)
- return 1;
- else if (d1 < d2)
- return -1;
- }
+ for (i = sizeof (HashCode512) / sizeof (unsigned int) - 1; i >= 0; i--)
+ {
+ d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
+ d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
+ if (d1 > d2)
+ return 1;
+ else if (d1 < d2)
+ return -1;
+ }
return 0;
}
Modified: GNUnet/src/util/crypto/hashingtest.c
===================================================================
--- GNUnet/src/util/crypto/hashingtest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/crypto/hashingtest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -28,38 +28,43 @@
#include "gnunet_util_crypto.h"
#include "platform.h"
-static int test(int number) {
+static int
+test (int number)
+{
HashCode512 h1;
HashCode512 h2;
EncName enc;
- memset(&h1,
- number,
- sizeof(HashCode512));
- hash2enc(&h1, &enc);
- if (OK != enc2hash((char*)&enc, &h2)) {
- printf("enc2hash failed!\n");
+ memset (&h1, number, sizeof (HashCode512));
+ hash2enc (&h1, &enc);
+ if (OK != enc2hash ((char *) &enc, &h2))
+ {
+ printf ("enc2hash failed!\n");
+ return 1;
+ }
+ if (!equalsHashCode512 (&h1, &h2))
return 1;
- }
- if (! equalsHashCode512(&h1, &h2))
- return 1;
return 0;
}
-static int testEncoding() {
+static int
+testEncoding ()
+{
int i;
- for (i=0;i<255;i++)
- if (0 != test(i))
+ for (i = 0; i < 255; i++)
+ if (0 != test (i))
return 1;
return 0;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
int i;
- for (i=0;i<10;i++)
- failureCount += testEncoding();
+ for (i = 0; i < 10; i++)
+ failureCount += testEncoding ();
if (failureCount != 0)
return 1;
return 0;
Modified: GNUnet/src/util/crypto/hashperf.c
===================================================================
--- GNUnet/src/util/crypto/hashperf.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/crypto/hashperf.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -28,37 +28,35 @@
#include "gnunet_util_crypto.h"
#include "platform.h"
-static void perfHash() {
+static void
+perfHash ()
+{
HashCode512 hc1;
HashCode512 hc2;
HashCode512 hc3;
int i;
- char * buf;
+ char *buf;
- buf = MALLOC(1024*64);
- memset(buf, 1, 1024 * 64);
- hash("foo", 3, &hc1);
- for (i=0;i<1024;i++) {
- hash(&hc1,
- sizeof(HashCode512),
- &hc2);
- hash(&hc2,
- sizeof(HashCode512),
- &hc1);
- hash(buf,
- 1024 * 64,
- &hc3);
- }
- FREE(buf);
+ buf = MALLOC (1024 * 64);
+ memset (buf, 1, 1024 * 64);
+ hash ("foo", 3, &hc1);
+ for (i = 0; i < 1024; i++)
+ {
+ hash (&hc1, sizeof (HashCode512), &hc2);
+ hash (&hc2, sizeof (HashCode512), &hc1);
+ hash (buf, 1024 * 64, &hc3);
+ }
+ FREE (buf);
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
cron_t start;
- start = get_time();
- perfHash();
- printf("Hash perf took %llu ms\n",
- get_time() - start);
+ start = get_time ();
+ perfHash ();
+ printf ("Hash perf took %llu ms\n", get_time () - start);
return 0;
}
Modified: GNUnet/src/util/crypto/hostkey_gcrypt.c
===================================================================
--- GNUnet/src/util/crypto/hostkey_gcrypt.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/crypto/hostkey_gcrypt.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -46,7 +46,8 @@
/**
* The private information of an RSA key pair.
*/
-struct PrivateKey {
+struct PrivateKey
+{
gcry_sexp_t sexp;
};
@@ -76,65 +77,57 @@
* end of the size-sized buffer and zero out the
* first target-size bytes.
*/
-static void adjust(unsigned char * buf,
- size_t size,
- size_t target) {
- if (size < target) {
- memmove(&buf[target-size],
- buf,
- size);
- memset(buf,
- 0,
- target-size);
- }
+static void
+adjust (unsigned char *buf, size_t size, size_t target)
+{
+ if (size < target)
+ {
+ memmove (&buf[target - size], buf, size);
+ memset (buf, 0, target - size);
+ }
}
/**
* This HostKey implementation uses RSA.
*/
-struct PrivateKey * makePrivateKey() {
- struct PrivateKey * ret;
+struct PrivateKey *
+makePrivateKey ()
+{
+ struct PrivateKey *ret;
gcry_sexp_t s_key;
gcry_sexp_t s_keyparam;
int rc;
- lockGcrypt();
- rc = gcry_sexp_build(&s_keyparam,
- NULL,
- "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
- HOSTKEY_LEN);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_sexp_build",
- rc);
- unlockGcrypt();
- return NULL;
- }
- rc = gcry_pk_genkey(&s_key,
- s_keyparam);
- gcry_sexp_release(s_keyparam);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_pk_genkey",
- rc);
- unlockGcrypt();
- return NULL;
- }
+ lockGcrypt ();
+ rc = gcry_sexp_build (&s_keyparam,
+ NULL,
+ "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
+ HOSTKEY_LEN);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_sexp_build", rc);
+ unlockGcrypt ();
+ return NULL;
+ }
+ rc = gcry_pk_genkey (&s_key, s_keyparam);
+ gcry_sexp_release (s_keyparam);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_pk_genkey", rc);
+ unlockGcrypt ();
+ return NULL;
+ }
#if EXTRA_CHECKS
- if ((rc=gcry_pk_testkey(s_key))) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_pk_testkey",
- rc);
- unlockGcrypt();
- return NULL;
- }
+ if ((rc = gcry_pk_testkey (s_key)))
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_pk_testkey", rc);
+ unlockGcrypt ();
+ return NULL;
+ }
#endif
- unlockGcrypt();
- ret = MALLOC(sizeof(struct PrivateKey));
+ unlockGcrypt ();
+ ret = MALLOC (sizeof (struct PrivateKey));
ret->sexp = s_key;
return ret;
}
@@ -142,61 +135,70 @@
/**
* Free memory occupied by hostkey
*/
-void freePrivateKey(struct PrivateKey * hostkey) {
- lockGcrypt();
- gcry_sexp_release(hostkey->sexp);
- unlockGcrypt();
- FREE(hostkey);
+void
+freePrivateKey (struct PrivateKey *hostkey)
+{
+ lockGcrypt ();
+ gcry_sexp_release (hostkey->sexp);
+ unlockGcrypt ();
+ FREE (hostkey);
}
-static int key_from_sexp( gcry_mpi_t *array,
- gcry_sexp_t sexp,
- const char *topname,
- const char *elems ) {
+static int
+key_from_sexp (gcry_mpi_t * array,
+ gcry_sexp_t sexp, const char *topname, const char *elems)
+{
gcry_sexp_t list, l2;
const char *s;
int i, idx;
- lockGcrypt();
- list = gcry_sexp_find_token( sexp, topname, 0 );
- if( !list ) {
- unlockGcrypt();
- return 1;
- }
- l2 = gcry_sexp_cadr( list );
- gcry_sexp_release ( list );
+ lockGcrypt ();
+ list = gcry_sexp_find_token (sexp, topname, 0);
+ if (!list)
+ {
+ unlockGcrypt ();
+ return 1;
+ }
+ l2 = gcry_sexp_cadr (list);
+ gcry_sexp_release (list);
list = l2;
- if( !list ) {
- unlockGcrypt();
- return 2;
- }
+ if (!list)
+ {
+ unlockGcrypt ();
+ return 2;
+ }
idx = 0;
- for(s=elems; *s; s++, idx++ ) {
- l2 = gcry_sexp_find_token( list, s, 1 );
- if( !l2 ) {
- for(i=0; i<idx; i++) {
- gcry_free( array[i] );
- array[i] = NULL;
- }
- gcry_sexp_release ( list );
- unlockGcrypt();
- return 3; /* required parameter not found */
+ for (s = elems; *s; s++, idx++)
+ {
+ l2 = gcry_sexp_find_token (list, s, 1);
+ if (!l2)
+ {
+ for (i = 0; i < idx; i++)
+ {
+ gcry_free (array[i]);
+ array[i] = NULL;
+ }
+ gcry_sexp_release (list);
+ unlockGcrypt ();
+ return 3; /* required parameter not found */
+ }
+ array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
+ gcry_sexp_release (l2);
+ if (!array[idx])
+ {
+ for (i = 0; i < idx; i++)
+ {
+ gcry_free (array[i]);
+ array[i] = NULL;
+ }
+ gcry_sexp_release (list);
+ unlockGcrypt ();
+ return 4; /* required parameter is invalid */
+ }
}
- array[idx] = gcry_sexp_nth_mpi( l2, 1, GCRYMPI_FMT_USG );
- gcry_sexp_release ( l2 );
- if( !array[idx] ) {
- for(i=0; i<idx; i++) {
- gcry_free( array[i] );
- array[i] = NULL;
- }
- gcry_sexp_release ( list );
- unlockGcrypt();
- return 4; /* required parameter is invalid */
- }
- }
- gcry_sexp_release ( list );
- unlockGcrypt();
+ gcry_sexp_release (list);
+ unlockGcrypt ();
return 0;
}
@@ -205,56 +207,40 @@
* @param hostkey the hostkey to extract into the result.
* @param result where to write the result.
*/
-void getPublicKey(const struct PrivateKey * hostkey,
- PublicKey * result) {
+void
+getPublicKey (const struct PrivateKey *hostkey, PublicKey * result)
+{
gcry_mpi_t skey[2];
size_t size;
int rc;
- lockGcrypt();
- rc = key_from_sexp(skey,
- hostkey->sexp,
- "public-key",
- "ne");
+ lockGcrypt ();
+ rc = key_from_sexp (skey, hostkey->sexp, "public-key", "ne");
if (rc)
- rc = key_from_sexp(skey,
- hostkey->sexp,
- "private-key",
- "ne");
+ rc = key_from_sexp (skey, hostkey->sexp, "private-key", "ne");
if (rc)
- rc = key_from_sexp(skey,
- hostkey->sexp,
- "rsa",
- "ne");
+ rc = key_from_sexp (skey, hostkey->sexp, "rsa", "ne");
if (rc)
- DIE_GCRY(NULL, "key_from_sexp", rc);
+ DIE_GCRY (NULL, "key_from_sexp", rc);
- result->len = htons(sizeof(PublicKey) - sizeof(result->padding));
- result->sizen = htons(RSA_ENC_LEN);
+ result->len = htons (sizeof (PublicKey) - sizeof (result->padding));
+ result->sizen = htons (RSA_ENC_LEN);
result->padding = 0;
size = RSA_ENC_LEN;
- rc = gcry_mpi_print(GCRYMPI_FMT_USG,
- &result->key[0],
- size,
- &size,
- skey[0]);
+ rc = gcry_mpi_print (GCRYMPI_FMT_USG,
+ &result->key[0], size, &size, skey[0]);
if (rc)
- DIE_GCRY(NULL, "gcry_mpi_print", rc);
- adjust(&result->key[0], size, RSA_ENC_LEN);
+ DIE_GCRY (NULL, "gcry_mpi_print", rc);
+ adjust (&result->key[0], size, RSA_ENC_LEN);
size = RSA_KEY_LEN - RSA_ENC_LEN;
- rc = gcry_mpi_print(GCRYMPI_FMT_USG,
- &result->key[RSA_ENC_LEN],
- size,
- &size,
- skey[1]);
+ rc = gcry_mpi_print (GCRYMPI_FMT_USG,
+ &result->key[RSA_ENC_LEN], size, &size, skey[1]);
if (rc)
- DIE_GCRY(NULL, "gcry_mpi_print", rc);
- adjust(&result->key[RSA_ENC_LEN],
- size,
- RSA_KEY_LEN - RSA_ENC_LEN);
- gcry_mpi_release(skey[0]);
- gcry_mpi_release(skey[1]);
- unlockGcrypt();
+ DIE_GCRY (NULL, "gcry_mpi_print", rc);
+ adjust (&result->key[RSA_ENC_LEN], size, RSA_KEY_LEN - RSA_ENC_LEN);
+ gcry_mpi_release (skey[0]);
+ gcry_mpi_release (skey[1]);
+ unlockGcrypt ();
}
@@ -265,8 +251,9 @@
* key but rather an sexpression for the public key!
*/
static struct PrivateKey *
-public2PrivateKey(const PublicKey * publicKey) {
- struct PrivateKey * ret;
+public2PrivateKey (const PublicKey * publicKey)
+{
+ struct PrivateKey *ret;
gcry_sexp_t result;
gcry_mpi_t n;
gcry_mpi_t e;
@@ -274,49 +261,45 @@
size_t erroff;
int rc;
- if ( ( ntohs(publicKey->sizen) != RSA_ENC_LEN ) ||
- ( ntohs(publicKey->len) != sizeof(PublicKey) -
sizeof(publicKey->padding)) ) {
- GE_BREAK(NULL, 0);
- return NULL;
- }
+ if ((ntohs (publicKey->sizen) != RSA_ENC_LEN) ||
+ (ntohs (publicKey->len) !=
+ sizeof (PublicKey) - sizeof (publicKey->padding)))
+ {
+ GE_BREAK (NULL, 0);
+ return NULL;
+ }
size = RSA_ENC_LEN;
- lockGcrypt();
- rc = gcry_mpi_scan(&n,
- GCRYMPI_FMT_USG,
- &publicKey->key[0],
- size,
- &size);
- if (rc) {
- LOG_GCRY(NULL, LOG_ERROR, "gcry_mpi_scan", rc);
- unlockGcrypt();
- return NULL;
- }
+ lockGcrypt ();
+ rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_scan", rc);
+ unlockGcrypt ();
+ return NULL;
+ }
size = RSA_KEY_LEN - RSA_ENC_LEN;
- rc = gcry_mpi_scan(&e,
- GCRYMPI_FMT_USG,
- &publicKey->key[RSA_ENC_LEN],
- size,
- &size);
- if (rc) {
- LOG_GCRY(NULL, LOG_ERROR, "gcry_mpi_scan", rc);
- gcry_mpi_release(n);
- unlockGcrypt();
- return NULL;
- }
- rc = gcry_sexp_build(&result,
- &erroff,
- "(public-key(rsa(n %m)(e %m)))",
- n,
- e);
- gcry_mpi_release(n);
- gcry_mpi_release(e);
- if (rc) {
- LOG_GCRY(NULL, LOG_ERROR, "gcry_sexp_build", rc); /* erroff gives more
info */
- unlockGcrypt();
- return NULL;
- }
- unlockGcrypt();
- ret = MALLOC(sizeof(struct PrivateKey));
+ rc = gcry_mpi_scan (&e,
+ GCRYMPI_FMT_USG,
+ &publicKey->key[RSA_ENC_LEN], size, &size);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_scan", rc);
+ gcry_mpi_release (n);
+ unlockGcrypt ();
+ return NULL;
+ }
+ rc = gcry_sexp_build (&result,
+ &erroff, "(public-key(rsa(n %m)(e %m)))", n, e);
+ gcry_mpi_release (n);
+ gcry_mpi_release (e);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_sexp_build", rc); /* erroff
gives more info */
+ unlockGcrypt ();
+ return NULL;
+ }
+ unlockGcrypt ();
+ ret = MALLOC (sizeof (struct PrivateKey));
ret->sexp = result;
return ret;
}
@@ -328,131 +311,103 @@
* The first 4 bytes give the size of the array, as usual.
*/
PrivateKeyEncoded *
-encodePrivateKey(const struct PrivateKey * hostkey) {
- PrivateKeyEncoded * retval;
+encodePrivateKey (const struct PrivateKey * hostkey)
+{
+ PrivateKeyEncoded *retval;
gcry_mpi_t pkv[6];
- void * pbu[6];
+ void *pbu[6];
size_t sizes[6];
int rc;
int i;
int size;
- lockGcrypt();
+ lockGcrypt ();
#if EXTRA_CHECKS
- if (gcry_pk_testkey(hostkey->sexp)) {
- GE_BREAK(NULL, 0);
- unlockGcrypt();
- return NULL;
- }
+ if (gcry_pk_testkey (hostkey->sexp))
+ {
+ GE_BREAK (NULL, 0);
+ unlockGcrypt ();
+ return NULL;
+ }
#endif
- memset(pkv, 0, sizeof(gcry_mpi_t) * 6);
- rc = key_from_sexp(pkv,
- hostkey->sexp,
- "private-key",
- "nedpqu");
+ memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
+ rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
if (rc)
- rc = key_from_sexp(pkv,
- hostkey->sexp,
- "rsa",
- "nedpqu");
+ rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
if (rc)
- rc = key_from_sexp(pkv,
- hostkey->sexp,
- "private-key",
- "nedpq");
+ rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
if (rc)
- rc = key_from_sexp(pkv,
- hostkey->sexp,
- "rsa",
- "nedpq");
+ rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
if (rc)
- rc = key_from_sexp(pkv,
- hostkey->sexp,
- "private-key",
- "ned");
+ rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
if (rc)
- rc = key_from_sexp(pkv,
- hostkey->sexp,
- "rsa",
- "ned");
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "key_from_sexp",
- rc);
- unlockGcrypt();
- return NULL;
- }
- size = sizeof(PrivateKeyEncoded);
- for (i=0;i<6;i++) {
- if (pkv[i] != NULL) {
- rc = gcry_mpi_aprint(GCRYMPI_FMT_USG,
- (unsigned char**) &pbu[i],
- &sizes[i],
- pkv[i]);
- size += sizes[i];
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_aprint",
- rc);
- while (i>0)
- if (pbu[i] != NULL)
- free(pbu[--i]);
- for (i=0;i<6;i++)
- if (pkv[i] != NULL)
- gcry_mpi_release(pkv[i]);
- unlockGcrypt();
- return NULL;
- }
- } else {
- pbu[i] = NULL;
- sizes[i] = 0;
+ rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "key_from_sexp", rc);
+ unlockGcrypt ();
+ return NULL;
}
- }
- GE_ASSERT(NULL, size < 65536);
- retval = MALLOC(size);
- retval->len = htons(size);
+ size = sizeof (PrivateKeyEncoded);
+ for (i = 0; i < 6; i++)
+ {
+ if (pkv[i] != NULL)
+ {
+ rc = gcry_mpi_aprint (GCRYMPI_FMT_USG,
+ (unsigned char **) &pbu[i],
+ &sizes[i], pkv[i]);
+ size += sizes[i];
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_aprint", rc);
+ while (i > 0)
+ if (pbu[i] != NULL)
+ free (pbu[--i]);
+ for (i = 0; i < 6; i++)
+ if (pkv[i] != NULL)
+ gcry_mpi_release (pkv[i]);
+ unlockGcrypt ();
+ return NULL;
+ }
+ }
+ else
+ {
+ pbu[i] = NULL;
+ sizes[i] = 0;
+ }
+ }
+ GE_ASSERT (NULL, size < 65536);
+ retval = MALLOC (size);
+ retval->len = htons (size);
i = 0;
- retval->sizen = htons(sizes[0]);
- memcpy(&((char*)(&retval[1]))[i],
- pbu[0],
- sizes[0]);
+ retval->sizen = htons (sizes[0]);
+ memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
i += sizes[0];
- retval->sizee = htons(sizes[1]);
- memcpy(&((char*)(&retval[1]))[i],
- pbu[1],
- sizes[1]);
+ retval->sizee = htons (sizes[1]);
+ memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
i += sizes[1];
- retval->sized = htons(sizes[2]);
- memcpy(&((char*)(&retval[1]))[i],
- pbu[2],
- sizes[2]);
+ retval->sized = htons (sizes[2]);
+ memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
i += sizes[2];
/* swap p and q! */
- retval->sizep = htons(sizes[4]);
- memcpy(&((char*)(&retval[1]))[i],
- pbu[4],
- sizes[4]);
+ retval->sizep = htons (sizes[4]);
+ memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
i += sizes[4];
- retval->sizeq = htons(sizes[3]);
- memcpy(&((char*)(&retval[1]))[i],
- pbu[3],
- sizes[3]);
+ retval->sizeq = htons (sizes[3]);
+ memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
i += sizes[3];
- retval->sizedmp1 = htons(0);
- retval->sizedmq1 = htons(0);
- memcpy(&((char*)(&retval[1]))[i],
- pbu[5],
- sizes[5]);
- for (i=0;i<6;i++) {
- if (pkv[i] != NULL)
- gcry_mpi_release(pkv[i]);
- if (pbu[i] != NULL)
- free(pbu[i]);
- }
- unlockGcrypt();
+ retval->sizedmp1 = htons (0);
+ retval->sizedmq1 = htons (0);
+ memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
+ for (i = 0; i < 6; i++)
+ {
+ if (pkv[i] != NULL)
+ gcry_mpi_release (pkv[i]);
+ if (pbu[i] != NULL)
+ free (pbu[i]);
+ }
+ unlockGcrypt ();
return retval;
}
@@ -461,183 +416,169 @@
* to the "normal", internal format.
*/
struct PrivateKey *
-decodePrivateKey(const PrivateKeyEncoded * encoding) {
- struct PrivateKey * ret;
+decodePrivateKey (const PrivateKeyEncoded * encoding)
+{
+ struct PrivateKey *ret;
gcry_sexp_t res;
- gcry_mpi_t n,e,d,p,q,u;
+ gcry_mpi_t n, e, d, p, q, u;
int rc;
size_t size;
int pos;
pos = 0;
- size = ntohs(encoding->sizen);
- lockGcrypt();
- rc = gcry_mpi_scan(&n,
- GCRYMPI_FMT_USG,
- &((const unsigned char*)(&encoding[1]))[pos],
- size,
- &size);
- pos += ntohs(encoding->sizen);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_scan",
- rc);
- unlockGcrypt();
- return NULL;
- }
- size = ntohs(encoding->sizee);
- rc = gcry_mpi_scan(&e,
- GCRYMPI_FMT_USG,
- &((const unsigned char*)(&encoding[1]))[pos],
- size,
- &size);
- pos += ntohs(encoding->sizee);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_scan",
- rc);
- gcry_mpi_release(n);
- unlockGcrypt();
- return NULL;
- }
- size = ntohs(encoding->sized);
- rc = gcry_mpi_scan(&d,
- GCRYMPI_FMT_USG,
- &((const unsigned char*)(&encoding[1]))[pos],
- size,
- &size);
- pos += ntohs(encoding->sized);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_scan",
- rc);
- gcry_mpi_release(n);
- gcry_mpi_release(e);
- unlockGcrypt();
- return NULL;
- }
- /* swap p and q! */
- size = ntohs(encoding->sizep);
- if (size > 0) {
- rc = gcry_mpi_scan(&q,
- GCRYMPI_FMT_USG,
- &((const unsigned char*)(&encoding[1]))[pos],
- size,
- &size);
- pos += ntohs(encoding->sizep);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_scan",
- rc);
- gcry_mpi_release(n);
- gcry_mpi_release(e);
- gcry_mpi_release(d);
- unlockGcrypt();
+ size = ntohs (encoding->sizen);
+ lockGcrypt ();
+ rc = gcry_mpi_scan (&n,
+ GCRYMPI_FMT_USG,
+ &((const unsigned char *) (&encoding[1]))[pos],
+ size, &size);
+ pos += ntohs (encoding->sizen);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_scan", rc);
+ unlockGcrypt ();
return NULL;
}
- } else
- q = NULL;
- size = ntohs(encoding->sizeq);
- if (size > 0) {
- rc = gcry_mpi_scan(&p,
- GCRYMPI_FMT_USG,
- &((const unsigned char*)(&encoding[1]))[pos],
- size,
- &size);
- pos += ntohs(encoding->sizeq);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_scan",
- rc);
- gcry_mpi_release(n);
- gcry_mpi_release(e);
- gcry_mpi_release(d);
- if (q != NULL)
- gcry_mpi_release(q);
- unlockGcrypt();
+ size = ntohs (encoding->sizee);
+ rc = gcry_mpi_scan (&e,
+ GCRYMPI_FMT_USG,
+ &((const unsigned char *) (&encoding[1]))[pos],
+ size, &size);
+ pos += ntohs (encoding->sizee);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_scan", rc);
+ gcry_mpi_release (n);
+ unlockGcrypt ();
return NULL;
}
- } else
- p = NULL;
- pos += ntohs(encoding->sizedmp1);
- pos += ntohs(encoding->sizedmq1);
- size = ntohs(encoding->len) - sizeof(PrivateKeyEncoded) - pos;
- if (size > 0) {
- rc = gcry_mpi_scan(&u,
- GCRYMPI_FMT_USG,
- &((const unsigned char*)(&encoding[1]))[pos],
- size,
- &size);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_scan",
- rc);
- gcry_mpi_release(n);
- gcry_mpi_release(e);
- gcry_mpi_release(d);
- if (p != NULL)
- gcry_mpi_release(p);
- if (q != NULL)
- gcry_mpi_release(q);
- unlockGcrypt();
+ size = ntohs (encoding->sized);
+ rc = gcry_mpi_scan (&d,
+ GCRYMPI_FMT_USG,
+ &((const unsigned char *) (&encoding[1]))[pos],
+ size, &size);
+ pos += ntohs (encoding->sized);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_scan", rc);
+ gcry_mpi_release (n);
+ gcry_mpi_release (e);
+ unlockGcrypt ();
return NULL;
}
- } else
+ /* swap p and q! */
+ size = ntohs (encoding->sizep);
+ if (size > 0)
+ {
+ rc = gcry_mpi_scan (&q,
+ GCRYMPI_FMT_USG,
+ &((const unsigned char *) (&encoding[1]))[pos],
+ size, &size);
+ pos += ntohs (encoding->sizep);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_scan", rc);
+ gcry_mpi_release (n);
+ gcry_mpi_release (e);
+ gcry_mpi_release (d);
+ unlockGcrypt ();
+ return NULL;
+ }
+ }
+ else
+ q = NULL;
+ size = ntohs (encoding->sizeq);
+ if (size > 0)
+ {
+ rc = gcry_mpi_scan (&p,
+ GCRYMPI_FMT_USG,
+ &((const unsigned char *) (&encoding[1]))[pos],
+ size, &size);
+ pos += ntohs (encoding->sizeq);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_scan", rc);
+ gcry_mpi_release (n);
+ gcry_mpi_release (e);
+ gcry_mpi_release (d);
+ if (q != NULL)
+ gcry_mpi_release (q);
+ unlockGcrypt ();
+ return NULL;
+ }
+ }
+ else
+ p = NULL;
+ pos += ntohs (encoding->sizedmp1);
+ pos += ntohs (encoding->sizedmq1);
+ size = ntohs (encoding->len) - sizeof (PrivateKeyEncoded) - pos;
+ if (size > 0)
+ {
+ rc = gcry_mpi_scan (&u,
+ GCRYMPI_FMT_USG,
+ &((const unsigned char *) (&encoding[1]))[pos],
+ size, &size);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_scan", rc);
+ gcry_mpi_release (n);
+ gcry_mpi_release (e);
+ gcry_mpi_release (d);
+ if (p != NULL)
+ gcry_mpi_release (p);
+ if (q != NULL)
+ gcry_mpi_release (q);
+ unlockGcrypt ();
+ return NULL;
+ }
+ }
+ else
u = NULL;
- if ( (p != NULL) &&
- (q != NULL) &&
- (u != NULL) ) {
- rc = gcry_sexp_build(&res,
- &size, /* erroff */
- "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
- n, e, d, p, q, u);
- } else {
- if ( (p != NULL) &&
- (q != NULL) ) {
- rc = gcry_sexp_build(&res,
- &size, /* erroff */
- "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
- n, e, d, p, q);
- } else {
- rc = gcry_sexp_build(&res,
- &size, /* erroff */
- "(private-key(rsa(n %m)(e %m)(d %m)))",
- n, e, d);
+ if ((p != NULL) && (q != NULL) && (u != NULL))
+ {
+ rc = gcry_sexp_build (&res, &size, /* erroff */
+ "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u
%m)))",
+ n, e, d, p, q, u);
}
- }
- gcry_mpi_release(n);
- gcry_mpi_release(e);
- gcry_mpi_release(d);
+ else
+ {
+ if ((p != NULL) && (q != NULL))
+ {
+ rc = gcry_sexp_build (&res, &size, /* erroff */
+ "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q
%m)))",
+ n, e, d, p, q);
+ }
+ else
+ {
+ rc = gcry_sexp_build (&res, &size, /* erroff */
+ "(private-key(rsa(n %m)(e %m)(d %m)))",
+ n, e, d);
+ }
+ }
+ gcry_mpi_release (n);
+ gcry_mpi_release (e);
+ gcry_mpi_release (d);
if (p != NULL)
- gcry_mpi_release(p);
+ gcry_mpi_release (p);
if (q != NULL)
- gcry_mpi_release(q);
+ gcry_mpi_release (q);
if (u != NULL)
- gcry_mpi_release(u);
+ gcry_mpi_release (u);
if (rc)
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_sexp_build", rc);
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_sexp_build", rc);
#if EXTRA_CHECKS
- if (gcry_pk_testkey(res)) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_pk_testkey", rc);
- unlockGcrypt();
- return NULL;
- }
+ if (gcry_pk_testkey (res))
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_pk_testkey", rc);
+ unlockGcrypt ();
+ return NULL;
+ }
#endif
- ret = MALLOC(sizeof(struct PrivateKey));
+ ret = MALLOC (sizeof (struct PrivateKey));
ret->sexp = res;
- unlockGcrypt();
+ unlockGcrypt ();
return ret;
}
@@ -651,97 +592,75 @@
* @param target where to store the encrypted block
* @returns SYSERR on error, OK if ok
*/
-int encryptPrivateKey(const void * block,
- unsigned short size,
- const PublicKey * publicKey,
- RSAEncryptedData * target) {
+int
+encryptPrivateKey (const void *block,
+ unsigned short size,
+ const PublicKey * publicKey, RSAEncryptedData * target)
+{
gcry_sexp_t result;
gcry_sexp_t data;
- struct PrivateKey * pubkey;
+ struct PrivateKey *pubkey;
gcry_mpi_t val;
gcry_mpi_t rval;
size_t isize;
size_t erroff;
int rc;
- GE_ASSERT(NULL, size <= sizeof(HashCode512));
- pubkey = public2PrivateKey(publicKey);
+ GE_ASSERT (NULL, size <= sizeof (HashCode512));
+ pubkey = public2PrivateKey (publicKey);
isize = size;
- lockGcrypt();
- rc = gcry_mpi_scan(&val,
- GCRYMPI_FMT_USG,
- block,
- isize,
- &isize);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_scan", rc);
- freePrivateKey(pubkey);
- unlockGcrypt();
- return SYSERR;
- }
- rc = gcry_sexp_build(&data,
- &erroff,
- "(data (flags pkcs1)(value %m))",
- val);
- gcry_mpi_release(val);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_sexp_build",
- rc); /* more info in erroff */
- freePrivateKey(pubkey);
- unlockGcrypt();
- return SYSERR;
- }
+ lockGcrypt ();
+ rc = gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_scan", rc);
+ freePrivateKey (pubkey);
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ rc = gcry_sexp_build (&data,
+ &erroff, "(data (flags pkcs1)(value %m))", val);
+ gcry_mpi_release (val);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_sexp_build", rc); /* more info
in erroff */
+ freePrivateKey (pubkey);
+ unlockGcrypt ();
+ return SYSERR;
+ }
- rc = gcry_pk_encrypt(&result, data, pubkey->sexp);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_pk_encrypt",
- rc);
- gcry_sexp_release(data);
- freePrivateKey(pubkey);
- unlockGcrypt();
- return SYSERR;
- }
- gcry_sexp_release(data);
- freePrivateKey(pubkey);
+ rc = gcry_pk_encrypt (&result, data, pubkey->sexp);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_pk_encrypt", rc);
+ gcry_sexp_release (data);
+ freePrivateKey (pubkey);
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ gcry_sexp_release (data);
+ freePrivateKey (pubkey);
- rc = key_from_sexp(&rval,
- result,
- "rsa",
- "a");
- gcry_sexp_release(result);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "key_from_sexp",
- rc);
- unlockGcrypt();
- return SYSERR;
- }
- isize = sizeof(RSAEncryptedData);
- rc = gcry_mpi_print(GCRYMPI_FMT_USG,
- (unsigned char*)target,
- isize,
- &isize,
- rval);
- gcry_mpi_release(rval);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_print",
- rc);
- unlockGcrypt();
- return SYSERR;
- }
- adjust(&target->encoding[0],
- isize,
- sizeof(RSAEncryptedData));
- unlockGcrypt();
+ rc = key_from_sexp (&rval, result, "rsa", "a");
+ gcry_sexp_release (result);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "key_from_sexp", rc);
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ isize = sizeof (RSAEncryptedData);
+ rc = gcry_mpi_print (GCRYMPI_FMT_USG,
+ (unsigned char *) target, isize, &isize, rval);
+ gcry_mpi_release (rval);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_print", rc);
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ adjust (&target->encoding[0], isize, sizeof (RSAEncryptedData));
+ unlockGcrypt ();
return OK;
}
@@ -755,108 +674,83 @@
* the decrypted block is bigger, an error is returned
* @returns the size of the decrypted block, -1 on error
*/
-int decryptPrivateKey(const struct PrivateKey * hostkey,
- const RSAEncryptedData * block,
- void * result,
- unsigned short max) {
+int
+decryptPrivateKey (const struct PrivateKey *hostkey,
+ const RSAEncryptedData * block,
+ void *result, unsigned short max)
+{
gcry_sexp_t resultsexp;
gcry_sexp_t data;
size_t erroff;
size_t size;
gcry_mpi_t val;
int rc;
- unsigned char * endp;
- unsigned char * tmp;
+ unsigned char *endp;
+ unsigned char *tmp;
- lockGcrypt();
+ lockGcrypt ();
#if EXTRA_CHECKS
- rc = gcry_pk_testkey(hostkey->sexp);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_pk_testkey",
- rc);
- unlockGcrypt();
- return -1;
- }
+ rc = gcry_pk_testkey (hostkey->sexp);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_pk_testkey", rc);
+ unlockGcrypt ();
+ return -1;
+ }
#endif
- size = sizeof(RSAEncryptedData);
- rc = gcry_mpi_scan(&val,
- GCRYMPI_FMT_USG,
- &block->encoding[0],
- size,
- &size);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_scan",
- rc);
- unlockGcrypt();
- return SYSERR;
- }
- rc = gcry_sexp_build(&data,
- &erroff,
- "(enc-val(flags)(rsa(a %m)))",
- val);
- gcry_mpi_release(val);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_sexp_build",
- rc); /* more info in erroff */
- unlockGcrypt();
- return SYSERR;
- }
- rc = gcry_pk_decrypt(&resultsexp,
- data,
- hostkey->sexp);
- gcry_sexp_release(data);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_pk_decrypt",
- rc);
- unlockGcrypt();
- return SYSERR;
- }
+ size = sizeof (RSAEncryptedData);
+ rc = gcry_mpi_scan (&val,
+ GCRYMPI_FMT_USG, &block->encoding[0], size, &size);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_scan", rc);
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ rc = gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))", val);
+ gcry_mpi_release (val);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_sexp_build", rc); /* more info
in erroff */
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ rc = gcry_pk_decrypt (&resultsexp, data, hostkey->sexp);
+ gcry_sexp_release (data);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_pk_decrypt", rc);
+ unlockGcrypt ();
+ return SYSERR;
+ }
/* resultsexp has format "(value %m)" */
- val = gcry_sexp_nth_mpi(resultsexp, 1, GCRYMPI_FMT_USG);
- gcry_sexp_release(resultsexp);
- if (val == NULL) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_sexp_nth_mpi",
- rc);
- unlockGcrypt();
- return SYSERR;
- }
- tmp = MALLOC(max + HOSTKEY_LEN/8);
- size = max+HOSTKEY_LEN/8;
- rc = gcry_mpi_print(GCRYMPI_FMT_USG,
- tmp,
- size,
- &size,
- val);
- gcry_mpi_release(val);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_print",
- rc);
- FREE(tmp);
- unlockGcrypt();
- return SYSERR;
- }
+ val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG);
+ gcry_sexp_release (resultsexp);
+ if (val == NULL)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_sexp_nth_mpi", rc);
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ tmp = MALLOC (max + HOSTKEY_LEN / 8);
+ size = max + HOSTKEY_LEN / 8;
+ rc = gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val);
+ gcry_mpi_release (val);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_print", rc);
+ FREE (tmp);
+ unlockGcrypt ();
+ return SYSERR;
+ }
endp = tmp;
endp += (size - max);
size = max;
- memcpy(result,
- endp,
- size);
- FREE(tmp);
- unlockGcrypt();
+ memcpy (result, endp, size);
+ FREE (tmp);
+ unlockGcrypt ();
return size;
}
@@ -869,85 +763,66 @@
* @param sig where to write the signature
* @return SYSERR on error, OK on success
*/
-int sign(const struct PrivateKey * hostkey,
- unsigned short size,
- const void * block,
- Signature * sig) {
+int
+sign (const struct PrivateKey *hostkey,
+ unsigned short size, const void *block, Signature * sig)
+{
gcry_sexp_t result;
gcry_sexp_t data;
size_t ssize;
gcry_mpi_t rval;
HashCode512 hc;
- char * buff;
+ char *buff;
int bufSize;
int rc;
- hash(block, size, &hc);
+ hash (block, size, &hc);
#define FORMATSTRING
"(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
- bufSize = strlen(FORMATSTRING) + 1;
- buff = MALLOC(bufSize);
- memcpy(buff,
- FORMATSTRING,
- bufSize);
- memcpy(&buff[bufSize -
strlen("0123456789012345678901234567890123456789012345678901234567890123))") -
1],
- &hc,
- sizeof(HashCode512));
- lockGcrypt();
- rc = gcry_sexp_new(&data,
- buff,
- bufSize,
- 0);
- FREE(buff);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_sexp_new",
- rc);
- unlockGcrypt();
- return SYSERR;
- }
- rc = gcry_pk_sign(&result, data, hostkey->sexp);
- gcry_sexp_release(data);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_pk_sign",
- rc);
- unlockGcrypt();
- return SYSERR;
- }
- rc = key_from_sexp(&rval,
- result,
- "rsa",
- "s");
- gcry_sexp_release(result);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "key_from_sexp",
- rc);
- unlockGcrypt();
- return SYSERR;
- }
- ssize = sizeof(Signature);
- rc = gcry_mpi_print(GCRYMPI_FMT_USG,
- (unsigned char*)sig,
- ssize,
- &ssize,
- rval);
- gcry_mpi_release(rval);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_print",
- rc);
- unlockGcrypt();
- return SYSERR;
- }
- adjust(&sig->sig[0],
- ssize,
- sizeof(Signature));
- unlockGcrypt();
+ bufSize = strlen (FORMATSTRING) + 1;
+ buff = MALLOC (bufSize);
+ memcpy (buff, FORMATSTRING, bufSize);
+ memcpy (&buff
+ [bufSize -
+ strlen
+
("0123456789012345678901234567890123456789012345678901234567890123))")
+ - 1], &hc, sizeof (HashCode512));
+ lockGcrypt ();
+ rc = gcry_sexp_new (&data, buff, bufSize, 0);
+ FREE (buff);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_sexp_new", rc);
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ rc = gcry_pk_sign (&result, data, hostkey->sexp);
+ gcry_sexp_release (data);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_pk_sign", rc);
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ rc = key_from_sexp (&rval, result, "rsa", "s");
+ gcry_sexp_release (result);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "key_from_sexp", rc);
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ ssize = sizeof (Signature);
+ rc = gcry_mpi_print (GCRYMPI_FMT_USG,
+ (unsigned char *) sig, ssize, &ssize, rval);
+ gcry_mpi_release (rval);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_print", rc);
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ adjust (&sig->sig[0], ssize, sizeof (Signature));
+ unlockGcrypt ();
return OK;
}
@@ -960,88 +835,76 @@
* @param publicKey public key of the signer
* @returns OK if ok, SYSERR if invalid
*/
-int verifySig(const void * block,
- unsigned short len,
- const Signature * sig,
- const PublicKey * publicKey) {
+int
+verifySig (const void *block,
+ unsigned short len,
+ const Signature * sig, const PublicKey * publicKey)
+{
gcry_sexp_t data;
gcry_sexp_t sigdata;
size_t size;
gcry_mpi_t val;
- struct PrivateKey * hostkey;
+ struct PrivateKey *hostkey;
HashCode512 hc;
- char * buff;
+ char *buff;
int bufSize;
size_t erroff;
int rc;
- size = sizeof(Signature);
- lockGcrypt();
- rc = gcry_mpi_scan(&val,
- GCRYMPI_FMT_USG,
- (const unsigned char*)sig,
- size,
- &size);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_mpi_scan",
- rc);
- unlockGcrypt();
- return SYSERR;
- }
- rc = gcry_sexp_build(&sigdata,
- &erroff,
- "(sig-val(rsa(s %m)))",
- val);
- gcry_mpi_release(val);
- if (rc) {
- LOG_GCRY(NULL,
- LOG_ERROR,
- "gcry_sexp_build",
- rc);
- unlockGcrypt();
- return SYSERR;
- }
- hash(block, len, &hc);
- bufSize = strlen(FORMATSTRING) + 1;
- buff = MALLOC(bufSize);
- memcpy(buff,
- FORMATSTRING,
- bufSize);
- memcpy(&buff[strlen(FORMATSTRING) -
-
strlen("0123456789012345678901234567890123456789012345678901234567890123))")],
- &hc,
- sizeof(HashCode512));
- rc = gcry_sexp_new(&data,
- buff,
- bufSize,
- 0);
- FREE(buff);
- hostkey = public2PrivateKey(publicKey);
- if (hostkey == NULL) {
- gcry_sexp_release(data);
- gcry_sexp_release(sigdata);
- return SYSERR;
- }
- rc = gcry_pk_verify(sigdata,
- data,
- hostkey->sexp);
- freePrivateKey(hostkey);
- gcry_sexp_release(data);
- gcry_sexp_release(sigdata);
- if (rc) {
- GE_LOG(NULL,
- GE_WARNING | GE_USER | GE_BULK | GE_DEVELOPER,
- _("RSA signature verification failed at %s:%d: %s\n"),
- __FILE__, __LINE__,
- gcry_strerror(rc));
- unlockGcrypt();
- return SYSERR;
- } else {
- unlockGcrypt();
- return OK;
- }
+ size = sizeof (Signature);
+ lockGcrypt ();
+ rc = gcry_mpi_scan (&val,
+ GCRYMPI_FMT_USG,
+ (const unsigned char *) sig, size, &size);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_mpi_scan", rc);
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ rc = gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))", val);
+ gcry_mpi_release (val);
+ if (rc)
+ {
+ LOG_GCRY (NULL, LOG_ERROR, "gcry_sexp_build", rc);
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ hash (block, len, &hc);
+ bufSize = strlen (FORMATSTRING) + 1;
+ buff = MALLOC (bufSize);
+ memcpy (buff, FORMATSTRING, bufSize);
+ memcpy (&buff[strlen (FORMATSTRING) -
+ strlen
+
("0123456789012345678901234567890123456789012345678901234567890123))")],
+ &hc, sizeof (HashCode512));
+ rc = gcry_sexp_new (&data, buff, bufSize, 0);
+ FREE (buff);
+ hostkey = public2PrivateKey (publicKey);
+ if (hostkey == NULL)
+ {
+ gcry_sexp_release (data);
+ gcry_sexp_release (sigdata);
+ return SYSERR;
+ }
+ rc = gcry_pk_verify (sigdata, data, hostkey->sexp);
+ freePrivateKey (hostkey);
+ gcry_sexp_release (data);
+ gcry_sexp_release (sigdata);
+ if (rc)
+ {
+ GE_LOG (NULL,
+ GE_WARNING | GE_USER | GE_BULK | GE_DEVELOPER,
+ _("RSA signature verification failed at %s:%d: %s\n"),
+ __FILE__, __LINE__, gcry_strerror (rc));
+ unlockGcrypt ();
+ return SYSERR;
+ }
+ else
+ {
+ unlockGcrypt ();
+ return OK;
+ }
}
Modified: GNUnet/src/util/crypto/hostkeytest.c
===================================================================
--- GNUnet/src/util/crypto/hostkeytest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/crypto/hostkeytest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -34,8 +34,10 @@
#define PERF NO
-static int testEncryptDecrypt() {
- struct PrivateKey * hostkey;
+static int
+testEncryptDecrypt ()
+{
+ struct PrivateKey *hostkey;
PublicKey pkey;
RSAEncryptedData target;
char result[MAX_TESTVAL];
@@ -43,48 +45,42 @@
TIME_T start;
int ok;
- fprintf(stderr, "W");
- hostkey = makePrivateKey();
- getPublicKey(hostkey, &pkey);
+ fprintf (stderr, "W");
+ hostkey = makePrivateKey ();
+ getPublicKey (hostkey, &pkey);
ok = 0;
- TIME(&start);
- for (i=0;i<ITER;i++) {
- fprintf(stderr, ".");
- if (SYSERR == encryptPrivateKey(TESTSTRING,
- strlen(TESTSTRING)+1,
- &pkey,
- &target)) {
- fprintf(stderr,
- "encryptPrivateKey returned SYSERR\n");
- ok++;
- continue;
- }
- if (-1 == decryptPrivateKey(hostkey,
- &target,
- result,
- strlen(TESTSTRING)+1)) {
- fprintf(stderr,
- "decryptPrivateKey returned SYSERR\n");
- ok++;
- continue;
+ TIME (&start);
+ for (i = 0; i < ITER; i++)
+ {
+ fprintf (stderr, ".");
+ if (SYSERR == encryptPrivateKey (TESTSTRING,
+ strlen (TESTSTRING) + 1,
+ &pkey, &target))
+ {
+ fprintf (stderr, "encryptPrivateKey returned SYSERR\n");
+ ok++;
+ continue;
+ }
+ if (-1 == decryptPrivateKey (hostkey,
+ &target, result, strlen (TESTSTRING) + 1))
+ {
+ fprintf (stderr, "decryptPrivateKey returned SYSERR\n");
+ ok++;
+ continue;
+ }
+ if (strncmp (TESTSTRING, result, strlen (TESTSTRING)) != 0)
+ {
+ printf ("%s != %.*s - testEncryptDecrypt failed!\n",
+ TESTSTRING, MAX_TESTVAL, result);
+ ok++;
+ continue;
+ }
}
- if (strncmp(TESTSTRING, result,
- strlen(TESTSTRING)) != 0) {
- printf("%s != %.*s - testEncryptDecrypt failed!\n",
- TESTSTRING,
- MAX_TESTVAL,
- result);
- ok++;
- continue;
- }
- }
- printf("%d RSA encrypt/decrypt operations %ds (%d failures)\n",
- ITER,
- (int) (TIME(NULL)-start),
- ok);
- freePrivateKey(hostkey);
+ printf ("%d RSA encrypt/decrypt operations %ds (%d failures)\n",
+ ITER, (int) (TIME (NULL) - start), ok);
+ freePrivateKey (hostkey);
if (ok == 0)
return OK;
else
@@ -92,45 +88,47 @@
}
#if PERF
-static int testEncryptPerformance() {
- struct PrivateKey * hostkey;
+static int
+testEncryptPerformance ()
+{
+ struct PrivateKey *hostkey;
PublicKey pkey;
RSAEncryptedData target;
int i;
cron_t start;
int ok;
- fprintf(stderr, "W");
- hostkey = makePrivateKey();
- getPublicKey(hostkey, &pkey);
+ fprintf (stderr, "W");
+ hostkey = makePrivateKey ();
+ getPublicKey (hostkey, &pkey);
ok = 0;
- start = get_time();
- for (i=0;i<ITER;i++) {
- fprintf(stderr, ".");
- if (SYSERR == encryptPrivateKey(TESTSTRING,
- strlen(TESTSTRING)+1,
- &pkey,
- &target)) {
- fprintf(stderr,
- "encryptPrivateKey returned SYSERR\n");
- ok++;
- continue;
+ start = get_time ();
+ for (i = 0; i < ITER; i++)
+ {
+ fprintf (stderr, ".");
+ if (SYSERR == encryptPrivateKey (TESTSTRING,
+ strlen (TESTSTRING) + 1,
+ &pkey, &target))
+ {
+ fprintf (stderr, "encryptPrivateKey returned SYSERR\n");
+ ok++;
+ continue;
+ }
}
- }
- printf("%d RSA encrypt operations %llu ms (%d failures)\n",
- ITER,
- get_time() - start,
- ok);
- freePrivateKey(hostkey);
+ printf ("%d RSA encrypt operations %llu ms (%d failures)\n",
+ ITER, get_time () - start, ok);
+ freePrivateKey (hostkey);
if (ok != 0)
return SYSERR;
return OK;
}
#endif
-static int testEncryptDecryptSK() {
- struct PrivateKey * hostkey;
+static int
+testEncryptDecryptSK ()
+{
+ struct PrivateKey *hostkey;
PublicKey pkey;
RSAEncryptedData target;
SESSIONKEY insk;
@@ -139,126 +137,117 @@
TIME_T start;
int ok;
- fprintf(stderr, "W");
- hostkey = makePrivateKey();
- getPublicKey(hostkey, &pkey);
+ fprintf (stderr, "W");
+ hostkey = makePrivateKey ();
+ getPublicKey (hostkey, &pkey);
ok = 0;
- TIME(&start);
- for (i=0;i<ITER;i++) {
- fprintf(stderr, ".");
- makeSessionkey(&insk);
- if (SYSERR == encryptPrivateKey(&insk,
- sizeof(SESSIONKEY),
- &pkey,
- &target)) {
- fprintf(stderr,
- "encryptPrivateKey returned SYSERR\n");
- ok++;
- continue;
+ TIME (&start);
+ for (i = 0; i < ITER; i++)
+ {
+ fprintf (stderr, ".");
+ makeSessionkey (&insk);
+ if (SYSERR == encryptPrivateKey (&insk,
+ sizeof (SESSIONKEY), &pkey, &target))
+ {
+ fprintf (stderr, "encryptPrivateKey returned SYSERR\n");
+ ok++;
+ continue;
+ }
+ if (-1 == decryptPrivateKey (hostkey,
+ &target, &outsk, sizeof (SESSIONKEY)))
+ {
+ fprintf (stderr, "decryptPrivateKey returned SYSERR\n");
+ ok++;
+ continue;
+ }
+ if (0 != memcmp (&insk, &outsk, sizeof (SESSIONKEY)))
+ {
+ printf ("testEncryptDecryptSK failed!\n");
+ ok++;
+ continue;
+ }
}
- if (-1 == decryptPrivateKey(hostkey,
- &target,
- &outsk,
- sizeof(SESSIONKEY))) {
- fprintf(stderr,
- "decryptPrivateKey returned SYSERR\n");
- ok++;
- continue;
- }
- if (0 != memcmp(&insk,
- &outsk,
- sizeof(SESSIONKEY))) {
- printf("testEncryptDecryptSK failed!\n");
- ok++;
- continue;
- }
- }
- printf("%d RSA encrypt/decrypt SK operations %ds (%d failures)\n",
- ITER,
- (int) (TIME(NULL)-start),
- ok);
- freePrivateKey(hostkey);
+ printf ("%d RSA encrypt/decrypt SK operations %ds (%d failures)\n",
+ ITER, (int) (TIME (NULL) - start), ok);
+ freePrivateKey (hostkey);
if (ok != 0)
return SYSERR;
return OK;
}
-static int testSignVerify() {
- struct PrivateKey * hostkey;
+static int
+testSignVerify ()
+{
+ struct PrivateKey *hostkey;
Signature sig;
PublicKey pkey;
int i;
TIME_T start;
int ok = OK;
- fprintf(stderr, "W");
- hostkey = makePrivateKey();
- getPublicKey(hostkey, &pkey);
- TIME(&start);
- for (i=0;i<ITER;i++) {
- fprintf(stderr, ".");
- if (SYSERR == sign(hostkey,
- strlen(TESTSTRING),
- TESTSTRING,
- &sig)) {
- fprintf(stderr,
- "sign returned SYSERR\n");
- ok = SYSERR;
- continue;
+ fprintf (stderr, "W");
+ hostkey = makePrivateKey ();
+ getPublicKey (hostkey, &pkey);
+ TIME (&start);
+ for (i = 0; i < ITER; i++)
+ {
+ fprintf (stderr, ".");
+ if (SYSERR == sign (hostkey, strlen (TESTSTRING), TESTSTRING, &sig))
+ {
+ fprintf (stderr, "sign returned SYSERR\n");
+ ok = SYSERR;
+ continue;
+ }
+ if (SYSERR == verifySig (TESTSTRING, strlen (TESTSTRING), &sig, &pkey))
+ {
+ printf ("testSignVerify failed!\n");
+ ok = SYSERR;
+ continue;
+ }
}
- if (SYSERR == verifySig(TESTSTRING,
- strlen(TESTSTRING),
- &sig,
- &pkey)) {
- printf("testSignVerify failed!\n");
- ok = SYSERR;
- continue;
- }
- }
- printf("%d RSA sign/verify operations %ds\n",
- ITER,
- (int) (TIME(NULL)-start));
- freePrivateKey(hostkey);
+ printf ("%d RSA sign/verify operations %ds\n",
+ ITER, (int) (TIME (NULL) - start));
+ freePrivateKey (hostkey);
return ok;
}
#if PERF
-static int testSignPerformance() {
- struct PrivateKey * hostkey;
+static int
+testSignPerformance ()
+{
+ struct PrivateKey *hostkey;
Signature sig;
PublicKey pkey;
int i;
cron_t start;
int ok = OK;
- fprintf(stderr, "W");
- hostkey = makePrivateKey();
- getPublicKey(hostkey, &pkey);
- start = get_time();
- for (i=0;i<ITER;i++) {
- fprintf(stderr, ".");
- if (SYSERR == sign(hostkey,
- strlen(TESTSTRING),
- TESTSTRING,
- &sig)) {
- fprintf(stderr,
- "sign returned SYSERR\n");
- ok = SYSERR;
- continue;
+ fprintf (stderr, "W");
+ hostkey = makePrivateKey ();
+ getPublicKey (hostkey, &pkey);
+ start = get_time ();
+ for (i = 0; i < ITER; i++)
+ {
+ fprintf (stderr, ".");
+ if (SYSERR == sign (hostkey, strlen (TESTSTRING), TESTSTRING, &sig))
+ {
+ fprintf (stderr, "sign returned SYSERR\n");
+ ok = SYSERR;
+ continue;
+ }
}
- }
- printf("%d RSA sign operations %llu ms\n",
- ITER,
- get_time() - start);
- freePrivateKey(hostkey);
+ printf ("%d RSA sign operations %llu ms\n", ITER, get_time () - start);
+ freePrivateKey (hostkey);
return ok;
}
#endif
-static int testPrivateKeyEncoding() {
- struct PrivateKey * hostkey;
- PrivateKeyEncoded * encoding;
+static int
+testPrivateKeyEncoding ()
+{
+ struct PrivateKey *hostkey;
+ PrivateKeyEncoded *encoding;
PublicKey pkey;
RSAEncryptedData target;
char result[MAX_TESTVAL];
@@ -266,80 +255,78 @@
TIME_T start;
int ok = OK;
- fprintf(stderr, "W");
- hostkey = makePrivateKey();
+ fprintf (stderr, "W");
+ hostkey = makePrivateKey ();
- TIME(&start);
- for (i=0;i<ITER;i++) {
- fprintf(stderr, ".");
- getPublicKey(hostkey, &pkey);
- if (SYSERR == encryptPrivateKey(TESTSTRING,
- strlen(TESTSTRING)+1,
- &pkey,
- &target)) {
- fprintf(stderr,
- "encryptPrivateKey returned SYSERR\n");
- ok = SYSERR;
- continue;
+ TIME (&start);
+ for (i = 0; i < ITER; i++)
+ {
+ fprintf (stderr, ".");
+ getPublicKey (hostkey, &pkey);
+ if (SYSERR == encryptPrivateKey (TESTSTRING,
+ strlen (TESTSTRING) + 1,
+ &pkey, &target))
+ {
+ fprintf (stderr, "encryptPrivateKey returned SYSERR\n");
+ ok = SYSERR;
+ continue;
+ }
+ encoding = encodePrivateKey (hostkey);
+ freePrivateKey (hostkey);
+ if (encoding == NULL)
+ {
+ fprintf (stderr, "encodePrivateKey returned NULL\n");
+ ok = SYSERR;
+ continue;
+ }
+ hostkey = decodePrivateKey (encoding);
+ FREE (encoding);
+ if (SYSERR == decryptPrivateKey (hostkey,
+ &target,
+ result, strlen (TESTSTRING) + 1))
+ {
+ fprintf (stderr, "decryptPrivateKey returned SYSERR\n");
+ ok = SYSERR;
+ continue;
+ }
+ if (strncmp (TESTSTRING, result, strlen (TESTSTRING)) != 0)
+ {
+ printf ("%s != %.*s - testEncryptDecrypt failed!\n",
+ TESTSTRING, (int) strlen (TESTSTRING), result);
+ ok = SYSERR;
+ continue;
+ }
}
- encoding = encodePrivateKey(hostkey);
- freePrivateKey(hostkey);
- if (encoding == NULL) {
- fprintf(stderr,
- "encodePrivateKey returned NULL\n");
- ok = SYSERR;
- continue;
- }
- hostkey = decodePrivateKey(encoding);
- FREE(encoding);
- if (SYSERR == decryptPrivateKey(hostkey,
- &target,
- result,
- strlen(TESTSTRING)+1)) {
- fprintf(stderr,
- "decryptPrivateKey returned SYSERR\n");
- ok = SYSERR;
- continue;
- }
- if (strncmp(TESTSTRING, result,
- strlen(TESTSTRING)) != 0) {
- printf("%s != %.*s - testEncryptDecrypt failed!\n",
- TESTSTRING,
- (int) strlen(TESTSTRING),
- result);
- ok = SYSERR;
- continue;
- }
- }
- freePrivateKey(hostkey);
- printf("%d RSA encrypt/encode/decode/decrypt operations %ds\n",
- ITER,
- (int) (TIME(NULL)-start));
+ freePrivateKey (hostkey);
+ printf ("%d RSA encrypt/encode/decode/decrypt operations %ds\n",
+ ITER, (int) (TIME (NULL) - start));
return ok;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
#if PERF
- if (OK != testEncryptPerformance())
- failureCount++;
- if (OK != testSignPerformance())
- failureCount++;
+ if (OK != testEncryptPerformance ())
+ failureCount++;
+ if (OK != testSignPerformance ())
+ failureCount++;
#endif
- if (OK != testEncryptDecryptSK())
- failureCount++;
- if (OK != testEncryptDecrypt())
- failureCount++;
- if (OK != testSignVerify())
+ if (OK != testEncryptDecryptSK ())
failureCount++;
- if (OK != testPrivateKeyEncoding())
+ if (OK != testEncryptDecrypt ())
failureCount++;
+ if (OK != testSignVerify ())
+ failureCount++;
+ if (OK != testPrivateKeyEncoding ())
+ failureCount++;
- if (failureCount != 0) {
- printf("\n\n%d TESTS FAILED!\n\n",
- failureCount);
- return -1;
- }
+ if (failureCount != 0)
+ {
+ printf ("\n\n%d TESTS FAILED!\n\n", failureCount);
+ return -1;
+ }
return 0;
-} /* end of main*/
+} /* end of main */
Modified: GNUnet/src/util/crypto/kblockkey.c
===================================================================
--- GNUnet/src/util/crypto/kblockkey.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/crypto/kblockkey.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -37,116 +37,121 @@
#include "gnunet_util_crypto.h"
#include <gmp.h>
-typedef struct {
- mpz_t n; /* public modulus */
- mpz_t e; /* public exponent */
- mpz_t d; /* exponent */
- mpz_t p; /* prime p. */
- mpz_t q; /* prime q. */
- mpz_t u; /* inverse of p mod q. */
+typedef struct
+{
+ mpz_t n; /* public modulus */
+ mpz_t e; /* public exponent */
+ mpz_t d; /* exponent */
+ mpz_t p; /* prime p. */
+ mpz_t q; /* prime q. */
+ mpz_t u; /* inverse of p mod q. */
} KBlock_secret_key;
/* Note: 2 is not included because it can be tested more easily by
looking at bit 0. The last entry in this list is marked by a zero */
static unsigned short small_prime_numbers[] = {
- 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
- 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
- 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
- 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
- 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
- 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
- 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
- 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
- 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
- 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,
- 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
- 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
- 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,
- 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,
- 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
- 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,
- 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,
- 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,
- 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
- 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,
- 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,
- 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,
- 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
- 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
- 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,
- 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,
- 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,
- 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,
- 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
- 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
- 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,
- 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,
- 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,
- 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
- 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,
- 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,
- 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,
- 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,
- 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
- 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,
- 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,
- 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,
- 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,
- 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
- 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,
- 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,
- 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,
- 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,
- 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
- 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,
- 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,
- 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,
- 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,
- 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
- 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,
- 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,
- 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,
- 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,
- 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
- 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,
- 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,
- 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,
- 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,
- 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
- 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,
- 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,
- 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,
- 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,
- 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
- 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,
- 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,
- 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,
- 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,
- 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
- 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,
- 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,
- 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,
- 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,
- 4957, 4967, 4969, 4973, 4987, 4993, 4999,
- 0
+ 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
+ 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
+ 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
+ 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
+ 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
+ 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
+ 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
+ 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
+ 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
+ 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,
+ 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
+ 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
+ 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,
+ 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,
+ 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
+ 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,
+ 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,
+ 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,
+ 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
+ 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,
+ 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,
+ 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,
+ 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
+ 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
+ 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,
+ 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,
+ 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,
+ 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,
+ 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
+ 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
+ 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,
+ 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,
+ 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,
+ 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
+ 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,
+ 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,
+ 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,
+ 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,
+ 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
+ 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,
+ 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,
+ 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,
+ 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,
+ 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
+ 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,
+ 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,
+ 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,
+ 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,
+ 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
+ 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,
+ 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,
+ 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,
+ 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,
+ 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
+ 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,
+ 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,
+ 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,
+ 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,
+ 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
+ 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,
+ 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,
+ 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,
+ 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,
+ 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
+ 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,
+ 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,
+ 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,
+ 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,
+ 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
+ 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,
+ 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,
+ 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,
+ 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,
+ 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
+ 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,
+ 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,
+ 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,
+ 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,
+ 4957, 4967, 4969, 4973, 4987, 4993, 4999,
+ 0
};
#define DIM(v) (sizeof(v)/sizeof((v)[0]))
-static int no_of_small_prime_numbers = DIM(small_prime_numbers) - 1;
+static int no_of_small_prime_numbers = DIM (small_prime_numbers) - 1;
-static unsigned int get_nbits(mpz_t a) {
- return mpz_sizeinbase(a, 2);
+ static unsigned int
+ get_nbits (mpz_t a)
+{
+ return mpz_sizeinbase (a, 2);
}
/**
* Count the number of zerobits at the low end of A
*/
-static unsigned int get_trailing_zeros(mpz_t a) {
+static unsigned int
+get_trailing_zeros (mpz_t a)
+{
unsigned int count = 0;
- unsigned int nbits = get_nbits(a);
+ unsigned int nbits = get_nbits (a);
- while ( (mpz_tstbit(a, count)) && (count < nbits) )
+ while ((mpz_tstbit (a, count)) && (count < nbits))
count++;
return count;
}
@@ -154,47 +159,47 @@
/**
* Set bit N of A. and clear all bits above
*/
-static void set_highbit(mpz_t a,
- unsigned int n) {
+static void
+set_highbit (mpz_t a, unsigned int n)
+{
unsigned int nbits;
- nbits = get_nbits(a);
+ nbits = get_nbits (a);
while (nbits > n)
- mpz_clrbit(a, nbits--);
- mpz_setbit(a, n);
+ mpz_clrbit (a, nbits--);
+ mpz_setbit (a, n);
}
-static void mpz_randomize(mpz_t n,
- unsigned int nbits,
- HashCode512 * rnd) {
- HashCode512 * tmp;
+static void
+mpz_randomize (mpz_t n, unsigned int nbits, HashCode512 * rnd)
+{
+ HashCode512 *tmp;
int cnt;
int i;
- cnt = (nbits / sizeof(HashCode512) / 8) + 1;
- tmp = MALLOC(sizeof(HashCode512) * cnt);
+ cnt = (nbits / sizeof (HashCode512) / 8) + 1;
+ tmp = MALLOC (sizeof (HashCode512) * cnt);
tmp[0] = *rnd;
- for (i=0;i<cnt-1;i++) {
- hash(&tmp[i],
- sizeof(HashCode512),
- &tmp[i+1]);
- }
- *rnd = tmp[cnt-1];
- mpz_import(n, cnt * sizeof(HashCode512) / sizeof(unsigned int),
- 1, sizeof(unsigned int), 1, 0, tmp);
- FREE(tmp);
- i = get_nbits(n);
+ for (i = 0; i < cnt - 1; i++)
+ {
+ hash (&tmp[i], sizeof (HashCode512), &tmp[i + 1]);
+ }
+ *rnd = tmp[cnt - 1];
+ mpz_import (n, cnt * sizeof (HashCode512) / sizeof (unsigned int),
+ 1, sizeof (unsigned int), 1, 0, tmp);
+ FREE (tmp);
+ i = get_nbits (n);
while (i > nbits)
- mpz_clrbit(n, i--);
+ mpz_clrbit (n, i--);
}
/**
* Return true if n is probably a prime
*/
-static int is_prime (mpz_t n,
- int steps,
- HashCode512 * hc) {
+static int
+is_prime (mpz_t n, int steps, HashCode512 * hc)
+{
mpz_t x;
mpz_t y;
mpz_t z;
@@ -205,152 +210,164 @@
int rc = 0;
unsigned int nbits;
- mpz_init(x);
- mpz_init(y);
- mpz_init(z);
- mpz_init(nminus1);
- mpz_init_set_ui(a2, 2);
- nbits = get_nbits( n );
- mpz_sub_ui(nminus1, n, 1 );
+ mpz_init (x);
+ mpz_init (y);
+ mpz_init (z);
+ mpz_init (nminus1);
+ mpz_init_set_ui (a2, 2);
+ nbits = get_nbits (n);
+ mpz_sub_ui (nminus1, n, 1);
/* Find q and k, so that n = 1 + 2^k * q . */
- mpz_init_set(q, nminus1);
- k = get_trailing_zeros(q);
- mpz_tdiv_q_2exp(q, q, k);
+ mpz_init_set (q, nminus1);
+ k = get_trailing_zeros (q);
+ mpz_tdiv_q_2exp (q, q, k);
- for (i=0 ; i < steps; i++ ) {
- if( !i ) {
- mpz_set_ui( x, 2 );
- } else {
- mpz_randomize( x, nbits, hc );
+ for (i = 0; i < steps; i++)
+ {
+ if (!i)
+ {
+ mpz_set_ui (x, 2);
+ }
+ else
+ {
+ mpz_randomize (x, nbits, hc);
- /* Make sure that the number is smaller than the prime and
- keep the randomness of the high bit. */
- if (mpz_tstbit(x, nbits-2) ) {
- set_highbit(x, nbits-2); /* Clear all higher bits. */
- } else {
- set_highbit(x, nbits-2 );
- mpz_clrbit( x, nbits-2 );
- }
- GE_ASSERT(NULL,
- mpz_cmp( x, nminus1 ) < 0 && mpz_cmp_ui( x, 1 ) > 0 );
+ /* Make sure that the number is smaller than the prime and
+ keep the randomness of the high bit. */
+ if (mpz_tstbit (x, nbits - 2))
+ {
+ set_highbit (x, nbits - 2); /* Clear all higher bits. */
+ }
+ else
+ {
+ set_highbit (x, nbits - 2);
+ mpz_clrbit (x, nbits - 2);
+ }
+ GE_ASSERT (NULL, mpz_cmp (x, nminus1) < 0 && mpz_cmp_ui (x, 1) > 0);
+ }
+ mpz_powm (y, x, q, n);
+ if (mpz_cmp_ui (y, 1) && mpz_cmp (y, nminus1))
+ {
+ for (j = 1; j < k && mpz_cmp (y, nminus1); j++)
+ {
+ mpz_powm (y, y, a2, n);
+ if (!mpz_cmp_ui (y, 1))
+ goto leave; /* Not a prime. */
+ }
+ if (mpz_cmp (y, nminus1))
+ goto leave; /* Not a prime. */
+ }
}
- mpz_powm ( y, x, q, n);
- if ( mpz_cmp_ui(y, 1) && mpz_cmp( y, nminus1 ) ) {
- for ( j=1; j < k && mpz_cmp( y, nminus1 ); j++ ) {
- mpz_powm(y, y, a2, n);
- if( !mpz_cmp_ui( y, 1 ) )
- goto leave; /* Not a prime. */
- }
- if (mpz_cmp( y, nminus1 ) )
- goto leave; /* Not a prime. */
- }
- }
- rc = 1; /* May be a prime. */
+ rc = 1; /* May be a prime. */
- leave:
- mpz_clear( x );
- mpz_clear( y );
- mpz_clear( z );
- mpz_clear( nminus1 );
- mpz_clear( q );
- mpz_clear( a2 );
+leave:
+ mpz_clear (x);
+ mpz_clear (y);
+ mpz_clear (z);
+ mpz_clear (nminus1);
+ mpz_clear (q);
+ mpz_clear (a2);
return rc;
}
-static void gen_prime(mpz_t ptest,
- unsigned int nbits,
- HashCode512 * hc) {
+static void
+gen_prime (mpz_t ptest, unsigned int nbits, HashCode512 * hc)
+{
mpz_t prime, pminus1, val_2, val_3, result;
int i;
unsigned x, step;
int *mods;
mpz_t tmp;
- GE_ASSERT(NULL, nbits >= 16);
+ GE_ASSERT (NULL, nbits >= 16);
- mods = MALLOC(no_of_small_prime_numbers * sizeof(*mods));
+ mods = MALLOC (no_of_small_prime_numbers * sizeof (*mods));
/* Make nbits fit into mpz_t implementation. */
- mpz_init_set_ui(val_2, 2);
- mpz_init_set_ui(val_3, 3);
- mpz_init(prime);
- mpz_init(result);
- mpz_init(pminus1);
- mpz_init(ptest);
- while (1) {
- /* generate a random number */
- mpz_randomize( prime, nbits, hc );
- /* Set high order bit to 1, set low order bit to 1. If we are
- generating a secret prime we are most probably doing that
- for RSA, to make sure that the modulus does have the
- requested key size we set the 2 high order bits. */
- set_highbit (prime, nbits-1);
- mpz_setbit(prime, nbits-2);
- mpz_setbit(prime, 0);
+ mpz_init_set_ui (val_2, 2);
+ mpz_init_set_ui (val_3, 3);
+ mpz_init (prime);
+ mpz_init (result);
+ mpz_init (pminus1);
+ mpz_init (ptest);
+ while (1)
+ {
+ /* generate a random number */
+ mpz_randomize (prime, nbits, hc);
+ /* Set high order bit to 1, set low order bit to 1. If we are
+ generating a secret prime we are most probably doing that
+ for RSA, to make sure that the modulus does have the
+ requested key size we set the 2 high order bits. */
+ set_highbit (prime, nbits - 1);
+ mpz_setbit (prime, nbits - 2);
+ mpz_setbit (prime, 0);
- /* Calculate all remainders. */
- mpz_init(tmp);
- for (i=0; (x = small_prime_numbers[i]); i++ )
- mods[i] = mpz_fdiv_r_ui(tmp, prime, x);
- mpz_clear(tmp);
- /* Now try some primes starting with prime. */
- for (step=0; step < 20000; step += 2 ) {
- /* Check against all the small primes we have in mods. */
- for (i=0; (x = small_prime_numbers[i]); i++ ) {
- while ( mods[i] + step >= x )
- mods[i] -= x;
- if ( !(mods[i] + step) )
- break;
- }
- if (x)
- continue; /* Found a multiple of an already known prime. */
+ /* Calculate all remainders. */
+ mpz_init (tmp);
+ for (i = 0; (x = small_prime_numbers[i]); i++)
+ mods[i] = mpz_fdiv_r_ui (tmp, prime, x);
+ mpz_clear (tmp);
+ /* Now try some primes starting with prime. */
+ for (step = 0; step < 20000; step += 2)
+ {
+ /* Check against all the small primes we have in mods. */
+ for (i = 0; (x = small_prime_numbers[i]); i++)
+ {
+ while (mods[i] + step >= x)
+ mods[i] -= x;
+ if (!(mods[i] + step))
+ break;
+ }
+ if (x)
+ continue; /* Found a multiple of an already known prime.
*/
- mpz_add_ui( ptest, prime, step );
- if (! mpz_tstbit( ptest, nbits-2 ))
- break;
+ mpz_add_ui (ptest, prime, step);
+ if (!mpz_tstbit (ptest, nbits - 2))
+ break;
- /* Do a fast Fermat test now. */
- mpz_sub_ui( pminus1, ptest, 1);
- mpz_powm( result, val_2, pminus1, ptest );
- if ( ( !mpz_cmp_ui( result, 1 ) ) &&
- (is_prime(ptest, 5, hc) ) ) {
- /* Got it. */
- mpz_clear(val_2);
- mpz_clear(val_3);
- mpz_clear(result);
- mpz_clear(pminus1);
- mpz_clear(prime);
- FREE(mods);
- return;
- }
+ /* Do a fast Fermat test now. */
+ mpz_sub_ui (pminus1, ptest, 1);
+ mpz_powm (result, val_2, pminus1, ptest);
+ if ((!mpz_cmp_ui (result, 1)) && (is_prime (ptest, 5, hc)))
+ {
+ /* Got it. */
+ mpz_clear (val_2);
+ mpz_clear (val_3);
+ mpz_clear (result);
+ mpz_clear (pminus1);
+ mpz_clear (prime);
+ FREE (mods);
+ return;
+ }
+ }
}
- }
}
/**
* Find the greatest common divisor G of A and B.
* Return: 1 if this 1, 0 in all other cases
*/
-static int test_gcd(mpz_t g,
- mpz_t xa,
- mpz_t xb) {
+static int
+test_gcd (mpz_t g, mpz_t xa, mpz_t xb)
+{
mpz_t a, b;
- mpz_init_set(a, xa);
- mpz_init_set(b, xb);
+ mpz_init_set (a, xa);
+ mpz_init_set (b, xb);
/* TAOCP Vol II, 4.5.2, Algorithm A */
- while (mpz_cmp_ui( b, 0 ) ) {
- mpz_fdiv_r(g, a, b); /* g used as temorary variable */
- mpz_set(a,b);
- mpz_set(b,g);
- }
- mpz_set(g, a);
+ while (mpz_cmp_ui (b, 0))
+ {
+ mpz_fdiv_r (g, a, b); /* g used as temorary variable */
+ mpz_set (a, b);
+ mpz_set (b, g);
+ }
+ mpz_set (g, a);
- mpz_clear(a);
- mpz_clear(b);
- return (0 == mpz_cmp_ui(g, 1));
+ mpz_clear (a);
+ mpz_clear (b);
+ return (0 == mpz_cmp_ui (g, 1));
}
/**
@@ -359,64 +376,70 @@
* @param nbits the number of bits to use
* @param hc the HC to use for PRNG (modified!)
*/
-static void generate_kblock_key(KBlock_secret_key *sk,
- unsigned int nbits,
- HashCode512 * hc) {
+static void
+generate_kblock_key (KBlock_secret_key * sk,
+ unsigned int nbits, HashCode512 * hc)
+{
mpz_t t1, t2;
- mpz_t phi; /* helper: (p-1)(q-1) */
+ mpz_t phi; /* helper: (p-1)(q-1) */
mpz_t g;
mpz_t f;
/* make sure that nbits is even so that we generate p, q of equal size */
- if ( (nbits&1) )
+ if ((nbits & 1))
nbits++;
- mpz_init_set_ui(sk->e, 257);
- mpz_init(sk->n);
- mpz_init(sk->p);
- mpz_init(sk->q);
- mpz_init(sk->d);
- mpz_init(sk->u);
+ mpz_init_set_ui (sk->e, 257);
+ mpz_init (sk->n);
+ mpz_init (sk->p);
+ mpz_init (sk->q);
+ mpz_init (sk->d);
+ mpz_init (sk->u);
- mpz_init(t1);
- mpz_init(t2);
- mpz_init(phi);
- mpz_init(g);
- mpz_init(f);
+ mpz_init (t1);
+ mpz_init (t2);
+ mpz_init (phi);
+ mpz_init (g);
+ mpz_init (f);
- do {
- do {
- mpz_clear(sk->p);
- mpz_clear(sk->q);
- gen_prime(sk->p, nbits/2, hc);
- gen_prime(sk->q, nbits/2, hc);
+ do
+ {
+ do
+ {
+ mpz_clear (sk->p);
+ mpz_clear (sk->q);
+ gen_prime (sk->p, nbits / 2, hc);
+ gen_prime (sk->q, nbits / 2, hc);
- if (mpz_cmp (sk->p, sk->q) > 0 ) /* p shall be smaller than q (for calc
of u)*/
- mpz_swap(sk->p, sk->q);
- /* calculate the modulus */
- mpz_mul(sk->n, sk->p, sk->q );
- } while (get_nbits(sk->n) != nbits);
+ if (mpz_cmp (sk->p, sk->q) > 0) /* p shall be smaller than q
(for calc of u) */
+ mpz_swap (sk->p, sk->q);
+ /* calculate the modulus */
+ mpz_mul (sk->n, sk->p, sk->q);
+ }
+ while (get_nbits (sk->n) != nbits);
- /* calculate Euler totient: phi = (p-1)(q-1) */
- mpz_sub_ui(t1, sk->p, 1 );
- mpz_sub_ui(t2, sk->q, 1 );
- mpz_mul(phi, t1, t2 );
- mpz_gcd(g, t1, t2);
- mpz_fdiv_q(f, phi, g);
+ /* calculate Euler totient: phi = (p-1)(q-1) */
+ mpz_sub_ui (t1, sk->p, 1);
+ mpz_sub_ui (t2, sk->q, 1);
+ mpz_mul (phi, t1, t2);
+ mpz_gcd (g, t1, t2);
+ mpz_fdiv_q (f, phi, g);
- while (0 == test_gcd(t1, sk->e, phi)) { /* (while gcd is not 1) */
- mpz_add_ui (sk->e, sk->e, 2);
+ while (0 == test_gcd (t1, sk->e, phi))
+ { /* (while gcd is not 1) */
+ mpz_add_ui (sk->e, sk->e, 2);
+ }
+
+ /* calculate the secret key d = e^1 mod phi */
}
+ while ((0 == mpz_invert (sk->d, sk->e, f)) ||
+ (0 == mpz_invert (sk->u, sk->p, sk->q)));
- /* calculate the secret key d = e^1 mod phi */
- } while ( (0 == mpz_invert(sk->d, sk->e, f )) ||
- (0 == mpz_invert(sk->u, sk->p, sk->q )) );
-
- mpz_clear(t1);
- mpz_clear(t2);
- mpz_clear(phi);
- mpz_clear(f);
- mpz_clear(g);
+ mpz_clear (t1);
+ mpz_clear (t2);
+ mpz_clear (phi);
+ mpz_clear (f);
+ mpz_clear (g);
}
/**
@@ -424,143 +447,131 @@
* given HashCode as input to the PRNG.
*/
static PrivateKeyEncoded *
-makeKblockKeyInternal(const HashCode512 * hc) {
+makeKblockKeyInternal (const HashCode512 * hc)
+{
KBlock_secret_key sk;
HashCode512 hx;
- void * pbu[6];
- mpz_t * pkv[6];
+ void *pbu[6];
+ mpz_t *pkv[6];
size_t sizes[6];
- PrivateKeyEncoded * retval;
+ PrivateKeyEncoded *retval;
int i;
size_t size;
hx = *hc;
- generate_kblock_key(&sk,
- 1024, /* at least 10x as fast than 2048 bits
- -- we simply cannot afford 2048 bits
- even on modern hardware, and especially
- not since clearly a dictionary attack
- will still be much cheaper
- than breaking a 1024 bit RSA key.
- If an adversary can spend the time to
- break a 1024 bit RSA key just to forge
- a signature -- SO BE IT. [ CG, 6/2005 ] */
- &hx);
+ generate_kblock_key (&sk, 1024, /* at least 10x as fast than 2048 bits
+ -- we simply cannot afford 2048 bits
+ even on modern hardware, and
especially
+ not since clearly a dictionary
attack
+ will still be much cheaper
+ than breaking a 1024 bit RSA key.
+ If an adversary can spend the time
to
+ break a 1024 bit RSA key just to
forge
+ a signature -- SO BE IT. [ CG,
6/2005 ] */
+ &hx);
pkv[0] = &sk.n;
pkv[1] = &sk.e;
pkv[2] = &sk.d;
pkv[3] = &sk.p;
pkv[4] = &sk.q;
pkv[5] = &sk.u;
- size = sizeof(PrivateKeyEncoded);
- for (i=0;i<6;i++) {
- pbu[i] = mpz_export(NULL,
- &sizes[i],
- 1, /* most significant word first */
- 1, /* unit is bytes */
- 1, /* big endian */
- 0, /* nails */
- *pkv[i]);
- size += sizes[i];
- }
- GE_ASSERT(NULL, size < 65536);
- retval = MALLOC(size);
- retval->len = htons(size);
+ size = sizeof (PrivateKeyEncoded);
+ for (i = 0; i < 6; i++)
+ {
+ pbu[i] = mpz_export (NULL, &sizes[i], 1, /* most significant word first
*/
+ 1, /* unit is bytes */
+ 1, /* big endian */
+ 0, /* nails */
+ *pkv[i]);
+ size += sizes[i];
+ }
+ GE_ASSERT (NULL, size < 65536);
+ retval = MALLOC (size);
+ retval->len = htons (size);
i = 0;
- retval->sizen = htons(sizes[0]);
- memcpy(&((char*)&retval[1])[i],
- pbu[0],
- sizes[0]);
+ retval->sizen = htons (sizes[0]);
+ memcpy (&((char *) &retval[1])[i], pbu[0], sizes[0]);
i += sizes[0];
- retval->sizee = htons(sizes[1]);
- memcpy(&((char*)&retval[1])[i],
- pbu[1],
- sizes[1]);
+ retval->sizee = htons (sizes[1]);
+ memcpy (&((char *) &retval[1])[i], pbu[1], sizes[1]);
i += sizes[1];
- retval->sized = htons(sizes[2]);
- memcpy(&((char*)&retval[1])[i],
- pbu[2],
- sizes[2]);
+ retval->sized = htons (sizes[2]);
+ memcpy (&((char *) &retval[1])[i], pbu[2], sizes[2]);
i += sizes[2];
/* swap p and q! */
- retval->sizep = htons(sizes[4]);
- memcpy(&((char*)&retval[1])[i],
- pbu[4],
- sizes[4]);
+ retval->sizep = htons (sizes[4]);
+ memcpy (&((char *) &retval[1])[i], pbu[4], sizes[4]);
i += sizes[4];
- retval->sizeq = htons(sizes[3]);
- memcpy(&((char*)&retval[1])[i],
- pbu[3],
- sizes[3]);
+ retval->sizeq = htons (sizes[3]);
+ memcpy (&((char *) &retval[1])[i], pbu[3], sizes[3]);
i += sizes[3];
- retval->sizedmp1 = htons(0);
- retval->sizedmq1 = htons(0);
- memcpy(&((char*)&retval[1])[i],
- pbu[5],
- sizes[5]);
- for (i=0;i<6;i++) {
- mpz_clear(*pkv[i]);
- free(pbu[i]);
- }
+ retval->sizedmp1 = htons (0);
+ retval->sizedmq1 = htons (0);
+ memcpy (&((char *) &retval[1])[i], pbu[5], sizes[5]);
+ for (i = 0; i < 6; i++)
+ {
+ mpz_clear (*pkv[i]);
+ free (pbu[i]);
+ }
return retval;
}
-typedef struct {
+typedef struct
+{
HashCode512 hc;
- PrivateKeyEncoded * pke;
+ PrivateKeyEncoded *pke;
} KBlockKeyCacheLine;
-static KBlockKeyCacheLine ** cache;
+static KBlockKeyCacheLine **cache;
static unsigned int cacheSize;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
/**
* Deterministically (!) create a hostkey using only the
* given HashCode as input to the PRNG.
*/
-struct PrivateKey * makeKblockKey(const HashCode512 * hc) {
- struct PrivateKey * ret;
- KBlockKeyCacheLine * line;
+struct PrivateKey *
+makeKblockKey (const HashCode512 * hc)
+{
+ struct PrivateKey *ret;
+ KBlockKeyCacheLine *line;
int i;
- MUTEX_LOCK(lock);
- for (i=0;i<cacheSize;i++) {
- if (equalsHashCode512(hc,
- &cache[i]->hc)) {
- ret = decodePrivateKey(cache[i]->pke);
- MUTEX_UNLOCK(lock);
- return ret;
+ MUTEX_LOCK (lock);
+ for (i = 0; i < cacheSize; i++)
+ {
+ if (equalsHashCode512 (hc, &cache[i]->hc))
+ {
+ ret = decodePrivateKey (cache[i]->pke);
+ MUTEX_UNLOCK (lock);
+ return ret;
+ }
}
- }
- line
- = MALLOC(sizeof(KBlockKeyCacheLine));
+ line = MALLOC (sizeof (KBlockKeyCacheLine));
line->hc = *hc;
- line->pke
- = makeKblockKeyInternal(hc);
- GROW(cache,
- cacheSize,
- cacheSize+1);
- cache[cacheSize-1]
- = line;
- MUTEX_UNLOCK(lock);
- return decodePrivateKey(line->pke);
+ line->pke = makeKblockKeyInternal (hc);
+ GROW (cache, cacheSize, cacheSize + 1);
+ cache[cacheSize - 1] = line;
+ MUTEX_UNLOCK (lock);
+ return decodePrivateKey (line->pke);
}
-void __attribute__ ((constructor)) gnunet_crypto_kblock_ltdl_init(void) {
- lock = MUTEX_CREATE(NO);
+void __attribute__ ((constructor)) gnunet_crypto_kblock_ltdl_init (void)
+{
+ lock = MUTEX_CREATE (NO);
}
-void __attribute__ ((destructor)) gnunet_crypto_kblock_ltdl_fini(void) {
+void __attribute__ ((destructor)) gnunet_crypto_kblock_ltdl_fini (void)
+{
int i;
- for (i=0;i<cacheSize;i++) {
- FREE(cache[i]->pke);
- FREE(cache[i]);
- }
- GROW(cache,
- cacheSize,
- 0);
- MUTEX_DESTROY(lock);
+ for (i = 0; i < cacheSize; i++)
+ {
+ FREE (cache[i]->pke);
+ FREE (cache[i]);
+ }
+ GROW (cache, cacheSize, 0);
+ MUTEX_DESTROY (lock);
}
/* end of kblockkey.c */
Modified: GNUnet/src/util/crypto/kblockkey_test.c
===================================================================
--- GNUnet/src/util/crypto/kblockkey_test.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/crypto/kblockkey_test.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -34,51 +34,56 @@
#define ITER 10
-static int testMultiKey(const char * word) {
+static int
+testMultiKey (const char *word)
+{
HashCode512 in;
- struct PrivateKey * hostkey;
+ struct PrivateKey *hostkey;
PublicKey pkey;
PublicKey pkey1;
int i;
- fprintf(stderr,
- "Testing KBlock key uniqueness (%s) ",
- word);
- hash(word, strlen(word), &in);
- hostkey = makeKblockKey(&in);
- if (hostkey == NULL) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- getPublicKey(hostkey, &pkey);
- /*
- for (i=0;i<sizeof(PublicKey);i++)
- printf("%02x", ((unsigned char*) &pkey)[i]);
- printf("\n"); */
- freePrivateKey(hostkey);
- for (i=0;i<UNIQUE_ITER;i++) {
- fprintf(stderr, ".");
- hostkey = makeKblockKey(&in);
- if (hostkey == NULL) {
- GE_BREAK(NULL, 0);
- fprintf(stderr, " ERROR\n");
+ fprintf (stderr, "Testing KBlock key uniqueness (%s) ", word);
+ hash (word, strlen (word), &in);
+ hostkey = makeKblockKey (&in);
+ if (hostkey == NULL)
+ {
+ GE_BREAK (NULL, 0);
return SYSERR;
}
- getPublicKey(hostkey, &pkey1);
- freePrivateKey(hostkey);
- if (0 != memcmp(&pkey, &pkey1,
- sizeof(PublicKey))) {
- GE_BREAK(NULL, 0);
- fprintf(stderr, " ERROR\n");
- return SYSERR;
+ getPublicKey (hostkey, &pkey);
+ /*
+ for (i=0;i<sizeof(PublicKey);i++)
+ printf("%02x", ((unsigned char*) &pkey)[i]);
+ printf("\n"); */
+ freePrivateKey (hostkey);
+ for (i = 0; i < UNIQUE_ITER; i++)
+ {
+ fprintf (stderr, ".");
+ hostkey = makeKblockKey (&in);
+ if (hostkey == NULL)
+ {
+ GE_BREAK (NULL, 0);
+ fprintf (stderr, " ERROR\n");
+ return SYSERR;
+ }
+ getPublicKey (hostkey, &pkey1);
+ freePrivateKey (hostkey);
+ if (0 != memcmp (&pkey, &pkey1, sizeof (PublicKey)))
+ {
+ GE_BREAK (NULL, 0);
+ fprintf (stderr, " ERROR\n");
+ return SYSERR;
+ }
}
- }
- fprintf(stderr, " OK\n");
+ fprintf (stderr, " OK\n");
return OK;
}
-static int testEncryptDecrypt(struct PrivateKey * hostkey) {
+static int
+testEncryptDecrypt (struct PrivateKey *hostkey)
+{
PublicKey pkey;
RSAEncryptedData target;
char result[MAX_TESTVAL];
@@ -86,89 +91,83 @@
TIME_T start;
int ok;
- fprintf(stderr, "W");
- getPublicKey(hostkey, &pkey);
+ fprintf (stderr, "W");
+ getPublicKey (hostkey, &pkey);
ok = 0;
- TIME(&start);
- for (i=0;i<ITER;i++) {
- fprintf(stderr, ".");
- if (SYSERR == encryptPrivateKey(TESTSTRING,
- strlen(TESTSTRING)+1,
- &pkey,
- &target)) {
- fprintf(stderr,
- "encryptPrivateKey returned SYSERR\n");
- ok++;
- continue;
+ TIME (&start);
+ for (i = 0; i < ITER; i++)
+ {
+ fprintf (stderr, ".");
+ if (SYSERR == encryptPrivateKey (TESTSTRING,
+ strlen (TESTSTRING) + 1,
+ &pkey, &target))
+ {
+ fprintf (stderr, "encryptPrivateKey returned SYSERR\n");
+ ok++;
+ continue;
+ }
+ if (-1 == decryptPrivateKey (hostkey,
+ &target, result, strlen (TESTSTRING) + 1))
+ {
+ fprintf (stderr, "decryptPrivateKey returned SYSERR\n");
+ ok++;
+ continue;
+ }
+ if (strncmp (TESTSTRING, result, strlen (TESTSTRING)) != 0)
+ {
+ printf ("%s != %.*s - testEncryptDecrypt failed!\n",
+ TESTSTRING, MAX_TESTVAL, result);
+ ok++;
+ continue;
+ }
}
- if (-1 == decryptPrivateKey(hostkey,
- &target,
- result,
- strlen(TESTSTRING)+1)) {
- fprintf(stderr,
- "decryptPrivateKey returned SYSERR\n");
- ok++;
- continue;
- }
- if (strncmp(TESTSTRING, result,
- strlen(TESTSTRING)) != 0) {
- printf("%s != %.*s - testEncryptDecrypt failed!\n",
- TESTSTRING,
- MAX_TESTVAL,
- result);
- ok++;
- continue;
- }
- }
- printf("%d RSA encrypt/decrypt operations %ds (%d failures)\n",
- ITER,
- (int) (TIME(NULL)-start),
- ok);
+ printf ("%d RSA encrypt/decrypt operations %ds (%d failures)\n",
+ ITER, (int) (TIME (NULL) - start), ok);
if (ok == 0)
return OK;
else
return SYSERR;
}
-static int testSignVerify(struct PrivateKey * hostkey) {
+static int
+testSignVerify (struct PrivateKey *hostkey)
+{
Signature sig;
PublicKey pkey;
int i;
TIME_T start;
int ok = OK;
- fprintf(stderr, "W");
- getPublicKey(hostkey, &pkey);
- TIME(&start);
- for (i=0;i<ITER;i++) {
- fprintf(stderr, ".");
- if (SYSERR == sign(hostkey,
- strlen(TESTSTRING),
- TESTSTRING, &sig)) {
- fprintf(stderr,
- "sign returned SYSERR\n");
- ok = SYSERR;
- continue;
+ fprintf (stderr, "W");
+ getPublicKey (hostkey, &pkey);
+ TIME (&start);
+ for (i = 0; i < ITER; i++)
+ {
+ fprintf (stderr, ".");
+ if (SYSERR == sign (hostkey, strlen (TESTSTRING), TESTSTRING, &sig))
+ {
+ fprintf (stderr, "sign returned SYSERR\n");
+ ok = SYSERR;
+ continue;
+ }
+ if (SYSERR == verifySig (TESTSTRING, strlen (TESTSTRING), &sig, &pkey))
+ {
+ printf ("testSignVerify failed!\n");
+ ok = SYSERR;
+ continue;
+ }
}
- if (SYSERR == verifySig(TESTSTRING,
- strlen(TESTSTRING),
- &sig,
- &pkey)) {
- printf("testSignVerify failed!\n");
- ok = SYSERR;
- continue;
- }
- }
- printf("%d RSA sign/verify operations %ds\n",
- ITER,
- (int) (TIME(NULL)-start));
+ printf ("%d RSA sign/verify operations %ds\n",
+ ITER, (int) (TIME (NULL) - start));
return ok;
}
-static int testPrivateKeyEncoding(const struct PrivateKey * hostkey) {
- PrivateKeyEncoded * encoding;
- struct PrivateKey * hostkey2;
+static int
+testPrivateKeyEncoding (const struct PrivateKey *hostkey)
+{
+ PrivateKeyEncoded *encoding;
+ struct PrivateKey *hostkey2;
PublicKey pkey;
RSAEncryptedData target;
char result[MAX_TESTVAL];
@@ -176,85 +175,84 @@
TIME_T start;
int ok = OK;
- fprintf(stderr, "W");
+ fprintf (stderr, "W");
- TIME(&start);
- for (i=0;i<ITER;i++) {
- fprintf(stderr, ".");
- getPublicKey(hostkey, &pkey);
- if (SYSERR == encryptPrivateKey(TESTSTRING,
- strlen(TESTSTRING)+1,
- &pkey,
- &target)) {
- fprintf(stderr,
- "encryptPrivateKey returned SYSERR\n");
- ok = SYSERR;
- continue;
+ TIME (&start);
+ for (i = 0; i < ITER; i++)
+ {
+ fprintf (stderr, ".");
+ getPublicKey (hostkey, &pkey);
+ if (SYSERR == encryptPrivateKey (TESTSTRING,
+ strlen (TESTSTRING) + 1,
+ &pkey, &target))
+ {
+ fprintf (stderr, "encryptPrivateKey returned SYSERR\n");
+ ok = SYSERR;
+ continue;
+ }
+ encoding = encodePrivateKey (hostkey);
+ if (encoding == NULL)
+ {
+ fprintf (stderr, "encodePrivateKey returned NULL\n");
+ ok = SYSERR;
+ continue;
+ }
+ hostkey2 = decodePrivateKey (encoding);
+ FREE (encoding);
+ if (SYSERR == decryptPrivateKey (hostkey2,
+ &target,
+ result, strlen (TESTSTRING) + 1))
+ {
+ fprintf (stderr, "decryptPrivateKey returned SYSERR\n");
+ ok = SYSERR;
+ freePrivateKey (hostkey2);
+ continue;
+ }
+ freePrivateKey (hostkey2);
+ if (strncmp (TESTSTRING, result, strlen (TESTSTRING)) != 0)
+ {
+ printf ("%s != %.*s - testEncryptDecrypt failed!\n",
+ TESTSTRING, (int) strlen (TESTSTRING), result);
+ ok = SYSERR;
+ continue;
+ }
}
- encoding = encodePrivateKey(hostkey);
- if (encoding == NULL) {
- fprintf(stderr,
- "encodePrivateKey returned NULL\n");
- ok = SYSERR;
- continue;
- }
- hostkey2 = decodePrivateKey(encoding);
- FREE(encoding);
- if (SYSERR == decryptPrivateKey(hostkey2,
- &target,
- result,
- strlen(TESTSTRING)+1)) {
- fprintf(stderr,
- "decryptPrivateKey returned SYSERR\n");
- ok = SYSERR;
- freePrivateKey(hostkey2);
- continue;
- }
- freePrivateKey(hostkey2);
- if (strncmp(TESTSTRING, result,
- strlen(TESTSTRING)) != 0) {
- printf("%s != %.*s - testEncryptDecrypt failed!\n",
- TESTSTRING,
- (int) strlen(TESTSTRING),
- result);
- ok = SYSERR;
- continue;
- }
- }
- printf("%d RSA encrypt/encode/decode/decrypt operations %ds\n",
- ITER,
- (int) (TIME(NULL)-start));
+ printf ("%d RSA encrypt/encode/decode/decrypt operations %ds\n",
+ ITER, (int) (TIME (NULL) - start));
return ok;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
HashCode512 in;
- struct PrivateKey * hostkey;
+ struct PrivateKey *hostkey;
- makeRandomId(&in);
- hostkey = makeKblockKey(&in);
- if (hostkey == NULL) {
- printf("\nmakeKblockKey failed!\n");
- return 1;
- }
+ makeRandomId (&in);
+ hostkey = makeKblockKey (&in);
+ if (hostkey == NULL)
+ {
+ printf ("\nmakeKblockKey failed!\n");
+ return 1;
+ }
- if (OK != testMultiKey("foo"))
+ if (OK != testMultiKey ("foo"))
failureCount++;
- if (OK != testMultiKey("bar"))
+ if (OK != testMultiKey ("bar"))
failureCount++;
- if (OK != testEncryptDecrypt(hostkey))
+ if (OK != testEncryptDecrypt (hostkey))
failureCount++;
- if (OK != testSignVerify(hostkey))
+ if (OK != testSignVerify (hostkey))
failureCount++;
- if (OK != testPrivateKeyEncoding(hostkey))
+ if (OK != testPrivateKeyEncoding (hostkey))
failureCount++;
- freePrivateKey(hostkey);
+ freePrivateKey (hostkey);
- if (failureCount != 0) {
- printf("\n\n%d TESTS FAILED!\n\n",
- failureCount);
- return -1;
- }
+ if (failureCount != 0)
+ {
+ printf ("\n\n%d TESTS FAILED!\n\n", failureCount);
+ return -1;
+ }
return 0;
}
Modified: GNUnet/src/util/crypto/locking_gcrypt.c
===================================================================
--- GNUnet/src/util/crypto/locking_gcrypt.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/crypto/locking_gcrypt.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -37,57 +37,63 @@
#define USE_LOCK NO
#if USE_LOCK
-static struct MUTEX * gcrypt_shared_lock;
+static struct MUTEX *gcrypt_shared_lock;
#else
GCRY_THREAD_OPTION_PTHREAD_IMPL;
#endif
-void lockGcrypt() {
+void
+lockGcrypt ()
+{
#if USE_LOCK
- MUTEX_LOCK(gcrypt_shared_lock);
+ MUTEX_LOCK (gcrypt_shared_lock);
#endif
}
-void unlockGcrypt() {
+void
+unlockGcrypt ()
+{
#if USE_LOCK
- MUTEX_UNLOCK(gcrypt_shared_lock);
+ MUTEX_UNLOCK (gcrypt_shared_lock);
#endif
}
-static void dummy_logger(void * arg,
- int level,
- const char * format,
- va_list args) {
+static void
+dummy_logger (void *arg, int level, const char *format, va_list args)
+{
/* do nothing -- ignore libgcyrpt errors */
}
-void __attribute__ ((constructor)) gnunet_crypto_ltdl_init() {
+void __attribute__ ((constructor)) gnunet_crypto_ltdl_init ()
+{
#if USE_LOCK
- gcrypt_shared_lock = MUTEX_CREATE(YES);
+ gcrypt_shared_lock = MUTEX_CREATE (YES);
#else
gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
#endif
- gcry_control(GCRYCTL_DISABLE_SECMEM, 0);
- if (! gcry_check_version(GCRYPT_VERSION)) {
- fprintf(stderr,
- _("libgcrypt has not the expected version (version %s is required).\n"),
- GCRYPT_VERSION);
- abort();
- }
- srand((unsigned int)time(NULL));
- gcry_set_log_handler(&dummy_logger, NULL);
+ gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
+ if (!gcry_check_version (GCRYPT_VERSION))
+ {
+ fprintf (stderr,
+ _
+ ("libgcrypt has not the expected version (version %s is
required).\n"),
+ GCRYPT_VERSION);
+ abort ();
+ }
+ srand ((unsigned int) time (NULL));
+ gcry_set_log_handler (&dummy_logger, NULL);
#ifdef gcry_fast_random_poll
- lockGcrypt();
+ lockGcrypt ();
gcry_fast_random_poll ();
- unlockGcrypt();
+ unlockGcrypt ();
#endif
}
-void __attribute__ ((destructor)) gnunet_crypto_ltdl_fini() {
+void __attribute__ ((destructor)) gnunet_crypto_ltdl_fini ()
+{
#if USE_LOCK
- MUTEX_DESTROY(gcrypt_shared_lock);
+ MUTEX_DESTROY (gcrypt_shared_lock);
gcrypt_shared_lock = NULL;
#endif
}
-
Modified: GNUnet/src/util/crypto/locking_gcrypt.h
===================================================================
--- GNUnet/src/util/crypto/locking_gcrypt.h 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/crypto/locking_gcrypt.h 2007-07-10 08:36:37 UTC (rev
5295)
@@ -22,8 +22,8 @@
#ifndef LOCKING_GCRYPT_H
#define LOCKING_GCRYPT_H
-void lockGcrypt();
+void lockGcrypt ();
-void unlockGcrypt();
+void unlockGcrypt ();
#endif
Modified: GNUnet/src/util/crypto/random.c
===================================================================
--- GNUnet/src/util/crypto/random.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/crypto/random.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,26 +33,27 @@
/**
* @return a random value in the interval [0,i[.
*/
-unsigned int randomi(unsigned int i) {
+unsigned int
+randomi (unsigned int i)
+{
#ifdef gcry_fast_random_poll
static unsigned int invokeCount;
#endif
unsigned int ret;
- GE_ASSERT(NULL, i > 0);
- lockGcrypt();
+ GE_ASSERT (NULL, i > 0);
+ lockGcrypt ();
/* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
#ifdef gcry_fast_random_poll
- if ( (invokeCount++ % 256) == 0)
- gcry_fast_random_poll();
+ if ((invokeCount++ % 256) == 0)
+ gcry_fast_random_poll ();
#endif
- ret = rand(); /* in case gcry_randomize fails,
- we at least get a pseudo-
- random number this way */
- gcry_randomize((unsigned char*)&ret,
- sizeof(unsigned int),
- GCRY_STRONG_RANDOM);
- unlockGcrypt();
+ ret = rand (); /* in case gcry_randomize fails,
+ we at least get a pseudo-
+ random number this way */
+ gcry_randomize ((unsigned char *) &ret,
+ sizeof (unsigned int), GCRY_STRONG_RANDOM);
+ unlockGcrypt ();
return ret % i;
}
@@ -63,62 +64,70 @@
* @param n the size of the array
* @return the permutation array (allocated from heap)
*/
-int * permute(int mode, int n) {
- int * ret;
+int *
+permute (int mode, int n)
+{
+ int *ret;
int i;
int tmp;
unsigned int x;
unsigned int (*prng) (unsigned int u);
- GE_ASSERT(NULL, n > 0);
- ret = MALLOC(n * sizeof(int));
+ GE_ASSERT (NULL, n > 0);
+ ret = MALLOC (n * sizeof (int));
prng = (mode == STRONG) ? randomi : weak_randomi;
- for (i=0;i<n;i++)
+ for (i = 0; i < n; i++)
ret[i] = i;
- for (i=0;i<n;i++) {
- x = prng(n);
- tmp = ret[x];
- ret[x] = ret[i];
- ret[i] = tmp;
- }
+ for (i = 0; i < n; i++)
+ {
+ x = prng (n);
+ tmp = ret[x];
+ ret[x] = ret[i];
+ ret[i] = tmp;
+ }
return ret;
}
/**
* Random on unsigned 64-bit values.
*/
-unsigned long long randomi64(unsigned long long u) {
+unsigned long long
+randomi64 (unsigned long long u)
+{
unsigned long long ret;
- GE_ASSERT(NULL, u > 0);
- lockGcrypt();
- gcry_randomize((unsigned char *) &ret,
- sizeof(unsigned long long),
- GCRY_STRONG_RANDOM);
- unlockGcrypt();
+ GE_ASSERT (NULL, u > 0);
+ lockGcrypt ();
+ gcry_randomize ((unsigned char *) &ret,
+ sizeof (unsigned long long), GCRY_STRONG_RANDOM);
+ unlockGcrypt ();
return ret % u;
}
/**
* @return a cryptographically weak random value in the interval [0,i[.
*/
-unsigned int weak_randomi(unsigned int i) {
+unsigned int
+weak_randomi (unsigned int i)
+{
unsigned int ret;
- GE_ASSERT(NULL, i > 0);
- ret = i * ((double) RANDOM() / RAND_MAX);
+ GE_ASSERT (NULL, i > 0);
+ ret = i * ((double) RANDOM () / RAND_MAX);
if (ret >= i)
ret = i - 1;
return ret;
}
-unsigned long long weak_randomi64(unsigned long long u) {
+unsigned long long
+weak_randomi64 (unsigned long long u)
+{
unsigned long long ret;
- GE_ASSERT(NULL, u > 0);
- ret = u * ((double) RANDOM() / RAND_MAX);
+ GE_ASSERT (NULL, u > 0);
+ ret = u * ((double) RANDOM () / RAND_MAX);
if (ret >= u)
- ret = u-1;
+ ret = u - 1;
return ret;
}
Modified: GNUnet/src/util/crypto/symcipher_gcrypt.c
===================================================================
--- GNUnet/src/util/crypto/symcipher_gcrypt.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/crypto/symcipher_gcrypt.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -56,13 +56,13 @@
/**
* Create a new SessionKey (for AES-256).
*/
-void makeSessionkey(SESSIONKEY * key) {
- lockGcrypt();
- gcry_randomize(&key->key[0],
- SESSIONKEY_LEN,
- GCRY_STRONG_RANDOM);
- unlockGcrypt();
- key->crc32 = htonl(crc32N(key, SESSIONKEY_LEN));
+void
+makeSessionkey (SESSIONKEY * key)
+{
+ lockGcrypt ();
+ gcry_randomize (&key->key[0], SESSIONKEY_LEN, GCRY_STRONG_RANDOM);
+ unlockGcrypt ();
+ key->crc32 = htonl (crc32N (key, SESSIONKEY_LEN));
}
/**
@@ -76,74 +76,65 @@
* @param result the output parameter in which to store the encrypted result
* @returns the size of the encrypted block, -1 for errors
*/
-int encryptBlock(const void * block,
- unsigned short len,
- const SESSIONKEY * sessionkey,
- const INITVECTOR * iv,
- void * result) {
+int
+encryptBlock (const void *block,
+ unsigned short len,
+ const SESSIONKEY * sessionkey,
+ const INITVECTOR * iv, void *result)
+{
gcry_cipher_hd_t handle;
int rc;
- if (sessionkey->crc32 !=
- htonl(crc32N(sessionkey, SESSIONKEY_LEN))) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- lockGcrypt();
- rc = gcry_cipher_open(&handle,
- GCRY_CIPHER_AES256,
- GCRY_CIPHER_MODE_CFB,
- 0);
- if (rc) {
- LOG_GCRY(NULL,
- GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
- "gcry_cipher_open",
- rc);
- unlockGcrypt();
- return -1;
- }
- rc = gcry_cipher_setkey(handle,
- sessionkey,
- SESSIONKEY_LEN);
+ if (sessionkey->crc32 != htonl (crc32N (sessionkey, SESSIONKEY_LEN)))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ lockGcrypt ();
+ rc = gcry_cipher_open (&handle,
+ GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CFB, 0);
+ if (rc)
+ {
+ LOG_GCRY (NULL,
+ GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
+ "gcry_cipher_open", rc);
+ unlockGcrypt ();
+ return -1;
+ }
+ rc = gcry_cipher_setkey (handle, sessionkey, SESSIONKEY_LEN);
- if (rc && ((char)rc != GPG_ERR_WEAK_KEY)) {
- LOG_GCRY(NULL,
- GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
- "gcry_cipher_setkey",
- rc);
- gcry_cipher_close(handle);
- unlockGcrypt();
- return -1;
- }
- rc = gcry_cipher_setiv(handle,
- iv,
- sizeof(INITVECTOR));
- if (rc && ((char)rc != GPG_ERR_WEAK_KEY)) {
- LOG_GCRY(NULL,
- GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
- "gcry_cipher_setiv",
- rc);
- gcry_cipher_close(handle);
- unlockGcrypt();
- return -1;
- }
+ if (rc && ((char) rc != GPG_ERR_WEAK_KEY))
+ {
+ LOG_GCRY (NULL,
+ GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
+ "gcry_cipher_setkey", rc);
+ gcry_cipher_close (handle);
+ unlockGcrypt ();
+ return -1;
+ }
+ rc = gcry_cipher_setiv (handle, iv, sizeof (INITVECTOR));
+ if (rc && ((char) rc != GPG_ERR_WEAK_KEY))
+ {
+ LOG_GCRY (NULL,
+ GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
+ "gcry_cipher_setiv", rc);
+ gcry_cipher_close (handle);
+ unlockGcrypt ();
+ return -1;
+ }
- rc = gcry_cipher_encrypt(handle,
- result,
- len,
- block,
- len);
- if (rc) {
- LOG_GCRY(NULL,
- GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
- "gcry_cipher_encrypt",
- rc);
- gcry_cipher_close(handle);
- unlockGcrypt();
- return -1;
- }
- gcry_cipher_close(handle);
- unlockGcrypt();
+ rc = gcry_cipher_encrypt (handle, result, len, block, len);
+ if (rc)
+ {
+ LOG_GCRY (NULL,
+ GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
+ "gcry_cipher_encrypt", rc);
+ gcry_cipher_close (handle);
+ unlockGcrypt ();
+ return -1;
+ }
+ gcry_cipher_close (handle);
+ unlockGcrypt ();
return len;
}
@@ -157,74 +148,64 @@
* @param result address to store the result at
* @return -1 on failure, size of decrypted block on success
*/
-int decryptBlock(const SESSIONKEY * sessionkey,
- const void * block,
- unsigned short size,
- const INITVECTOR * iv,
- void * result) {
+int
+decryptBlock (const SESSIONKEY * sessionkey,
+ const void *block,
+ unsigned short size, const INITVECTOR * iv, void *result)
+{
gcry_cipher_hd_t handle;
int rc;
- if (sessionkey->crc32 !=
- htonl(crc32N(sessionkey, SESSIONKEY_LEN))) {
- GE_BREAK(NULL, 0);
- return SYSERR;
- }
- lockGcrypt();
- rc = gcry_cipher_open(&handle,
- GCRY_CIPHER_AES256,
- GCRY_CIPHER_MODE_CFB,
- 0);
- if (rc) {
- LOG_GCRY(NULL,
- GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
- "gcry_cipher_open",
- rc);
- unlockGcrypt();
- return -1;
- }
- rc = gcry_cipher_setkey(handle,
- sessionkey,
- SESSIONKEY_LEN);
+ if (sessionkey->crc32 != htonl (crc32N (sessionkey, SESSIONKEY_LEN)))
+ {
+ GE_BREAK (NULL, 0);
+ return SYSERR;
+ }
+ lockGcrypt ();
+ rc = gcry_cipher_open (&handle,
+ GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CFB, 0);
+ if (rc)
+ {
+ LOG_GCRY (NULL,
+ GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
+ "gcry_cipher_open", rc);
+ unlockGcrypt ();
+ return -1;
+ }
+ rc = gcry_cipher_setkey (handle, sessionkey, SESSIONKEY_LEN);
- if (rc && ((char)rc != GPG_ERR_WEAK_KEY)) {
- LOG_GCRY(NULL,
- GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
- "gcry_cipher_setkey",
- rc);
- gcry_cipher_close(handle);
- unlockGcrypt();
- return -1;
- }
- rc = gcry_cipher_setiv(handle,
- iv,
- sizeof(INITVECTOR));
+ if (rc && ((char) rc != GPG_ERR_WEAK_KEY))
+ {
+ LOG_GCRY (NULL,
+ GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
+ "gcry_cipher_setkey", rc);
+ gcry_cipher_close (handle);
+ unlockGcrypt ();
+ return -1;
+ }
+ rc = gcry_cipher_setiv (handle, iv, sizeof (INITVECTOR));
- if (rc && ((char)rc != GPG_ERR_WEAK_KEY)) {
- LOG_GCRY(NULL,
- GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
- "gcry_cipher_setiv",
- rc);
- gcry_cipher_close(handle);
- unlockGcrypt();
- return -1;
- }
- rc = gcry_cipher_decrypt(handle,
- result,
- size,
- block,
- size);
- if (rc) {
- LOG_GCRY(NULL,
- GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
- "gcry_cipher_decrypt",
- rc);
- gcry_cipher_close(handle);
- unlockGcrypt();
- return -1;
- }
- gcry_cipher_close(handle);
- unlockGcrypt();
+ if (rc && ((char) rc != GPG_ERR_WEAK_KEY))
+ {
+ LOG_GCRY (NULL,
+ GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
+ "gcry_cipher_setiv", rc);
+ gcry_cipher_close (handle);
+ unlockGcrypt ();
+ return -1;
+ }
+ rc = gcry_cipher_decrypt (handle, result, size, block, size);
+ if (rc)
+ {
+ LOG_GCRY (NULL,
+ GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
+ "gcry_cipher_decrypt", rc);
+ gcry_cipher_close (handle);
+ unlockGcrypt ();
+ return -1;
+ }
+ gcry_cipher_close (handle);
+ unlockGcrypt ();
return size;
}
Modified: GNUnet/src/util/crypto/symciphertest.c
===================================================================
--- GNUnet/src/util/crypto/symciphertest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/crypto/symciphertest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -31,123 +31,135 @@
#define TESTSTRING "Hello World!"
#define INITVALUE "InitializationVectorValue"
-static int testSymcipher() {
+static int
+testSymcipher ()
+{
SESSIONKEY key;
char result[100];
int size;
char res[100];
- makeSessionkey(&key);
- size = encryptBlock(TESTSTRING,
- strlen(TESTSTRING)+1,
- &key,
- (const INITVECTOR*) INITVALUE,
- result);
- if (size == -1) {
- printf("symciphertest failed: encryptBlock returned %d\n",
- size);
- return 1;
- }
- size = decryptBlock(&key,
- result,
- size,
- (const INITVECTOR*) INITVALUE,
- res);
- if (strlen(TESTSTRING)+1
- != size) {
- printf("symciphertest failed: decryptBlock returned %d\n",
- size);
- return 1;
- }
- if (0 != strcmp(res,TESTSTRING)) {
- printf("symciphertest failed: %s != %s\n",
- res, TESTSTRING);
- return 1;
- } else
+ makeSessionkey (&key);
+ size = encryptBlock (TESTSTRING,
+ strlen (TESTSTRING) + 1,
+ &key, (const INITVECTOR *) INITVALUE, result);
+ if (size == -1)
+ {
+ printf ("symciphertest failed: encryptBlock returned %d\n", size);
+ return 1;
+ }
+ size = decryptBlock (&key,
+ result, size, (const INITVECTOR *) INITVALUE, res);
+ if (strlen (TESTSTRING) + 1 != size)
+ {
+ printf ("symciphertest failed: decryptBlock returned %d\n", size);
+ return 1;
+ }
+ if (0 != strcmp (res, TESTSTRING))
+ {
+ printf ("symciphertest failed: %s != %s\n", res, TESTSTRING);
+ return 1;
+ }
+ else
return 0;
}
-int verifyCrypto() {
+int
+verifyCrypto ()
+{
SESSIONKEY key;
char result[SESSIONKEY_LEN];
- char * res;
+ char *res;
int ret;
- unsigned char plain[] = {29, 128, 192, 253, 74, 171, 38, 187, 84, 219, 76,
76, 209, 118, 33, 249, 172, 124, 96, 9, 157, 110, 8, 215, 200, 63, 69, 230,
157, 104, 247, 164};
- unsigned char raw_key[] = {106, 74, 209, 88, 145, 55, 189, 135, 125, 180,
225, 108, 183, 54, 25, 169, 129, 188, 131, 75, 227, 245, 105, 10, 225, 15, 115,
159, 148, 184, 34, 191};
- unsigned char encrresult[] = {167, 102, 230, 233, 127, 195, 176, 107, 17,
91, 199, 127, 96, 113, 75, 195, 245, 217, 61, 236, 159, 165, 103, 121, 203, 99,
202, 41, 23, 222, 25, 102, 1 };
+ unsigned char plain[] =
+ { 29, 128, 192, 253, 74, 171, 38, 187, 84, 219, 76, 76, 209, 118, 33, 249,
+ 172, 124, 96, 9, 157, 110, 8, 215, 200, 63, 69, 230, 157, 104, 247, 164
+ };
+ unsigned char raw_key[] =
+ { 106, 74, 209, 88, 145, 55, 189, 135, 125, 180, 225, 108, 183, 54, 25,
+ 169, 129, 188, 131, 75, 227, 245, 105, 10, 225, 15, 115, 159, 148, 184,
+ 34, 191
+ };
+ unsigned char encrresult[] =
+ { 167, 102, 230, 233, 127, 195, 176, 107, 17, 91, 199, 127, 96, 113, 75,
+ 195, 245, 217, 61, 236, 159, 165, 103, 121, 203, 99, 202, 41, 23, 222, 25,
+ 102, 1
+ };
res = NULL;
ret = 0;
- memcpy(key.key, raw_key, SESSIONKEY_LEN);
- key.crc32 = htonl(crc32N(&key, SESSIONKEY_LEN));
+ memcpy (key.key, raw_key, SESSIONKEY_LEN);
+ key.crc32 = htonl (crc32N (&key, SESSIONKEY_LEN));
- if (ntohl(key.crc32) != (unsigned int) 38125195LL) {
- printf("Static key has different CRC: %u - %u\n",
- ntohl(key.crc32),
- key.crc32);
+ if (ntohl (key.crc32) != (unsigned int) 38125195LL)
+ {
+ printf ("Static key has different CRC: %u - %u\n",
+ ntohl (key.crc32), key.crc32);
- ret = 1;
- goto error;
- }
+ ret = 1;
+ goto error;
+ }
if (SESSIONKEY_LEN !=
- encryptBlock(plain,
- SESSIONKEY_LEN,
- &key,
- (const INITVECTOR*) "testtesttesttest",
- result)) {
- printf("Wrong return value from encrypt block.\n");
- ret = 1;
- goto error;
- }
+ encryptBlock (plain,
+ SESSIONKEY_LEN,
+ &key, (const INITVECTOR *) "testtesttesttest", result))
+ {
+ printf ("Wrong return value from encrypt block.\n");
+ ret = 1;
+ goto error;
+ }
- if (memcmp(encrresult,
- result,
- SESSIONKEY_LEN) != 0) {
- printf("Encrypted result wrong.\n");
- ret = 1;
- goto error;
- }
+ if (memcmp (encrresult, result, SESSIONKEY_LEN) != 0)
+ {
+ printf ("Encrypted result wrong.\n");
+ ret = 1;
+ goto error;
+ }
- res = MALLOC(SESSIONKEY_LEN);
+ res = MALLOC (SESSIONKEY_LEN);
if (SESSIONKEY_LEN !=
- decryptBlock(&key,
- result,
- SESSIONKEY_LEN,
- (const INITVECTOR*) "testtesttesttest",
- res)) {
- printf("Wrong return value from decrypt block.\n");
- ret = 1;
- goto error;
- }
+ decryptBlock (&key,
+ result,
+ SESSIONKEY_LEN,
+ (const INITVECTOR *) "testtesttesttest", res))
+ {
+ printf ("Wrong return value from decrypt block.\n");
+ ret = 1;
+ goto error;
+ }
- if (memcmp(res, plain, SESSIONKEY_LEN) != 0) {
- printf("Decrypted result does not match input.\n");
+ if (memcmp (res, plain, SESSIONKEY_LEN) != 0)
+ {
+ printf ("Decrypted result does not match input.\n");
- ret = 1;
- }
+ ret = 1;
+ }
error:
- FREENONNULL(res);
+ FREENONNULL (res);
return ret;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
- GE_ASSERT(NULL, strlen(INITVALUE) > sizeof(INITVECTOR));
- failureCount += testSymcipher();
- failureCount += verifyCrypto();
+ GE_ASSERT (NULL, strlen (INITVALUE) > sizeof (INITVECTOR));
+ failureCount += testSymcipher ();
+ failureCount += verifyCrypto ();
- if (failureCount != 0) {
- printf("%d TESTS FAILED!\n",failureCount);
- return -1;
- }
+ if (failureCount != 0)
+ {
+ printf ("%d TESTS FAILED!\n", failureCount);
+ return -1;
+ }
return 0;
}
Modified: GNUnet/src/util/crypto/weakkeytest.c
===================================================================
--- GNUnet/src/util/crypto/weakkeytest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/crypto/weakkeytest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -35,90 +35,92 @@
#define GENERATE_WEAK_KEYS NO
#define WEAK_KEY_TESTSTRING "I hate weak keys."
-static void printWeakKey(SESSIONKEY* key) {
+static void
+printWeakKey (SESSIONKEY * key)
+{
int i;
- for (i = 0; i < SESSIONKEY_LEN; i++) {
- printf("%x ",
- (int)(key->key[i]));
- }
+ for (i = 0; i < SESSIONKEY_LEN; i++)
+ {
+ printf ("%x ", (int) (key->key[i]));
+ }
}
-static int testWeakKey() {
+static int
+testWeakKey ()
+{
char result[100];
char res[100];
int size;
SESSIONKEY weak_key;
INITVECTOR INITVALUE;
- memset(&INITVALUE, 42, sizeof(INITVECTOR));
+ memset (&INITVALUE, 42, sizeof (INITVECTOR));
/* sorry, this is not a weak key -- I don't have
any at the moment! */
- weak_key.key[0]= (char)(0x4c);
- weak_key.key[1]= (char)(0x31);
- weak_key.key[2]= (char)(0xc6);
- weak_key.key[3]= (char)(0x2b);
- weak_key.key[4]= (char)(0xc1);
- weak_key.key[5]= (char)(0x5f);
- weak_key.key[6]= (char)(0x4d);
- weak_key.key[7]= (char)(0x1f);
- weak_key.key[8]= (char)(0x31);
- weak_key.key[9]= (char)(0xaa);
- weak_key.key[10]= (char)(0x12);
- weak_key.key[11]= (char)(0x2e);
- weak_key.key[12]= (char)(0xb7);
- weak_key.key[13]= (char)(0x82);
- weak_key.key[14]= (char)(0xc0);
- weak_key.key[15]= (char)(0xb6);
- weak_key.key[16]= (char)(0x4d);
- weak_key.key[17]= (char)(0x1f);
- weak_key.key[18]= (char)(0x31);
- weak_key.key[19]= (char)(0xaa);
- weak_key.key[20]= (char)(0x4c);
- weak_key.key[21]= (char)(0x31);
- weak_key.key[22]= (char)(0xc6);
- weak_key.key[23]= (char)(0x2b);
- weak_key.key[24]= (char)(0xc1);
- weak_key.key[25]= (char)(0x5f);
- weak_key.key[26]= (char)(0x4d);
- weak_key.key[27]= (char)(0x1f);
- weak_key.key[28]= (char)(0x31);
- weak_key.key[29]= (char)(0xaa);
- weak_key.key[30]= (char)(0xaa);
- weak_key.key[31]= (char)(0xaa);
+ weak_key.key[0] = (char) (0x4c);
+ weak_key.key[1] = (char) (0x31);
+ weak_key.key[2] = (char) (0xc6);
+ weak_key.key[3] = (char) (0x2b);
+ weak_key.key[4] = (char) (0xc1);
+ weak_key.key[5] = (char) (0x5f);
+ weak_key.key[6] = (char) (0x4d);
+ weak_key.key[7] = (char) (0x1f);
+ weak_key.key[8] = (char) (0x31);
+ weak_key.key[9] = (char) (0xaa);
+ weak_key.key[10] = (char) (0x12);
+ weak_key.key[11] = (char) (0x2e);
+ weak_key.key[12] = (char) (0xb7);
+ weak_key.key[13] = (char) (0x82);
+ weak_key.key[14] = (char) (0xc0);
+ weak_key.key[15] = (char) (0xb6);
+ weak_key.key[16] = (char) (0x4d);
+ weak_key.key[17] = (char) (0x1f);
+ weak_key.key[18] = (char) (0x31);
+ weak_key.key[19] = (char) (0xaa);
+ weak_key.key[20] = (char) (0x4c);
+ weak_key.key[21] = (char) (0x31);
+ weak_key.key[22] = (char) (0xc6);
+ weak_key.key[23] = (char) (0x2b);
+ weak_key.key[24] = (char) (0xc1);
+ weak_key.key[25] = (char) (0x5f);
+ weak_key.key[26] = (char) (0x4d);
+ weak_key.key[27] = (char) (0x1f);
+ weak_key.key[28] = (char) (0x31);
+ weak_key.key[29] = (char) (0xaa);
+ weak_key.key[30] = (char) (0xaa);
+ weak_key.key[31] = (char) (0xaa);
/* memset(&weak_key, 0, 32); */
- weak_key.crc32 = htonl(crc32N(&weak_key,
- SESSIONKEY_LEN));
+ weak_key.crc32 = htonl (crc32N (&weak_key, SESSIONKEY_LEN));
- size = encryptBlock(WEAK_KEY_TESTSTRING,
- strlen(WEAK_KEY_TESTSTRING)+1,
- &weak_key,
- &INITVALUE,
- result);
+ size = encryptBlock (WEAK_KEY_TESTSTRING,
+ strlen (WEAK_KEY_TESTSTRING) + 1,
+ &weak_key, &INITVALUE, result);
- if (size == -1) {
- GE_BREAK(NULL, 0);
- return 1;
- }
+ if (size == -1)
+ {
+ GE_BREAK (NULL, 0);
+ return 1;
+ }
- size = decryptBlock(&weak_key,
- result,
- size,
- &INITVALUE,
- res);
+ size = decryptBlock (&weak_key, result, size, &INITVALUE, res);
- if ((strlen(WEAK_KEY_TESTSTRING)+1) != size) {
- GE_BREAK(NULL, 0);
- return 1;
- }
- if (0 != strcmp(res,
- WEAK_KEY_TESTSTRING)) {
- GE_BREAK(NULL, 0);
- return 1;
- } else
+ if ((strlen (WEAK_KEY_TESTSTRING) + 1) != size)
+ {
+ GE_BREAK (NULL, 0);
+ return 1;
+ }
+ if (0 != strcmp (res, WEAK_KEY_TESTSTRING))
+ {
+ GE_BREAK (NULL, 0);
+ return 1;
+ }
+ else
return 0;
}
-static int getWeakKeys() {
+static int
+getWeakKeys ()
+{
SESSIONKEY sessionkey;
int number_of_weak_keys = 0;
int number_of_runs;
@@ -127,66 +129,68 @@
int rc;
for (number_of_runs = 0; number_of_runs < MAX_WEAK_KEY_TRIALS;
- number_of_runs++) {
+ number_of_runs++)
+ {
- if (number_of_runs % 1000 == 0)
- fprintf(stderr, ".");
- /*printf("Got to run number %d.\n", number_of_runs);*/
- makeSessionkey(&sessionkey);
+ if (number_of_runs % 1000 == 0)
+ fprintf (stderr, ".");
+ /*printf("Got to run number %d.\n", number_of_runs); */
+ makeSessionkey (&sessionkey);
- rc = gcry_cipher_open(&handle,
- GCRY_CIPHER_AES256,
- GCRY_CIPHER_MODE_CFB,
- 0);
+ rc = gcry_cipher_open (&handle,
+ GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CFB, 0);
- if (rc) {
- printf("testweakkey: gcry_cipher_open failed on trial %d. %s\n",
- number_of_runs,
- gcry_strerror(rc));
- rc = 0;
- continue;
- }
+ if (rc)
+ {
+ printf ("testweakkey: gcry_cipher_open failed on trial %d. %s\n",
+ number_of_runs, gcry_strerror (rc));
+ rc = 0;
+ continue;
+ }
- rc = gcry_cipher_setkey(handle,
- &sessionkey,
- SESSIONKEY_LEN);
+ rc = gcry_cipher_setkey (handle, &sessionkey, SESSIONKEY_LEN);
- if ((char)rc == GPG_ERR_WEAK_KEY) {
- printf("\nWeak key (in hex): ");
- printWeakKey(&sessionkey);
- printf("\n");
- number_of_weak_keys++;
- }
- else if (rc) {
- printf("\nUnexpected error generating keys. Error is %s\n",
- gcry_strerror(rc));
- }
+ if ((char) rc == GPG_ERR_WEAK_KEY)
+ {
+ printf ("\nWeak key (in hex): ");
+ printWeakKey (&sessionkey);
+ printf ("\n");
+ number_of_weak_keys++;
+ }
+ else if (rc)
+ {
+ printf ("\nUnexpected error generating keys. Error is %s\n",
+ gcry_strerror (rc));
+ }
- gcry_cipher_close(handle);
+ gcry_cipher_close (handle);
- }
+ }
return number_of_weak_keys;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int weak_keys;
- if (GENERATE_WEAK_KEYS) {
- weak_keys = getWeakKeys();
+ if (GENERATE_WEAK_KEYS)
+ {
+ weak_keys = getWeakKeys ();
- if (weak_keys == 0) {
- printf("\nNo weak keys found in %d runs.\n",
- MAX_WEAK_KEY_TRIALS);
+ if (weak_keys == 0)
+ {
+ printf ("\nNo weak keys found in %d runs.\n", MAX_WEAK_KEY_TRIALS);
+ }
+ else
+ {
+ printf ("\n%d weak keys found in %d runs.\n",
+ weak_keys, MAX_WEAK_KEY_TRIALS);
+ }
}
- else {
- printf("\n%d weak keys found in %d runs.\n",
- weak_keys,
- MAX_WEAK_KEY_TRIALS);
- }
- }
- if (testWeakKey() != 0)
+ if (testWeakKey () != 0)
return -1;
return 0;
}
Modified: GNUnet/src/util/disk/storage.c
===================================================================
--- GNUnet/src/util/disk/storage.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/disk/storage.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -46,8 +46,8 @@
#include <sys/statvfs.h>
#else
#ifdef MINGW
-#define _IFMT 0170000 /* type of file */
-#define _IFLNK 0120000 /* symbolic link */
+#define _IFMT 0170000 /* type of file */
+#define _IFLNK 0120000 /* symbolic link */
#define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
#else
#error PORT-ME: need to port statfs (how much space is left on the drive?)
@@ -58,88 +58,85 @@
#endif
#ifndef SOMEBSD
- #ifndef WINDOWS
- #ifndef OSX
- #include <wordexp.h>
- #endif
- #endif
+#ifndef WINDOWS
+#ifndef OSX
+#include <wordexp.h>
#endif
+#endif
+#endif
-typedef struct {
- struct GE_Context * ectx;
+typedef struct
+{
+ struct GE_Context *ectx;
unsigned long long total;
int include_sym_links;
} GetFileSizeData;
-static int getSizeRec(const char * filename,
- const char * dirname,
- void * ptr) {
- GetFileSizeData * gfsd = ptr;
+static int
+getSizeRec (const char *filename, const char *dirname, void *ptr)
+{
+ GetFileSizeData *gfsd = ptr;
#ifdef HAVE_STAT64
struct stat64 buf;
#else
struct stat buf;
#endif
- char * fn;
+ char *fn;
- GE_ASSERT(gfsd->ectx, filename != NULL);
- if ( (dirname != NULL) &&
- (strlen(dirname) > 0) ) {
- fn = MALLOC(strlen(filename) + strlen(dirname) + 3);
- if (strlen(dirname) > 0) {
- strcpy(fn, dirname);
- if (dirname[strlen(dirname)-1] != DIR_SEPARATOR)
- strcat(fn, DIR_SEPARATOR_STR); /* add tailing / if needed */
- }
- /* Windows paths don't start with / */
+ GE_ASSERT (gfsd->ectx, filename != NULL);
+ if ((dirname != NULL) && (strlen (dirname) > 0))
+ {
+ fn = MALLOC (strlen (filename) + strlen (dirname) + 3);
+ if (strlen (dirname) > 0)
+ {
+ strcpy (fn, dirname);
+ if (dirname[strlen (dirname) - 1] != DIR_SEPARATOR)
+ strcat (fn, DIR_SEPARATOR_STR); /* add tailing / if needed */
+ }
+ /* Windows paths don't start with / */
#ifndef MINGW
- else
- strcpy(fn, DIR_SEPARATOR_STR);
+ else
+ strcpy (fn, DIR_SEPARATOR_STR);
#endif
- if (filename[0] == DIR_SEPARATOR)
- /* if filename starts with a "/", don't copy it */
- strcat(fn, &filename[1]);
- else
- strcat(fn, filename);
- } else
- fn = STRDUP(filename);
+ if (filename[0] == DIR_SEPARATOR)
+ /* if filename starts with a "/", don't copy it */
+ strcat (fn, &filename[1]);
+ else
+ strcat (fn, filename);
+ }
+ else
+ fn = STRDUP (filename);
#ifdef HAVE_STAT64
- if (0 != STAT64(fn, &buf)) {
- GE_LOG_STRERROR_FILE(gfsd->ectx,
- GE_WARNING | GE_USER | GE_REQUEST,
- "stat64",
- fn);
- FREE(fn);
- return SYSERR;
- }
+ if (0 != STAT64 (fn, &buf))
+ {
+ GE_LOG_STRERROR_FILE (gfsd->ectx,
+ GE_WARNING | GE_USER | GE_REQUEST, "stat64", fn);
+ FREE (fn);
+ return SYSERR;
+ }
#else
- if (0 != STAT(fn, &buf)) {
- GE_LOG_STRERROR_FILE(gfsd->ectx,
- GE_WARNING | GE_USER | GE_REQUEST,
- "stat",
- fn);
- FREE(fn);
- return SYSERR;
- }
+ if (0 != STAT (fn, &buf))
+ {
+ GE_LOG_STRERROR_FILE (gfsd->ectx,
+ GE_WARNING | GE_USER | GE_REQUEST, "stat", fn);
+ FREE (fn);
+ return SYSERR;
+ }
#endif
- if ( (! S_ISLNK(buf.st_mode)) ||
- (gfsd->include_sym_links == YES) )
+ if ((!S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == YES))
gfsd->total += buf.st_size;
- if ( (S_ISDIR(buf.st_mode)) &&
- (0 == ACCESS(fn, X_OK)) &&
- ( (!S_ISLNK(buf.st_mode)) ||
- (gfsd->include_sym_links == YES) ) ) {
- if (SYSERR ==
- disk_directory_scan(gfsd->ectx,
- fn,
- &getSizeRec,
- gfsd)) {
- FREE(fn);
- return SYSERR;
+ if ((S_ISDIR (buf.st_mode)) &&
+ (0 == ACCESS (fn, X_OK)) &&
+ ((!S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == YES)))
+ {
+ if (SYSERR == disk_directory_scan (gfsd->ectx, fn, &getSizeRec, gfsd))
+ {
+ FREE (fn);
+ return SYSERR;
+ }
}
- }
- FREE(fn);
+ FREE (fn);
return OK;
}
@@ -149,18 +146,19 @@
*
* @return SYSERR on error, OK on success
*/
-int disk_file_size(struct GE_Context * ectx,
- const char * filename,
- unsigned long long * size,
- int includeSymLinks) {
+int
+disk_file_size (struct GE_Context *ectx,
+ const char *filename,
+ unsigned long long *size, int includeSymLinks)
+{
GetFileSizeData gfsd;
int ret;
- GE_ASSERT(ectx, size != NULL);
+ GE_ASSERT (ectx, size != NULL);
gfsd.ectx = ectx;
gfsd.total = 0;
gfsd.include_sym_links = includeSymLinks;
- ret = getSizeRec(filename, "", &gfsd);
+ ret = getSizeRec (filename, "", &gfsd);
*size = gfsd.total;
return ret;
}
@@ -172,50 +170,46 @@
* @param part a file on the partition to check
* @return -1 on errors, otherwise the number of free blocks
*/
-long disk_get_blocks_available(struct GE_Context * ectx,
- const char * part) {
+long
+disk_get_blocks_available (struct GE_Context *ectx, const char *part)
+{
#ifdef SOLARIS
struct statvfs buf;
- if (0 != statvfs(part, &buf)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- "statfs",
- part);
- return -1;
- }
+ if (0 != statvfs (part, &buf))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
+ "statfs", part);
+ return -1;
+ }
return buf.f_bavail;
#elif MINGW
DWORD dwDummy;
DWORD dwBlocks;
char szDrive[4];
- memcpy(szDrive, part, 3);
+ memcpy (szDrive, part, 3);
szDrive[3] = 0;
- if (!GetDiskFreeSpace(szDrive,
- &dwDummy,
- &dwDummy,
- &dwBlocks,
- &dwDummy)) {
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- _("`%s' failed for drive `%s': %u\n"),
- "GetDiskFreeSpace",
- szDrive,
- GetLastError());
+ if (!GetDiskFreeSpace (szDrive, &dwDummy, &dwDummy, &dwBlocks, &dwDummy))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
+ _("`%s' failed for drive `%s': %u\n"),
+ "GetDiskFreeSpace", szDrive, GetLastError ());
- return -1;
- }
+ return -1;
+ }
return dwBlocks;
#else
struct statfs s;
- if (0 != statfs(part, &s)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- "statfs",
- part);
- return -1;
- }
+ if (0 != statfs (part, &s))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
+ "statfs", part);
+ return -1;
+ }
return s.f_bavail;
#endif
}
@@ -226,31 +220,33 @@
* @return YES if yes, NO if not, SYSERR if it
* does not exist
*/
-int disk_directory_test(struct GE_Context * ectx,
- const char * fil) {
+int
+disk_directory_test (struct GE_Context *ectx, const char *fil)
+{
struct stat filestat;
int ret;
- ret = STAT(fil, &filestat);
- if (ret != 0) {
- if (errno != ENOENT) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_REQUEST,
- "stat",
- fil);
- return SYSERR;
+ ret = STAT (fil, &filestat);
+ if (ret != 0)
+ {
+ if (errno != ENOENT)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_REQUEST,
+ "stat", fil);
+ return SYSERR;
+ }
+ return NO;
}
+ if (!S_ISDIR (filestat.st_mode))
return NO;
- }
- if (! S_ISDIR(filestat.st_mode))
- return NO;
- if (ACCESS(fil, R_OK | X_OK) < 0 ) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_REQUEST,
- "access",
- fil);
- return SYSERR;
- }
+ if (ACCESS (fil, R_OK | X_OK) < 0)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_REQUEST,
+ "access", fil);
+ return SYSERR;
+ }
return YES;
}
@@ -260,43 +256,45 @@
* @returns YES if yes, NO if not a file, SYSERR if something
* else (will print an error message in that case, too).
*/
-int disk_file_test(struct GE_Context * ectx,
- const char * fil) {
+int
+disk_file_test (struct GE_Context *ectx, const char *fil)
+{
struct stat filestat;
int ret;
- char * rdir;
+ char *rdir;
- rdir = string_expandFileName(ectx,
- fil);
+ rdir = string_expandFileName (ectx, fil);
if (rdir == NULL)
return SYSERR;
- ret = STAT(rdir, &filestat);
- if (ret != 0) {
- if (errno != ENOENT) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_REQUEST,
- "stat",
- rdir);
- FREE(rdir);
+ ret = STAT (rdir, &filestat);
+ if (ret != 0)
+ {
+ if (errno != ENOENT)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_REQUEST,
+ "stat", rdir);
+ FREE (rdir);
+ return SYSERR;
+ }
+ FREE (rdir);
+ return NO;
+ }
+ if (!S_ISREG (filestat.st_mode))
+ {
+ FREE (rdir);
+ return NO;
+ }
+ if (ACCESS (rdir, R_OK) < 0)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_REQUEST,
+ "access", rdir);
+ FREE (rdir);
return SYSERR;
}
- FREE(rdir);
- return NO;
- }
- if (! S_ISREG(filestat.st_mode)) {
- FREE(rdir);
- return NO;
- }
- if (ACCESS(rdir, R_OK) < 0 ) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_REQUEST,
- "access",
- rdir);
- FREE(rdir);
- return SYSERR;
- }
- FREE(rdir);
+ FREE (rdir);
return YES;
}
@@ -305,70 +303,73 @@
* @param dir the directory to create
* @returns OK on success, SYSERR on failure
*/
-int disk_directory_create(struct GE_Context * ectx,
- const char * dir) {
- char * rdir;
+int
+disk_directory_create (struct GE_Context *ectx, const char *dir)
+{
+ char *rdir;
int len;
int pos;
int ret = OK;
- rdir = string_expandFileName(ectx,
- dir);
+ rdir = string_expandFileName (ectx, dir);
if (rdir == NULL)
return SYSERR;
- len = strlen(rdir);
+ len = strlen (rdir);
#ifndef MINGW
- pos = 1; /* skip heading '/' */
+ pos = 1; /* skip heading '/' */
#else
/* Local or Network path? */
- if (strncmp(rdir, "\\\\", 2) == 0) {
- pos = 2;
- while (rdir[pos]) {
- if (rdir[pos] == '\\') {
- pos++;
- break;
- }
- pos++;
+ if (strncmp (rdir, "\\\\", 2) == 0)
+ {
+ pos = 2;
+ while (rdir[pos])
+ {
+ if (rdir[pos] == '\\')
+ {
+ pos++;
+ break;
+ }
+ pos++;
+ }
}
- } else {
- pos = 3; /* strlen("C:\\") */
- }
+ else
+ {
+ pos = 3; /* strlen("C:\\") */
+ }
#endif
- while (pos <= len) {
- if ( (rdir[pos] == DIR_SEPARATOR) ||
- (pos == len) ) {
- rdir[pos] = '\0';
- ret = disk_directory_test(ectx, rdir);
- if (ret == SYSERR) {
- FREE(rdir);
- return SYSERR;
- }
- if (ret == NO) {
+ while (pos <= len)
+ {
+ if ((rdir[pos] == DIR_SEPARATOR) || (pos == len))
+ {
+ rdir[pos] = '\0';
+ ret = disk_directory_test (ectx, rdir);
+ if (ret == SYSERR)
+ {
+ FREE (rdir);
+ return SYSERR;
+ }
+ if (ret == NO)
+ {
#ifndef MINGW
- ret = mkdir(rdir,
- S_IRUSR | S_IWUSR |
- S_IXUSR | S_IRGRP |
- S_IXGRP | S_IROTH |
- S_IXOTH); /* 755 */
+ ret = mkdir (rdir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP |
S_IXGRP | S_IROTH | S_IXOTH); /* 755 */
#else
- ret = mkdir(rdir);
+ ret = mkdir (rdir);
#endif
- if ( (ret != 0) &&
- (errno != EEXIST) ) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- "mkdir",
- rdir);
- FREE(rdir);
- return SYSERR;
- }
- }
- rdir[pos] = DIR_SEPARATOR;
+ if ((ret != 0) && (errno != EEXIST))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ "mkdir", rdir);
+ FREE (rdir);
+ return SYSERR;
+ }
+ }
+ rdir[pos] = DIR_SEPARATOR;
+ }
+ pos++;
}
- pos++;
- }
- FREE(rdir);
+ FREE (rdir);
return OK;
}
@@ -380,23 +381,22 @@
* @param filename name of a file in the directory
* @returns OK on success, SYSERR on failure
*/
-int disk_directory_create_for_file(struct GE_Context * ectx,
- const char * dir) {
- char * rdir;
+int
+disk_directory_create_for_file (struct GE_Context *ectx, const char *dir)
+{
+ char *rdir;
int len;
int ret;
- rdir = string_expandFileName(ectx,
- dir);
+ rdir = string_expandFileName (ectx, dir);
if (rdir == NULL)
return SYSERR;
- len = strlen(rdir);
- while ( (len > 0) &&
- (rdir[len] != DIR_SEPARATOR) )
+ len = strlen (rdir);
+ while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
len--;
rdir[len] = '\0';
- ret = disk_directory_create(ectx, rdir);
- FREE(rdir);
+ ret = disk_directory_create (ectx, rdir);
+ FREE (rdir);
return ret;
}
@@ -408,27 +408,24 @@
* @param result the buffer to write the result to
* @return the number of bytes read on success, -1 on failure
*/
-int disk_file_read(struct GE_Context * ectx,
- const char * fileName,
- int len,
- void * result) {
+int
+disk_file_read (struct GE_Context *ectx,
+ const char *fileName, int len, void *result)
+{
/* open file, must exist, open read only */
int handle;
int size;
- GE_ASSERT(ectx, fileName != NULL);
- GE_ASSERT(ectx, len > 0);
+ GE_ASSERT (ectx, fileName != NULL);
+ GE_ASSERT (ectx, len > 0);
if (len == 0)
return 0;
- GE_ASSERT(ectx, result != NULL);
- handle = disk_file_open(ectx,
- fileName,
- O_RDONLY,
- S_IRUSR);
+ GE_ASSERT (ectx, result != NULL);
+ handle = disk_file_open (ectx, fileName, O_RDONLY, S_IRUSR);
if (handle < 0)
return -1;
- size = READ(handle, result, len);
- disk_file_close(ectx, fileName, handle);
+ size = READ (handle, result, len);
+ disk_file_close (ectx, fileName, handle);
return size;
}
@@ -436,13 +433,16 @@
/**
* Convert string to value ('755' for chmod-call)
*/
-static int atoo(const char *s) {
+static int
+atoo (const char *s)
+{
int n = 0;
- while ( ('0' <= *s) && (*s < '8') ) {
- n <<= 3;
- n += *s++ - '0';
- }
+ while (('0' <= *s) && (*s < '8'))
+ {
+ n <<= 3;
+ n += *s++ - '0';
+ }
return n;
}
@@ -454,47 +454,41 @@
* @param mode permissions to set on the file
* @return OK on success, SYSERR on error
*/
-int disk_file_write(struct GE_Context * ectx,
- const char * fileName,
- const void * buffer,
- unsigned int n,
- const char * mode) {
+int
+disk_file_write (struct GE_Context *ectx,
+ const char *fileName,
+ const void *buffer, unsigned int n, const char *mode)
+{
int handle;
- char * fn;
+ char *fn;
/* open file, open with 600, create if not
present, otherwise overwrite */
- GE_ASSERT(ectx, fileName != NULL);
- fn = string_expandFileName(ectx, fileName);
- handle = disk_file_open(ectx,
- fn,
- O_CREAT | O_WRONLY,
- S_IRUSR | S_IWUSR);
- if (handle == -1) {
- FREE(fn);
- return SYSERR;
- }
- GE_ASSERT(ectx,
- (n == 0) || (buffer != NULL));
+ GE_ASSERT (ectx, fileName != NULL);
+ fn = string_expandFileName (ectx, fileName);
+ handle = disk_file_open (ectx, fn, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
+ if (handle == -1)
+ {
+ FREE (fn);
+ return SYSERR;
+ }
+ GE_ASSERT (ectx, (n == 0) || (buffer != NULL));
/* write the buffer take length from the beginning */
- if (n != WRITE(handle, buffer, n)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_IMMEDIATE,
- "write",
- fn);
- disk_file_close(ectx, fn, handle);
- FREE(fn);
- return SYSERR;
- }
- disk_file_close(ectx, fn, handle);
- if (0 != CHMOD(fn,
- atoo(mode))) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "chmod",
- fn);
- }
- FREE(fn);
+ if (n != WRITE (handle, buffer, n))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_IMMEDIATE, "write", fn);
+ disk_file_close (ectx, fn, handle);
+ FREE (fn);
+ return SYSERR;
+ }
+ disk_file_close (ectx, fn, handle);
+ if (0 != CHMOD (fn, atoo (mode)))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_BULK, "chmod", fn);
+ }
+ FREE (fn);
return OK;
}
@@ -508,80 +502,77 @@
* @return the number of files found, SYSERR on error or
* ieration aborted by callback returning SYSERR
*/
-int disk_directory_scan(struct GE_Context * ectx,
- const char * dirName,
- DirectoryEntryCallback callback,
- void * data) {
- DIR * dinfo;
+int
+disk_directory_scan (struct GE_Context *ectx,
+ const char *dirName,
+ DirectoryEntryCallback callback, void *data)
+{
+ DIR *dinfo;
struct dirent *finfo;
struct stat istat;
int count = 0;
- GE_ASSERT(ectx, dirName != NULL);
- if (0 != STAT(dirName, &istat)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "stat",
- dirName);
- return SYSERR;
- }
- if (!S_ISDIR(istat.st_mode)) {
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Expected `%s' to be a directory!\n"),
- dirName);
- return SYSERR;
- }
+ GE_ASSERT (ectx, dirName != NULL);
+ if (0 != STAT (dirName, &istat))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_BULK, "stat", dirName);
+ return SYSERR;
+ }
+ if (!S_ISDIR (istat.st_mode))
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Expected `%s' to be a directory!\n"), dirName);
+ return SYSERR;
+ }
errno = 0;
- dinfo = OPENDIR(dirName);
- if ( (errno == EACCES) || (dinfo == NULL)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "opendir",
- dirName);
- return SYSERR;
- }
- while ((finfo = readdir(dinfo)) != NULL) {
- if ( (0 == strcmp(finfo->d_name, ".")) ||
- (0 == strcmp(finfo->d_name, "..")) )
- continue;
- if (callback != NULL) {
- if (OK != callback(finfo->d_name,
- dirName,
- data)) {
- closedir(dinfo);
- return SYSERR;
- }
+ dinfo = OPENDIR (dirName);
+ if ((errno == EACCES) || (dinfo == NULL))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ "opendir", dirName);
+ return SYSERR;
}
- count++;
- }
- closedir(dinfo);
+ while ((finfo = readdir (dinfo)) != NULL)
+ {
+ if ((0 == strcmp (finfo->d_name, ".")) ||
+ (0 == strcmp (finfo->d_name, "..")))
+ continue;
+ if (callback != NULL)
+ {
+ if (OK != callback (finfo->d_name, dirName, data))
+ {
+ closedir (dinfo);
+ return SYSERR;
+ }
+ }
+ count++;
+ }
+ closedir (dinfo);
return count;
}
/**
* Callback for disk_directory_remove
*/
-static int rmHelper(const char * fil,
- const char * dir,
- void * ctx) {
- struct GE_Context * ectx = ctx;
- char * fn;
+static int
+rmHelper (const char *fil, const char *dir, void *ctx)
+{
+ struct GE_Context *ectx = ctx;
+ char *fn;
size_t n;
- n = strlen(dir) + strlen(fil) + 2;
- fn = MALLOC(n);
- SNPRINTF(fn,
- n,
- "%s/%s",
- dir,
- fil);
- if (SYSERR == disk_directory_remove(ectx,
- fn)) {
- FREE(fn);
- return SYSERR;
- }
- FREE(fn);
+ n = strlen (dir) + strlen (fil) + 2;
+ fn = MALLOC (n);
+ SNPRINTF (fn, n, "%s/%s", dir, fil);
+ if (SYSERR == disk_directory_remove (ectx, fn))
+ {
+ FREE (fn);
+ return SYSERR;
+ }
+ FREE (fn);
return OK;
}
@@ -593,94 +584,88 @@
* @param fileName the file to remove
* @return OK on success, SYSERR on error
*/
-int disk_directory_remove(struct GE_Context * ectx,
- const char * fileName) {
+int
+disk_directory_remove (struct GE_Context *ectx, const char *fileName)
+{
struct stat istat;
- if (0 != STAT(fileName, &istat))
- return NO; /* file may not exist... */
- if (UNLINK(fileName) == 0)
+ if (0 != STAT (fileName, &istat))
+ return NO; /* file may not exist... */
+ if (UNLINK (fileName) == 0)
return OK;
- if ( (errno != EISDIR) &&
- /* EISDIR is not sufficient in all cases, e.g.
- sticky /tmp directory may result in EPERM on BSD.
- So we also explicitly check "isDirectory" */
- (YES != disk_directory_test(ectx, fileName)) ) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- "rmdir",
- fileName);
+ if ((errno != EISDIR) &&
+ /* EISDIR is not sufficient in all cases, e.g.
+ sticky /tmp directory may result in EPERM on BSD.
+ So we also explicitly check "isDirectory" */
+ (YES != disk_directory_test (ectx, fileName)))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
+ "rmdir", fileName);
+ return SYSERR;
+ }
+ if (SYSERR == disk_directory_scan (ectx, fileName, &rmHelper, ectx))
return SYSERR;
- }
- if (SYSERR == disk_directory_scan(ectx,
- fileName,
- &rmHelper,
- ectx))
- return SYSERR;
- if (0 != RMDIR(fileName)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- "rmdir",
- fileName);
- return SYSERR;
- }
+ if (0 != RMDIR (fileName))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
+ "rmdir", fileName);
+ return SYSERR;
+ }
return OK;
}
-void disk_file_close(struct GE_Context * ectx,
- const char * filename,
- int fd) {
- if (0 != CLOSE(fd))
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "close",
- filename);
+void
+disk_file_close (struct GE_Context *ectx, const char *filename, int fd)
+{
+ if (0 != CLOSE (fd))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_BULK, "close", filename);
}
-int disk_file_open(struct GE_Context * ectx,
- const char * filename,
- int oflag,
- ...) {
- char * fn;
+int
+disk_file_open (struct GE_Context *ectx, const char *filename, int oflag, ...)
+{
+ char *fn;
int mode;
int ret;
#ifdef MINGW
char szFile[_MAX_PATH + 1];
long lRet;
- if ((lRet = plibc_conv_to_win_path(filename,
- szFile)) != ERROR_SUCCESS) {
- errno = ENOENT;
- SetLastError(lRet);
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_DEVELOPER | GE_ADMIN | GE_BULK,
- "plibc_conv_to_win_path",
- filename);
- return -1;
- }
- fn = STRDUP(szFile);
+ if ((lRet = plibc_conv_to_win_path (filename, szFile)) != ERROR_SUCCESS)
+ {
+ errno = ENOENT;
+ SetLastError (lRet);
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_DEVELOPER | GE_ADMIN |
+ GE_BULK, "plibc_conv_to_win_path", filename);
+ return -1;
+ }
+ fn = STRDUP (szFile);
#else
- fn = string_expandFileName(ectx, filename);
+ fn = string_expandFileName (ectx, filename);
#endif
- if (oflag & O_CREAT) {
- va_list arg;
- va_start(arg, oflag);
- mode = va_arg(arg, int);
- va_end(arg);
- } else {
- mode = 0;
- }
+ if (oflag & O_CREAT)
+ {
+ va_list arg;
+ va_start (arg, oflag);
+ mode = va_arg (arg, int);
+ va_end (arg);
+ }
+ else
+ {
+ mode = 0;
+ }
#ifdef MINGW
/* set binary mode */
oflag |= O_BINARY;
#endif
- ret = open(fn, oflag, mode);
+ ret = open (fn, oflag, mode);
if (ret == -1)
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "open",
- fn);
- FREE(fn);
+ GE_LOG_STRERROR_FILE (ectx, GE_WARNING | GE_USER | GE_BULK, "open", fn);
+ FREE (fn);
return ret;
}
@@ -690,56 +675,51 @@
* Copy a file.
* @return OK on success, SYSERR on error
*/
-int disk_file_copy(struct GE_Context * ectx,
- const char * src,
- const char * dst) {
- char * buf;
+int
+disk_file_copy (struct GE_Context *ectx, const char *src, const char *dst)
+{
+ char *buf;
unsigned long long pos;
unsigned long long size;
unsigned long long len;
int in;
int out;
- if (OK != disk_file_size(ectx,
- src,
- &size,
- YES))
+ if (OK != disk_file_size (ectx, src, &size, YES))
return SYSERR;
pos = 0;
- in = disk_file_open(ectx,
- src,
- O_RDONLY | O_LARGEFILE);
+ in = disk_file_open (ectx, src, O_RDONLY | O_LARGEFILE);
if (in == -1)
return SYSERR;
- out = disk_file_open(ectx,
- dst,
- O_LARGEFILE | O_WRONLY | O_CREAT | O_EXCL,
- S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
- if (out == -1) {
- disk_file_close(ectx,
- src,
- in);
- return SYSERR;
- }
- buf = MALLOC(COPY_BLK_SIZE);
- while (pos < size) {
- len = COPY_BLK_SIZE;
- if (len > size - pos)
- len = size - pos;
- if (len != READ(in, buf, len))
- goto FAIL;
- if (len != WRITE(out, buf, len))
- goto FAIL;
- pos += len;
- }
- FREE(buf);
- disk_file_close(ectx, src, in);
- disk_file_close(ectx, dst, out);
+ out = disk_file_open (ectx,
+ dst,
+ O_LARGEFILE | O_WRONLY | O_CREAT | O_EXCL,
+ S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
+ if (out == -1)
+ {
+ disk_file_close (ectx, src, in);
+ return SYSERR;
+ }
+ buf = MALLOC (COPY_BLK_SIZE);
+ while (pos < size)
+ {
+ len = COPY_BLK_SIZE;
+ if (len > size - pos)
+ len = size - pos;
+ if (len != READ (in, buf, len))
+ goto FAIL;
+ if (len != WRITE (out, buf, len))
+ goto FAIL;
+ pos += len;
+ }
+ FREE (buf);
+ disk_file_close (ectx, src, in);
+ disk_file_close (ectx, dst, out);
return OK;
- FAIL:
- FREE(buf);
- disk_file_close(ectx, src, in);
- disk_file_close(ectx, dst, out);
+FAIL:
+ FREE (buf);
+ disk_file_close (ectx, src, in);
+ disk_file_close (ectx, dst, out);
return SYSERR;
}
@@ -747,21 +727,25 @@
* @brief Removes special characters as ':' from a filename.
* @param fn the filename to canonicalize
*/
-void disk_filename_canonicalize(char *fn) {
+void
+disk_filename_canonicalize (char *fn)
+{
char *idx;
char c;
idx = fn;
- while (*idx) {
- c = *idx;
+ while (*idx)
+ {
+ c = *idx;
- if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' ||
- c == '"' || c == '<' || c == '>' || c == '|') {
- *idx = '_';
- }
+ if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' ||
+ c == '"' || c == '<' || c == '>' || c == '|')
+ {
+ *idx = '_';
+ }
- idx++;
- }
+ idx++;
+ }
}
/* end of storage.c */
Modified: GNUnet/src/util/disk/storagetest.c
===================================================================
--- GNUnet/src/util/disk/storagetest.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/disk/storagetest.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -29,40 +29,34 @@
#define TESTSTRING "Hello World\0"
-static int testReadWrite() {
+static int
+testReadWrite ()
+{
char tmp[100];
- disk_file_write(NULL,
- ".testfile",
- TESTSTRING,
- strlen(TESTSTRING),
- "644");
- tmp[disk_file_read(NULL,
- ".testfile",
- 100,
- tmp)] = '\0';
- if (0 != memcmp(tmp,
- TESTSTRING,
- strlen(TESTSTRING)+1)) {
- fprintf(stderr,
- "Error in testReadWrite: *%s* != *%s* for file %s\n",
- tmp,
- TESTSTRING,
- ".testfile");
- return 1;
- }
- UNLINK(".testfile");
+ disk_file_write (NULL, ".testfile", TESTSTRING, strlen (TESTSTRING), "644");
+ tmp[disk_file_read (NULL, ".testfile", 100, tmp)] = '\0';
+ if (0 != memcmp (tmp, TESTSTRING, strlen (TESTSTRING) + 1))
+ {
+ fprintf (stderr,
+ "Error in testReadWrite: *%s* != *%s* for file %s\n",
+ tmp, TESTSTRING, ".testfile");
+ return 1;
+ }
+ UNLINK (".testfile");
return 0;
}
-int main(int argc, char * argv[]) {
+int
+main (int argc, char *argv[])
+{
int failureCount = 0;
- failureCount += testReadWrite();
- if (failureCount != 0) {
- fprintf(stderr,
- "\n\n%d TESTS FAILED!\n\n",failureCount);
- return -1;
- }
+ failureCount += testReadWrite ();
+ if (failureCount != 0)
+ {
+ fprintf (stderr, "\n\n%d TESTS FAILED!\n\n", failureCount);
+ return -1;
+ }
return 0;
-} /* end of main */
+} /* end of main */
Modified: GNUnet/src/util/error/error.c
===================================================================
--- GNUnet/src/util/error/error.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/error/error.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,12 +33,13 @@
* Default context for logging errors; used
* if NULL is passed to GE_LOG.
*/
-static struct GE_Context * defaultContext;
+static struct GE_Context *defaultContext;
-typedef struct GE_Context {
+typedef struct GE_Context
+{
GE_KIND mask;
GE_LogHandler handler;
- void * cls;
+ void *cls;
GE_CtxFree destruct;
GE_Confirm confirm;
} GE_Context;
@@ -48,83 +49,76 @@
* @param have the event type
* @param mask the filter mask
*/
-int GE_applies(GE_KIND have,
- GE_KIND mask) {
+int
+GE_applies (GE_KIND have, GE_KIND mask)
+{
GE_KIND both = mask & have;
- return ( (both & GE_EVENTKIND) &&
- (both & GE_USERKIND) &&
- (both & GE_ROUTEKIND) );
+ return ((both & GE_EVENTKIND) &&
+ (both & GE_USERKIND) && (both & GE_ROUTEKIND));
}
-void GE_LOG(struct GE_Context * ctx,
- GE_KIND kind,
- const char * message,
- ...) {
+void
+GE_LOG (struct GE_Context *ctx, GE_KIND kind, const char *message, ...)
+{
va_list va;
char date[64];
time_t timetmp;
- struct tm * tmptr;
+ struct tm *tmptr;
size_t size;
- char * buf;
+ char *buf;
if (ctx == NULL)
ctx = defaultContext;
- if ( (ctx != NULL) &&
- (! GE_applies(kind, ctx->mask)) )
+ if ((ctx != NULL) && (!GE_applies (kind, ctx->mask)))
return;
- if ( (ctx == NULL) &&
- ( ((kind & (GE_IMMEDIATE | GE_BULK)) == 0) ||
- ((kind & (GE_FATAL | GE_ERROR | GE_WARNING)) == 0) ) )
+ if ((ctx == NULL) &&
+ (((kind & (GE_IMMEDIATE | GE_BULK)) == 0) ||
+ ((kind & (GE_FATAL | GE_ERROR | GE_WARNING)) == 0)))
return;
- va_start(va, message);
- size = VSNPRINTF(NULL, 0, message, va) + 1;
- va_end(va);
- buf = malloc(size);
+ va_start (va, message);
+ size = VSNPRINTF (NULL, 0, message, va) + 1;
+ va_end (va);
+ buf = malloc (size);
if (buf == NULL)
- return; /* oops */
- va_start(va, message);
- VSNPRINTF(buf, size, message, va);
- va_end(va);
- time(&timetmp);
- memset(date, 0, 64);
- tmptr = localtime(&timetmp);
- strftime(date,
- 64,
- "%b %d %H:%M:%S",
- tmptr);
+ return; /* oops */
+ va_start (va, message);
+ VSNPRINTF (buf, size, message, va);
+ va_end (va);
+ time (&timetmp);
+ memset (date, 0, 64);
+ tmptr = localtime (&timetmp);
+ strftime (date, 64, "%b %d %H:%M:%S", tmptr);
if (ctx != NULL)
- ctx->handler(ctx->cls,
- kind,
- date,
- buf);
+ ctx->handler (ctx->cls, kind, date, buf);
else
- fprintf(stderr,
- "%s %s",
- date,
- buf);
- free(buf);
+ fprintf (stderr, "%s %s", date, buf);
+ free (buf);
}
/**
* @brief Get user confirmation (e.g. before the app shuts down and closes the
* error message
*/
-void GE_CONFIRM(struct GE_Context * ctx) {
- if (ctx == NULL) {
- /* @TODO: we probably ought to get confirmations in all graphical
- environments */
+void
+GE_CONFIRM (struct GE_Context *ctx)
+{
+ if (ctx == NULL)
+ {
+ /* @TODO: we probably ought to get confirmations in all graphical
+ environments */
#ifdef WINDOWS
- /* Console open? */
- if (GetStdHandle(STD_ERROR_HANDLE) != NULL) {
- fprintf(stderr,
- _("\nPress any key to continue\n"));
- getch();
- }
+ /* Console open? */
+ if (GetStdHandle (STD_ERROR_HANDLE) != NULL)
+ {
+ fprintf (stderr, _("\nPress any key to continue\n"));
+ getch ();
+ }
#endif
- } else if (ctx->confirm)
- ctx->confirm(ctx->cls);
+ }
+ else if (ctx->confirm)
+ ctx->confirm (ctx->cls);
}
/**
@@ -136,17 +130,17 @@
* to be passed to this handler
*/
struct GE_Context *
-GE_create_context_callback(GE_KIND mask,
- GE_LogHandler handler,
- void * ctx,
- GE_CtxFree liberator,
- GE_Confirm confirm) {
- GE_Context * ret;
+GE_create_context_callback (GE_KIND mask,
+ GE_LogHandler handler,
+ void *ctx,
+ GE_CtxFree liberator, GE_Confirm confirm)
+{
+ GE_Context *ret;
- ret = malloc(sizeof(GE_Context));
+ ret = malloc (sizeof (GE_Context));
if (ret == NULL)
return NULL;
- memset(ret, 0, sizeof(GE_Context));
+ memset (ret, 0, sizeof (GE_Context));
ret->mask = mask;
ret->handler = handler;
ret->cls = ctx;
@@ -158,12 +152,14 @@
/**
* Free a log context.
*/
-void GE_free_context(GE_Context * ctx) {
+void
+GE_free_context (GE_Context * ctx)
+{
if (ctx == NULL)
return;
if (ctx->destruct != NULL)
- ctx->destruct(ctx->cls);
- free(ctx);
+ ctx->destruct (ctx->cls);
+ free (ctx);
}
/**
@@ -172,12 +168,12 @@
* @param ctx the logger
* @param have the kind of event
*/
-int GE_isLogged(GE_Context * ctx,
- GE_KIND kind) {
+int
+GE_isLogged (GE_Context * ctx, GE_KIND kind)
+{
if (ctx == NULL)
return YES;
- return GE_applies(kind,
- ctx->mask);
+ return GE_applies (kind, ctx->mask);
}
/**
@@ -185,42 +181,32 @@
* to the respective GE_KIND.
* @returns GE_INVALID if log does not parse
*/
-GE_KIND GE_getKIND(const char * log) {
- if (0 == strcasecmp(log,
- _("DEBUG")))
+GE_KIND
+GE_getKIND (const char *log)
+{
+ if (0 == strcasecmp (log, _("DEBUG")))
return GE_DEBUG;
- if (0 == strcasecmp(log,
- _("STATUS")))
+ if (0 == strcasecmp (log, _("STATUS")))
return GE_STATUS;
- if (0 == strcasecmp(log,
- _("WARNING")))
+ if (0 == strcasecmp (log, _("WARNING")))
return GE_WARNING;
- if (0 == strcasecmp(log,
- _("ERROR")))
+ if (0 == strcasecmp (log, _("ERROR")))
return GE_ERROR;
- if (0 == strcasecmp(log,
- _("FATAL")))
+ if (0 == strcasecmp (log, _("FATAL")))
return GE_FATAL;
- if (0 == strcasecmp(log,
- _("USER")))
+ if (0 == strcasecmp (log, _("USER")))
return GE_USER;
- if (0 == strcasecmp(log,
- _("ADMIN")))
+ if (0 == strcasecmp (log, _("ADMIN")))
return GE_ADMIN;
- if (0 == strcasecmp(log,
- _("DEVELOPER")))
+ if (0 == strcasecmp (log, _("DEVELOPER")))
return GE_DEVELOPER;
- if (0 == strcasecmp(log,
- _("REQUEST")))
+ if (0 == strcasecmp (log, _("REQUEST")))
return GE_REQUEST;
- if (0 == strcasecmp(log,
- _("BULK")))
+ if (0 == strcasecmp (log, _("BULK")))
return GE_BULK;
- if (0 == strcasecmp(log,
- _("IMMEDIATE")))
+ if (0 == strcasecmp (log, _("IMMEDIATE")))
return GE_IMMEDIATE;
- if (0 == strcasecmp(log,
- _("ALL")))
+ if (0 == strcasecmp (log, _("ALL")))
return GE_ALL;
return GE_INVALID;
@@ -229,68 +215,74 @@
/**
* Convert KIND to String
*/
-const char * GE_kindToString(GE_KIND kind) {
- if ( (kind & GE_DEBUG) > 0)
+const char *
+GE_kindToString (GE_KIND kind)
+{
+ if ((kind & GE_DEBUG) > 0)
return _("DEBUG");
- if ( (kind & GE_STATUS) > 0)
+ if ((kind & GE_STATUS) > 0)
return _("STATUS");
- if ( (kind & GE_INFO) > 0)
+ if ((kind & GE_INFO) > 0)
return _("INFO");
- if ( (kind & GE_WARNING) > 0)
+ if ((kind & GE_WARNING) > 0)
return _("WARNING");
- if ( (kind & GE_ERROR) > 0)
+ if ((kind & GE_ERROR) > 0)
return _("ERROR");
- if ( (kind & GE_FATAL) > 0)
+ if ((kind & GE_FATAL) > 0)
return _("FATAL");
- if ( (kind & GE_USER) > 0)
+ if ((kind & GE_USER) > 0)
return _("USER");
- if ( (kind & GE_ADMIN) > 0)
+ if ((kind & GE_ADMIN) > 0)
return _("ADMIN");
- if ( (kind & GE_DEVELOPER) > 0)
+ if ((kind & GE_DEVELOPER) > 0)
return _("DEVELOPER");
- if ( (kind & GE_REQUEST) > 0)
+ if ((kind & GE_REQUEST) > 0)
return _("REQUEST");
- if ( (kind & GE_BULK) > 0)
+ if ((kind & GE_BULK) > 0)
return _("BULK");
- if ( (kind & GE_IMMEDIATE) > 0)
+ if ((kind & GE_IMMEDIATE) > 0)
return _("IMMEDIATE");
return _("NOTHING");
}
-typedef struct {
- struct GE_Context * c1;
- struct GE_Context * c2;
+typedef struct
+{
+ struct GE_Context *c1;
+ struct GE_Context *c2;
} CPair;
-static void multiplexer(void * ctx,
- GE_KIND kind,
- const char * date,
- const char * msg) {
- CPair * pair = ctx;
+static void
+multiplexer (void *ctx, GE_KIND kind, const char *date, const char *msg)
+{
+ CPair *pair = ctx;
- if (GE_applies(kind, pair->c1->mask))
- pair->c1->handler(pair->c1->cls, kind, date, msg);
- if (GE_applies(kind, pair->c2->mask))
- pair->c2->handler(pair->c2->cls, kind, date, msg);
+ if (GE_applies (kind, pair->c1->mask))
+ pair->c1->handler (pair->c1->cls, kind, date, msg);
+ if (GE_applies (kind, pair->c2->mask))
+ pair->c2->handler (pair->c2->cls, kind, date, msg);
}
-static void multi_confirm(void * ctx) {
- CPair * pair = ctx;
+static void
+multi_confirm (void *ctx)
+{
+ CPair *pair = ctx;
if (pair->c1->confirm)
- pair->c1->confirm(pair->c1->cls);
+ pair->c1->confirm (pair->c1->cls);
if (pair->c2->confirm)
- pair->c2->confirm(pair->c2->cls);
+ pair->c2->confirm (pair->c2->cls);
}
-static void pairdestruct(void * ctx) {
- CPair * pair = ctx;
+static void
+pairdestruct (void *ctx)
+{
+ CPair *pair = ctx;
- GE_free_context(pair->c1);
- GE_free_context(pair->c2);
- free(ctx);
+ GE_free_context (pair->c1);
+ GE_free_context (pair->c2);
+ free (ctx);
}
/**
@@ -298,22 +290,24 @@
* Note that the client must stop using ctx1/ctx2 henceforth.
*/
struct GE_Context *
-GE_create_context_multiplexer(struct GE_Context * ctx1,
- struct GE_Context * ctx2) {
- CPair * cls;
- GE_Context * ret;
+GE_create_context_multiplexer (struct GE_Context *ctx1,
+ struct GE_Context *ctx2)
+{
+ CPair *cls;
+ GE_Context *ret;
- cls = malloc(sizeof(CPair));
+ cls = malloc (sizeof (CPair));
if (cls == NULL)
return NULL;
cls->c1 = ctx1;
cls->c2 = ctx2;
- ret = malloc(sizeof(GE_Context));
- if (ret == NULL) {
- free(cls);
- return NULL;
- }
- memset(ret, 0, sizeof(GE_Context));
+ ret = malloc (sizeof (GE_Context));
+ if (ret == NULL)
+ {
+ free (cls);
+ return NULL;
+ }
+ memset (ret, 0, sizeof (GE_Context));
ret->cls = cls;
ret->handler = &multiplexer;
ret->mask = ctx1->mask | ctx2->mask;
@@ -323,10 +317,14 @@
}
-void GE_setDefaultContext(struct GE_Context * ctx) {
+void
+GE_setDefaultContext (struct GE_Context *ctx)
+{
defaultContext = ctx;
}
-const char *GE_strerror(int errnum) {
- return STRERROR(errnum);
+const char *
+GE_strerror (int errnum)
+{
+ return STRERROR (errnum);
}
Modified: GNUnet/src/util/getopt/getopt.c
===================================================================
--- GNUnet/src/util/getopt/getopt.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/getopt/getopt.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -88,7 +88,8 @@
one). For long options that have a zero `flag' field, `getopt'
returns the contents of the `val' field. */
-struct GNoption {
+struct GNoption
+{
const char *name;
/* has_arg can't be an enum because some compilers complain about
type mismatches in all the code that assumes it is an int. */
@@ -220,7 +221,7 @@
while (*str)
{
if (*str == chr)
- return (char *) str;
+ return (char *) str;
str++;
}
return 0;
@@ -268,14 +269,14 @@
is valid for the getopt call we must make sure that the ARGV passed
to getopt is that one passed to the process. */
static void
-__attribute__ ((unused))
-store_args_and_env (int argc, char *const *argv)
+ __attribute__ ((unused)) store_args_and_env (int argc, char *const *argv)
{
/* XXX This is no good solution. We should rather copy the args so
that we can compare them later. But we must not use malloc(3). */
original_argc = argc;
original_argv = argv;
}
+
text_set_element (__libc_subinit, store_args_and_env);
# define SWAP_FLAGS(ch1, ch2) \
@@ -285,9 +286,9 @@
__getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
__getopt_nonoption_flags[ch2] = __tmp; \
}
-#else /* !_LIBC */
+#else /* !_LIBC */
# define SWAP_FLAGS(ch1, ch2)
-#endif /* _LIBC */
+#endif /* _LIBC */
/* Exchange two adjacent subsequences of ARGV.
One subsequence is elements [first_nonopt,last_nonopt)
@@ -323,57 +324,57 @@
if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
{
/* We must extend the array. The user plays games with us and
- presents new arguments. */
+ presents new arguments. */
char *new_str = malloc (top + 1);
if (new_str == NULL)
- nonoption_flags_len = nonoption_flags_max_len = 0;
+ nonoption_flags_len = nonoption_flags_max_len = 0;
else
- {
- memcpy (new_str, __getopt_nonoption_flags, nonoption_flags_max_len);
- memset (&new_str[nonoption_flags_max_len], '\0',
- top + 1 - nonoption_flags_max_len);
- nonoption_flags_max_len = top + 1;
- __getopt_nonoption_flags = new_str;
- }
+ {
+ memcpy (new_str, __getopt_nonoption_flags, nonoption_flags_max_len);
+ memset (&new_str[nonoption_flags_max_len], '\0',
+ top + 1 - nonoption_flags_max_len);
+ nonoption_flags_max_len = top + 1;
+ __getopt_nonoption_flags = new_str;
+ }
}
#endif
while (top > middle && middle > bottom)
{
if (top - middle > middle - bottom)
- {
- /* Bottom segment is the short one. */
- int len = middle - bottom;
- register int i;
+ {
+ /* Bottom segment is the short one. */
+ int len = middle - bottom;
+ register int i;
- /* Swap it with the top part of the top segment. */
- for (i = 0; i < len; i++)
- {
- tem = argv[bottom + i];
- argv[bottom + i] = argv[top - (middle - bottom) + i];
- argv[top - (middle - bottom) + i] = tem;
- SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
- }
- /* Exclude the moved bottom segment from further swapping. */
- top -= len;
- }
+ /* Swap it with the top part of the top segment. */
+ for (i = 0; i < len; i++)
+ {
+ tem = argv[bottom + i];
+ argv[bottom + i] = argv[top - (middle - bottom) + i];
+ argv[top - (middle - bottom) + i] = tem;
+ SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
+ }
+ /* Exclude the moved bottom segment from further swapping. */
+ top -= len;
+ }
else
- {
- /* Top segment is the short one. */
- int len = top - middle;
- register int i;
+ {
+ /* Top segment is the short one. */
+ int len = top - middle;
+ register int i;
- /* Swap it with the bottom part of the bottom segment. */
- for (i = 0; i < len; i++)
- {
- tem = argv[bottom + i];
- argv[bottom + i] = argv[middle + i];
- argv[middle + i] = tem;
- SWAP_FLAGS (bottom + i, middle + i);
- }
- /* Exclude the moved top segment from further swapping. */
- bottom += len;
- }
+ /* Swap it with the bottom part of the bottom segment. */
+ for (i = 0; i < len; i++)
+ {
+ tem = argv[bottom + i];
+ argv[bottom + i] = argv[middle + i];
+ argv[middle + i] = tem;
+ SWAP_FLAGS (bottom + i, middle + i);
+ }
+ /* Exclude the moved top segment from further swapping. */
+ bottom += len;
+ }
}
/* Update records for the slots the non-options now occupy. */
@@ -425,28 +426,28 @@
&& argc == original_argc && argv == original_argv)
{
if (nonoption_flags_max_len == 0)
- {
- if (__getopt_nonoption_flags == NULL
- || __getopt_nonoption_flags[0] == '\0')
- nonoption_flags_max_len = -1;
- else
- {
- const char *orig_str = __getopt_nonoption_flags;
- int len = nonoption_flags_max_len = strlen (orig_str);
- if (nonoption_flags_max_len < argc)
- nonoption_flags_max_len = argc;
- __getopt_nonoption_flags =
- (char *) malloc (nonoption_flags_max_len);
- if (__getopt_nonoption_flags == NULL)
- nonoption_flags_max_len = -1;
- else
- {
- memcpy (__getopt_nonoption_flags, orig_str, len);
- memset (&__getopt_nonoption_flags[len], '\0',
- nonoption_flags_max_len - len);
- }
- }
- }
+ {
+ if (__getopt_nonoption_flags == NULL
+ || __getopt_nonoption_flags[0] == '\0')
+ nonoption_flags_max_len = -1;
+ else
+ {
+ const char *orig_str = __getopt_nonoption_flags;
+ int len = nonoption_flags_max_len = strlen (orig_str);
+ if (nonoption_flags_max_len < argc)
+ nonoption_flags_max_len = argc;
+ __getopt_nonoption_flags =
+ (char *) malloc (nonoption_flags_max_len);
+ if (__getopt_nonoption_flags == NULL)
+ nonoption_flags_max_len = -1;
+ else
+ {
+ memcpy (__getopt_nonoption_flags, orig_str, len);
+ memset (&__getopt_nonoption_flags[len], '\0',
+ nonoption_flags_max_len - len);
+ }
+ }
+ }
nonoption_flags_len = nonoption_flags_max_len;
}
else
@@ -526,7 +527,7 @@
if (GNoptind == 0 || !__getopt_initialized)
{
if (GNoptind == 0)
- GNoptind = 1; /* Don't scan ARGV[0], the program name. */
+ GNoptind = 1; /* Don't scan ARGV[0], the program name. */
optstring = _getopt_initialize (argc, argv, optstring);
__getopt_initialized = 1;
}
@@ -548,76 +549,76 @@
/* Advance to the next ARGV-element. */
/* Give FIRST_NONOPT & LAST_NONOPT rational values if GNoptind has been
- moved back by the user (who may also have changed the arguments). */
+ moved back by the user (who may also have changed the arguments). */
if (last_nonopt > GNoptind)
- last_nonopt = GNoptind;
+ last_nonopt = GNoptind;
if (first_nonopt > GNoptind)
- first_nonopt = GNoptind;
+ first_nonopt = GNoptind;
if (ordering == PERMUTE)
- {
- /* If we have just processed some options following some non-options,
- exchange them so that the options come first. */
+ {
+ /* If we have just processed some options following some non-options,
+ exchange them so that the options come first. */
- if (first_nonopt != last_nonopt && last_nonopt != GNoptind)
- exchange ((char **) argv);
- else if (last_nonopt != GNoptind)
- first_nonopt = GNoptind;
+ if (first_nonopt != last_nonopt && last_nonopt != GNoptind)
+ exchange ((char **) argv);
+ else if (last_nonopt != GNoptind)
+ first_nonopt = GNoptind;
- /* Skip any additional non-options
- and extend the range of non-options previously skipped. */
+ /* Skip any additional non-options
+ and extend the range of non-options previously skipped. */
- while (GNoptind < argc && NONOPTION_P)
- GNoptind++;
- last_nonopt = GNoptind;
- }
+ while (GNoptind < argc && NONOPTION_P)
+ GNoptind++;
+ last_nonopt = GNoptind;
+ }
/* The special ARGV-element `--' means premature end of options.
- Skip it like a null option,
- then exchange with previous non-options as if it were an option,
- then skip everything else like a non-option. */
+ Skip it like a null option,
+ then exchange with previous non-options as if it were an option,
+ then skip everything else like a non-option. */
if (GNoptind != argc && !strcmp (argv[GNoptind], "--"))
- {
- GNoptind++;
+ {
+ GNoptind++;
- if (first_nonopt != last_nonopt && last_nonopt != GNoptind)
- exchange ((char **) argv);
- else if (first_nonopt == last_nonopt)
- first_nonopt = GNoptind;
- last_nonopt = argc;
+ if (first_nonopt != last_nonopt && last_nonopt != GNoptind)
+ exchange ((char **) argv);
+ else if (first_nonopt == last_nonopt)
+ first_nonopt = GNoptind;
+ last_nonopt = argc;
- GNoptind = argc;
- }
+ GNoptind = argc;
+ }
/* If we have done all the ARGV-elements, stop the scan
- and back over any non-options that we skipped and permuted. */
+ and back over any non-options that we skipped and permuted. */
if (GNoptind == argc)
- {
- /* Set the next-arg-index to point at the non-options
- that we previously skipped, so the caller will digest them. */
- if (first_nonopt != last_nonopt)
- GNoptind = first_nonopt;
- return -1;
- }
+ {
+ /* Set the next-arg-index to point at the non-options
+ that we previously skipped, so the caller will digest them. */
+ if (first_nonopt != last_nonopt)
+ GNoptind = first_nonopt;
+ return -1;
+ }
/* If we have come to a non-option and did not permute it,
- either stop the scan or describe it to the caller and pass it by. */
+ either stop the scan or describe it to the caller and pass it by. */
if (NONOPTION_P)
- {
- if (ordering == REQUIRE_ORDER)
- return -1;
- GNoptarg = argv[GNoptind++];
- return 1;
- }
+ {
+ if (ordering == REQUIRE_ORDER)
+ return -1;
+ GNoptarg = argv[GNoptind++];
+ return 1;
+ }
/* We have found another option-ARGV-element.
- Skip the initial punctuation. */
+ Skip the initial punctuation. */
nextchar = (argv[GNoptind] + 1
- + (longopts != NULL && argv[GNoptind][1] == '-'));
+ + (longopts != NULL && argv[GNoptind][1] == '-'));
}
/* Decode the current option-ARGV-element. */
@@ -637,7 +638,9 @@
if (longopts != NULL
&& (argv[GNoptind][1] == '-'
- || (long_only && (argv[GNoptind][2] || !my_index (optstring,
argv[GNoptind][1])))))
+ || (long_only
+ && (argv[GNoptind][2]
+ || !my_index (optstring, argv[GNoptind][1])))))
{
char *nameend;
const struct GNoption *p;
@@ -648,124 +651,131 @@
int option_index;
for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
- /* Do nothing. */ ;
+ /* Do nothing. */ ;
/* Test all long options for either exact match
- or abbreviated matches. */
+ or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
- if (!strncmp (p->name, nextchar, nameend - nextchar))
- {
- if ((unsigned int) (nameend - nextchar)
- == (unsigned int) strlen (p->name))
+ if (!strncmp (p->name, nextchar, nameend - nextchar))
+ {
+ if ((unsigned int) (nameend - nextchar)
+ == (unsigned int) strlen (p->name))
+ {
+ /* Exact match found. */
+ pfound = p;
+ indfound = option_index;
+ exact = 1;
+ break;
+ }
+ else if (pfound == NULL)
+ {
+ /* First nonexact match found. */
+ pfound = p;
+ indfound = option_index;
+ }
+ else
+ /* Second or later nonexact match found. */
+ ambig = 1;
+ }
+
+ if (ambig && !exact)
{
- /* Exact match found. */
- pfound = p;
- indfound = option_index;
- exact = 1;
- break;
+ if (GNopterr)
+ fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
+ argv[0], argv[GNoptind]);
+ nextchar += strlen (nextchar);
+ GNoptind++;
+ GNoptopt = 0;
+ return '?';
}
- else if (pfound == NULL)
- {
- /* First nonexact match found. */
- pfound = p;
- indfound = option_index;
- }
- else
- /* Second or later nonexact match found. */
- ambig = 1;
- }
- if (ambig && !exact)
- {
- if (GNopterr)
- fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
- argv[0], argv[GNoptind]);
- nextchar += strlen (nextchar);
- GNoptind++;
- GNoptopt = 0;
- return '?';
- }
-
if (pfound != NULL)
- {
- option_index = indfound;
- GNoptind++;
- if (*nameend)
- {
- /* Don't test has_arg with >, because some C compilers don't
- allow it to be used on enums. */
- if (pfound->has_arg)
- GNoptarg = nameend + 1;
- else
- {
- if (GNopterr) {
- if (argv[GNoptind - 1][1] == '-')
- /* --option */
- fprintf (stderr,
- _("%s: option `--%s' does not allow an argument\n"),
- argv[0], pfound->name);
- else
- /* +option or -option */
- fprintf (stderr,
- _("%s: option `%c%s' does not allow an argument\n"),
- argv[0], argv[GNoptind - 1][0], pfound->name);
- }
- nextchar += strlen (nextchar);
+ {
+ option_index = indfound;
+ GNoptind++;
+ if (*nameend)
+ {
+ /* Don't test has_arg with >, because some C compilers don't
+ allow it to be used on enums. */
+ if (pfound->has_arg)
+ GNoptarg = nameend + 1;
+ else
+ {
+ if (GNopterr)
+ {
+ if (argv[GNoptind - 1][1] == '-')
+ /* --option */
+ fprintf (stderr,
+ _
+ ("%s: option `--%s' does not allow an
argument\n"),
+ argv[0], pfound->name);
+ else
+ /* +option or -option */
+ fprintf (stderr,
+ _
+ ("%s: option `%c%s' does not allow an
argument\n"),
+ argv[0], argv[GNoptind - 1][0],
+ pfound->name);
+ }
+ nextchar += strlen (nextchar);
- GNoptopt = pfound->val;
- return '?';
- }
- }
- else if (pfound->has_arg == 1)
- {
- if (GNoptind < argc) {
- GNoptarg = argv[GNoptind++];
- } else
- {
- if (GNopterr) {
- fprintf (stderr,
- _("%s: option `%s' requires an argument\n"),
- argv[0], argv[GNoptind - 1]);
- }
- nextchar += strlen (nextchar);
- GNoptopt = pfound->val;
- return (optstring[0] == ':') ? ':' : '?';
- }
- }
- nextchar += strlen (nextchar);
- if (longind != NULL)
- *longind = option_index;
- if (pfound->flag)
- {
- *(pfound->flag) = pfound->val;
- return 0;
- }
- return pfound->val;
- }
+ GNoptopt = pfound->val;
+ return '?';
+ }
+ }
+ else if (pfound->has_arg == 1)
+ {
+ if (GNoptind < argc)
+ {
+ GNoptarg = argv[GNoptind++];
+ }
+ else
+ {
+ if (GNopterr)
+ {
+ fprintf (stderr,
+ _("%s: option `%s' requires an argument\n"),
+ argv[0], argv[GNoptind - 1]);
+ }
+ nextchar += strlen (nextchar);
+ GNoptopt = pfound->val;
+ return (optstring[0] == ':') ? ':' : '?';
+ }
+ }
+ nextchar += strlen (nextchar);
+ if (longind != NULL)
+ *longind = option_index;
+ if (pfound->flag)
+ {
+ *(pfound->flag) = pfound->val;
+ return 0;
+ }
+ return pfound->val;
+ }
/* Can't find it as a long option. If this is not getopt_long_only,
- or the option starts with '--' or is not a valid short
- option, then it's an error.
- Otherwise interpret it as a short option. */
+ or the option starts with '--' or is not a valid short
+ option, then it's an error.
+ Otherwise interpret it as a short option. */
if (!long_only || argv[GNoptind][1] == '-'
- || my_index (optstring, *nextchar) == NULL)
- {
- if (GNopterr)
- {
- if (argv[GNoptind][1] == '-')
- /* --option */
- fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
- argv[0], nextchar);
- else
- /* +option or -option */
- fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
- argv[0], argv[GNoptind][0], nextchar);
- }
- nextchar = (char *) "";
- GNoptind++;
- GNoptopt = 0;
- return '?';
- }
+ || my_index (optstring, *nextchar) == NULL)
+ {
+ if (GNopterr)
+ {
+ if (argv[GNoptind][1] == '-')
+ /* --option */
+ fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
+ argv[0], nextchar);
+ else
+ /* +option or -option */
+ fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
+ argv[0], argv[GNoptind][0], nextchar);
+ }
+ nextchar = (char *) "";
+ GNoptind++;
+ GNoptopt = 0;
+ return '?';
+ }
}
/* Look at and handle the next short option-character. */
@@ -780,205 +790,198 @@
if (temp == NULL || c == ':')
{
- if (GNopterr)
- {
- if (posixly_correct)
- /* 1003.2 specifies the format of this message. */
- fprintf (stderr, _("%s: illegal option -- %c\n"),
- argv[0], c);
- else
- fprintf (stderr, _("%s: invalid option -- %c\n"),
- argv[0], c);
- }
- GNoptopt = c;
- return '?';
+ if (GNopterr)
+ {
+ if (posixly_correct)
+ /* 1003.2 specifies the format of this message. */
+ fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
+ else
+ fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
+ }
+ GNoptopt = c;
+ return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';')
{
- char *nameend;
- const struct GNoption *p;
- const struct GNoption *pfound = NULL;
- int exact = 0;
- int ambig = 0;
- int indfound = 0;
- int option_index;
+ char *nameend;
+ const struct GNoption *p;
+ const struct GNoption *pfound = NULL;
+ int exact = 0;
+ int ambig = 0;
+ int indfound = 0;
+ int option_index;
- /* This is an option that requires an argument. */
- if (*nextchar != '\0')
- {
- GNoptarg = nextchar;
- /* If we end this ARGV-element by taking the rest as an arg,
- we must advance to the next element now. */
- GNoptind++;
- }
- else if (GNoptind == argc)
- {
- if (GNopterr)
- {
- /* 1003.2 specifies the format of this message. */
- fprintf (stderr, _("%s: option requires an argument -- %c\n"),
- argv[0], c);
- }
- GNoptopt = c;
- if (optstring[0] == ':')
- c = ':';
- else
- c = '?';
- return c;
- }
- else
- /* We already incremented `GNoptind' once;
- increment it again when taking next ARGV-elt as argument. */
- GNoptarg = argv[GNoptind++];
+ /* This is an option that requires an argument. */
+ if (*nextchar != '\0')
+ {
+ GNoptarg = nextchar;
+ /* If we end this ARGV-element by taking the rest as an arg,
+ we must advance to the next element now. */
+ GNoptind++;
+ }
+ else if (GNoptind == argc)
+ {
+ if (GNopterr)
+ {
+ /* 1003.2 specifies the format of this message. */
+ fprintf (stderr, _("%s: option requires an argument -- %c\n"),
+ argv[0], c);
+ }
+ GNoptopt = c;
+ if (optstring[0] == ':')
+ c = ':';
+ else
+ c = '?';
+ return c;
+ }
+ else
+ /* We already incremented `GNoptind' once;
+ increment it again when taking next ARGV-elt as argument. */
+ GNoptarg = argv[GNoptind++];
- /* GNoptarg is now the argument, see if it's in the
- table of longopts. */
+ /* GNoptarg is now the argument, see if it's in the
+ table of longopts. */
- for (nextchar = nameend = GNoptarg; *nameend && *nameend != '='; nameend++)
- /* Do nothing. */ ;
+ for (nextchar = nameend = GNoptarg; *nameend && *nameend != '=';
+ nameend++)
+ /* Do nothing. */ ;
- /* Test all long options for either exact match
- or abbreviated matches. */
- for (p = longopts, option_index = 0; p->name; p++, option_index++)
- if (!strncmp (p->name, nextchar, nameend - nextchar))
- {
- if ((unsigned int) (nameend - nextchar) == strlen (p->name))
- {
- /* Exact match found. */
- pfound = p;
- indfound = option_index;
- exact = 1;
- break;
- }
- else if (pfound == NULL)
- {
- /* First nonexact match found. */
- pfound = p;
- indfound = option_index;
- }
- else
- /* Second or later nonexact match found. */
- ambig = 1;
- }
- if (ambig && !exact)
- {
- if (GNopterr)
- fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
- argv[0], argv[GNoptind]);
- nextchar += strlen (nextchar);
- GNoptind++;
- return '?';
- }
- if (pfound != NULL)
- {
- option_index = indfound;
- if (*nameend)
- {
- /* Don't test has_arg with >, because some C compilers don't
- allow it to be used on enums. */
- if (pfound->has_arg)
- GNoptarg = nameend + 1;
- else
- {
- if (GNopterr)
- fprintf (stderr, _("\
-%s: option `-W %s' does not allow an argument\n"),
- argv[0], pfound->name);
+ /* Test all long options for either exact match
+ or abbreviated matches. */
+ for (p = longopts, option_index = 0; p->name; p++, option_index++)
+ if (!strncmp (p->name, nextchar, nameend - nextchar))
+ {
+ if ((unsigned int) (nameend - nextchar) == strlen (p->name))
+ {
+ /* Exact match found. */
+ pfound = p;
+ indfound = option_index;
+ exact = 1;
+ break;
+ }
+ else if (pfound == NULL)
+ {
+ /* First nonexact match found. */
+ pfound = p;
+ indfound = option_index;
+ }
+ else
+ /* Second or later nonexact match found. */
+ ambig = 1;
+ }
+ if (ambig && !exact)
+ {
+ if (GNopterr)
+ fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
+ argv[0], argv[GNoptind]);
+ nextchar += strlen (nextchar);
+ GNoptind++;
+ return '?';
+ }
+ if (pfound != NULL)
+ {
+ option_index = indfound;
+ if (*nameend)
+ {
+ /* Don't test has_arg with >, because some C compilers don't
+ allow it to be used on enums. */
+ if (pfound->has_arg)
+ GNoptarg = nameend + 1;
+ else
+ {
+ if (GNopterr)
+ fprintf (stderr, _("\
+%s: option `-W %s' does not allow an argument\n"), argv[0], pfound->name);
- nextchar += strlen (nextchar);
- return '?';
- }
- }
- else if (pfound->has_arg == 1)
- {
- if (GNoptind < argc)
- GNoptarg = argv[GNoptind++];
- else
- {
- if (GNopterr)
- fprintf (stderr,
- _("%s: option `%s' requires an argument\n"),
- argv[0], argv[GNoptind - 1]);
- nextchar += strlen (nextchar);
- return optstring[0] == ':' ? ':' : '?';
- }
- }
- nextchar += strlen (nextchar);
- if (longind != NULL)
- *longind = option_index;
- if (pfound->flag)
- {
- *(pfound->flag) = pfound->val;
- return 0;
- }
- return pfound->val;
- }
- nextchar = NULL;
- return 'W'; /* Let the application handle it. */
+ nextchar += strlen (nextchar);
+ return '?';
+ }
+ }
+ else if (pfound->has_arg == 1)
+ {
+ if (GNoptind < argc)
+ GNoptarg = argv[GNoptind++];
+ else
+ {
+ if (GNopterr)
+ fprintf (stderr,
+ _("%s: option `%s' requires an argument\n"),
+ argv[0], argv[GNoptind - 1]);
+ nextchar += strlen (nextchar);
+ return optstring[0] == ':' ? ':' : '?';
+ }
+ }
+ nextchar += strlen (nextchar);
+ if (longind != NULL)
+ *longind = option_index;
+ if (pfound->flag)
+ {
+ *(pfound->flag) = pfound->val;
+ return 0;
+ }
+ return pfound->val;
+ }
+ nextchar = NULL;
+ return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':')
{
- if (temp[2] == ':')
- {
- /* This is an option that accepts an argument optionally. */
- if (*nextchar != '\0')
- {
- GNoptarg = nextchar;
- GNoptind++;
- }
- else
- GNoptarg = NULL;
- nextchar = NULL;
- }
- else
- {
- /* This is an option that requires an argument. */
- if (*nextchar != '\0')
- {
- GNoptarg = nextchar;
- /* If we end this ARGV-element by taking the rest as an arg,
- we must advance to the next element now. */
- GNoptind++;
- }
- else if (GNoptind == argc)
- {
- if (GNopterr)
- {
- /* 1003.2 specifies the format of this message. */
- fprintf (stderr,
- _("%s: option requires an argument -- %c\n"),
- argv[0], c);
- }
- GNoptopt = c;
- if (optstring[0] == ':')
- c = ':';
- else
- c = '?';
- }
- else
- /* We already incremented `GNoptind' once;
- increment it again when taking next ARGV-elt as argument. */
- GNoptarg = argv[GNoptind++];
- nextchar = NULL;
- }
+ if (temp[2] == ':')
+ {
+ /* This is an option that accepts an argument optionally. */
+ if (*nextchar != '\0')
+ {
+ GNoptarg = nextchar;
+ GNoptind++;
+ }
+ else
+ GNoptarg = NULL;
+ nextchar = NULL;
+ }
+ else
+ {
+ /* This is an option that requires an argument. */
+ if (*nextchar != '\0')
+ {
+ GNoptarg = nextchar;
+ /* If we end this ARGV-element by taking the rest as an arg,
+ we must advance to the next element now. */
+ GNoptind++;
+ }
+ else if (GNoptind == argc)
+ {
+ if (GNopterr)
+ {
+ /* 1003.2 specifies the format of this message. */
+ fprintf (stderr,
+ _("%s: option requires an argument -- %c\n"),
+ argv[0], c);
+ }
+ GNoptopt = c;
+ if (optstring[0] == ':')
+ c = ':';
+ else
+ c = '?';
+ }
+ else
+ /* We already incremented `GNoptind' once;
+ increment it again when taking next ARGV-elt as argument. */
+ GNoptarg = argv[GNoptind++];
+ nextchar = NULL;
+ }
}
return c;
}
}
static int
-GNgetopt_long(int argc,
- char * const * argv,
- const char * options,
- const struct GNoption * long_options,
- int * opt_index) {
- return GN_getopt_internal(argc,
- argv,
- options,
- long_options,
- opt_index,
- 0);
+GNgetopt_long (int argc,
+ char *const *argv,
+ const char *options,
+ const struct GNoption *long_options, int *opt_index)
+{
+ return GN_getopt_internal (argc, argv, options, long_options, opt_index, 0);
}
/* ******************** now the GNUnet specific modifications...
********************* */
@@ -995,44 +998,46 @@
* @return index into argv with first non-option
* argument, or -1 on error
*/
-int gnunet_parse_options(const char * binaryOptions,
- struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const CommandLineOption * allOptions,
- unsigned int argc,
- char * const * argv) {
- struct GNoption * long_options;
+int
+gnunet_parse_options (const char *binaryOptions,
+ struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const CommandLineOption * allOptions,
+ unsigned int argc, char *const *argv)
+{
+ struct GNoption *long_options;
CommandLineProcessorContext clpc;
int count;
int i;
- char * shorts;
+ char *shorts;
int spos;
int cont;
int c;
- GE_ASSERT(ectx, argc > 0);
+ GE_ASSERT (ectx, argc > 0);
clpc.binaryName = argv[0];
clpc.binaryOptions = binaryOptions;
clpc.allOptions = allOptions;
clpc.argv = argv;
clpc.argc = argc;
clpc.ectx = ectx;
- clpc.cfg = cfg;
+ clpc.cfg = cfg;
count = 0;
while (allOptions[count].name != NULL)
count++;
- long_options = MALLOC(sizeof(struct GNoption) * (count+1));
- shorts = MALLOC(count*2+1);
+ long_options = MALLOC (sizeof (struct GNoption) * (count + 1));
+ shorts = MALLOC (count * 2 + 1);
spos = 0;
- for (i=0;i<count;i++) {
- long_options[i].name = allOptions[i].name;
- long_options[i].has_arg = allOptions[i].require_argument;
- long_options[i].flag = NULL;
- long_options[i].val = allOptions[i].shortName;
- shorts[spos++] = allOptions[i].shortName;
- if (allOptions[i].require_argument != 0)
- shorts[spos++] = ':';
- }
+ for (i = 0; i < count; i++)
+ {
+ long_options[i].name = allOptions[i].name;
+ long_options[i].has_arg = allOptions[i].require_argument;
+ long_options[i].flag = NULL;
+ long_options[i].val = allOptions[i].shortName;
+ shorts[spos++] = allOptions[i].shortName;
+ if (allOptions[i].require_argument != 0)
+ shorts[spos++] = ':';
+ }
long_options[count].name = NULL;
long_options[count].has_arg = 0;
long_options[count].flag = NULL;
@@ -1040,37 +1045,36 @@
shorts[spos++] = '\0';
cont = OK;
/* main getopt loop */
- while (cont == OK) {
- int option_index = 0;
- c = GNgetopt_long(argc,
- argv,
- shorts,
- long_options,
- &option_index);
+ while (cont == OK)
+ {
+ int option_index = 0;
+ c = GNgetopt_long (argc, argv, shorts, long_options, &option_index);
- if (c == SYSERR)
- break; /* No more flags to process */
+ if (c == SYSERR)
+ break; /* No more flags to process */
- for (i=0;i<count;i++) {
- clpc.currentArgument = GNoptind - 1;
- if ((char)c == allOptions[i].shortName) {
- cont = allOptions[i].processor(&clpc,
- allOptions[i].scls,
- allOptions[i].name,
- GNoptarg);
- break;
- }
+ for (i = 0; i < count; i++)
+ {
+ clpc.currentArgument = GNoptind - 1;
+ if ((char) c == allOptions[i].shortName)
+ {
+ cont = allOptions[i].processor (&clpc,
+ allOptions[i].scls,
+ allOptions[i].name, GNoptarg);
+ break;
+ }
+ }
+ if (i == count)
+ {
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_IMMEDIATE,
+ _("Use --help to get a list of options.\n"));
+ cont = SYSERR;
+ }
}
- if (i == count) {
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_IMMEDIATE,
- _("Use --help to get a list of options.\n"));
- cont = SYSERR;
- }
- }
- FREE(shorts);
- FREE(long_options);
+ FREE (shorts);
+ FREE (long_options);
if (cont == SYSERR)
return SYSERR;
return GNoptind;
Modified: GNUnet/src/util/getopt/printhelp.c
===================================================================
--- GNUnet/src/util/getopt/printhelp.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/getopt/printhelp.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -30,93 +30,85 @@
#define BORDER 29
-int gnunet_getopt_format_help(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value) {
- const char * about = scls;
+int
+gnunet_getopt_format_help (CommandLineProcessorContext * ctx,
+ void *scls, const char *option, const char *value)
+{
+ const char *about = scls;
int slen;
int i;
int j;
int ml;
int p;
- char * scp;
- const char * trans;
- const struct CommandLineOption * opt;
+ char *scp;
+ const char *trans;
+ const struct CommandLineOption *opt;
- printf("%s\n%s\n",
- ctx->binaryOptions,
- gettext(about));
- printf(_("Arguments mandatory for long options are also mandatory for short
options.\n"));
+ printf ("%s\n%s\n", ctx->binaryOptions, gettext (about));
+ printf (_
+ ("Arguments mandatory for long options are also mandatory for short
options.\n"));
slen = 0;
i = 0;
opt = ctx->allOptions;
- while (opt[i].description != NULL) {
- if (opt[i].shortName == '\0')
- printf(" ");
- else
- printf(" -%c, ",
- opt[i].shortName);
- printf("--%s",
- opt[i].name);
- slen = 8 + strlen(opt[i].name);
- if (opt[i].argumentHelp != NULL) {
- printf("=%s",
- opt[i].argumentHelp);
- slen += 1+strlen(opt[i].argumentHelp);
+ while (opt[i].description != NULL)
+ {
+ if (opt[i].shortName == '\0')
+ printf (" ");
+ else
+ printf (" -%c, ", opt[i].shortName);
+ printf ("--%s", opt[i].name);
+ slen = 8 + strlen (opt[i].name);
+ if (opt[i].argumentHelp != NULL)
+ {
+ printf ("=%s", opt[i].argumentHelp);
+ slen += 1 + strlen (opt[i].argumentHelp);
+ }
+ if (slen > BORDER)
+ {
+ printf ("\n%*s", BORDER, "");
+ slen = BORDER;
+ }
+ if (slen < BORDER)
+ {
+ printf ("%*s", BORDER - slen, "");
+ slen = BORDER;
+ }
+ trans = gettext (opt[i].description);
+ ml = strlen (trans);
+ p = 0;
+ OUTER:
+ while (ml - p > 78 - slen)
+ {
+ for (j = p + 78 - slen; j > p; j--)
+ {
+ if (isspace (trans[j]))
+ {
+ scp = MALLOC (j - p + 1);
+ memcpy (scp, &trans[p], j - p);
+ scp[j - p] = '\0';
+ printf ("%s\n%*s", scp, BORDER + 2, "");
+ FREE (scp);
+ p = j + 1;
+ slen = BORDER + 2;
+ goto OUTER;
+ }
+ }
+ /* could not find space to break line */
+ scp = MALLOC (78 - slen + 1);
+ memcpy (scp, &trans[p], 78 - slen);
+ scp[78 - slen] = '\0';
+ printf ("%s\n%*s", scp, BORDER + 2, "");
+ FREE (scp);
+ slen = BORDER + 2;
+ p = p + 78 - slen;
+ }
+ /* print rest */
+ if (p < ml)
+ printf ("%s\n", &trans[p]);
+ if (strlen (trans) == 0)
+ printf ("\n");
+ i++;
}
- if (slen > BORDER) {
- printf("\n%*s", BORDER, "");
- slen = BORDER;
- }
- if (slen < BORDER) {
- printf("%*s", BORDER-slen, "");
- slen = BORDER;
- }
- trans = gettext(opt[i].description);
- ml = strlen(trans);
- p = 0;
- OUTER:
- while (ml - p > 78 - slen) {
- for (j=p+78-slen;j>p;j--) {
- if (isspace(trans[j])) {
- scp = MALLOC(j-p+1);
- memcpy(scp,
- &trans[p],
- j-p);
- scp[j-p] = '\0';
- printf("%s\n%*s",
- scp,
- BORDER+2,
- "");
- FREE(scp);
- p = j+1;
- slen = BORDER+2;
- goto OUTER;
- }
- }
- /* could not find space to break line */
- scp = MALLOC(78 - slen + 1);
- memcpy(scp,
- &trans[p],
- 78 - slen);
- scp[78 - slen] = '\0';
- printf("%s\n%*s",
- scp,
- BORDER+2,
- "");
- FREE(scp);
- slen = BORDER+2;
- p = p + 78 - slen;
- }
- /* print rest */
- if (p < ml)
- printf("%s\n",
- &trans[p]);
- if (strlen(trans) == 0)
- printf("\n");
- i++;
- }
return SYSERR;
}
Modified: GNUnet/src/util/getopt/printversion.c
===================================================================
--- GNUnet/src/util/getopt/printversion.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/getopt/printversion.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -28,15 +28,14 @@
#include "gnunet_util_getopt.h"
#include "platform.h"
-int gnunet_getopt_print_version(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value) {
- const char * version = scls;
+int
+gnunet_getopt_print_version (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option, const char *value)
+{
+ const char *version = scls;
- printf("%s v%s\n",
- ctx->binaryName,
- version);
+ printf ("%s v%s\n", ctx->binaryName, version);
return SYSERR;
}
Modified: GNUnet/src/util/getopt/setoption.c
===================================================================
--- GNUnet/src/util/getopt/setoption.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/getopt/setoption.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -30,75 +30,70 @@
#include "platform.h"
-int gnunet_getopt_configure_set_option(CommandLineProcessorContext * ctx,
- void * scls,
- const char * cmdLineOption,
- const char * value) {
- char * section = STRDUP(scls);
- struct GC_Configuration * cfg = ctx->cfg;
- char * option;
+int
+gnunet_getopt_configure_set_option (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *cmdLineOption,
+ const char *value)
+{
+ char *section = STRDUP (scls);
+ struct GC_Configuration *cfg = ctx->cfg;
+ char *option;
int ret;
- option = strstr(section, ":");
- GE_ASSERT(ctx->ectx,
- option != NULL);
+ option = strstr (section, ":");
+ GE_ASSERT (ctx->ectx, option != NULL);
option[0] = '\0';
option++;
if (value == NULL)
value = "YES";
- ret = GC_set_configuration_value_string(cfg,
- ctx->ectx,
- section,
- option,
- value);
+ ret = GC_set_configuration_value_string (cfg,
+ ctx->ectx, section, option, value);
- if (ret != 0) {
- GE_LOG(ctx->ectx,
- GE_USER | GE_BULK | GE_ERROR,
- _("Setting option `%s' in section `%s' to `%s' when processing command
line option `%s' was denied.\n"),
- option,
- section,
- value,
- cmdLineOption);
- FREE(section);
- return SYSERR;
- }
- FREE(section);
+ if (ret != 0)
+ {
+ GE_LOG (ctx->ectx,
+ GE_USER | GE_BULK | GE_ERROR,
+ _
+ ("Setting option `%s' in section `%s' to `%s' when processing
command line option `%s' was denied.\n"),
+ option, section, value, cmdLineOption);
+ FREE (section);
+ return SYSERR;
+ }
+ FREE (section);
return OK;
}
-int gnunet_getopt_configure_increment_value(CommandLineProcessorContext * ctx,
- void * scls,
- const char * cmdLineOption,
- const char * value) {
- char * section = STRDUP(scls);
- struct GC_Configuration * cfg = ctx->cfg;
- char * option;
+int
+gnunet_getopt_configure_increment_value (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *cmdLineOption,
+ const char *value)
+{
+ char *section = STRDUP (scls);
+ struct GC_Configuration *cfg = ctx->cfg;
+ char *option;
int ret;
unsigned long long old;
- option = strstr(section, ":");
- GE_ASSERT(ctx->ectx,
- option != NULL);
+ option = strstr (section, ":");
+ GE_ASSERT (ctx->ectx, option != NULL);
option[0] = '\0';
option++;
- ret = GC_get_configuration_value_number(cfg,
- section,
- option,
- 0,
- (unsigned long long) -1L,
- 0,
- &old);
- if (ret == SYSERR) {
- FREE(section);
- return SYSERR;
- }
- ret = GC_set_configuration_value_number(cfg,
- ctx->ectx,
- section,
- option,
- old+1);
- FREE(section);
+ ret = GC_get_configuration_value_number (cfg,
+ section,
+ option,
+ 0,
+ (unsigned long long) -1L, 0, &old);
+ if (ret == SYSERR)
+ {
+ FREE (section);
+ return SYSERR;
+ }
+ ret = GC_set_configuration_value_number (cfg,
+ ctx->ectx,
+ section, option, old + 1);
+ FREE (section);
if (ret == 0)
ret = OK;
else
@@ -106,54 +101,58 @@
return ret;
}
-int gnunet_getopt_configure_set_one(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value) {
- int * val = scls;
+int
+gnunet_getopt_configure_set_one (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option, const char *value)
+{
+ int *val = scls;
*val = 1;
return OK;
}
-int gnunet_getopt_configure_set_string(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value) {
- char ** val = scls;
+int
+gnunet_getopt_configure_set_string (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option, const char *value)
+{
+ char **val = scls;
- GE_ASSERT(NULL, value != NULL);
- *val = STRDUP(value);
+ GE_ASSERT (NULL, value != NULL);
+ *val = STRDUP (value);
return OK;
}
-int gnunet_getopt_configure_set_ulong(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value) {
- unsigned long long * val = scls;
- if (1 != SSCANF(value, "%llu", val)) {
- GE_LOG(ctx->ectx,
- GE_ERROR | GE_IMMEDIATE | GE_USER,
- _("You must pass a number to the `%s' option.\n"),
- "-X");
- return SYSERR;
- }
+int
+gnunet_getopt_configure_set_ulong (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option, const char *value)
+{
+ unsigned long long *val = scls;
+ if (1 != SSCANF (value, "%llu", val))
+ {
+ GE_LOG (ctx->ectx,
+ GE_ERROR | GE_IMMEDIATE | GE_USER,
+ _("You must pass a number to the `%s' option.\n"), "-X");
+ return SYSERR;
+ }
return OK;
}
-int gnunet_getopt_configure_set_uint(CommandLineProcessorContext * ctx,
- void * scls,
- const char * option,
- const char * value) {
- unsigned int * val = scls;
+int
+gnunet_getopt_configure_set_uint (CommandLineProcessorContext * ctx,
+ void *scls,
+ const char *option, const char *value)
+{
+ unsigned int *val = scls;
- if (1 != SSCANF(value, "%u", val)) {
- GE_LOG(ctx->ectx,
- GE_ERROR | GE_IMMEDIATE | GE_USER,
- _("You must pass a number to the `%s' option.\n"),
- "-X");
- return SYSERR;
- }
+ if (1 != SSCANF (value, "%u", val))
+ {
+ GE_LOG (ctx->ectx,
+ GE_ERROR | GE_IMMEDIATE | GE_USER,
+ _("You must pass a number to the `%s' option.\n"), "-X");
+ return SYSERR;
+ }
return OK;
}
Modified: GNUnet/src/util/loggers/file.c
===================================================================
--- GNUnet/src/util/loggers/file.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/loggers/file.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -24,7 +24,7 @@
*
* @author Christian Grothoff
*/
-#define _XOPEN_SOURCE /* glibc2 needs this */
+#define _XOPEN_SOURCE /* glibc2 needs this */
#include "gnunet_util_error_loggers.h"
#include "gnunet_util_string.h"
#include "gnunet_util.h"
@@ -34,33 +34,34 @@
/**
* Context for file logger.
*/
-typedef struct FileContext {
+typedef struct FileContext
+{
/**
* Error context for errors
*/
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
/**
* File handle used for logging.
*/
- FILE * handle;
+ FILE *handle;
/**
* Filename that we log to (mostly for printing
* error messages) and rotation.
*/
- char * filename;
+ char *filename;
/**
* Base filename (extended for log rotatation).
*/
- char * basename;
+ char *basename;
/**
* Lock.
*/
- struct MUTEX * lock;
+ struct MUTEX *lock;
/**
* Should we log the current date with each message?
@@ -93,23 +94,25 @@
} FileContext;
static char *
-getDateFormat() {
- char * datefmt;
+getDateFormat ()
+{
+ char *datefmt;
char *idx;
char c;
#if ENABLE_NLS
- datefmt = STRDUP(nl_langinfo(D_FMT));
+ datefmt = STRDUP (nl_langinfo (D_FMT));
#else
- datefmt = STRDUP("%Y-%m-%d");
+ datefmt = STRDUP ("%Y-%m-%d");
#endif
/* Remove slashes */
idx = datefmt;
- while ('\0' != (c = *idx)) {
- if ((c == '\\') || (c == '/'))
- *idx = '_';
- idx++;
- }
+ while ('\0' != (c = *idx))
+ {
+ if ((c == '\\') || (c == '/'))
+ *idx = '_';
+ idx++;
+ }
return datefmt;
}
@@ -117,48 +120,45 @@
* Remove file if it is an old log
*/
static int
-removeOldLog(const char * fil,
- const char * dir,
- void * ptr) {
- const FileContext * ctx = ptr;
+removeOldLog (const char *fil, const char *dir, void *ptr)
+{
+ const FileContext *ctx = ptr;
struct tm t;
- char * fullname;
- const char * logdate;
- const char * ret;
+ char *fullname;
+ const char *logdate;
+ const char *ret;
time_t curtime;
struct tm lcltime;
- const char * def;
- char * datefmt;
+ const char *def;
+ char *datefmt;
- time(&curtime);
- lcltime = *localtime(&curtime);
+ time (&curtime);
+ lcltime = *localtime (&curtime);
def = ctx->basename;
- fullname = MALLOC(strlen(dir) + strlen(fil) + 2);
- strcpy(fullname, dir);
- if (dir[strlen(dir)-1] != DIR_SEPARATOR)
- strcat(fullname, DIR_SEPARATOR_STR);
- strcat(fullname, fil);
- if (0 != strncmp(def,
- fullname,
- strlen(def))) {
- FREE(fullname);
- return OK;
- }
- logdate = &fullname[strlen(def)];
- datefmt = getDateFormat();
- ret = strptime(logdate, datefmt, &t);
- FREE(datefmt);
- if ( (ret == NULL) ||
- (ret[0] != '\0') ) {
- FREE(fullname);
- return OK; /* not a logfile */
- }
+ fullname = MALLOC (strlen (dir) + strlen (fil) + 2);
+ strcpy (fullname, dir);
+ if (dir[strlen (dir) - 1] != DIR_SEPARATOR)
+ strcat (fullname, DIR_SEPARATOR_STR);
+ strcat (fullname, fil);
+ if (0 != strncmp (def, fullname, strlen (def)))
+ {
+ FREE (fullname);
+ return OK;
+ }
+ logdate = &fullname[strlen (def)];
+ datefmt = getDateFormat ();
+ ret = strptime (logdate, datefmt, &t);
+ FREE (datefmt);
+ if ((ret == NULL) || (ret[0] != '\0'))
+ {
+ FREE (fullname);
+ return OK; /* not a logfile */
+ }
if (ctx->logrotate
+ t.tm_year * 365 + t.tm_yday
- - lcltime.tm_year * 365 - lcltime.tm_yday
- <= 0 )
- UNLINK(fullname); /* TODO: add ctx->fctx */
- FREE(fullname);
+ - lcltime.tm_year * 365 - lcltime.tm_yday <= 0)
+ UNLINK (fullname); /* TODO: add ctx->fctx */
+ FREE (fullname);
return OK;
}
@@ -167,133 +167,121 @@
* formatted for appending to the filename.
*/
static char *
-getLogFileName(struct GE_Context * fctx,
- const char * name) {
+getLogFileName (struct GE_Context *fctx, const char *name)
+{
time_t curtime;
struct tm lcltime;
- char * datefmt;
- char * ret;
+ char *datefmt;
+ char *ret;
char date[81];
size_t size;
- time(&curtime);
- lcltime = *localtime(&curtime);
- datefmt = getDateFormat();
+ time (&curtime);
+ lcltime = *localtime (&curtime);
+ datefmt = getDateFormat ();
#ifdef localtime_r
- localtime_r(&curtime, &lcltime);
+ localtime_r (&curtime, &lcltime);
#else
- lcltime = *localtime(&curtime);
+ lcltime = *localtime (&curtime);
#endif
- /* Format current date for filename*/
- GE_ASSERT(fctx,
- 0 != strftime(date,
- 80,
- datefmt,
- &lcltime));
- FREE(datefmt);
+ /* Format current date for filename */
+ GE_ASSERT (fctx, 0 != strftime (date, 80, datefmt, &lcltime));
+ FREE (datefmt);
/* Remove special chars */
- disk_filename_canonicalize(date);
+ disk_filename_canonicalize (date);
- size = strlen(name) + 82;
- ret = MALLOC(size);
- SNPRINTF(ret,
- size,
- "%s-%s",
- name,
- date);
+ size = strlen (name) + 82;
+ ret = MALLOC (size);
+ SNPRINTF (ret, size, "%s-%s", name, date);
return ret;
}
static void
-filelogger(void * cls,
- GE_KIND kind,
- const char * date,
- const char * msg) {
- FileContext * fctx = cls;
- char * name;
+filelogger (void *cls, GE_KIND kind, const char *date, const char *msg)
+{
+ FileContext *fctx = cls;
+ char *name;
int ret;
- char * dirname;
+ char *dirname;
- MUTEX_LOCK(fctx->lock);
- if (fctx->logrotate) {
- name = getLogFileName(fctx->ectx,
- fctx->basename);
- if ( (fctx->first_start == YES) ||
- (0 != strcmp(name,
- fctx->filename)) ) {
- fctx->first_start = NO;
- fclose(fctx->handle);
- fctx->handle = FOPEN(name, "a+");
- if (fctx->handle == NULL) {
- fctx->handle = stderr;
- fprintf(stderr,
- _("Failed to open log-file `%s': %s\n"),
- name,
- STRERROR(errno));
- }
- FREE(fctx->filename);
- fctx->filename = name;
- dirname = STRDUP(name);
- while ( (strlen(dirname) > 0) &&
- (dirname[strlen(dirname)-1] != DIR_SEPARATOR) )
- dirname[strlen(dirname)-1] = '\0';
- disk_directory_scan(fctx->ectx,
- dirname,
- &removeOldLog,
- fctx);
- FREE(dirname);
- } else {
- FREE(name);
+ MUTEX_LOCK (fctx->lock);
+ if (fctx->logrotate)
+ {
+ name = getLogFileName (fctx->ectx, fctx->basename);
+ if ((fctx->first_start == YES) || (0 != strcmp (name, fctx->filename)))
+ {
+ fctx->first_start = NO;
+ fclose (fctx->handle);
+ fctx->handle = FOPEN (name, "a+");
+ if (fctx->handle == NULL)
+ {
+ fctx->handle = stderr;
+ fprintf (stderr,
+ _("Failed to open log-file `%s': %s\n"),
+ name, STRERROR (errno));
+ }
+ FREE (fctx->filename);
+ fctx->filename = name;
+ dirname = STRDUP (name);
+ while ((strlen (dirname) > 0) &&
+ (dirname[strlen (dirname) - 1] != DIR_SEPARATOR))
+ dirname[strlen (dirname) - 1] = '\0';
+ disk_directory_scan (fctx->ectx, dirname, &removeOldLog, fctx);
+ FREE (dirname);
+ }
+ else
+ {
+ FREE (name);
+ }
}
- }
#ifdef WINDOWS
- /* Most tools disband the console window early in the initialization
- process, so we have to create a new one if we're logging to the
console. */
- if ((fctx->handle == stderr || fctx->handle == stdout)) {
- AllocConsole();
- SetConsoleTitle(_("GNUnet error log"));
+ /* Most tools disband the console window early in the initialization
+ process, so we have to create a new one if we're logging to the console.
*/
+ if ((fctx->handle == stderr || fctx->handle == stdout))
+ {
+ AllocConsole ();
+ SetConsoleTitle (_("GNUnet error log"));
}
#endif
- if (fctx->logdate) {
- ret = fprintf(fctx->handle,
- "%s %s: %s",
- date,
- GE_kindToString(kind & GE_EVENTKIND),
- msg);
- } else {
- ret = fprintf(fctx->handle,
- "%s: %s",
- GE_kindToString(kind & GE_EVENTKIND),
- msg);
- }
+ if (fctx->logdate)
+ {
+ ret = fprintf (fctx->handle,
+ "%s %s: %s",
+ date, GE_kindToString (kind & GE_EVENTKIND), msg);
+ }
+ else
+ {
+ ret = fprintf (fctx->handle,
+ "%s: %s", GE_kindToString (kind & GE_EVENTKIND), msg);
+ }
if (ret < 0)
- GE_LOG_STRERROR(fctx->ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE | GE_BULK,
- "fclose");
+ GE_LOG_STRERROR (fctx->ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE | GE_BULK,
+ "fclose");
- fflush(fctx->handle);
- MUTEX_UNLOCK(fctx->lock);
+ fflush (fctx->handle);
+ MUTEX_UNLOCK (fctx->lock);
}
static void
-fileclose(void * cls) {
- FileContext * fctx = cls;
+fileclose (void *cls)
+{
+ FileContext *fctx = cls;
- MUTEX_DESTROY(fctx->lock);
- FREENONNULL(fctx->filename);
- FREENONNULL(fctx->basename);
- if ( (fctx->handle != stderr) &&
- (fctx->handle != stdout) &&
- (0 != fclose(fctx->handle)) )
- GE_LOG_STRERROR(fctx->ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE | GE_BULK,
- "fclose");
- FREE(fctx);
+ MUTEX_DESTROY (fctx->lock);
+ FREENONNULL (fctx->filename);
+ FREENONNULL (fctx->basename);
+ if ((fctx->handle != stderr) &&
+ (fctx->handle != stdout) && (0 != fclose (fctx->handle)))
+ GE_LOG_STRERROR (fctx->ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE | GE_BULK,
+ "fclose");
+ FREE (fctx);
}
-
+
/**
* Create a logger that writes events to a file.
*
@@ -304,47 +292,45 @@
* files be deleted (use 0 for no rotation)
*/
struct GE_Context *
-GE_create_context_logfile(struct GE_Context * ectx,
- GE_KIND mask,
- const char * filename,
- int logDate,
- int logrotate) {
- FileContext * fctx;
- FILE * fd;
- char * name;
+GE_create_context_logfile (struct GE_Context *ectx,
+ GE_KIND mask,
+ const char *filename, int logDate, int logrotate)
+{
+ FileContext *fctx;
+ FILE *fd;
+ char *name;
TIME_T start;
- TIME(&start);
- if (logrotate != 0) {
- name = getLogFileName(NULL,
- filename);
- } else {
- name = STRDUP(filename);
- }
- fd = FOPEN(name, "a+");
- if (fd == NULL) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE | GE_BULK,
- "fopen",
- name);
- FREE(name);
- return NULL; /* ERROR! */
- }
- fctx = MALLOC(sizeof(FileContext));
+ TIME (&start);
+ if (logrotate != 0)
+ {
+ name = getLogFileName (NULL, filename);
+ }
+ else
+ {
+ name = STRDUP (filename);
+ }
+ fd = FOPEN (name, "a+");
+ if (fd == NULL)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE |
+ GE_BULK, "fopen", name);
+ FREE (name);
+ return NULL; /* ERROR! */
+ }
+ fctx = MALLOC (sizeof (FileContext));
fctx->first_start = YES;
fctx->ectx = ectx;
fctx->logdate = logDate;
fctx->logrotate = logrotate;
fctx->handle = fd;
fctx->filename = name;
- fctx->basename = STRDUP(filename);
+ fctx->basename = STRDUP (filename);
fctx->logstart = start;
- fctx->lock = MUTEX_CREATE(YES);
- return GE_create_context_callback(mask,
- &filelogger,
- fctx,
- &fileclose,
- NULL);
+ fctx->lock = MUTEX_CREATE (YES);
+ return GE_create_context_callback (mask,
+ &filelogger, fctx, &fileclose, NULL);
}
@@ -354,11 +340,11 @@
* @param mask which events should be logged?
*/
struct GE_Context *
-GE_create_context_stderr(int logDate,
- GE_KIND mask) {
- FileContext * fctx;
+GE_create_context_stderr (int logDate, GE_KIND mask)
+{
+ FileContext *fctx;
- fctx = MALLOC(sizeof(FileContext));
+ fctx = MALLOC (sizeof (FileContext));
fctx->ectx = NULL;
fctx->logdate = logDate;
fctx->logrotate = 0;
@@ -367,12 +353,9 @@
fctx->basename = NULL;
fctx->logstart = 0;
fctx->first_start = NO;
- fctx->lock = MUTEX_CREATE(YES);
- return GE_create_context_callback(mask,
- &filelogger,
- fctx,
- &fileclose,
- NULL);
+ fctx->lock = MUTEX_CREATE (YES);
+ return GE_create_context_callback (mask,
+ &filelogger, fctx, &fileclose, NULL);
}
@@ -382,11 +365,11 @@
* @param mask which events should be logged?
*/
struct GE_Context *
-GE_create_context_stdout(int logDate,
- GE_KIND mask) {
- FileContext * fctx;
+GE_create_context_stdout (int logDate, GE_KIND mask)
+{
+ FileContext *fctx;
- fctx = MALLOC(sizeof(FileContext));
+ fctx = MALLOC (sizeof (FileContext));
fctx->ectx = NULL;
fctx->logdate = logDate;
fctx->logrotate = 0;
@@ -395,11 +378,8 @@
fctx->filename = NULL;
fctx->basename = NULL;
fctx->logstart = 0;
- fctx->lock = MUTEX_CREATE(YES);
- return GE_create_context_callback(mask,
- &filelogger,
- fctx,
- &fileclose,
- NULL);
+ fctx->lock = MUTEX_CREATE (YES);
+ return GE_create_context_callback (mask,
+ &filelogger, fctx, &fileclose, NULL);
}
Modified: GNUnet/src/util/loggers/memory.c
===================================================================
--- GNUnet/src/util/loggers/memory.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/loggers/memory.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -29,53 +29,54 @@
#include "gnunet_util.h"
#include "platform.h"
-typedef struct GE_Message {
- char * date;
- char * msg;
+typedef struct GE_Message
+{
+ char *date;
+ char *msg;
GE_KIND mask;
} GE_Message;
-typedef struct GE_Memory {
- GE_Message * messages;
- struct MUTEX * lock;
+typedef struct GE_Memory
+{
+ GE_Message *messages;
+ struct MUTEX *lock;
unsigned int maxSize;
unsigned int size;
unsigned int pos;
} GE_Memory;
static void
-memorylogger(void * cls,
- GE_KIND kind,
- const char * date,
- const char * msg) {
- GE_Memory * ctx = cls;
+memorylogger (void *cls, GE_KIND kind, const char *date, const char *msg)
+{
+ GE_Memory *ctx = cls;
unsigned int max;
- MUTEX_LOCK(ctx->lock);
- if (ctx->pos == ctx->size) {
- if ( (ctx->maxSize != 0) &&
- (ctx->size == ctx->maxSize) ) {
- MUTEX_UNLOCK(ctx->lock);
- return;
+ MUTEX_LOCK (ctx->lock);
+ if (ctx->pos == ctx->size)
+ {
+ if ((ctx->maxSize != 0) && (ctx->size == ctx->maxSize))
+ {
+ MUTEX_UNLOCK (ctx->lock);
+ return;
+ }
+ max = ctx->pos * 2 + 16;
+ if ((ctx->maxSize == 0) && (max > ctx->maxSize))
+ max = ctx->maxSize;
+ GROW (ctx->messages, ctx->size, max);
}
- max = ctx->pos * 2 + 16;
- if ( (ctx->maxSize == 0) &&
- (max > ctx->maxSize) )
- max = ctx->maxSize;
- GROW(ctx->messages,
- ctx->size,
- max);
- }
- ctx->messages[ctx->pos].date = STRDUP(date);
- if (ctx->pos == ctx->maxSize-1) {
- ctx->messages[ctx->pos].msg = STRDUP(_("Out of memory (for logging)"));
- ctx->messages[ctx->pos].mask = GE_STATUS | GE_USER | GE_BULK;
- } else {
- ctx->messages[ctx->pos].msg = STRDUP(msg);
- ctx->messages[ctx->pos].mask = kind;
- }
+ ctx->messages[ctx->pos].date = STRDUP (date);
+ if (ctx->pos == ctx->maxSize - 1)
+ {
+ ctx->messages[ctx->pos].msg = STRDUP (_("Out of memory (for logging)"));
+ ctx->messages[ctx->pos].mask = GE_STATUS | GE_USER | GE_BULK;
+ }
+ else
+ {
+ ctx->messages[ctx->pos].msg = STRDUP (msg);
+ ctx->messages[ctx->pos].mask = kind;
+ }
ctx->pos++;
- MUTEX_UNLOCK(ctx->lock);
+ MUTEX_UNLOCK (ctx->lock);
}
/**
@@ -83,13 +84,9 @@
* queried later in bulk).
*/
struct GE_Context *
-GE_create_context_memory(GE_KIND mask,
- struct GE_Memory * memory) {
- return GE_create_context_callback(mask,
- &memorylogger,
- memory,
- NULL,
- NULL);
+GE_create_context_memory (GE_KIND mask, struct GE_Memory *memory)
+{
+ return GE_create_context_callback (mask, &memorylogger, memory, NULL, NULL);
}
/**
@@ -104,15 +101,16 @@
* will be set to a corresponding warning)
*/
struct GE_Memory *
-GE_memory_create(unsigned int maxSize) {
- GE_Memory * ret;
+GE_memory_create (unsigned int maxSize)
+{
+ GE_Memory *ret;
- ret = MALLOC(sizeof(GE_Memory));
+ ret = MALLOC (sizeof (GE_Memory));
ret->maxSize = maxSize;
ret->size = 0;
ret->pos = 0;
ret->messages = NULL;
- ret->lock = MUTEX_CREATE(NO);
+ ret->lock = MUTEX_CREATE (NO);
return ret;
}
@@ -120,8 +118,8 @@
* Get a particular log message from the store.
*/
const char *
-GE_memory_get(struct GE_Memory * memory,
- unsigned int index) {
+GE_memory_get (struct GE_Memory *memory, unsigned int index)
+{
if (index > memory->pos || memory->messages == NULL)
return NULL;
return memory->messages[index].msg;
@@ -131,48 +129,50 @@
* For all messages stored in the memory, call the handler.
* Also clears the memory.
*/
-void GE_memory_poll(struct GE_Memory * memory,
- GE_LogHandler handler,
- void * ctx) {
+void
+GE_memory_poll (struct GE_Memory *memory, GE_LogHandler handler, void *ctx)
+{
int i;
- MUTEX_LOCK(memory->lock);
- for (i=0;i<memory->pos;i++) {
- handler(ctx,
- memory->messages[i].mask,
- memory->messages[i].date,
- memory->messages[i].msg);
- FREE(memory->messages[i].date);
- FREE(memory->messages[i].msg);
- }
+ MUTEX_LOCK (memory->lock);
+ for (i = 0; i < memory->pos; i++)
+ {
+ handler (ctx,
+ memory->messages[i].mask,
+ memory->messages[i].date, memory->messages[i].msg);
+ FREE (memory->messages[i].date);
+ FREE (memory->messages[i].msg);
+ }
memory->pos = 0;
- MUTEX_UNLOCK(memory->lock);
+ MUTEX_UNLOCK (memory->lock);
}
-void GE_memory_reset(struct GE_Memory * memory) {
+void
+GE_memory_reset (struct GE_Memory *memory)
+{
int i;
- MUTEX_LOCK(memory->lock);
- for (i=memory->pos-1;i>=0;i--) {
- FREE(memory->messages[i].date);
- FREE(memory->messages[i].msg);
- }
- GROW(memory->messages,
- memory->size,
- 0);
- MUTEX_UNLOCK(memory->lock);
+ MUTEX_LOCK (memory->lock);
+ for (i = memory->pos - 1; i >= 0; i--)
+ {
+ FREE (memory->messages[i].date);
+ FREE (memory->messages[i].msg);
+ }
+ GROW (memory->messages, memory->size, 0);
+ MUTEX_UNLOCK (memory->lock);
}
-void GE_memory_free(struct GE_Memory * memory) {
+void
+GE_memory_free (struct GE_Memory *memory)
+{
int i;
- MUTEX_DESTROY(memory->lock);
- for (i=memory->pos-1;i>=0;i--) {
- FREE(memory->messages[i].date);
- FREE(memory->messages[i].msg);
- }
- GROW(memory->messages,
- memory->size,
- 0);
- FREE(memory);
+ MUTEX_DESTROY (memory->lock);
+ for (i = memory->pos - 1; i >= 0; i--)
+ {
+ FREE (memory->messages[i].date);
+ FREE (memory->messages[i].msg);
+ }
+ GROW (memory->messages, memory->size, 0);
+ FREE (memory);
}
Modified: GNUnet/src/util/loggers/smtp.c
===================================================================
--- GNUnet/src/util/loggers/smtp.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/loggers/smtp.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -35,13 +35,13 @@
* should be accumulated before an e-mail is transmitted?
*/
struct GE_Context *
-GE_create_context_email(struct GE_Context * ectx,
- GE_MASK mask,
- const char * address,
- const char * server,
- unsigned short port,
- int logDate,
- unsigned int bulkSize) {
+GE_create_context_email (struct GE_Context *ectx,
+ GE_MASK mask,
+ const char *address,
+ const char *server,
+ unsigned short port,
+ int logDate, unsigned int bulkSize)
+{
return NULL;
}
Modified: GNUnet/src/util/network/dns.c
===================================================================
--- GNUnet/src/util/network/dns.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/network/dns.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -34,10 +34,11 @@
#endif
-struct IPCache {
- struct IPCache * next;
- char * addr;
- struct sockaddr * sa;
+struct IPCache
+{
+ struct IPCache *next;
+ char *addr;
+ struct sockaddr *sa;
cron_t last_refresh;
cron_t last_request;
unsigned int salen;
@@ -47,139 +48,131 @@
#endif
};
-static struct IPCache * head;
+static struct IPCache *head;
-static struct MUTEX * lock;
+static struct MUTEX *lock;
#if HAVE_ADNS
static adns_state a_state;
#endif
-static void cache_resolve(struct IPCache * cache) {
+static void
+cache_resolve (struct IPCache *cache)
+{
#if HAVE_ADNS
- adns_answer * answer;
+ adns_answer *answer;
adns_status ret;
- struct IPCache * rec;
+ struct IPCache *rec;
int reti;
- if (cache->posted == NO) {
- ret = adns_submit_reverse(a_state,
- cache->sa,
- adns_r_ptr,
+ if (cache->posted == NO)
+ {
+ ret = adns_submit_reverse (a_state, cache->sa, adns_r_ptr,
#ifdef adns_qf_none
- adns_qf_none,
+ adns_qf_none,
#else
- 0,
+ 0,
#endif
- cache,
- &cache->query);
- if (adns_s_ok == ret)
- cache->posted = YES;
- }
- adns_processany(a_state);
+ cache, &cache->query);
+ if (adns_s_ok == ret)
+ cache->posted = YES;
+ }
+ adns_processany (a_state);
answer = NULL;
- reti = adns_check(a_state,
- &cache->query,
- &answer,
- (void**)&rec);
- if (reti == 0) {
- if (answer != NULL) {
- if ( (answer->rrs.str != NULL) &&
- (*(answer->rrs.str) != NULL) )
- cache->addr = STRDUP(*(answer->rrs.str));
- free(answer);
+ reti = adns_check (a_state, &cache->query, &answer, (void **) &rec);
+ if (reti == 0)
+ {
+ if (answer != NULL)
+ {
+ if ((answer->rrs.str != NULL) && (*(answer->rrs.str) != NULL))
+ cache->addr = STRDUP (*(answer->rrs.str));
+ free (answer);
+ }
+ cache->posted = NO;
}
- cache->posted = NO;
- }
#else
#if HAVE_GETNAMEINFO
char hostname[256];
- if (0 == getnameinfo(cache->sa,
- cache->salen,
- hostname,
- 255,
- NULL, 0,
- 0))
- cache->addr = STRDUP(hostname);
+ if (0 == getnameinfo (cache->sa, cache->salen, hostname, 255, NULL, 0, 0))
+ cache->addr = STRDUP (hostname);
#else
#if HAVE_GETHOSTBYADDR
- struct hostent * ent;
+ struct hostent *ent;
- switch (cache->sa->sa_family) {
- case AF_INET:
- ent = gethostbyaddr(&((struct sockaddr_in*) cache->sa)->sin_addr,
- sizeof(IPaddr),
- AF_INET);
- break;
- case AF_INET6:
- ent = gethostbyaddr(&((struct sockaddr_in6*) cache->sa)->sin6_addr,
- sizeof(IPaddr6),
- AF_INET6);
- break;
- default:
- ent = NULL;
- }
+ switch (cache->sa->sa_family)
+ {
+ case AF_INET:
+ ent = gethostbyaddr (&((struct sockaddr_in *) cache->sa)->sin_addr,
+ sizeof (IPaddr), AF_INET);
+ break;
+ case AF_INET6:
+ ent = gethostbyaddr (&((struct sockaddr_in6 *) cache->sa)->sin6_addr,
+ sizeof (IPaddr6), AF_INET6);
+ break;
+ default:
+ ent = NULL;
+ }
if (ent != NULL)
- cache->addr = STRDUP(ent->h_name);
+ cache->addr = STRDUP (ent->h_name);
#endif
#endif
#endif
}
static struct IPCache *
-resolve(const struct sockaddr * sa,
- unsigned int salen) {
- struct IPCache * ret;
+resolve (const struct sockaddr *sa, unsigned int salen)
+{
+ struct IPCache *ret;
- ret = MALLOC(sizeof(struct IPCache));
+ ret = MALLOC (sizeof (struct IPCache));
#if HAVE_ADNS
ret->posted = NO;
#endif
ret->next = head;
ret->salen = salen;
- ret->sa = salen == 0 ? NULL : MALLOC(salen);
- memcpy(ret->sa,
- sa,
- salen);
- ret->last_request = get_time();
- ret->last_refresh = get_time();
+ ret->sa = salen == 0 ? NULL : MALLOC (salen);
+ memcpy (ret->sa, sa, salen);
+ ret->last_request = get_time ();
+ ret->last_refresh = get_time ();
ret->addr = NULL;
- cache_resolve(ret);
+ cache_resolve (ret);
head = ret;
return ret;
}
-static char * no_resolve(const struct sockaddr * sa,
- unsigned int salen) {
- char * ret;
+static char *
+no_resolve (const struct sockaddr *sa, unsigned int salen)
+{
+ char *ret;
char inet6[INET6_ADDRSTRLEN];
- if (salen < sizeof(struct sockaddr))
+ if (salen < sizeof (struct sockaddr))
return NULL;
- switch (sa->sa_family) {
- case AF_INET:
- if (salen != sizeof(struct sockaddr_in))
- return NULL;
- ret = STRDUP("255.255.255.255");
- SNPRINTF(ret,
- strlen("255.255.255.255")+1,
- "%u.%u.%u.%u",
- PRIP(ntohl(*(int*)&((struct sockaddr_in*)sa)->sin_addr)));
- break;
- case AF_INET6:
- if (salen != sizeof(struct sockaddr_in6))
- return NULL;
- inet_ntop(AF_INET6,
- &((struct sockaddr_in6*) sa)->sin6_addr,
- inet6,
- INET6_ADDRSTRLEN);
- ret = STRDUP(inet6);
- break;
- default:
- ret = NULL;
- break;
- }
+ switch (sa->sa_family)
+ {
+ case AF_INET:
+ if (salen != sizeof (struct sockaddr_in))
+ return NULL;
+ ret = STRDUP ("255.255.255.255");
+ SNPRINTF (ret,
+ strlen ("255.255.255.255") + 1,
+ "%u.%u.%u.%u",
+ PRIP (ntohl
+ (*(int *) &((struct sockaddr_in *) sa)->sin_addr)));
+ break;
+ case AF_INET6:
+ if (salen != sizeof (struct sockaddr_in6))
+ return NULL;
+ inet_ntop (AF_INET6,
+ &((struct sockaddr_in6 *) sa)->sin6_addr,
+ inet6, INET6_ADDRSTRLEN);
+ ret = STRDUP (inet6);
+ break;
+ default:
+ ret = NULL;
+ break;
+ }
return ret;
}
@@ -191,105 +184,116 @@
*
* @param sa should be of type "struct sockaddr*"
*/
-char * network_get_ip_as_string(const void * sav,
- unsigned int salen,
- int do_resolve) {
- const struct sockaddr * sa = sav;
- char * ret;
- struct IPCache * cache;
- struct IPCache * prev;
+char *
+network_get_ip_as_string (const void *sav, unsigned int salen, int do_resolve)
+{
+ const struct sockaddr *sa = sav;
+ char *ret;
+ struct IPCache *cache;
+ struct IPCache *prev;
cron_t now;
- if (salen < sizeof(struct sockaddr))
+ if (salen < sizeof (struct sockaddr))
return NULL;
- now = get_time();
- MUTEX_LOCK(lock);
+ now = get_time ();
+ MUTEX_LOCK (lock);
cache = head;
prev = NULL;
- while ( (cache != NULL) &&
- ( (cache->salen != salen) ||
- (0 != memcmp(cache->sa,
- sa,
- salen) ) ) ) {
- if (cache->last_request + 60 * cronMINUTES < now) {
+ while ((cache != NULL) &&
+ ((cache->salen != salen) || (0 != memcmp (cache->sa, sa, salen))))
+ {
+ if (cache->last_request + 60 * cronMINUTES < now)
+ {
#if HAVE_ADNS
- if (cache->posted == YES) {
- adns_cancel(cache->query);
- cache->posted = NO;
- }
+ if (cache->posted == YES)
+ {
+ adns_cancel (cache->query);
+ cache->posted = NO;
+ }
#endif
- if (prev != NULL) {
- prev->next = cache->next;
- FREENONNULL(cache->addr);
- FREE(cache->sa);
- FREE(cache);
- cache = prev->next;
- } else {
- head = cache->next;
- FREENONNULL(cache->addr);
- FREE(cache->sa);
- FREE(cache);
- cache = head;
- }
- continue;
+ if (prev != NULL)
+ {
+ prev->next = cache->next;
+ FREENONNULL (cache->addr);
+ FREE (cache->sa);
+ FREE (cache);
+ cache = prev->next;
+ }
+ else
+ {
+ head = cache->next;
+ FREENONNULL (cache->addr);
+ FREE (cache->sa);
+ FREE (cache);
+ cache = head;
+ }
+ continue;
+ }
+ prev = cache;
+ cache = cache->next;
}
- prev = cache;
- cache = cache->next;
- }
- if (cache != NULL) {
- cache->last_request = now;
- if (cache->last_refresh + 12 * cronHOURS < now) {
- FREENONNULL(cache->addr);
- cache->addr = NULL;
- cache->salen = 0;
- cache_resolve(cache);
- }
+ if (cache != NULL)
+ {
+ cache->last_request = now;
+ if (cache->last_refresh + 12 * cronHOURS < now)
+ {
+ FREENONNULL (cache->addr);
+ cache->addr = NULL;
+ cache->salen = 0;
+ cache_resolve (cache);
+ }
#if HAVE_ADNS
- if (cache->posted == YES) {
- cache_resolve(cache);
+ if (cache->posted == YES)
+ {
+ cache_resolve (cache);
+ }
+#endif
}
-#endif
- } else if (do_resolve == NO) {
- MUTEX_UNLOCK(lock);
- return no_resolve(sav, salen);
- } else
- cache = resolve(sa, salen);
- ret = (cache->addr == NULL) ? NULL : STRDUP(cache->addr);
+ else if (do_resolve == NO)
+ {
+ MUTEX_UNLOCK (lock);
+ return no_resolve (sav, salen);
+ }
+ else
+ cache = resolve (sa, salen);
+ ret = (cache->addr == NULL) ? NULL : STRDUP (cache->addr);
if (ret == NULL)
- ret = no_resolve(sa, salen);
- MUTEX_UNLOCK(lock);
+ ret = no_resolve (sa, salen);
+ MUTEX_UNLOCK (lock);
return ret;
}
-void __attribute__ ((constructor)) gnunet_dns_ltdl_init() {
- lock = MUTEX_CREATE(YES);
+void __attribute__ ((constructor)) gnunet_dns_ltdl_init ()
+{
+ lock = MUTEX_CREATE (YES);
#if HAVE_ADNS
- adns_init(&a_state,
- adns_if_noerrprint,
- NULL);
+ adns_init (&a_state, adns_if_noerrprint, NULL);
#endif
}
-void __attribute__ ((destructor)) gnunet_dns_ltdl_fini() {
- struct IPCache * pos;
- MUTEX_DESTROY(lock);
- while (head != NULL) {
- pos = head->next;
+void __attribute__ ((destructor)) gnunet_dns_ltdl_fini ()
+{
+ struct IPCache *pos;
+ MUTEX_DESTROY (lock);
+ while (head != NULL)
+ {
+ pos = head->next;
#if HAVE_ADNS
- if (head->posted == YES) {
- adns_cancel(head->query);
- head->posted = NO;
- }
+ if (head->posted == YES)
+ {
+ adns_cancel (head->query);
+ head->posted = NO;
+ }
#endif
- FREENONNULL(head->addr);
- FREE(head->sa);
- FREE(head);
- head = pos;
- }
+ FREENONNULL (head->addr);
+ FREE (head->sa);
+ FREE (head);
+ head = pos;
+ }
#if HAVE_ADNS
- adns_finish(a_state);
+ adns_finish (a_state);
#endif
}
Modified: GNUnet/src/util/network/endian.c
===================================================================
--- GNUnet/src/util/network/endian.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/network/endian.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -27,19 +27,23 @@
#include "platform.h"
#include "gnunet_util_network.h"
-unsigned long long ntohll(unsigned long long n) {
+unsigned long long
+ntohll (unsigned long long n)
+{
#if __BYTE_ORDER == __BIG_ENDIAN
return n;
#else
- return (((unsigned long long)ntohl(n)) << 32) + ntohl(n >> 32);
+ return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
#endif
}
-unsigned long long htonll(unsigned long long n) {
+unsigned long long
+htonll (unsigned long long n)
+{
#if __BYTE_ORDER == __BIG_ENDIAN
return n;
#else
- return (((unsigned long long)htonl(n)) << 32) + htonl(n >> 32);
+ return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
#endif
}
Modified: GNUnet/src/util/network/io.c
===================================================================
--- GNUnet/src/util/network/io.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/network/io.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,32 +33,36 @@
/**
* Global lock for gethostbyname.
*/
-static struct MUTEX * lock;
+static struct MUTEX *lock;
#ifndef MINGW
-static struct SignalHandlerContext * sctx;
+static struct SignalHandlerContext *sctx;
-static void catcher() {
+static void
+catcher ()
+{
}
#endif
-void __attribute__ ((constructor)) gnunet_network_io_init() {
- lock = MUTEX_CREATE(NO);
+void __attribute__ ((constructor)) gnunet_network_io_init ()
+{
+ lock = MUTEX_CREATE (NO);
#ifndef MINGW
- sctx = signal_handler_install(SIGPIPE, &catcher);
+ sctx = signal_handler_install (SIGPIPE, &catcher);
#else
- InitWinEnv(NULL);
+ InitWinEnv (NULL);
#endif
}
-void __attribute__ ((destructor)) gnunet_network_io_fini() {
- MUTEX_DESTROY(lock);
+void __attribute__ ((destructor)) gnunet_network_io_fini ()
+{
+ MUTEX_DESTROY (lock);
lock = NULL;
#ifndef MINGW
- signal_handler_uninstall(SIGPIPE, &catcher, sctx);
+ signal_handler_uninstall (SIGPIPE, &catcher, sctx);
sctx = NULL;
#else
- ShutdownWinEnv();
+ ShutdownWinEnv ();
#endif
}
@@ -66,162 +70,158 @@
* Get the IP address of the given host.
* @return OK on success, SYSERR on error
*/
-int get_host_by_name(struct GE_Context * ectx,
- const char * hostname,
- IPaddr * ip) {
- struct hostent * he;
+int
+get_host_by_name (struct GE_Context *ectx, const char *hostname, IPaddr * ip)
+{
+ struct hostent *he;
/* slight hack: re-use config lock */
- MUTEX_LOCK(lock);
- he = GETHOSTBYNAME(hostname);
- if (he == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- _("Could not find IP of host `%s': %s\n"),
- hostname,
- hstrerror(h_errno));
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- if (he->h_addrtype != AF_INET) {
- GE_BREAK(ectx, 0);
- MUTEX_UNLOCK(lock);
- return SYSERR;
- }
- memcpy(ip,
- &((struct in_addr*)he->h_addr_list[0])->s_addr,
- sizeof(struct in_addr));
- MUTEX_UNLOCK(lock);
+ MUTEX_LOCK (lock);
+ he = GETHOSTBYNAME (hostname);
+ if (he == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK,
+ _("Could not find IP of host `%s': %s\n"),
+ hostname, hstrerror (h_errno));
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ if (he->h_addrtype != AF_INET)
+ {
+ GE_BREAK (ectx, 0);
+ MUTEX_UNLOCK (lock);
+ return SYSERR;
+ }
+ memcpy (ip,
+ &((struct in_addr *) he->h_addr_list[0])->s_addr,
+ sizeof (struct in_addr));
+ MUTEX_UNLOCK (lock);
return OK;
}
struct SocketHandle *
-socket_create(struct GE_Context * ectx,
- struct LoadMonitor * mon,
- int osSocket) {
- SocketHandle * ret;
+socket_create (struct GE_Context *ectx, struct LoadMonitor *mon, int osSocket)
+{
+ SocketHandle *ret;
- ret = MALLOC(sizeof(SocketHandle));
+ ret = MALLOC (sizeof (SocketHandle));
ret->ectx = ectx;
ret->mon = mon;
ret->handle = osSocket;
- ret->checksum = - ret->handle;
+ ret->checksum = -ret->handle;
return ret;
}
-void socket_close(struct SocketHandle * s) {
- GE_ASSERT(NULL, s != NULL);
- if ( (0 != SHUTDOWN(s->handle,
- SHUT_RDWR)) &&
+void
+socket_close (struct SocketHandle *s)
+{
+ GE_ASSERT (NULL, s != NULL);
+ if ((0 != SHUTDOWN (s->handle, SHUT_RDWR)) &&
#ifdef OSX
- (errno != EINVAL) && /* OS X returns these instead of ENOTCONN */
- (errno != EHOSTDOWN) &&
- (errno != EHOSTUNREACH) &&
+ (errno != EINVAL) && /* OS X returns these instead of ENOTCONN */
+ (errno != EHOSTDOWN) && (errno != EHOSTUNREACH) &&
#endif
- (errno != ENOTCONN) )
- GE_LOG_STRERROR(s->ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "shutdown");
- if (0 != CLOSE(s->handle))
- GE_LOG_STRERROR(s->ectx,
- GE_WARNING | GE_USER | GE_DEVELOPER | GE_BULK,
- "close");
+ (errno != ENOTCONN))
+ GE_LOG_STRERROR (s->ectx, GE_WARNING | GE_ADMIN | GE_BULK, "shutdown");
+ if (0 != CLOSE (s->handle))
+ GE_LOG_STRERROR (s->ectx,
+ GE_WARNING | GE_USER | GE_DEVELOPER | GE_BULK, "close");
s->handle = -1;
s->checksum = 1;
}
-void socket_destroy(struct SocketHandle * s) {
- GE_ASSERT(NULL, s != NULL);
- if (s->handle != -1) {
- if ( (0 != SHUTDOWN(s->handle,
- SHUT_RDWR)) &&
+void
+socket_destroy (struct SocketHandle *s)
+{
+ GE_ASSERT (NULL, s != NULL);
+ if (s->handle != -1)
+ {
+ if ((0 != SHUTDOWN (s->handle, SHUT_RDWR)) &&
#ifdef OSX
- (errno != EINVAL) && /* OS X returns these instead of ENOTCONN */
- (errno != EHOSTDOWN) &&
- (errno != EHOSTUNREACH) &&
+ (errno != EINVAL) && /* OS X returns these instead of ENOTCONN */
+ (errno != EHOSTDOWN) && (errno != EHOSTUNREACH) &&
#endif
- (errno != ENOTCONN) )
- GE_LOG_STRERROR(s->ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "shutdown");
- if (0 != CLOSE(s->handle))
- GE_LOG_STRERROR(s->ectx,
- GE_WARNING | GE_USER | GE_DEVELOPER | GE_BULK,
- "close");
- }
- FREE(s);
+ (errno != ENOTCONN))
+ GE_LOG_STRERROR (s->ectx,
+ GE_WARNING | GE_ADMIN | GE_BULK, "shutdown");
+ if (0 != CLOSE (s->handle))
+ GE_LOG_STRERROR (s->ectx,
+ GE_WARNING | GE_USER | GE_DEVELOPER | GE_BULK,
+ "close");
+ }
+ FREE (s);
}
/* TODO: log errors! */
#ifdef OSX
-static int socket_set_nosigpipe(struct SocketHandle * s,
- int dontSigPipe) {
- return setsockopt(s->handle,
- SOL_SOCKET, SO_NOSIGPIPE,
- (void *)&dontSigPipe,
- sizeof(dontSigPipe));
+static int
+socket_set_nosigpipe (struct SocketHandle *s, int dontSigPipe)
+{
+ return setsockopt (s->handle,
+ SOL_SOCKET, SO_NOSIGPIPE,
+ (void *) &dontSigPipe, sizeof (dontSigPipe));
}
#endif
/* TODO: log errors! */
-int socket_set_blocking(struct SocketHandle * s,
- int doBlock) {
+int
+socket_set_blocking (struct SocketHandle *s, int doBlock)
+{
#if MINGW
u_long mode;
mode = !doBlock;
- if (ioctlsocket(s->handle,
- FIONBIO, &mode) == SOCKET_ERROR) {
- SetErrnoFromWinsockError(WSAGetLastError());
+ if (ioctlsocket (s->handle, FIONBIO, &mode) == SOCKET_ERROR)
+ {
+ SetErrnoFromWinsockError (WSAGetLastError ());
- return -1;
- } else {
- /* store the blocking mode */
- __win_SetHandleBlockingMode(s->handle, doBlock);
- return 0;
- }
+ return -1;
+ }
+ else
+ {
+ /* store the blocking mode */
+ __win_SetHandleBlockingMode (s->handle, doBlock);
+ return 0;
+ }
#else
- int flags = fcntl(s->handle, F_GETFL);
+ int flags = fcntl (s->handle, F_GETFL);
if (doBlock)
flags &= ~O_NONBLOCK;
else
flags |= O_NONBLOCK;
- return fcntl(s->handle,
- F_SETFL,
- flags);
+ return fcntl (s->handle, F_SETFL, flags);
#endif
}
-int socket_test_blocking(struct SocketHandle * s)
+int
+socket_test_blocking (struct SocketHandle *s)
{
#ifndef MINGW
- return (fcntl(s->handle,
- F_GETFL) & O_NONBLOCK) ? NO : YES;
+ return (fcntl (s->handle, F_GETFL) & O_NONBLOCK) ? NO : YES;
#else
- return __win_IsHandleMarkedAsBlocking(s->handle);
+ return __win_IsHandleMarkedAsBlocking (s->handle);
#endif
}
-int socket_recv(struct SocketHandle * s,
- NC_KIND nc,
- void * buf,
- size_t max,
- size_t * read) {
+int
+socket_recv (struct SocketHandle *s,
+ NC_KIND nc, void *buf, size_t max, size_t * read)
+{
int flags;
size_t pos;
size_t ret;
- GE_ASSERT(NULL, s->checksum == - s->handle);
- socket_set_blocking(s,
- 0 != (nc & NC_Blocking));
+ GE_ASSERT (NULL, s->checksum == -s->handle);
+ socket_set_blocking (s, 0 != (nc & NC_Blocking));
flags = 0;
#ifdef CYGWIN
if (0 == (nc & NC_IgnoreInt))
flags |= MSG_NOSIGNAL;
#elif OSX
- socket_set_nosigpipe(s, 0 == (nc & NC_IgnoreInt));
+ socket_set_nosigpipe (s, 0 == (nc & NC_IgnoreInt));
if (0 == (nc & NC_Blocking))
flags |= MSG_DONTWAIT;
#elif SOMEBSD || SOLARIS
@@ -236,74 +236,69 @@
/* good luck */
#endif
pos = 0;
- do {
- GE_ASSERT(NULL, s->checksum == - s->handle);
- GE_ASSERT(NULL, max > pos);
- ret = (size_t) RECV(s->handle,
- &((char*)buf)[pos],
- max - pos,
- flags);
- GE_ASSERT(NULL, s->checksum == - s->handle);
- if ( (ret == (size_t) -1) &&
- (errno == EINTR) &&
- (0 != (nc & NC_IgnoreInt)) )
- continue;
- if ( (ret == (size_t) -1) ||
- (ret > max - pos) ) {
- if (errno == EINTR) {
- *read = pos;
- return YES;
- }
- if (errno == EWOULDBLOCK) {
- if (0 != (nc & NC_Blocking))
- continue;
- *read = pos;
- return (pos == 0) ? NO : YES;
- }
+ do
+ {
+ GE_ASSERT (NULL, s->checksum == -s->handle);
+ GE_ASSERT (NULL, max > pos);
+ ret = (size_t) RECV (s->handle, &((char *) buf)[pos], max - pos, flags);
+ GE_ASSERT (NULL, s->checksum == -s->handle);
+ if ((ret == (size_t) - 1) &&
+ (errno == EINTR) && (0 != (nc & NC_IgnoreInt)))
+ continue;
+ if ((ret == (size_t) - 1) || (ret > max - pos))
+ {
+ if (errno == EINTR)
+ {
+ *read = pos;
+ return YES;
+ }
+ if (errno == EWOULDBLOCK)
+ {
+ if (0 != (nc & NC_Blocking))
+ continue;
+ *read = pos;
+ return (pos == 0) ? NO : YES;
+ }
#if DEBUG_IO
- GE_LOG_STRERROR(s->ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "recv");
+ GE_LOG_STRERROR (s->ectx, GE_DEBUG | GE_USER | GE_REQUEST, "recv");
#endif
- *read = pos;
- return SYSERR;
+ *read = pos;
+ return SYSERR;
+ }
+ if (ret == 0)
+ {
+ /* most likely: other side closed connection */
+ *read = pos;
+ return SYSERR;
+ }
+ if (s->mon != NULL)
+ os_network_monitor_notify_transmission (s->mon, Download, ret);
+ GE_ASSERT (NULL, pos + ret >= pos);
+ pos += ret;
}
- if (ret == 0) {
- /* most likely: other side closed connection */
- *read = pos;
- return SYSERR;
- }
- if (s->mon != NULL)
- os_network_monitor_notify_transmission(s->mon,
- Download,
- ret);
- GE_ASSERT(NULL, pos + ret >= pos);
- pos += ret;
- } while ( (pos < max) &&
- (0 != (nc & NC_Blocking)) );
+ while ((pos < max) && (0 != (nc & NC_Blocking)));
*read = pos;
return YES;
}
-int socket_recv_from(struct SocketHandle * s,
- NC_KIND nc,
- void * buf,
- size_t max,
- size_t * read,
- char * from,
- unsigned int * fromlen) {
+int
+socket_recv_from (struct SocketHandle *s,
+ NC_KIND nc,
+ void *buf,
+ size_t max,
+ size_t * read, char *from, unsigned int *fromlen)
+{
int flags;
size_t pos;
size_t ret;
- socket_set_blocking(s,
- 0 != (nc & NC_Blocking));
+ socket_set_blocking (s, 0 != (nc & NC_Blocking));
flags = 0;
#ifdef CYGWIN
if (0 == (nc & NC_IgnoreInt))
flags |= MSG_NOSIGNAL;
#elif OSX
- socket_set_nosigpipe(s, 0 == (nc & NC_IgnoreInt));
+ socket_set_nosigpipe (s, 0 == (nc & NC_IgnoreInt));
if (0 == (nc & NC_Blocking))
flags |= MSG_DONTWAIT;
#elif SOMEBSD || SOLARIS
@@ -318,70 +313,66 @@
/* good luck */
#endif
pos = 0;
- do {
- ret = (size_t) RECVFROM(s->handle,
- &((char*)buf)[pos],
- max - pos,
- flags,
- (struct sockaddr*) from,
- fromlen);
- if ( (ret == (size_t) -1) &&
- (errno == EINTR) &&
- (0 != (nc & NC_IgnoreInt)) )
- continue;
- if ( (ret == (size_t) -1) ||
- (ret > max - pos) ) {
- if (errno == EINTR) {
- *read = pos;
- return YES;
- }
- if (errno == EWOULDBLOCK) {
- if (0 != (nc & NC_Blocking))
- continue;
- *read = pos;
- return (pos == 0) ? NO : YES;
- }
+ do
+ {
+ ret = (size_t) RECVFROM (s->handle,
+ &((char *) buf)[pos],
+ max - pos,
+ flags, (struct sockaddr *) from, fromlen);
+ if ((ret == (size_t) - 1) &&
+ (errno == EINTR) && (0 != (nc & NC_IgnoreInt)))
+ continue;
+ if ((ret == (size_t) - 1) || (ret > max - pos))
+ {
+ if (errno == EINTR)
+ {
+ *read = pos;
+ return YES;
+ }
+ if (errno == EWOULDBLOCK)
+ {
+ if (0 != (nc & NC_Blocking))
+ continue;
+ *read = pos;
+ return (pos == 0) ? NO : YES;
+ }
#if DEBUG_IO
- GE_LOG_STRERROR(s->ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "recvfrom");
+ GE_LOG_STRERROR (s->ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST, "recvfrom");
#endif
- *read = pos;
- return SYSERR;
+ *read = pos;
+ return SYSERR;
+ }
+ if (ret == 0)
+ {
+ /* most likely: other side closed connection */
+ *read = pos;
+ return SYSERR;
+ }
+ if (s->mon != NULL)
+ os_network_monitor_notify_transmission (s->mon, Download, ret);
+ pos += ret;
}
- if (ret == 0) {
- /* most likely: other side closed connection */
- *read = pos;
- return SYSERR;
- }
- if (s->mon != NULL)
- os_network_monitor_notify_transmission(s->mon,
- Download,
- ret);
- pos += ret;
- } while ( (pos < max) &&
- (0 != (nc & NC_Blocking)) );
+ while ((pos < max) && (0 != (nc & NC_Blocking)));
*read = pos;
return YES;
}
-int socket_send(struct SocketHandle * s,
- NC_KIND nc,
- const void * buf,
- size_t max,
- size_t * sent) {
+int
+socket_send (struct SocketHandle *s,
+ NC_KIND nc, const void *buf, size_t max, size_t * sent)
+{
int flags;
size_t pos;
size_t ret;
- socket_set_blocking(s,
- 0 != (nc & NC_Blocking));
+ socket_set_blocking (s, 0 != (nc & NC_Blocking));
flags = 0;
#if SOMEBSD || SOLARIS
if (0 == (nc & NC_Blocking))
flags |= MSG_DONTWAIT;
#elif OSX
- socket_set_nosigpipe(s, 0 == (nc & NC_IgnoreInt));
+ socket_set_nosigpipe (s, 0 == (nc & NC_IgnoreInt));
if (0 == (nc & NC_Blocking))
flags |= MSG_DONTWAIT;
#elif CYGWIN
@@ -397,70 +388,65 @@
#endif
pos = 0;
- do {
- ret = (size_t) SEND(s->handle,
- &((char*)buf)[pos],
- max - pos,
- flags);
- if ( (ret == (size_t) -1) &&
- (errno == EINTR) &&
- (0 != (nc & NC_IgnoreInt)) )
- continue;
- if ( (ret == (size_t) -1) ||
- (ret > max - pos) ) {
- if (errno == EINTR) {
- *sent = pos;
- return YES;
- }
- if (errno == EWOULDBLOCK) {
- if (0 != (nc & NC_Blocking))
- continue;
- *sent = pos;
- return (pos == 0) ? NO : YES;
- }
+ do
+ {
+ ret = (size_t) SEND (s->handle, &((char *) buf)[pos], max - pos, flags);
+ if ((ret == (size_t) - 1) &&
+ (errno == EINTR) && (0 != (nc & NC_IgnoreInt)))
+ continue;
+ if ((ret == (size_t) - 1) || (ret > max - pos))
+ {
+ if (errno == EINTR)
+ {
+ *sent = pos;
+ return YES;
+ }
+ if (errno == EWOULDBLOCK)
+ {
+ if (0 != (nc & NC_Blocking))
+ continue;
+ *sent = pos;
+ return (pos == 0) ? NO : YES;
+ }
#if DEBUG_IO
- GE_LOG_STRERROR(s->ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "send");
+ GE_LOG_STRERROR (s->ectx, GE_DEBUG | GE_USER | GE_REQUEST, "send");
#endif
- *sent = pos;
- return SYSERR;
+ *sent = pos;
+ return SYSERR;
+ }
+ if (ret == 0)
+ {
+ /* strange error; most likely: other side closed connection */
+ *sent = pos;
+ return SYSERR;
+ }
+ if (s->mon != NULL)
+ os_network_monitor_notify_transmission (s->mon, Upload, ret);
+ pos += ret;
}
- if (ret == 0) {
- /* strange error; most likely: other side closed connection */
- *sent = pos;
- return SYSERR;
- }
- if (s->mon != NULL)
- os_network_monitor_notify_transmission(s->mon,
- Upload,
- ret);
- pos += ret;
- } while ( (pos < max) &&
- (0 != (nc & NC_Blocking)) );
+ while ((pos < max) && (0 != (nc & NC_Blocking)));
*sent = pos;
return YES;
}
-int socket_send_to(struct SocketHandle * s,
- NC_KIND nc,
- const void * buf,
- size_t max,
- size_t * sent,
- const char * dst,
- unsigned int dstlen) {
+int
+socket_send_to (struct SocketHandle *s,
+ NC_KIND nc,
+ const void *buf,
+ size_t max,
+ size_t * sent, const char *dst, unsigned int dstlen)
+{
int flags;
size_t pos;
size_t ret;
- socket_set_blocking(s,
- 0 != (nc & NC_Blocking));
+ socket_set_blocking (s, 0 != (nc & NC_Blocking));
flags = 0;
#if SOMEBSD || SOLARIS
if (0 == (nc & NC_Blocking))
flags |= MSG_DONTWAIT;
#elif OSX
- socket_set_nosigpipe(s, 0 == (nc & NC_IgnoreInt));
+ socket_set_nosigpipe (s, 0 == (nc & NC_IgnoreInt));
if (0 == (nc & NC_Blocking))
flags |= MSG_DONTWAIT;
#elif CYGWIN
@@ -476,49 +462,47 @@
#endif
pos = 0;
- do {
- ret = (size_t) SENDTO(s->handle,
- &((char*)buf)[pos],
- max - pos,
- flags,
- (const struct sockaddr*) dst,
- dstlen);
- if ( (ret == (size_t) -1) &&
- (errno == EINTR) &&
- (0 != (nc & NC_IgnoreInt)) )
- continue;
- if ( (ret == (size_t) -1) ||
- (ret > max - pos) ) {
- if (errno == EINTR) {
- *sent = pos;
- return YES;
- }
- if (errno == EWOULDBLOCK) {
- if (0 != (nc & NC_Blocking))
- continue;
- *sent = pos;
- return (pos == 0) ? NO : YES;
- }
+ do
+ {
+ ret = (size_t) SENDTO (s->handle,
+ &((char *) buf)[pos],
+ max - pos,
+ flags, (const struct sockaddr *) dst, dstlen);
+ if ((ret == (size_t) - 1) &&
+ (errno == EINTR) && (0 != (nc & NC_IgnoreInt)))
+ continue;
+ if ((ret == (size_t) - 1) || (ret > max - pos))
+ {
+ if (errno == EINTR)
+ {
+ *sent = pos;
+ return YES;
+ }
+ if (errno == EWOULDBLOCK)
+ {
+ if (0 != (nc & NC_Blocking))
+ continue;
+ *sent = pos;
+ return (pos == 0) ? NO : YES;
+ }
#if DEBUG_IO
- GE_LOG_STRERROR(s->ectx,
- GE_DEBUG | GE_USER | GE_REQUEST,
- "sendto");
+ GE_LOG_STRERROR (s->ectx,
+ GE_DEBUG | GE_USER | GE_REQUEST, "sendto");
#endif
- *sent = pos;
- return SYSERR;
+ *sent = pos;
+ return SYSERR;
+ }
+ if (ret == 0)
+ {
+ /* strange error; most likely: other side closed connection */
+ *sent = pos;
+ return SYSERR;
+ }
+ if (s->mon != NULL)
+ os_network_monitor_notify_transmission (s->mon, Upload, ret);
+ pos += ret;
}
- if (ret == 0) {
- /* strange error; most likely: other side closed connection */
- *sent = pos;
- return SYSERR;
- }
- if (s->mon != NULL)
- os_network_monitor_notify_transmission(s->mon,
- Upload,
- ret);
- pos += ret;
- } while ( (pos < max) &&
- (0 != (nc & NC_Blocking)) );
+ while ((pos < max) && (0 != (nc & NC_Blocking)));
*sent = pos;
return YES;
}
@@ -527,16 +511,15 @@
* Check if socket is valid
* @return 1 if valid, 0 otherwise
*/
-int socket_test_valid(struct SocketHandle * s) {
+int
+socket_test_valid (struct SocketHandle *s)
+{
#ifndef MINGW
struct stat buf;
- return -1 != fstat(s->handle,
- &buf);
+ return -1 != fstat (s->handle, &buf);
#else
long l;
- return ioctlsocket(s->handle,
- FIONREAD,
- &l) != SOCKET_ERROR;
+ return ioctlsocket (s->handle, FIONREAD, &l) != SOCKET_ERROR;
#endif
}
Modified: GNUnet/src/util/network/ip.c
===================================================================
--- GNUnet/src/util/network/ip.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/network/ip.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -49,71 +49,72 @@
* (connection information), conInfo.
* @return SYSERR on failure, OK on success
*/
-static int getAddressFromHostname(struct GE_Context * ectx,
- IPaddr * identity) {
+static int
+getAddressFromHostname (struct GE_Context *ectx, IPaddr * identity)
+{
char hostname[MAX_HOSTNAME];
int ret;
- if (0 != gethostname(hostname, MAX_HOSTNAME)) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "gethostname");
- return SYSERR;
- }
- ret = get_host_by_name(ectx,
- hostname,
- identity);
+ if (0 != gethostname (hostname, MAX_HOSTNAME))
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "gethostname");
+ return SYSERR;
+ }
+ ret = get_host_by_name (ectx, hostname, identity);
return ret;
}
#if HAVE_GETIFADDRS && HAVE_FREEIFADDRS
-static int getAddressFromGetIfAddrs(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- IPaddr * identity) {
- char * interfaces;
+static int
+getAddressFromGetIfAddrs (struct GC_Configuration *cfg,
+ struct GE_Context *ectx, IPaddr * identity)
+{
+ char *interfaces;
struct ifaddrs *ifa_first;
- if (-1 == GC_get_configuration_value_string(cfg,
- "NETWORK",
- "INTERFACE",
- "eth0",
- &interfaces)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("No interface specified in section `%s' under `%s'!\n"),
- "NETWORK",
- "INTERFACE");
- return SYSERR; /* that won't work! */
- }
+ if (-1 == GC_get_configuration_value_string (cfg,
+ "NETWORK",
+ "INTERFACE",
+ "eth0", &interfaces))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("No interface specified in section `%s' under `%s'!\n"),
+ "NETWORK", "INTERFACE");
+ return SYSERR; /* that won't work! */
+ }
- if (getifaddrs(&ifa_first) == 0) {
- struct ifaddrs *ifa_ptr;
+ if (getifaddrs (&ifa_first) == 0)
+ {
+ struct ifaddrs *ifa_ptr;
- ifa_ptr = ifa_first;
- for (ifa_ptr = ifa_first; ifa_ptr != NULL; ifa_ptr = ifa_ptr->ifa_next) {
- if (ifa_ptr->ifa_name != NULL &&
- ifa_ptr->ifa_addr != NULL &&
- (ifa_ptr->ifa_flags & IFF_UP) != 0) {
- if (strcmp(interfaces, (char *)ifa_ptr->ifa_name) != 0)
- continue;
- if (ifa_ptr->ifa_addr->sa_family != AF_INET)
- continue;
- memcpy(identity,
- &(((struct sockaddr_in *)ifa_ptr->ifa_addr)->sin_addr),
- sizeof(struct in_addr));
- freeifaddrs(ifa_first);
- FREE(interfaces);
- return OK;
- }
+ ifa_ptr = ifa_first;
+ for (ifa_ptr = ifa_first; ifa_ptr != NULL; ifa_ptr = ifa_ptr->ifa_next)
+ {
+ if (ifa_ptr->ifa_name != NULL &&
+ ifa_ptr->ifa_addr != NULL && (ifa_ptr->ifa_flags & IFF_UP) != 0)
+ {
+ if (strcmp (interfaces, (char *) ifa_ptr->ifa_name) != 0)
+ continue;
+ if (ifa_ptr->ifa_addr->sa_family != AF_INET)
+ continue;
+ memcpy (identity,
+ &(((struct sockaddr_in *) ifa_ptr->ifa_addr)->sin_addr),
+ sizeof (struct in_addr));
+ freeifaddrs (ifa_first);
+ FREE (interfaces);
+ return OK;
+ }
+ }
+ freeifaddrs (ifa_first);
}
- freeifaddrs(ifa_first);
- }
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Could not obtain IP for interface `%s' using `%s'.\n"),
- interfaces,
- "getifaddrs");
- FREE(interfaces);
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Could not obtain IP for interface `%s' using `%s'.\n"),
+ interfaces, "getifaddrs");
+ FREE (interfaces);
return SYSERR;
}
#endif
@@ -121,225 +122,209 @@
#if LINUX || SOMEBSD || MINGW
#define MAX_INTERFACES 16
-static int getAddressFromIOCTL(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- IPaddr * identity) {
- char * interfaces;
+static int
+getAddressFromIOCTL (struct GC_Configuration *cfg,
+ struct GE_Context *ectx, IPaddr * identity)
+{
+ char *interfaces;
#ifndef MINGW
struct ifreq ifr[MAX_INTERFACES];
struct ifconf ifc;
- int sockfd,ifCount;
+ int sockfd, ifCount;
#else
DWORD dwIP;
#endif
int i;
- if (-1 == GC_get_configuration_value_string(cfg,
- "NETWORK",
- "INTERFACE",
- "eth0",
- &interfaces)) {
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- _("No interface specified in section `%s' under `%s'!\n"),
- "NETWORK",
- "INTERFACE");
- return SYSERR; /* that won't work! */
- }
+ if (-1 == GC_get_configuration_value_string (cfg,
+ "NETWORK",
+ "INTERFACE",
+ "eth0", &interfaces))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ _("No interface specified in section `%s' under `%s'!\n"),
+ "NETWORK", "INTERFACE");
+ return SYSERR; /* that won't work! */
+ }
#ifndef MINGW
- sockfd = SOCKET(PF_INET, SOCK_DGRAM, 0);
- if (sockfd == -1) {
- FREE(interfaces);
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "socket");
- return SYSERR;
- }
- memset(&ifc,
- 0,
- sizeof(struct ifconf));
- ifc.ifc_len = sizeof(ifr);
- ifc.ifc_buf = (char*)𝔦
+ sockfd = SOCKET (PF_INET, SOCK_DGRAM, 0);
+ if (sockfd == -1)
+ {
+ FREE (interfaces);
+ GE_LOG_STRERROR (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK, "socket");
+ return SYSERR;
+ }
+ memset (&ifc, 0, sizeof (struct ifconf));
+ ifc.ifc_len = sizeof (ifr);
+ ifc.ifc_buf = (char *) 𝔦
- if (ioctl(sockfd,
- SIOCGIFCONF,
- &ifc) == -1) {
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
- "ioctl");
- if (0 != CLOSE(sockfd))
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "close");
- FREE(interfaces);
- return SYSERR;
- }
- ifCount = ifc.ifc_len / sizeof(struct ifreq);
+ if (ioctl (sockfd, SIOCGIFCONF, &ifc) == -1)
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_WARNING | GE_ADMIN | GE_USER | GE_BULK, "ioctl");
+ if (0 != CLOSE (sockfd))
+ GE_LOG_STRERROR (ectx, GE_WARNING | GE_ADMIN | GE_BULK, "close");
+ FREE (interfaces);
+ return SYSERR;
+ }
+ ifCount = ifc.ifc_len / sizeof (struct ifreq);
/* first, try to find exatly matching interface */
- for (i=0;i<ifCount;i++){
- if (ioctl(sockfd, SIOCGIFADDR, &ifr[i]) != 0)
- continue;
- if (ioctl(sockfd, SIOCGIFFLAGS, &ifr[i]) != 0)
- continue;
- if (!(ifr[i].ifr_flags & IFF_UP))
- continue;
- if (strcmp((char*) interfaces,
- (char*) ifr[i].ifr_name) != 0)
- continue;
- memcpy(identity,
- &(((struct sockaddr_in *)&ifr[i].ifr_addr)->sin_addr),
- sizeof(struct in_addr));
- if (0 != CLOSE(sockfd))
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "close");
- FREE(interfaces);
- return OK;
- }
- GE_LOG(ectx,
- GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
- _("Could not find interface `%s' using `%s', "
- "trying to find another interface.\n"),
- interfaces,
- "ioctl");
+ for (i = 0; i < ifCount; i++)
+ {
+ if (ioctl (sockfd, SIOCGIFADDR, &ifr[i]) != 0)
+ continue;
+ if (ioctl (sockfd, SIOCGIFFLAGS, &ifr[i]) != 0)
+ continue;
+ if (!(ifr[i].ifr_flags & IFF_UP))
+ continue;
+ if (strcmp ((char *) interfaces, (char *) ifr[i].ifr_name) != 0)
+ continue;
+ memcpy (identity,
+ &(((struct sockaddr_in *) &ifr[i].ifr_addr)->sin_addr),
+ sizeof (struct in_addr));
+ if (0 != CLOSE (sockfd))
+ GE_LOG_STRERROR (ectx, GE_WARNING | GE_ADMIN | GE_BULK, "close");
+ FREE (interfaces);
+ return OK;
+ }
+ GE_LOG (ectx,
+ GE_WARNING | GE_ADMIN | GE_USER | GE_BULK,
+ _("Could not find interface `%s' using `%s', "
+ "trying to find another interface.\n"), interfaces, "ioctl");
/* if no such interface exists, take any interface but loopback */
- for (i=0;i<ifCount;i++){
- if (ioctl(sockfd, SIOCGIFADDR, &ifr[i]) != 0)
- continue;
- if (ioctl(sockfd, SIOCGIFFLAGS, &ifr[i]) != 0)
- continue;
- if (!(ifr[i].ifr_flags & IFF_UP))
- continue;
- if (strncmp("lo",
- (char*) ifr[i].ifr_name, 2) == 0)
- continue;
- memcpy(identity,
- &(((struct sockaddr_in *)&ifr[i].ifr_addr)->sin_addr),
- sizeof(struct in_addr));
- if (0 != CLOSE(sockfd))
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "close");
- FREE(interfaces);
- return OK;
- }
+ for (i = 0; i < ifCount; i++)
+ {
+ if (ioctl (sockfd, SIOCGIFADDR, &ifr[i]) != 0)
+ continue;
+ if (ioctl (sockfd, SIOCGIFFLAGS, &ifr[i]) != 0)
+ continue;
+ if (!(ifr[i].ifr_flags & IFF_UP))
+ continue;
+ if (strncmp ("lo", (char *) ifr[i].ifr_name, 2) == 0)
+ continue;
+ memcpy (identity,
+ &(((struct sockaddr_in *) &ifr[i].ifr_addr)->sin_addr),
+ sizeof (struct in_addr));
+ if (0 != CLOSE (sockfd))
+ GE_LOG_STRERROR (ectx, GE_WARNING | GE_ADMIN | GE_BULK, "close");
+ FREE (interfaces);
+ return OK;
+ }
- if (0 != CLOSE(sockfd))
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "close");
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Could not obtain IP for interface `%s' using `%s'.\n"),
- interfaces,
- "ioctl");
- FREE(interfaces);
+ if (0 != CLOSE (sockfd))
+ GE_LOG_STRERROR (ectx, GE_WARNING | GE_ADMIN | GE_BULK, "close");
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Could not obtain IP for interface `%s' using `%s'.\n"),
+ interfaces, "ioctl");
+ FREE (interfaces);
return SYSERR;
#else /* MinGW */
/* Win 98 or Win NT SP 4 */
if (GNGetIpAddrTable)
- {
- PMIB_IFTABLE pTable;
- PMIB_IPADDRTABLE pAddrTable;
- DWORD dwIfIdx;
- unsigned int iAddrCount = 0;
+ {
+ PMIB_IFTABLE pTable;
+ PMIB_IPADDRTABLE pAddrTable;
+ DWORD dwIfIdx;
+ unsigned int iAddrCount = 0;
- dwIP = 0;
+ dwIP = 0;
- EnumNICs(&pTable, &pAddrTable);
+ EnumNICs (&pTable, &pAddrTable);
- for(dwIfIdx=0; dwIfIdx < pTable->dwNumEntries; dwIfIdx++) {
- unsigned long long l;
- BYTE bPhysAddr[MAXLEN_PHYSADDR];
+ for (dwIfIdx = 0; dwIfIdx < pTable->dwNumEntries; dwIfIdx++)
+ {
+ unsigned long long l;
+ BYTE bPhysAddr[MAXLEN_PHYSADDR];
- l = _atoi64(interfaces);
+ l = _atoi64 (interfaces);
- memset(bPhysAddr, 0, MAXLEN_PHYSADDR);
- memcpy(bPhysAddr,
- pTable->table[dwIfIdx].bPhysAddr,
- pTable->table[dwIfIdx].dwPhysAddrLen);
+ memset (bPhysAddr, 0, MAXLEN_PHYSADDR);
+ memcpy (bPhysAddr,
+ pTable->table[dwIfIdx].bPhysAddr,
+ pTable->table[dwIfIdx].dwPhysAddrLen);
- if (memcmp(bPhysAddr, &l, sizeof(l)) == 0) {
- for(i = 0; i < pAddrTable->dwNumEntries; i++) {
- if (pAddrTable->table[i].dwIndex
- == pTable->table[dwIfIdx].dwIndex) {
- iAddrCount++;
- dwIP = pAddrTable->table[i].dwAddr;
- }
+ if (memcmp (bPhysAddr, &l, sizeof (l)) == 0)
+ {
+ for (i = 0; i < pAddrTable->dwNumEntries; i++)
+ {
+ if (pAddrTable->table[i].dwIndex
+ == pTable->table[dwIfIdx].dwIndex)
+ {
+ iAddrCount++;
+ dwIP = pAddrTable->table[i].dwAddr;
+ }
+ }
+ }
}
- }
- }
- if (! iAddrCount)
- {
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("Could not find an IP address for "
- "interface `%s'.\n"),
- interfaces);
+ if (!iAddrCount)
+ {
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("Could not find an IP address for "
+ "interface `%s'.\n"), interfaces);
- GlobalFree(pTable);
- GlobalFree(pAddrTable);
- return SYSERR;
- }
- else if (iAddrCount > 1)
- GE_LOG(ectx, GE_WARNING | GE_BULK | GE_USER,
- _("There is more than one IP address specified"
- " for interface `%s'.\nGNUnet will "
- "use %u.%u.%u.%u.\n"),
- interfaces,
- PRIP(ntohl(dwIP)));
+ GlobalFree (pTable);
+ GlobalFree (pAddrTable);
+ return SYSERR;
+ }
+ else if (iAddrCount > 1)
+ GE_LOG (ectx, GE_WARNING | GE_BULK | GE_USER,
+ _("There is more than one IP address specified"
+ " for interface `%s'.\nGNUnet will "
+ "use %u.%u.%u.%u.\n"), interfaces, PRIP (ntohl (dwIP)));
- identity->addr = dwIP;
+ identity->addr = dwIP;
- GlobalFree(pTable);
- GlobalFree(pAddrTable);
- }
- else /* Win 95 */
- {
- SOCKET s;
- HOSTENT *pHost;
- SOCKADDR_IN theHost;
-
- s = SOCKET(PF_INET, SOCK_STREAM, 0);
- pHost = GETHOSTBYNAME("www.example.com");
- if (! pHost) {
- GE_LOG(ectx, GE_ERROR | GE_BULK | GE_USER,
- _("Could not resolve `%s' to "
- "determine our IP address: %s\n"),
- "www.example.com",
- STRERROR(errno));
- return SYSERR;
+ GlobalFree (pTable);
+ GlobalFree (pAddrTable);
}
+ else /* Win 95 */
+ {
+ SOCKET s;
+ HOSTENT *pHost;
+ SOCKADDR_IN theHost;
- theHost.sin_family = AF_INET;
- theHost.sin_port = htons(80);
- theHost.sin_addr.S_un.S_addr
- = *((unsigned long *) pHost->h_addr_list[0]);
- if (CONNECT(s,
- (SOCKADDR *) &theHost,
- sizeof(theHost)) == SOCKET_ERROR && errno != EWOULDBLOCK) {
- GE_LOG_STRERROR(ectx, GE_ERROR | GE_BULK | GE_USER,
- "connect");
- return SYSERR;
- }
+ s = SOCKET (PF_INET, SOCK_STREAM, 0);
+ pHost = GETHOSTBYNAME ("www.example.com");
+ if (!pHost)
+ {
+ GE_LOG (ectx, GE_ERROR | GE_BULK | GE_USER,
+ _("Could not resolve `%s' to "
+ "determine our IP address: %s\n"),
+ "www.example.com", STRERROR (errno));
+ return SYSERR;
+ }
- i = sizeof(theHost);
- if (GETSOCKNAME(s,
- (SOCKADDR *) &theHost,
- &i) == SOCKET_ERROR) {
- GE_LOG_STRERROR(ectx, GE_ERROR | GE_BULK | GE_USER,
- "getsockname");
- return SYSERR;
+ theHost.sin_family = AF_INET;
+ theHost.sin_port = htons (80);
+ theHost.sin_addr.S_un.S_addr
+ = *((unsigned long *) pHost->h_addr_list[0]);
+ if (CONNECT (s,
+ (SOCKADDR *) & theHost,
+ sizeof (theHost)) == SOCKET_ERROR && errno != EWOULDBLOCK)
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_BULK | GE_USER, "connect");
+ return SYSERR;
+ }
+
+ i = sizeof (theHost);
+ if (GETSOCKNAME (s, (SOCKADDR *) & theHost, &i) == SOCKET_ERROR)
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_BULK | GE_USER, "getsockname");
+ return SYSERR;
+ }
+ closesocket (s);
+ identity->addr = theHost.sin_addr.S_un.S_addr;
}
- closesocket(s);
- identity->addr = theHost.sin_addr.S_un.S_addr;
- }
- GE_LOG(ectx, GE_DEBUG | GE_REQUEST | GE_USER,
- _("GNUnet now uses the IP address %u.%u.%u.%u.\n"),
- PRIP(ntohl(identity->addr)));
+ GE_LOG (ectx, GE_DEBUG | GE_REQUEST | GE_USER,
+ _("GNUnet now uses the IP address %u.%u.%u.%u.\n"),
+ PRIP (ntohl (identity->addr)));
return OK;
#endif
@@ -351,57 +336,44 @@
* Get the IP address for the local machine.
* @return NULL on error, IP as string otherwise
*/
-char * network_get_local_ip(struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- IPaddr * addr) {
+char *
+network_get_local_ip (struct GC_Configuration *cfg,
+ struct GE_Context *ectx, IPaddr * addr)
+{
IPaddr address;
- char * ipString;
+ char *ipString;
int retval;
char buf[65];
retval = SYSERR;
- if (GC_have_configuration_value(cfg,
- "NETWORK",
- "IP")) {
- ipString = NULL;
- GC_get_configuration_value_string(cfg,
- "NETWORK",
- "IP",
- "",
- &ipString);
- if (strlen(ipString) > 0) {
- retval = get_host_by_name(ectx,
- ipString,
- &address);
+ if (GC_have_configuration_value (cfg, "NETWORK", "IP"))
+ {
+ ipString = NULL;
+ GC_get_configuration_value_string (cfg, "NETWORK", "IP", "", &ipString);
+ if (strlen (ipString) > 0)
+ {
+ retval = get_host_by_name (ectx, ipString, &address);
+ }
+ FREE (ipString);
}
- FREE(ipString);
- }
#if LINUX || SOMEBSD || MINGW
if (retval == SYSERR)
- if (OK == getAddressFromIOCTL(cfg,
- ectx,
- &address))
+ if (OK == getAddressFromIOCTL (cfg, ectx, &address))
retval = OK;
#endif
#if HAVE_GETIFADDRS && HAVE_FREEIFADDRS
if (retval == SYSERR)
- if (OK == getAddressFromGetIfAddrs(cfg,
- ectx,
- &address))
+ if (OK == getAddressFromGetIfAddrs (cfg, ectx, &address))
retval = OK;
#endif
if (retval == SYSERR)
- retval = getAddressFromHostname(ectx,
- &address);
+ retval = getAddressFromHostname (ectx, &address);
if (retval == SYSERR)
return NULL;
- SNPRINTF(buf,
- 64,
- "%u.%u.%u.%u",
- PRIP(ntohl(*(int*)&address)));
+ SNPRINTF (buf, 64, "%u.%u.%u.%u", PRIP (ntohl (*(int *) &address)));
if (addr != NULL)
*addr = address;
- return STRDUP(buf);
+ return STRDUP (buf);
}
Modified: GNUnet/src/util/network/ipcheck.c
===================================================================
--- GNUnet/src/util/network/ipcheck.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/network/ipcheck.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -32,7 +32,8 @@
/**
* @brief IPV4 network in CIDR notation.
*/
-typedef struct CIDRNetwork {
+typedef struct CIDRNetwork
+{
IPaddr network;
IPaddr netmask;
} CIDRNetwork;
@@ -40,7 +41,8 @@
/**
* @brief network in CIDR notation for IPV6.
*/
-typedef struct CIDR6Network {
+typedef struct CIDR6Network
+{
IP6addr network;
IP6addr netmask;
} CIDR6Network;
@@ -57,8 +59,10 @@
* @param routeList a string specifying the forbidden networks
* @return the converted list, NULL if the synatx is flawed
*/
-CIDRNetwork * parse_ipv4_network_specification(struct GE_Context * ectx,
- const char * routeList) {
+CIDRNetwork *
+parse_ipv4_network_specification (struct GE_Context *ectx,
+ const char *routeList)
+{
unsigned int count;
unsigned int i;
unsigned int j;
@@ -67,114 +71,115 @@
unsigned int pos;
unsigned int temps[8];
int slash;
- CIDRNetwork * result;
+ CIDRNetwork *result;
if (routeList == NULL)
return NULL;
- len = strlen(routeList);
+ len = strlen (routeList);
if (len == 0)
return NULL;
count = 0;
- for (i=0;i<len;i++)
+ for (i = 0; i < len; i++)
if (routeList[i] == ';')
count++;
- result = MALLOC(sizeof(CIDRNetwork) * (count+1));
+ result = MALLOC (sizeof (CIDRNetwork) * (count + 1));
/* add termination */
- memset(result,
- 0,
- sizeof(CIDRNetwork)*(count+1));
- i=0;
+ memset (result, 0, sizeof (CIDRNetwork) * (count + 1));
+ i = 0;
pos = 0;
- while (i < count) {
- cnt = sscanf(&routeList[pos],
- "%u.%u.%u.%u/%u.%u.%u.%u;",
- &temps[0],
- &temps[1],
- &temps[2],
- &temps[3],
- &temps[4],
- &temps[5],
- &temps[6],
- &temps[7]);
- if (cnt == 8) {
- for (j=0;j<8;j++)
- if (temps[j] > 0xFF) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("Invalid format for IP: `%s'\n"),
- &routeList[pos]);
- FREE(result);
- return NULL;
- }
- result[i].network.addr
- = htonl((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) + temps[3]);
- result[i].netmask.addr
- = htonl((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) + temps[7]);
- while (routeList[pos] != ';')
- pos++;
- pos++;
- i++;
- continue;
+ while (i < count)
+ {
+ cnt = sscanf (&routeList[pos],
+ "%u.%u.%u.%u/%u.%u.%u.%u;",
+ &temps[0],
+ &temps[1],
+ &temps[2],
+ &temps[3], &temps[4], &temps[5], &temps[6], &temps[7]);
+ if (cnt == 8)
+ {
+ for (j = 0; j < 8; j++)
+ if (temps[j] > 0xFF)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _("Invalid format for IP: `%s'\n"), &routeList[pos]);
+ FREE (result);
+ return NULL;
+ }
+ result[i].network.addr
+ =
+ htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
+ temps[3]);
+ result[i].netmask.addr =
+ htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
+ temps[7]);
+ while (routeList[pos] != ';')
+ pos++;
+ pos++;
+ i++;
+ continue;
+ }
+ /* try second notation */
+ cnt = sscanf (&routeList[pos],
+ "%u.%u.%u.%u/%u;",
+ &temps[0], &temps[1], &temps[2], &temps[3], &slash);
+ if (cnt == 5)
+ {
+ for (j = 0; j < 4; j++)
+ if (temps[j] > 0xFF)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _("Invalid format for IP: `%s'\n"), &routeList[pos]);
+ FREE (result);
+ return NULL;
+ }
+ result[i].network.addr
+ =
+ htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
+ temps[3]);
+ if ((slash <= 32) && (slash > 0))
+ {
+ result[i].netmask.addr = 0;
+ while (slash > 0)
+ {
+ result[i].netmask.addr
+ = (result[i].netmask.addr >> 1) + 0x80000000;
+ slash--;
+ }
+ result[i].netmask.addr = htonl (result[i].netmask.addr);
+ while (routeList[pos] != ';')
+ pos++;
+ pos++;
+ i++;
+ continue;
+ }
+ else
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _
+ ("Invalid network notation ('/%d' is not legal in IPv4
CIDR)."),
+ slash);
+ FREE (result);
+ return NULL; /* error */
+ }
+ }
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _("Invalid format for IP: `%s'\n"), &routeList[pos]);
+ FREE (result);
+ return NULL; /* error */
}
- /* try second notation */
- cnt = sscanf(&routeList[pos],
- "%u.%u.%u.%u/%u;",
- &temps[0],
- &temps[1],
- &temps[2],
- &temps[3],
- &slash);
- if (cnt == 5) {
- for (j=0;j<4;j++)
- if (temps[j] > 0xFF) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("Invalid format for IP: `%s'\n"),
- &routeList[pos]);
- FREE(result);
- return NULL;
- }
- result[i].network.addr
- = htonl((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) + temps[3]);
- if ( (slash <= 32) && (slash > 0) ) {
- result[i].netmask.addr = 0;
- while (slash > 0) {
- result[i].netmask.addr
- = (result[i].netmask.addr >> 1) + 0x80000000;
- slash--;
- }
- result[i].netmask.addr
- = htonl(result[i].netmask.addr);
- while (routeList[pos] != ';')
- pos++;
- pos++;
- i++;
- continue;
- } else {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
- slash);
- FREE(result);
- return NULL; /* error */
- }
+ if (pos < strlen (routeList))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _("Invalid format for IP: `%s'\n"), &routeList[pos]);
+ FREE (result);
+ return NULL; /* oops */
}
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("Invalid format for IP: `%s'\n"),
- &routeList[pos]);
- FREE(result);
- return NULL; /* error */
- }
- if (pos < strlen(routeList)) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("Invalid format for IP: `%s'\n"),
- &routeList[pos]);
- FREE(result);
- return NULL; /* oops */
- }
- return result; /* ok */
+ return result; /* ok */
}
@@ -189,8 +194,10 @@
* @param routeList a string specifying the forbidden networks
* @return the converted list, NULL if the synatx is flawed
*/
-CIDR6Network * parse_ipv6_network_specification(struct GE_Context * ectx,
- const char * routeListX) {
+CIDR6Network *
+parse_ipv6_network_specification (struct GE_Context * ectx,
+ const char *routeListX)
+{
unsigned int count;
unsigned int i;
unsigned int len;
@@ -198,80 +205,77 @@
int start;
int slash;
int ret;
- char * routeList;
- CIDR6Network * result;
+ char *routeList;
+ CIDR6Network *result;
if (routeListX == NULL)
return NULL;
- len = strlen(routeListX);
+ len = strlen (routeListX);
if (len == 0)
return NULL;
- routeList = STRDUP(routeListX);
+ routeList = STRDUP (routeListX);
count = 0;
- for (i=0;i<len;i++)
+ for (i = 0; i < len; i++)
if (routeList[i] == ';')
count++;
- if (routeList[len-1] != ';') {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("Invalid network notation (does not end with ';': `%s')\n"),
- routeList);
- FREE(routeList);
- return NULL;
- }
+ if (routeList[len - 1] != ';')
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _("Invalid network notation (does not end with ';': `%s')\n"),
+ routeList);
+ FREE (routeList);
+ return NULL;
+ }
- result = MALLOC(sizeof(CIDR6Network) * (count+1));
- memset(result,
- 0,
- sizeof(CIDR6Network) * (count+1));
- i=0;
+ result = MALLOC (sizeof (CIDR6Network) * (count + 1));
+ memset (result, 0, sizeof (CIDR6Network) * (count + 1));
+ i = 0;
pos = 0;
- while (i < count) {
- start = pos;
- while (routeList[pos] != ';')
+ while (i < count)
+ {
+ start = pos;
+ while (routeList[pos] != ';')
+ pos++;
+ slash = pos;
+ while ((slash >= start) && (routeList[slash] != '/'))
+ slash--;
+ if (slash < start)
+ {
+ memset (&result[i].netmask, 0xFF, sizeof (IP6addr));
+ slash = pos;
+ }
+ else
+ {
+ routeList[pos] = '\0';
+ ret = inet_pton (AF_INET6,
+ &routeList[slash + 1], &result[i].netmask);
+ if (ret <= 0)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _("Wrong format `%s' for netmask: %s\n"),
+ &routeList[slash + 1], STRERROR (errno));
+ FREE (result);
+ FREE (routeList);
+ return NULL;
+ }
+ }
+ routeList[slash] = '\0';
+ ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
+ if (ret <= 0)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_IMMEDIATE,
+ _("Wrong format `%s' for network: %s\n"),
+ &routeList[slash + 1], STRERROR (errno));
+ FREE (result);
+ FREE (routeList);
+ return NULL;
+ }
pos++;
- slash = pos;
- while ( (slash >= start) &&
- (routeList[slash] != '/') )
- slash--;
- if (slash < start) {
- memset(&result[i].netmask,
- 0xFF,
- sizeof(IP6addr));
- slash = pos;
- } else {
- routeList[pos] = '\0';
- ret = inet_pton(AF_INET6,
- &routeList[slash+1],
- &result[i].netmask);
- if (ret <= 0) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("Wrong format `%s' for netmask: %s\n"),
- &routeList[slash+1],
- STRERROR(errno));
- FREE(result);
- FREE(routeList);
- return NULL;
- }
}
- routeList[slash] = '\0';
- ret = inet_pton(AF_INET6,
- &routeList[start],
- &result[i].network);
- if (ret <= 0) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- _("Wrong format `%s' for network: %s\n"),
- &routeList[slash+1],
- STRERROR(errno));
- FREE(result);
- FREE(routeList);
- return NULL;
- }
- pos++;
- }
- FREE(routeList);
+ FREE (routeList);
return result;
}
@@ -283,23 +287,24 @@
* @param ip the IP to check (in network byte order)
* @return NO if the IP is not in the list, YES if it it is
*/
-int check_ipv4_listed(const CIDRNetwork * list,
- IPaddr ip) {
+int
+check_ipv4_listed (const CIDRNetwork * list, IPaddr ip)
+{
int i;
IPaddr add;
add = ip;
- i=0;
+ i = 0;
if (list == NULL)
return NO;
- while ( (list[i].network.addr != 0) ||
- (list[i].netmask.addr != 0) ) {
- if ( (add.addr & list[i].netmask.addr) ==
- (list[i].network.addr & list[i].netmask.addr) )
- return YES;
- i++;
- }
+ while ((list[i].network.addr != 0) || (list[i].netmask.addr != 0))
+ {
+ if ((add.addr & list[i].netmask.addr) ==
+ (list[i].network.addr & list[i].netmask.addr))
+ return YES;
+ i++;
+ }
return NO;
}
@@ -310,27 +315,30 @@
* @param ip the IP to check (in network byte order)
* @return NO if the IP is not in the list, YES if it it is
*/
-int check_ipv6_listed(const CIDR6Network * list,
- IP6addr ip) {
+int
+check_ipv6_listed (const CIDR6Network * list, IP6addr ip)
+{
unsigned int i;
unsigned int j;
struct in6_addr zero;
- i=0;
+ i = 0;
if (list == NULL)
return NO;
- memset(&zero, 0, sizeof(struct in6_addr));
- while ( (memcmp(&zero, &list[i].network, sizeof(struct in6_addr)) != 0) ||
- (memcmp(&zero, &list[i].netmask, sizeof(struct in6_addr)) != 0) ) {
- for (j=0;j<sizeof(struct in6_addr)/sizeof(int);j++)
- if ( ((((int*)&ip)[j] & ((int*)&list[i].netmask)[j])) !=
- (((int*)&list[i].network)[j] & ((int*)&list[i].netmask)[j]) ) {
- i++;
- continue;
+ memset (&zero, 0, sizeof (struct in6_addr));
+ while ((memcmp (&zero, &list[i].network, sizeof (struct in6_addr)) != 0) ||
+ (memcmp (&zero, &list[i].netmask, sizeof (struct in6_addr)) != 0))
+ {
+ for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
+ if (((((int *) &ip)[j] & ((int *) &list[i].netmask)[j])) !=
+ (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
+ {
+ i++;
+ continue;
+ }
+ return YES;
}
- return YES;
- }
return NO;
}
Modified: GNUnet/src/util/network/network.h
===================================================================
--- GNUnet/src/util/network/network.h 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/network/network.h 2007-07-10 08:36:37 UTC (rev 5295)
@@ -28,11 +28,12 @@
#define NETWORK_H
-typedef struct SocketHandle {
+typedef struct SocketHandle
+{
- struct LoadMonitor * mon;
+ struct LoadMonitor *mon;
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
int handle;
Modified: GNUnet/src/util/network/select.c
===================================================================
--- GNUnet/src/util/network/select.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/network/select.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -33,27 +33,28 @@
/**
* Select Session handle.
*/
-typedef struct {
+typedef struct
+{
/**
* the socket
*/
- struct SocketHandle * sock;
+ struct SocketHandle *sock;
/**
* Client connection context.
*/
- void * sock_ctx;
+ void *sock_ctx;
/**
* The read buffer.
*/
- char * rbuff;
+ char *rbuff;
/**
* The write buffer.
*/
- char * wbuff;
+ char *wbuff;
cron_t lastUse;
@@ -98,35 +99,36 @@
} Session;
-typedef struct SelectHandle {
+typedef struct SelectHandle
+{
- const char * description;
+ const char *description;
/**
* mutex for synchronized access
*/
- struct MUTEX * lock;
+ struct MUTEX *lock;
/**
* one thread for listening for new connections,
* and for reading on all open sockets
*/
- struct PTHREAD * thread;
+ struct PTHREAD *thread;
/**
* sock is the tcp socket that we listen on for new inbound
* connections. Maybe NULL if we are not listening.
*/
- struct SocketHandle * listen_sock;
+ struct SocketHandle *listen_sock;
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
- struct LoadMonitor * load_monitor;
+ struct LoadMonitor *load_monitor;
/**
* Array of currently active TCP sessions.
*/
- Session ** sessions;
+ Session **sessions;
SelectMessageHandler mh;
@@ -134,11 +136,11 @@
SelectCloseHandler ch;
- void * mh_cls;
+ void *mh_cls;
- void * ah_cls;
+ void *ah_cls;
- void * ch_cls;
+ void *ch_cls;
cron_t timeout;
@@ -165,11 +167,10 @@
} SelectHandle;
-static void add_to_select_set(struct SocketHandle * s,
- fd_set * set,
- int * max) {
- FD_SET(s->handle,
- set);
+static void
+add_to_select_set (struct SocketHandle *s, fd_set * set, int *max)
+{
+ FD_SET (s->handle, set);
if (*max < s->handle)
*max = s->handle;
}
@@ -178,23 +179,19 @@
* Write to the pipe to wake up the select thread (the set of
* files to watch has changed).
*/
-static void signalSelect(SelectHandle * sh) {
+static void
+signalSelect (SelectHandle * sh)
+{
static char i = '\0';
int ret;
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Signaling select %p.\n",
- sh);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK, "Signaling select %p.\n", sh);
#endif
- ret = WRITE(sh->signal_pipe[1],
- &i,
- sizeof(char));
- if (ret != sizeof(char))
- GE_LOG_STRERROR(sh->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "write");
+ ret = WRITE (sh->signal_pipe[1], &i, sizeof (char));
+ if (ret != sizeof (char))
+ GE_LOG_STRERROR (sh->ectx, GE_ERROR | GE_ADMIN | GE_BULK, "write");
}
/**
@@ -205,62 +202,50 @@
* This function may only be called if the tcplock is
* already held by the caller.
*/
-static void destroySession(SelectHandle * sh,
- Session * s) {
+static void
+destroySession (SelectHandle * sh, Session * s)
+{
int i;
- if (s->locked == 1) {
- s->locked = -1;
- return;
- }
+ if (s->locked == 1)
+ {
+ s->locked = -1;
+ return;
+ }
if (s->locked == 2)
- return; /* already in process of destroying! */
+ return; /* already in process of destroying! */
s->locked = 2;
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Destroying session %p of select %p with %u in read and %u in write
buffer.\n",
- s,
- sh,
- s->rsize,
- s->wsize);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Destroying session %p of select %p with %u in read and %u in write
buffer.\n",
+ s, sh, s->rsize, s->wsize);
#endif
#if 0
- if ( (s->pos > 0) ||
- (s->wapos > s->wspos) )
- fprintf(stderr,
- "Destroying session %p of select %p with loss of %u in read and %u in
write buffer.\n",
- s,
- sh,
- s->pos,
- s->wapos - s->wspos);
+ if ((s->pos > 0) || (s->wapos > s->wspos))
+ fprintf (stderr,
+ "Destroying session %p of select %p with loss of %u in read and
%u in write buffer.\n",
+ s, sh, s->pos, s->wapos - s->wspos);
#endif
- MUTEX_UNLOCK(sh->lock);
- sh->ch(sh->ch_cls,
- sh,
- s->sock,
- s->sock_ctx);
- MUTEX_LOCK(sh->lock);
- socket_destroy(s->sock);
+ MUTEX_UNLOCK (sh->lock);
+ sh->ch (sh->ch_cls, sh, s->sock, s->sock_ctx);
+ MUTEX_LOCK (sh->lock);
+ socket_destroy (s->sock);
sh->socket_quota++;
- GROW(s->rbuff,
- s->rsize,
- 0);
- GROW(s->wbuff,
- s->wsize,
- 0);
- for (i=0;i<sh->sessionCount;i++) {
- if (sh->sessions[i] == s) {
- sh->sessions[i] = sh->sessions[sh->sessionCount-1];
- sh->sessionCount--;
- break;
+ GROW (s->rbuff, s->rsize, 0);
+ GROW (s->wbuff, s->wsize, 0);
+ for (i = 0; i < sh->sessionCount; i++)
+ {
+ if (sh->sessions[i] == s)
+ {
+ sh->sessions[i] = sh->sessions[sh->sessionCount - 1];
+ sh->sessionCount--;
+ break;
+ }
}
- }
- FREE(s);
+ FREE (s);
if (sh->sessionCount * 2 < sh->sessionArrayLength)
- GROW(sh->sessions,
- sh->sessionArrayLength,
- sh->sessionCount);
+ GROW (sh->sessions, sh->sessionArrayLength, sh->sessionCount);
}
/**
@@ -271,88 +256,81 @@
* already held by the caller.
* @return OK for success, SYSERR if session was destroyed
*/
-static int readAndProcess(SelectHandle * sh,
- Session * session) {
- const MESSAGE_HEADER * pack;
+static int
+readAndProcess (SelectHandle * sh, Session * session)
+{
+ const MESSAGE_HEADER *pack;
int ret;
size_t recvd;
unsigned short len;
- if (session->rsize == session->pos) {
- /* read buffer too small, grow */
- GROW(session->rbuff,
- session->rsize,
- session->rsize + 1024);
- }
- ret = socket_recv(session->sock,
- NC_Nonblocking | NC_IgnoreInt,
- &session->rbuff[session->pos],
- session->rsize - session->pos,
- &recvd);
+ if (session->rsize == session->pos)
+ {
+ /* read buffer too small, grow */
+ GROW (session->rbuff, session->rsize, session->rsize + 1024);
+ }
+ ret = socket_recv (session->sock,
+ NC_Nonblocking | NC_IgnoreInt,
+ &session->rbuff[session->pos],
+ session->rsize - session->pos, &recvd);
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Receiving from session %p of select %p return %d-%u (%s).\n",
- sh,
- session,
- ret,
- recvd,
- STRERROR(errno));
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Receiving from session %p of select %p return %d-%u (%s).\n",
+ sh, session, ret, recvd, STRERROR (errno));
#endif
- if (ret != OK) {
- destroySession(sh, session);
- return SYSERR; /* other side closed connection */
- }
- session->pos += recvd;
- while ( (sh->shutdown == NO) &&
- (session->pos >= sizeof(MESSAGE_HEADER)) ) {
- pack = (const MESSAGE_HEADER*) &session->rbuff[0];
- len = ntohs(pack->size);
- /* check minimum size */
- if (len < sizeof(MESSAGE_HEADER)) {
- GE_LOG(sh->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Received malformed message (too small) from connection.
Closing.\n"));
- destroySession(sh, session);
- return SYSERR;
+ if (ret != OK)
+ {
+ destroySession (sh, session);
+ return SYSERR; /* other side closed connection */
}
- if (len > session->rsize) /* if message larger than read buffer, grow! */
- GROW(session->rbuff,
- session->rsize,
- len);
+ session->pos += recvd;
+ while ((sh->shutdown == NO) && (session->pos >= sizeof (MESSAGE_HEADER)))
+ {
+ pack = (const MESSAGE_HEADER *) &session->rbuff[0];
+ len = ntohs (pack->size);
+ /* check minimum size */
+ if (len < sizeof (MESSAGE_HEADER))
+ {
+ GE_LOG (sh->ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _
+ ("Received malformed message (too small) from connection.
Closing.\n"));
+ destroySession (sh, session);
+ return SYSERR;
+ }
+ if (len > session->rsize) /* if message larger than read buffer, grow! */
+ GROW (session->rbuff, session->rsize, len);
- /* do we have the entire message? */
- if (session->pos < len)
- break; /* wait for more */
- if (session->locked == 0)
- session->locked = 1;
- MUTEX_UNLOCK(sh->lock);
- if (OK != sh->mh(sh->mh_cls,
- sh,
- session->sock,
- session->sock_ctx,
- pack)) {
- MUTEX_LOCK(sh->lock);
+ /* do we have the entire message? */
+ if (session->pos < len)
+ break; /* wait for more */
+ if (session->locked == 0)
+ session->locked = 1;
+ MUTEX_UNLOCK (sh->lock);
+ if (OK != sh->mh (sh->mh_cls,
+ sh, session->sock, session->sock_ctx, pack))
+ {
+ MUTEX_LOCK (sh->lock);
+ if (session->locked == 1)
+ session->locked = 0;
+ destroySession (sh, session);
+ return SYSERR;
+ }
+ MUTEX_LOCK (sh->lock);
+ if (session->locked == -1)
+ {
+ session->locked = 0;
+ destroySession (sh, session);
+ return OK;
+ }
if (session->locked == 1)
- session->locked = 0;
- destroySession(sh, session);
- return SYSERR;
+ session->locked = 0;
+ /* shrink buffer adequately */
+ memmove (&session->rbuff[0], &session->rbuff[len], session->pos - len);
+ session->pos -= len;
}
- MUTEX_LOCK(sh->lock);
- if (session->locked == -1) {
- session->locked = 0;
- destroySession(sh, session);
- return OK;
- }
- if (session->locked == 1)
- session->locked = 0;
- /* shrink buffer adequately */
- memmove(&session->rbuff[0],
- &session->rbuff[len],
- session->pos - len);
- session->pos -= len;
- }
- session->lastUse = get_time();
+ session->lastUse = get_time ();
return OK;
}
@@ -364,83 +342,83 @@
* already held by the caller.
* @return OK for success, SYSERR if session was destroyed
*/
-static int writeAndProcess(SelectHandle * sh,
- Session * session) {
- SocketHandle * sock;
+static int
+writeAndProcess (SelectHandle * sh, Session * session)
+{
+ SocketHandle *sock;
int ret;
size_t size;
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Write and process called for session %p of select %p status %d.\n",
- sh,
- session,
- sh->shutdown);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Write and process called for session %p of select %p status %d.\n",
+ sh, session, sh->shutdown);
#endif
sock = session->sock;
- while (sh->shutdown == NO) {
- ret = socket_send(sock,
- NC_Nonblocking,
- &session->wbuff[session->wspos],
- session->wapos - session->wspos,
- &size);
+ while (sh->shutdown == NO)
+ {
+ ret = socket_send (sock,
+ NC_Nonblocking,
+ &session->wbuff[session->wspos],
+ session->wapos - session->wspos, &size);
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Sending %d bytes from session %p of select %p return %d.\n",
- session->wapos - session->wspos,
- sh,
- session,
- ret);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Sending %d bytes from session %p of select %p return %d.\n",
+ session->wapos - session->wspos, sh, session, ret);
#endif
- if (ret == SYSERR) {
- GE_LOG_STRERROR(sh->ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_BULK,
- "send");
- destroySession(sh, session);
- return SYSERR;
+ if (ret == SYSERR)
+ {
+ GE_LOG_STRERROR (sh->ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_BULK, "send");
+ destroySession (sh, session);
+ return SYSERR;
+ }
+ if (ret == OK)
+ {
+ if (size == 0)
+ {
+ /* send only returns 0 on error (happens if
+ other side closed connection), so close
+ the session */
+ destroySession (sh, session);
+ return SYSERR;
+ }
+ session->wspos += size;
+ if (session->wspos == session->wapos)
+ {
+ /* free compaction! */
+ session->wspos = 0;
+ session->wapos = 0;
+ if (session->wsize > sh->memory_quota)
+ {
+ /* if we went over quota before because of
+ force, use this opportunity to shrink
+ back to size! */
+ GROW (session->wbuff, session->wsize, sh->memory_quota);
+ }
+ }
+ break;
+ }
+ GE_ASSERT (sh->ectx, ret == NO);
+ /* this should only happen under Win9x because
+ of a bug in the socket implementation (KB177346).
+ Let's sleep and try again. */
+ PTHREAD_SLEEP (20 * cronMILLIS);
}
- if (ret == OK) {
- if (size == 0) {
- /* send only returns 0 on error (happens if
- other side closed connection), so close
- the session */
- destroySession(sh, session);
- return SYSERR;
- }
- session->wspos += size;
- if (session->wspos == session->wapos) {
- /* free compaction! */
- session->wspos = 0;
- session->wapos = 0;
- if (session->wsize > sh->memory_quota) {
- /* if we went over quota before because of
- force, use this opportunity to shrink
- back to size! */
- GROW(session->wbuff,
- session->wsize,
- sh->memory_quota);
- }
- }
- break;
- }
- GE_ASSERT(sh->ectx, ret == NO);
- /* this should only happen under Win9x because
- of a bug in the socket implementation (KB177346).
- Let's sleep and try again. */
- PTHREAD_SLEEP(20 * cronMILLIS);
- }
- session->lastUse = get_time();
+ session->lastUse = get_time ();
return OK;
}
/**
* Thread that selects until it is signaled to shut down.
*/
-static void * selectThread(void * ctx) {
- struct SelectHandle * sh = ctx;
- char * clientAddr;
+static void *
+selectThread (void *ctx)
+{
+ struct SelectHandle *sh = ctx;
+ char *clientAddr;
fd_set readSet;
fd_set errorSet;
fd_set writeSet;
@@ -450,367 +428,359 @@
int max;
int ret;
int s;
- void * sctx;
- SocketHandle * sock;
- Session * session;
+ void *sctx;
+ SocketHandle *sock;
+ Session *session;
size_t size;
int old_errno;
- clientAddr = MALLOC(sh->max_addr_len);
- MUTEX_LOCK(sh->lock);
- while (sh->shutdown == NO) {
- FD_ZERO(&readSet);
- FD_ZERO(&errorSet);
- FD_ZERO(&writeSet);
- if (sh->signal_pipe[0] != -1) {
- if (-1 == FSTAT(sh->signal_pipe[0], &buf)) {
- GE_LOG_STRERROR(sh->ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "fstat");
- sh->signal_pipe[0] = -1; /* prevent us from error'ing all the time */
- } else {
- FD_SET(sh->signal_pipe[0],
- &readSet);
- }
- }
- max = sh->signal_pipe[0];
- if (sh->listen_sock != NULL) {
- if (! socket_test_valid(sh->listen_sock)) {
- socket_destroy(sh->listen_sock);
- GE_LOG(sh->ectx,
- GE_USER | GE_ERROR | GE_BULK,
- _("select listen socket not valid!\n"));
- sh->listen_sock = NULL; /* prevent us from error'ing all the time */
- } else {
- add_to_select_set(sh->listen_sock, &readSet, &max);
- }
- }
- for (i=0;i<sh->sessionCount;i++) {
- Session * session = sh->sessions[i];
- struct SocketHandle * sock = session->sock;
+ clientAddr = MALLOC (sh->max_addr_len);
+ MUTEX_LOCK (sh->lock);
+ while (sh->shutdown == NO)
+ {
+ FD_ZERO (&readSet);
+ FD_ZERO (&errorSet);
+ FD_ZERO (&writeSet);
+ if (sh->signal_pipe[0] != -1)
+ {
+ if (-1 == FSTAT (sh->signal_pipe[0], &buf))
+ {
+ GE_LOG_STRERROR (sh->ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "fstat");
+ sh->signal_pipe[0] = -1; /* prevent us from error'ing all the
time */
+ }
+ else
+ {
+ FD_SET (sh->signal_pipe[0], &readSet);
+ }
+ }
+ max = sh->signal_pipe[0];
+ if (sh->listen_sock != NULL)
+ {
+ if (!socket_test_valid (sh->listen_sock))
+ {
+ socket_destroy (sh->listen_sock);
+ GE_LOG (sh->ectx,
+ GE_USER | GE_ERROR | GE_BULK,
+ _("select listen socket for `%s' not valid!\n"),
+ sh->description);
+ sh->listen_sock = NULL; /* prevent us from error'ing all the
time */
+ }
+ else
+ {
+ add_to_select_set (sh->listen_sock, &readSet, &max);
+ }
+ }
+ for (i = 0; i < sh->sessionCount; i++)
+ {
+ Session *session = sh->sessions[i];
+ struct SocketHandle *sock = session->sock;
- if (! socket_test_valid(sock)) {
+ if (!socket_test_valid (sock))
+ {
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Select %p destroys invalid client handle %p\n",
- sh,
- session);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Select %p destroys invalid client handle %p\n",
+ sh, session);
#endif
- destroySession(sh, session);
- } else {
- add_to_select_set(sock, &readSet, &max);
- add_to_select_set(sock, &errorSet, &max);
- GE_ASSERT(NULL, session->wapos >= session->wspos);
- if (session->wapos > session->wspos)
- add_to_select_set(sock, &writeSet, &max); /* do we have a pending write
request? */
- }
- }
- MUTEX_UNLOCK(sh->lock);
- ret = SELECT(max+1,
- &readSet,
- &writeSet,
- &errorSet,
- NULL);
- old_errno = errno;
- MUTEX_LOCK(sh->lock);
- if ( (ret == -1) &&
- ( (old_errno == EAGAIN) || (old_errno == EINTR) ) )
- continue;
- if (ret == -1) {
- errno = old_errno;
- if (errno == EBADF) {
- GE_LOG_STRERROR(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "select");
- } else {
- GE_DIE_STRERROR(sh->ectx,
- GE_FATAL | GE_ADMIN | GE_USER | GE_IMMEDIATE,
- "select");
- }
- continue;
- }
- if (sh->is_udp == NO) {
- if ( (sh->listen_sock != NULL) &&
- (FD_ISSET(sh->listen_sock->handle, &readSet)) ) {
- lenOfIncomingAddr = sh->max_addr_len;
- memset(clientAddr,
- 0,
- lenOfIncomingAddr);
- /* make sure this is non-blocking */
- socket_set_blocking(sh->listen_sock,
- NO);
- s = ACCEPT(sh->listen_sock->handle,
- (struct sockaddr *) clientAddr,
- &lenOfIncomingAddr);
- if (s == -1) {
- GE_LOG_STRERROR(sh->ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "accept");
- GE_LOG(sh->ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "Select %s failed to accept!\n",
- sh->description);
- if ( (errno == EAGAIN) || (errno == EWOULDBLOCK))
- continue; /* not good, but not fatal either */
- break;
- }
- if (sh->socket_quota <= 0) {
- SHUTDOWN(s, SHUT_WR);
- CLOSE(s);
- s = -1;
- continue;
- }
- sh->socket_quota--;
+ destroySession (sh, session);
+ }
+ else
+ {
+ add_to_select_set (sock, &readSet, &max);
+ add_to_select_set (sock, &errorSet, &max);
+ GE_ASSERT (NULL, session->wapos >= session->wspos);
+ if (session->wapos > session->wspos)
+ add_to_select_set (sock, &writeSet, &max); /* do we have
a pending write request? */
+ }
+ }
+ MUTEX_UNLOCK (sh->lock);
+ ret = SELECT (max + 1, &readSet, &writeSet, &errorSet, NULL);
+ old_errno = errno;
+ MUTEX_LOCK (sh->lock);
+ if ((ret == -1) && ((old_errno == EAGAIN) || (old_errno == EINTR)))
+ continue;
+ if (ret == -1)
+ {
+ errno = old_errno;
+ if (errno == EBADF)
+ {
+ GE_LOG_STRERROR (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK, "select");
+ }
+ else
+ {
+ GE_DIE_STRERROR (sh->ectx,
+ GE_FATAL | GE_ADMIN | GE_USER | GE_IMMEDIATE,
+ "select");
+ }
+ continue;
+ }
+ if (sh->is_udp == NO)
+ {
+ if ((sh->listen_sock != NULL) &&
+ (FD_ISSET (sh->listen_sock->handle, &readSet)))
+ {
+ lenOfIncomingAddr = sh->max_addr_len;
+ memset (clientAddr, 0, lenOfIncomingAddr);
+ /* make sure this is non-blocking */
+ socket_set_blocking (sh->listen_sock, NO);
+ s = ACCEPT (sh->listen_sock->handle,
+ (struct sockaddr *) clientAddr, &lenOfIncomingAddr);
+ if (s == -1)
+ {
+ GE_LOG_STRERROR (sh->ectx,
+ GE_WARNING | GE_ADMIN | GE_BULK, "accept");
+ GE_LOG (sh->ectx,
+ GE_WARNING | GE_ADMIN | GE_BULK,
+ "Select %s failed to accept!\n", sh->description);
+ if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
+ continue; /* not good, but not fatal either */
+ break;
+ }
+ if (sh->socket_quota <= 0)
+ {
+ SHUTDOWN (s, SHUT_WR);
+ CLOSE (s);
+ s = -1;
+ continue;
+ }
+ sh->socket_quota--;
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Select %p is accepting connection: %d\n",
- sh,
- s);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Select %p is accepting connection: %d\n", sh, s);
#endif
- sock = socket_create(sh->ectx,
- sh->load_monitor,
- s);
- MUTEX_UNLOCK(sh->lock);
- sctx = sh->ah(sh->ah_cls,
- sh,
- sock,
- clientAddr,
- lenOfIncomingAddr);
- MUTEX_LOCK(sh->lock);
+ sock = socket_create (sh->ectx, sh->load_monitor, s);
+ MUTEX_UNLOCK (sh->lock);
+ sctx = sh->ah (sh->ah_cls,
+ sh, sock, clientAddr, lenOfIncomingAddr);
+ MUTEX_LOCK (sh->lock);
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Select %p is accepting connection: %p\n",
- sh,
- sctx);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Select %p is accepting connection: %p\n", sh, sctx);
#endif
- if (sctx == NULL) {
- socket_destroy(sock);
- sh->socket_quota++;
- } else {
- session = MALLOC(sizeof(Session));
- memset(session,
- 0,
- sizeof(Session));
- session->sock = sock;
- session->sock_ctx = sctx;
- session->lastUse = get_time();
- if (sh->sessionArrayLength == sh->sessionCount)
- GROW(sh->sessions,
- sh->sessionArrayLength,
- sh->sessionArrayLength + 4);
- sh->sessions[sh->sessionCount++] = session;
- }
- }
- } else { /* is_udp == YES */
- if ( (sh->listen_sock != NULL) &&
- (FD_ISSET(sh->listen_sock->handle, &readSet)) ) {
- int pending;
- int udp_sock;
- int error;
- socklen_t optlen;
+ if (sctx == NULL)
+ {
+ socket_destroy (sock);
+ sh->socket_quota++;
+ }
+ else
+ {
+ session = MALLOC (sizeof (Session));
+ memset (session, 0, sizeof (Session));
+ session->sock = sock;
+ session->sock_ctx = sctx;
+ session->lastUse = get_time ();
+ if (sh->sessionArrayLength == sh->sessionCount)
+ GROW (sh->sessions,
+ sh->sessionArrayLength, sh->sessionArrayLength + 4);
+ sh->sessions[sh->sessionCount++] = session;
+ }
+ }
+ }
+ else
+ { /* is_udp == YES */
+ if ((sh->listen_sock != NULL) &&
+ (FD_ISSET (sh->listen_sock->handle, &readSet)))
+ {
+ int pending;
+ int udp_sock;
+ int error;
+ socklen_t optlen;
- udp_sock = sh->listen_sock->handle;
- lenOfIncomingAddr = sh->max_addr_len;
- memset(clientAddr,
- 0,
- lenOfIncomingAddr);
- pending = 0;
- optlen = sizeof(pending);
+ udp_sock = sh->listen_sock->handle;
+ lenOfIncomingAddr = sh->max_addr_len;
+ memset (clientAddr, 0, lenOfIncomingAddr);
+ pending = 0;
+ optlen = sizeof (pending);
#ifdef OSX
- error = GETSOCKOPT(udp_sock,
- SOL_SOCKET,
- SO_NREAD,
- &pending,
- &optlen);
+ error = GETSOCKOPT (udp_sock,
+ SOL_SOCKET, SO_NREAD, &pending, &optlen);
#elif MINGW
- error = ioctlsocket(udp_sock,
- FIONREAD,
- &pending);
+ error = ioctlsocket (udp_sock, FIONREAD, &pending);
#else
- error = ioctl(udp_sock,
- FIONREAD,
- &pending);
+ error = ioctl (udp_sock, FIONREAD, &pending);
#endif
- if ( (error != 0) ||
- (optlen != sizeof(pending)) ) {
- GE_LOG_STRERROR(sh->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "ioctl");
- pending = 65535; /* max */
- }
+ if ((error != 0) || (optlen != sizeof (pending)))
+ {
+ GE_LOG_STRERROR (sh->ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK, "ioctl");
+ pending = 65535; /* max */
+ }
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Select %p is preparing to receive %u bytes from UDP\n",
- sh,
- pending);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Select %p is preparing to receive %u bytes from UDP\n",
+ sh, pending);
#endif
- GE_ASSERT(sh->ectx,
- pending >= 0);
- if (pending >= 65536)
- pending = 65536;
- if (pending == 0) {
- /* maybe empty UDP packet was sent (see report on bug-gnunet,
- 5/11/6; read 0 bytes from UDP just to kill potential empty packet! */
- socket_recv_from(sh->listen_sock,
- NC_Nonblocking,
- NULL,
- 0,
- &size,
- clientAddr,
- &lenOfIncomingAddr);
- } else {
- char * msg;
+ GE_ASSERT (sh->ectx, pending >= 0);
+ if (pending >= 65536)
+ pending = 65536;
+ if (pending == 0)
+ {
+ /* maybe empty UDP packet was sent (see report on bug-gnunet,
+ 5/11/6; read 0 bytes from UDP just to kill potential
empty packet! */
+ socket_recv_from (sh->listen_sock,
+ NC_Nonblocking,
+ NULL,
+ 0, &size, clientAddr, &lenOfIncomingAddr);
+ }
+ else
+ {
+ char *msg;
- msg = MALLOC(pending);
- size = 0;
- if (YES != socket_recv_from(sh->listen_sock,
- NC_Nonblocking,
- msg,
- pending,
- &size,
- clientAddr,
- &lenOfIncomingAddr)) {
+ msg = MALLOC (pending);
+ size = 0;
+ if (YES != socket_recv_from (sh->listen_sock,
+ NC_Nonblocking,
+ msg,
+ pending,
+ &size,
+ clientAddr,
+ &lenOfIncomingAddr))
+ {
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Error in select %p -- failed to receive %u bytes\n",
- sh,
- pending);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Error in select %p -- failed to receive %u
bytes\n",
+ sh, pending);
#endif
- socket_close(sh->listen_sock);
- } else {
- /* validate msg format! */
- const MESSAGE_HEADER * hdr;
+ socket_close (sh->listen_sock);
+ }
+ else
+ {
+ /* validate msg format! */
+ const MESSAGE_HEADER *hdr;
- /* if size < pending, set pending to size */
- if (size < pending)
- pending = size;
- hdr = (const MESSAGE_HEADER*) msg;
- if ( (size == pending) &&
- (size >= sizeof(MESSAGE_HEADER)) &&
- (ntohs(hdr->size) == size) ) {
- void * sctx;
+ /* if size < pending, set pending to size */
+ if (size < pending)
+ pending = size;
+ hdr = (const MESSAGE_HEADER *) msg;
+ if ((size == pending) &&
+ (size >= sizeof (MESSAGE_HEADER)) &&
+ (ntohs (hdr->size) == size))
+ {
+ void *sctx;
- MUTEX_UNLOCK(sh->lock);
- sctx = sh->ah(sh->ah_cls,
- sh,
- NULL,
- clientAddr,
- lenOfIncomingAddr);
- MUTEX_LOCK(sh->lock);
- if (sctx != NULL) {
+ MUTEX_UNLOCK (sh->lock);
+ sctx = sh->ah (sh->ah_cls,
+ sh,
+ NULL, clientAddr, lenOfIncomingAddr);
+ MUTEX_LOCK (sh->lock);
+ if (sctx != NULL)
+ {
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Select %p is passing %u bytes from UDP to handler\n",
- sh,
- size);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Select %p is passing %u bytes from UDP
to handler\n",
+ sh, size);
#endif
- sh->mh(sh->mh_cls,
- sh,
- NULL,
- sctx,
- hdr);
- sh->ch(sh->ch_cls,
- sh,
- NULL,
- sctx);
- } else {
+ sh->mh (sh->mh_cls, sh, NULL, sctx, hdr);
+ sh->ch (sh->ch_cls, sh, NULL, sctx);
+ }
+ else
+ {
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Error in select %p -- connection refused\n",
- sh);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Error in select %p -- connection
refused\n",
+ sh);
#endif
- }
- } else {
+ }
+ }
+ else
+ {
#if DEBUG_SELECT
- GE_BREAK(sh->ectx, size == pending);
- GE_BREAK(sh->ectx, size >= sizeof(MESSAGE_HEADER));
- GE_BREAK(sh->ectx, (size >= sizeof(MESSAGE_HEADER)) &&
(ntohs(hdr->size) == size));
+ GE_BREAK (sh->ectx, size == pending);
+ GE_BREAK (sh->ectx,
+ size >= sizeof (MESSAGE_HEADER));
+ GE_BREAK (sh->ectx,
+ (size >= sizeof (MESSAGE_HEADER))
+ && (ntohs (hdr->size) == size));
#endif
- }
- }
- FREE(msg);
- }
- }
- } /* end UDP processing */
- if (FD_ISSET(sh->signal_pipe[0], &readSet)) {
- /* allow reading multiple signals in one go in case we get many
- in one shot... */
+ }
+ }
+ FREE (msg);
+ }
+ }
+ } /* end UDP processing */
+ if (FD_ISSET (sh->signal_pipe[0], &readSet))
+ {
+ /* allow reading multiple signals in one go in case we get many
+ in one shot... */
#define MAXSIG_BUF 128
- char buf[MAXSIG_BUF];
- /* just a signal to refresh sets, eat and continue */
- if (0 >= READ(sh->signal_pipe[0],
- &buf[0],
- MAXSIG_BUF)) {
- GE_LOG_STRERROR(sh->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "read");
- }
+ char buf[MAXSIG_BUF];
+ /* just a signal to refresh sets, eat and continue */
+ if (0 >= READ (sh->signal_pipe[0], &buf[0], MAXSIG_BUF))
+ {
+ GE_LOG_STRERROR (sh->ectx,
+ GE_WARNING | GE_USER | GE_BULK, "read");
+ }
+ }
+ for (i = 0; i < sh->sessionCount; i++)
+ {
+ session = sh->sessions[i];
+ sock = session->sock;
+ if ((FD_ISSET (sock->handle, &readSet)) &&
+ (SYSERR == readAndProcess (sh, session)))
+ {
+ i--;
+ continue;
+ }
+ if ((FD_ISSET (sock->handle, &writeSet)) &&
+ (SYSERR == writeAndProcess (sh, session)))
+ {
+ i--;
+ continue;
+ }
+ if (FD_ISSET (sock->handle, &errorSet))
+ {
+ destroySession (sh, session);
+ i--;
+ continue;
+ }
+ if (((sh->timeout != 0) &&
+ (get_time () > session->lastUse + sh->timeout)) ||
+ ((session->timeout != 0) &&
+ (get_time () > session->lastUse + session->timeout)))
+ {
+ destroySession (sh, session);
+ i--;
+ continue;
+ }
+ }
}
- for (i=0;i<sh->sessionCount;i++) {
- session = sh->sessions[i];
- sock = session->sock;
- if ( (FD_ISSET(sock->handle, &readSet)) &&
- (SYSERR == readAndProcess(sh,
- session)) ) {
- i--;
- continue;
- }
- if ( (FD_ISSET(sock->handle, &writeSet)) &&
- (SYSERR == writeAndProcess(sh,
- session)) ) {
- i--;
- continue;
- }
- if (FD_ISSET(sock->handle, &errorSet)) {
- destroySession(sh,
- session);
- i--;
- continue;
- }
- if ( ( (sh->timeout != 0) &&
- (get_time() > session->lastUse + sh->timeout) ) ||
- ( (session->timeout != 0) &&
- (get_time() > session->lastUse + session->timeout) ) ) {
- destroySession(sh, session);
- i--;
- continue;
- }
- }
- }
sh->description = "DEAD";
- MUTEX_UNLOCK(sh->lock);
- FREE(clientAddr);
+ MUTEX_UNLOCK (sh->lock);
+ FREE (clientAddr);
return NULL;
}
-static int makePipeNonblocking(struct GE_Context * ectx,
- int handle) {
+static int
+makePipeNonblocking (struct GE_Context *ectx, int handle)
+{
#if MINGW
DWORD mode;
mode = PIPE_NOWAIT;
- if (SetNamedPipeHandleState((HANDLE) handle, &mode, NULL, NULL))
- __win_SetHandleBlockingMode(handle, 0);
+ if (SetNamedPipeHandleState ((HANDLE) handle, &mode, NULL, NULL))
+ __win_SetHandleBlockingMode (handle, 0);
/* don't report errors because Win9x doesn't support
SetNamedPipeHandleState() */
#else
- int flags = fcntl(handle, F_GETFL);
+ int flags = fcntl (handle, F_GETFL);
flags |= O_NONBLOCK;
- if (-1 == fcntl(handle,
- F_SETFL,
- flags)) {
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "fcntl");
- return SYSERR;
- }
+ if (-1 == fcntl (handle, F_SETFL, flags))
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ "fcntl");
+ return SYSERR;
+ }
#endif
return OK;
}
@@ -829,53 +799,46 @@
* @return NULL on error
*/
SelectHandle *
-select_create(const char * description,
- int is_udp,
- struct GE_Context * ectx,
- struct LoadMonitor * mon,
- int sock,
- unsigned int max_addr_len,
- cron_t timeout,
- SelectMessageHandler mh,
- void * mh_cls,
- SelectAcceptHandler ah,
- void * ah_cls,
- SelectCloseHandler ch,
- void * ch_cls,
- unsigned int memory_quota,
- int socket_quota) {
- SelectHandle * sh;
+select_create (const char *description,
+ int is_udp,
+ struct GE_Context * ectx,
+ struct LoadMonitor * mon,
+ int sock,
+ unsigned int max_addr_len,
+ cron_t timeout,
+ SelectMessageHandler mh,
+ void *mh_cls,
+ SelectAcceptHandler ah,
+ void *ah_cls,
+ SelectCloseHandler ch,
+ void *ch_cls, unsigned int memory_quota, int socket_quota)
+{
+ SelectHandle *sh;
- if ( (is_udp == NO) &&
- (sock != -1) &&
- (0 != LISTEN(sock, 5)) ) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- "listen");
- return NULL;
- }
- GE_ASSERT(ectx, description != NULL);
- sh = MALLOC(sizeof(SelectHandle));
- memset(sh, 0, sizeof(SelectHandle));
+ if ((is_udp == NO) && (sock != -1) && (0 != LISTEN (sock, 5)))
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_USER | GE_IMMEDIATE, "listen");
+ return NULL;
+ }
+ GE_ASSERT (ectx, description != NULL);
+ sh = MALLOC (sizeof (SelectHandle));
+ memset (sh, 0, sizeof (SelectHandle));
sh->is_udp = is_udp;
sh->description = description;
- if (0 != PIPE(sh->signal_pipe)) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_USER | GE_IMMEDIATE,
- "pipe");
- FREE(sh);
- return NULL;
- }
- if (OK != makePipeNonblocking(sh->ectx,
- sh->signal_pipe[0])) {
- if ( (0 != CLOSE(sh->signal_pipe[0])) ||
- (0 != CLOSE(sh->signal_pipe[1])) )
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_IMMEDIATE | GE_ADMIN,
- "close");
- FREE(sh);
- return NULL;
- }
+ if (0 != PIPE (sh->signal_pipe))
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_USER | GE_IMMEDIATE, "pipe");
+ FREE (sh);
+ return NULL;
+ }
+ if (OK != makePipeNonblocking (sh->ectx, sh->signal_pipe[0]))
+ {
+ if ((0 != CLOSE (sh->signal_pipe[0])) ||
+ (0 != CLOSE (sh->signal_pipe[1])))
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_IMMEDIATE | GE_ADMIN, "close");
+ FREE (sh);
+ return NULL;
+ }
sh->shutdown = NO;
sh->ectx = ectx;
@@ -890,31 +853,25 @@
sh->memory_quota = memory_quota;
sh->socket_quota = socket_quota;
sh->timeout = timeout;
- sh->lock = MUTEX_CREATE(YES);
+ sh->lock = MUTEX_CREATE (YES);
if (sock != -1)
- sh->listen_sock = socket_create(ectx,
- mon,
- sock);
+ sh->listen_sock = socket_create (ectx, mon, sock);
else
sh->listen_sock = NULL;
- sh->thread = PTHREAD_CREATE(&selectThread,
- sh,
- 256 * 1024);
- if (sh->thread == NULL) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_IMMEDIATE | GE_ADMIN,
- "pthread_create");
- if (sh->listen_sock != NULL)
- socket_destroy(sh->listen_sock);
- if ( (0 != CLOSE(sh->signal_pipe[0])) ||
- (0 != CLOSE(sh->signal_pipe[1])) )
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_IMMEDIATE | GE_ADMIN,
- "close");
- MUTEX_DESTROY(sh->lock);
- FREE(sh);
- return NULL;
- }
+ sh->thread = PTHREAD_CREATE (&selectThread, sh, 256 * 1024);
+ if (sh->thread == NULL)
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_ERROR | GE_IMMEDIATE | GE_ADMIN, "pthread_create");
+ if (sh->listen_sock != NULL)
+ socket_destroy (sh->listen_sock);
+ if ((0 != CLOSE (sh->signal_pipe[0])) ||
+ (0 != CLOSE (sh->signal_pipe[1])))
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_IMMEDIATE | GE_ADMIN, "close");
+ MUTEX_DESTROY (sh->lock);
+ FREE (sh);
+ return NULL;
+ }
return sh;
}
@@ -922,39 +879,35 @@
* Terminate the select thread, close the socket and
* all associated connections.
*/
-void select_destroy(struct SelectHandle * sh) {
- void * unused;
+void
+select_destroy (struct SelectHandle *sh)
+{
+ void *unused;
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Destroying select %p\n",
- sh);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK, "Destroying select %p\n", sh);
#endif
sh->shutdown = YES;
- signalSelect(sh);
- PTHREAD_STOP_SLEEP(sh->thread);
- PTHREAD_JOIN(sh->thread, &unused);
+ signalSelect (sh);
+ PTHREAD_STOP_SLEEP (sh->thread);
+ PTHREAD_JOIN (sh->thread, &unused);
sh->thread = NULL;
- MUTEX_LOCK(sh->lock);
+ MUTEX_LOCK (sh->lock);
while (sh->sessionCount > 0)
- destroySession(sh, sh->sessions[0]);
- GROW(sh->sessions,
- sh->sessionArrayLength,
- 0);
- MUTEX_UNLOCK(sh->lock);
- MUTEX_DESTROY(sh->lock);
- if (0 != CLOSE(sh->signal_pipe[1]))
- GE_LOG_STRERROR(sh->ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "close");
- if (0 != CLOSE(sh->signal_pipe[0]))
- GE_LOG_STRERROR(sh->ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "close");
+ destroySession (sh, sh->sessions[0]);
+ GROW (sh->sessions, sh->sessionArrayLength, 0);
+ MUTEX_UNLOCK (sh->lock);
+ MUTEX_DESTROY (sh->lock);
+ if (0 != CLOSE (sh->signal_pipe[1]))
+ GE_LOG_STRERROR (sh->ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK, "close");
+ if (0 != CLOSE (sh->signal_pipe[0]))
+ GE_LOG_STRERROR (sh->ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK, "close");
if (sh->listen_sock != NULL)
- socket_destroy(sh->listen_sock);
- FREE(sh);
+ socket_destroy (sh->listen_sock);
+ FREE (sh);
}
/**
@@ -968,117 +921,120 @@
* NO if there was not enough memory to queue it,
* SYSERR if the sock does not belong with this select
*/
-int select_write(struct SelectHandle * sh,
- struct SocketHandle * sock,
- const MESSAGE_HEADER * msg,
- int mayBlock,
- int force) {
- Session * session;
+int
+select_write (struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ const MESSAGE_HEADER * msg, int mayBlock, int force)
+{
+ Session *session;
int i;
unsigned short len;
int fresh_write;
- char * newBuffer;
+ char *newBuffer;
unsigned int newBufferSize;
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Adding message of size %u to %p of select %p\n",
- ntohs(msg->size),
- sock,
- sh);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Adding message of size %u to %p of select %p\n",
+ ntohs (msg->size), sock, sh);
#endif
session = NULL;
- len = ntohs(msg->size);
- MUTEX_LOCK(sh->lock);
- for (i=0;i<sh->sessionCount;i++)
- if (sh->sessions[i]->sock == sock) {
- session = sh->sessions[i];
- break;
+ len = ntohs (msg->size);
+ MUTEX_LOCK (sh->lock);
+ for (i = 0; i < sh->sessionCount; i++)
+ if (sh->sessions[i]->sock == sock)
+ {
+ session = sh->sessions[i];
+ break;
+ }
+ if (session == NULL)
+ {
+ MUTEX_UNLOCK (sh->lock);
+ return SYSERR;
}
- if (session == NULL) {
- MUTEX_UNLOCK(sh->lock);
- return SYSERR;
- }
- GE_ASSERT(NULL, session->wapos >= session->wspos);
- if ( (sh->memory_quota > 0) &&
- (session->wapos - session->wspos + len > sh->memory_quota) &&
- (force == NO) ) {
- /* not enough free space, not allowed to grow that much */
- MUTEX_UNLOCK(sh->lock);
- return NO;
- }
+ GE_ASSERT (NULL, session->wapos >= session->wspos);
+ if ((sh->memory_quota > 0) &&
+ (session->wapos - session->wspos + len > sh->memory_quota) &&
+ (force == NO))
+ {
+ /* not enough free space, not allowed to grow that much */
+ MUTEX_UNLOCK (sh->lock);
+ return NO;
+ }
fresh_write = (session->wapos == session->wspos);
- if (session->wsize - session->wapos < len) {
- /* need to make space in some way or other */
- if (session->wapos - session->wspos + len <= session->wsize) {
- /* can compact buffer to get space */
- memmove(session->wbuff,
- &session->wbuff[session->wspos],
- session->wapos - session->wspos);
- session->wapos -= session->wspos;
- session->wspos = 0;
- } else {
- /* need to grow buffer */
- newBufferSize = session->wsize;
- if (session->wsize == 0)
- newBufferSize = 4092;
- while (newBufferSize < len + session->wapos - session->wspos)
- newBufferSize *= 2;
- if ( (sh->memory_quota > 0) &&
- (newBufferSize > sh->memory_quota) &&
- (force == NO) )
- newBufferSize = sh->memory_quota;
- GE_ASSERT(NULL,
- newBufferSize >= len + session->wapos - session->wspos);
- newBuffer = MALLOC(newBufferSize);
- memcpy(newBuffer,
- &session->wbuff[session->wspos],
- session->wapos - session->wspos);
- FREENONNULL(session->wbuff);
- session->wbuff = newBuffer;
- session->wsize = newBufferSize;
- session->wapos = session->wapos - session->wspos;
- session->wspos = 0;
+ if (session->wsize - session->wapos < len)
+ {
+ /* need to make space in some way or other */
+ if (session->wapos - session->wspos + len <= session->wsize)
+ {
+ /* can compact buffer to get space */
+ memmove (session->wbuff,
+ &session->wbuff[session->wspos],
+ session->wapos - session->wspos);
+ session->wapos -= session->wspos;
+ session->wspos = 0;
+ }
+ else
+ {
+ /* need to grow buffer */
+ newBufferSize = session->wsize;
+ if (session->wsize == 0)
+ newBufferSize = 4092;
+ while (newBufferSize < len + session->wapos - session->wspos)
+ newBufferSize *= 2;
+ if ((sh->memory_quota > 0) &&
+ (newBufferSize > sh->memory_quota) && (force == NO))
+ newBufferSize = sh->memory_quota;
+ GE_ASSERT (NULL,
+ newBufferSize >= len + session->wapos - session->wspos);
+ newBuffer = MALLOC (newBufferSize);
+ memcpy (newBuffer,
+ &session->wbuff[session->wspos],
+ session->wapos - session->wspos);
+ FREENONNULL (session->wbuff);
+ session->wbuff = newBuffer;
+ session->wsize = newBufferSize;
+ session->wapos = session->wapos - session->wspos;
+ session->wspos = 0;
+ }
}
- }
- GE_ASSERT(NULL,
- session->wapos + len <= session->wsize);
- memcpy(&session->wbuff[session->wapos],
- msg,
- len);
+ GE_ASSERT (NULL, session->wapos + len <= session->wsize);
+ memcpy (&session->wbuff[session->wapos], msg, len);
session->wapos += len;
- MUTEX_UNLOCK(sh->lock);
+ MUTEX_UNLOCK (sh->lock);
if (fresh_write)
- signalSelect(sh);
+ signalSelect (sh);
return OK;
}
/**
*/
-int select_update_closure(struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * old_sock_ctx,
- void * new_sock_ctx) {
- Session * session;
+int
+select_update_closure (struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ void *old_sock_ctx, void *new_sock_ctx)
+{
+ Session *session;
int i;
session = NULL;
- MUTEX_LOCK(sh->lock);
- for (i=0;i<sh->sessionCount;i++)
- if (sh->sessions[i]->sock == sock) {
- session = sh->sessions[i];
- break;
+ MUTEX_LOCK (sh->lock);
+ for (i = 0; i < sh->sessionCount; i++)
+ if (sh->sessions[i]->sock == sock)
+ {
+ session = sh->sessions[i];
+ break;
+ }
+ if (session == NULL)
+ {
+ MUTEX_UNLOCK (sh->lock);
+ return SYSERR;
}
- if (session == NULL) {
- MUTEX_UNLOCK(sh->lock);
- return SYSERR;
- }
- GE_ASSERT(NULL,
- session->sock_ctx == old_sock_ctx);
+ GE_ASSERT (NULL, session->sock_ctx == old_sock_ctx);
session->sock_ctx = new_sock_ctx;
- MUTEX_UNLOCK(sh->lock);
+ MUTEX_UNLOCK (sh->lock);
return OK;
}
@@ -1086,40 +1042,38 @@
* Add another (already connected) socket to the set of
* sockets managed by the select.
*/
-int select_connect(struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * sock_ctx) {
- Session * session;
+int
+select_connect (struct SelectHandle *sh,
+ struct SocketHandle *sock, void *sock_ctx)
+{
+ Session *session;
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Adding connection %p to selector %p\n",
- sock,
- sh);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Adding connection %p to selector %p\n", sock, sh);
#endif
- session = MALLOC(sizeof(Session));
- memset(session, 0, sizeof(Session));
+ session = MALLOC (sizeof (Session));
+ memset (session, 0, sizeof (Session));
session->sock = sock;
session->sock_ctx = sock_ctx;
- session->lastUse = get_time();
- MUTEX_LOCK(sh->lock);
+ session->lastUse = get_time ();
+ MUTEX_LOCK (sh->lock);
if (sh->sessionArrayLength == sh->sessionCount)
- GROW(sh->sessions,
- sh->sessionArrayLength,
- sh->sessionArrayLength + 4);
+ GROW (sh->sessions, sh->sessionArrayLength, sh->sessionArrayLength + 4);
sh->sessions[sh->sessionCount++] = session;
sh->socket_quota--;
- MUTEX_UNLOCK(sh->lock);
- signalSelect(sh);
+ MUTEX_UNLOCK (sh->lock);
+ signalSelect (sh);
return OK;
}
-static Session * findSession(struct SelectHandle * sh,
- struct SocketHandle * sock) {
+static Session *
+findSession (struct SelectHandle *sh, struct SocketHandle *sock)
+{
int i;
- for (i=0;i<sh->sessionCount;i++)
+ for (i = 0; i < sh->sessionCount; i++)
if (sh->sessions[i]->sock == sock)
return sh->sessions[i];
return NULL;
@@ -1129,27 +1083,26 @@
* Close the associated socket and remove it from the
* set of sockets managed by select.
*/
-int select_disconnect(struct SelectHandle * sh,
- struct SocketHandle * sock) {
- Session * session;
+int
+select_disconnect (struct SelectHandle *sh, struct SocketHandle *sock)
+{
+ Session *session;
#if DEBUG_SELECT
- GE_LOG(sh->ectx,
- GE_DEBUG | GE_DEVELOPER | GE_BULK,
- "Removing connection %p from selector %p\n",
- sock,
- sh);
+ GE_LOG (sh->ectx,
+ GE_DEBUG | GE_DEVELOPER | GE_BULK,
+ "Removing connection %p from selector %p\n", sock, sh);
#endif
- MUTEX_LOCK(sh->lock);
- session = findSession(sh,
- sock);
- if (session == NULL) {
- MUTEX_UNLOCK(sh->lock);
- return SYSERR;
- }
- destroySession(sh, session);
- MUTEX_UNLOCK(sh->lock);
- signalSelect(sh);
+ MUTEX_LOCK (sh->lock);
+ session = findSession (sh, sock);
+ if (session == NULL)
+ {
+ MUTEX_UNLOCK (sh->lock);
+ return SYSERR;
+ }
+ destroySession (sh, session);
+ MUTEX_UNLOCK (sh->lock);
+ signalSelect (sh);
return OK;
}
@@ -1158,20 +1111,21 @@
* value. Use 0 to use the default timeout for
* this select.
*/
-int select_change_timeout(struct SelectHandle * sh,
- struct SocketHandle * sock,
- cron_t timeout) {
- Session * session;
+int
+select_change_timeout (struct SelectHandle *sh,
+ struct SocketHandle *sock, cron_t timeout)
+{
+ Session *session;
- MUTEX_LOCK(sh->lock);
- session = findSession(sh,
- sock);
- if (session == NULL) {
- MUTEX_UNLOCK(sh->lock);
- return SYSERR;
- }
+ MUTEX_LOCK (sh->lock);
+ session = findSession (sh, sock);
+ if (session == NULL)
+ {
+ MUTEX_UNLOCK (sh->lock);
+ return SYSERR;
+ }
session->timeout = timeout;
- MUTEX_UNLOCK(sh->lock);
+ MUTEX_UNLOCK (sh->lock);
return OK;
}
@@ -1188,29 +1142,29 @@
* NO if there was not enough memory to queue it,
* SYSERR if the sock does not belong with this select
*/
-int select_would_try(struct SelectHandle * sh,
- struct SocketHandle * sock,
- unsigned int size,
- int mayBlock,
- int force) {
- Session * session;
+int
+select_would_try (struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ unsigned int size, int mayBlock, int force)
+{
+ Session *session;
- MUTEX_LOCK(sh->lock);
- session = findSession(sh,
- sock);
- if (session == NULL) {
- MUTEX_UNLOCK(sh->lock);
- return SYSERR;
- }
- GE_ASSERT(NULL,
- session->wapos >= session->wspos);
- if ( (sh->memory_quota > 0) &&
- (session->wapos - session->wspos + size > sh->memory_quota) &&
- (force == NO) ) {
- /* not enough free space, not allowed to grow that much */
- MUTEX_UNLOCK(sh->lock);
- return NO;
- }
- MUTEX_UNLOCK(sh->lock);
+ MUTEX_LOCK (sh->lock);
+ session = findSession (sh, sock);
+ if (session == NULL)
+ {
+ MUTEX_UNLOCK (sh->lock);
+ return SYSERR;
+ }
+ GE_ASSERT (NULL, session->wapos >= session->wspos);
+ if ((sh->memory_quota > 0) &&
+ (session->wapos - session->wspos + size > sh->memory_quota) &&
+ (force == NO))
+ {
+ /* not enough free space, not allowed to grow that much */
+ MUTEX_UNLOCK (sh->lock);
+ return NO;
+ }
+ MUTEX_UNLOCK (sh->lock);
return YES;
}
Modified: GNUnet/src/util/network/selecttest.c
===================================================================
--- GNUnet/src/util/network/selecttest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/network/selecttest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -46,7 +46,7 @@
#define DO_YIELD NO
#if DO_YIELD
-void pthread_yield(void);
+void pthread_yield (void);
#endif
/**
@@ -60,9 +60,9 @@
#endif
-static struct SocketHandle * out;
+static struct SocketHandle *out;
-static struct SocketHandle * in;
+static struct SocketHandle *in;
static unsigned int recvPos;
@@ -77,46 +77,41 @@
* @return OK if message was valid, SYSERR if corresponding
* socket should be closed
*/
-static int test_smh(void * mh_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * sock_ctx,
- const MESSAGE_HEADER * msg) {
+static int
+test_smh (void *mh_cls,
+ struct SelectHandle *sh,
+ struct SocketHandle *sock,
+ void *sock_ctx, const MESSAGE_HEADER * msg)
+{
static int sleeper;
- char * expect;
+ char *expect;
unsigned short size;
- size = ntohs(msg->size);
+ size = ntohs (msg->size);
throughput += size;
- expect = MALLOC(size);
- memset(expect,
- (size - sizeof(MESSAGE_HEADER)) % 251,
- size);
- if (0 != memcmp(&msg[1],
- expect,
- size - sizeof(MESSAGE_HEADER)) ) {
- fprintf(stderr,
- "Message of size %u corrupt!\n",
- size);
- FREE(expect);
- return OK;
- }
- FREE(expect);
- while (msg->type != htons(recvPos)) {
- fprintf(stderr,
- "Message %u lost!\n",
- recvPos);
- recvPos++;
- }
+ expect = MALLOC (size);
+ memset (expect, (size - sizeof (MESSAGE_HEADER)) % 251, size);
+ if (0 != memcmp (&msg[1], expect, size - sizeof (MESSAGE_HEADER)))
+ {
+ fprintf (stderr, "Message of size %u corrupt!\n", size);
+ FREE (expect);
+ return OK;
+ }
+ FREE (expect);
+ while (msg->type != htons (recvPos))
+ {
+ fprintf (stderr, "Message %u lost!\n", recvPos);
+ recvPos++;
+ }
recvPos++;
if (sleeper % 128 == 0)
- fprintf(stderr, ".");
+ fprintf (stderr, ".");
#if DO_SLEEP
if (sleeper % 5 == 0)
- PTHREAD_SLEEP(50 * cronMILLIS);
+ PTHREAD_SLEEP (50 * cronMILLIS);
#endif
sleeper++;
- return OK;
+ return OK;
}
@@ -131,167 +126,141 @@
* @return NULL to reject connection, otherwise value of sock_ctx
* for the new connection
*/
-static void * test_sah(void * ah_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- const void * addr,
- unsigned int addr_len) {
+static void *
+test_sah (void *ah_cls,
+ struct SelectHandle *sh,
+ struct SocketHandle *sock, const void *addr, unsigned int addr_len)
+{
static int ret_addr;
- GE_BREAK(NULL, in == NULL);
+ GE_BREAK (NULL, in == NULL);
in = sock;
- return &ret_addr; /* dummy value for accept */
+ return &ret_addr; /* dummy value for accept */
}
/**
* Select has been forced to close a connection.
* Free the associated context.
*/
-static void test_sch(void * ch_cls,
- struct SelectHandle * sh,
- struct SocketHandle * sock,
- void * sock_ctx) {
+static void
+test_sch (void *ch_cls,
+ struct SelectHandle *sh, struct SocketHandle *sock, void *sock_ctx)
+{
if (sock == in)
in = NULL;
else if (sock == out)
out = NULL;
else
- GE_BREAK(NULL, 0);
+ GE_BREAK (NULL, 0);
}
-static int check() {
+static int
+check ()
+{
static int zero = 0;
struct sockaddr_in serverAddr;
- struct SelectHandle * sh;
+ struct SelectHandle *sh;
int listen_sock;
int write_sock;
int i;
int msg;
- char * m;
- MESSAGE_HEADER * h;
+ char *m;
+ MESSAGE_HEADER *h;
cron_t start;
- listen_sock = SOCKET(PF_INET,
- SOCK_STREAM,
- 6); /* 6: TCP */
- if (listen_sock == -1) {
- GE_BREAK(NULL, 0);
- return 1;
- }
+ listen_sock = SOCKET (PF_INET, SOCK_STREAM, 6); /* 6: TCP */
+ if (listen_sock == -1)
+ {
+ GE_BREAK (NULL, 0);
+ return 1;
+ }
#if TCP_SYNCNT
/* only try a single packet to establish connection,
if that does not work, abort instantly */
- setsockopt(listen_sock,
- IPPROTO_TCP,
- TCP_SYNCNT,
- &zero,
- sizeof(zero));
+ setsockopt (listen_sock, IPPROTO_TCP, TCP_SYNCNT, &zero, sizeof (zero));
#endif
- memset((char *) &serverAddr,
- 0,
- sizeof(serverAddr));
- serverAddr.sin_family = AF_INET;
- serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
- serverAddr.sin_port = htons(PORT);
- if (BIND(listen_sock,
- (struct sockaddr *) &serverAddr,
- sizeof(serverAddr)) < 0) {
- CLOSE(listen_sock);
- return 1;
- }
- LISTEN(listen_sock, 5);
+ memset ((char *) &serverAddr, 0, sizeof (serverAddr));
+ serverAddr.sin_family = AF_INET;
+ serverAddr.sin_addr.s_addr = htonl (INADDR_ANY);
+ serverAddr.sin_port = htons (PORT);
+ if (BIND (listen_sock,
+ (struct sockaddr *) &serverAddr, sizeof (serverAddr)) < 0)
+ {
+ CLOSE (listen_sock);
+ return 1;
+ }
+ LISTEN (listen_sock, 5);
- sh = select_create("Select Tester",
- NO, /* tcp */
- NULL, /* ectx */
- NULL, /* no load monitoring */
- listen_sock,
- sizeof(IPaddr),
- 15 * cronSECONDS, /* inactive timeout */
- test_smh,
- NULL,
- test_sah,
- NULL,
- test_sch,
- NULL,
- 128 * 1024, /* memory quota */
- 128 /* socket quota */);
+ sh = select_create ("Select Tester", NO, /* tcp */
+ NULL, /* ectx */
+ NULL, /* no load monitoring */
+ listen_sock, sizeof (IPaddr), 15 * cronSECONDS, /*
inactive timeout */
+ test_smh, NULL, test_sah, NULL, test_sch, NULL, 128 *
1024, /* memory quota */
+ 128 /* socket quota */ );
- write_sock = SOCKET(PF_INET,
- SOCK_STREAM,
- 6);
+ write_sock = SOCKET (PF_INET, SOCK_STREAM, 6);
- memset((char *) &serverAddr,
- 0,
- sizeof(serverAddr));
- serverAddr.sin_family = AF_INET;
- serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
- serverAddr.sin_port = htons(PORT);
- i = CONNECT(write_sock,
- (struct sockaddr*)&serverAddr,
- sizeof(serverAddr));
- if ( (i < 0) &&
- (errno != EINPROGRESS) && (errno != EWOULDBLOCK) ) {
- CLOSE(write_sock);
- select_destroy(sh);
- return 1;
- }
- out = socket_create(NULL,
- NULL,
- write_sock);
- if (-1 == socket_set_blocking(out, NO)) {
- socket_destroy(out);
- select_destroy(sh);
- return 1;
- }
+ memset ((char *) &serverAddr, 0, sizeof (serverAddr));
+ serverAddr.sin_family = AF_INET;
+ serverAddr.sin_addr.s_addr = htonl (INADDR_ANY);
+ serverAddr.sin_port = htons (PORT);
+ i = CONNECT (write_sock,
+ (struct sockaddr *) &serverAddr, sizeof (serverAddr));
+ if ((i < 0) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK))
+ {
+ CLOSE (write_sock);
+ select_destroy (sh);
+ return 1;
+ }
+ out = socket_create (NULL, NULL, write_sock);
+ if (-1 == socket_set_blocking (out, NO))
+ {
+ socket_destroy (out);
+ select_destroy (sh);
+ return 1;
+ }
msg = 0;
- m = MALLOC(65536);
- h = (MESSAGE_HEADER*) m;
- select_connect(sh,
- out,
- NULL);
- start = get_time();
- for (i=0;i<ITER;i++) {
- if (GNUNET_SHUTDOWN_TEST() == YES)
- break;
- if (select_would_try(sh,
- out,
- (i % 60000) + sizeof(MESSAGE_HEADER),
- NO,
- NO)) {
- h->size = htons((i % 60000) + sizeof(MESSAGE_HEADER));
- h->type = htons(msg++);
- memset(&m[sizeof(MESSAGE_HEADER)],
- (i % 60000) % 251,
- i % 60000);
- select_write(sh,
- out,
- h,
- NO,
- NO);
- } else {
+ m = MALLOC (65536);
+ h = (MESSAGE_HEADER *) m;
+ select_connect (sh, out, NULL);
+ start = get_time ();
+ for (i = 0; i < ITER; i++)
+ {
+ if (GNUNET_SHUTDOWN_TEST () == YES)
+ break;
+ if (select_would_try (sh,
+ out,
+ (i % 60000) + sizeof (MESSAGE_HEADER), NO, NO))
+ {
+ h->size = htons ((i % 60000) + sizeof (MESSAGE_HEADER));
+ h->type = htons (msg++);
+ memset (&m[sizeof (MESSAGE_HEADER)], (i % 60000) % 251, i % 60000);
+ select_write (sh, out, h, NO, NO);
+ }
+ else
+ {
#if DO_YIELD
- pthread_yield();
+ pthread_yield ();
#endif
- }
+ }
#if DO_SLEEP
- if (i % 500 == 0)
- PTHREAD_SLEEP(500 * cronMILLIS);
+ if (i % 500 == 0)
+ PTHREAD_SLEEP (500 * cronMILLIS);
#endif
- }
+ }
/* give select time to send the rest... */
#if DO_SLEEP
- PTHREAD_SLEEP(2500 * cronMILLIS);
+ PTHREAD_SLEEP (2500 * cronMILLIS);
#endif
- select_disconnect(sh, out);
- select_destroy(sh);
- FREE(m);
- fprintf(stderr,
- "\nTransmitted %u test messages - received %u (performance: %llu kbps)\n",
- msg,
- recvPos,
- (throughput / 1024) * cronSECONDS / (get_time() - start));
+ select_disconnect (sh, out);
+ select_destroy (sh);
+ FREE (m);
+ fprintf (stderr,
+ "\nTransmitted %u test messages - received %u (performance: %llu
kbps)\n",
+ msg,
+ recvPos,
+ (throughput / 1024) * cronSECONDS / (get_time () - start));
#if DO_SLEEP
if (msg - recvPos > 30)
return 1;
@@ -299,14 +268,13 @@
return 0;
}
-int main(int argc,
- char * argv[]){
+int
+main (int argc, char *argv[])
+{
int ret;
- ret = check();
+ ret = check ();
if (ret != 0)
- fprintf(stderr,
- "ERROR %d.\n",
- ret);
+ fprintf (stderr, "ERROR %d.\n", ret);
return ret;
}
Modified: GNUnet/src/util/network_client/daemon.c
===================================================================
--- GNUnet/src/util/network_client/daemon.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/network_client/daemon.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -30,51 +30,51 @@
#include "gnunet_protocols.h"
#include "gnunet_util_threads.h"
-int connection_test_running(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- struct ClientServerConnection * sock;
+int
+connection_test_running (struct GE_Context *ectx,
+ struct GC_Configuration *cfg)
+{
+ struct ClientServerConnection *sock;
MESSAGE_HEADER csHdr;
int ret;
- sock = client_connection_create(ectx, cfg);
+ sock = client_connection_create (ectx, cfg);
if (sock == NULL)
return SYSERR;
- csHdr.size
- = htons(sizeof(MESSAGE_HEADER));
- csHdr.type
- = htons(CS_PROTO_traffic_COUNT);
- if (SYSERR == connection_write(sock,
- &csHdr)) {
- connection_destroy(sock);
- return SYSERR;
- }
- if (SYSERR == connection_read_result(sock,
- &ret)) {
- connection_destroy(sock);
- return SYSERR;
- }
- connection_destroy(sock);
+ csHdr.size = htons (sizeof (MESSAGE_HEADER));
+ csHdr.type = htons (CS_PROTO_traffic_COUNT);
+ if (SYSERR == connection_write (sock, &csHdr))
+ {
+ connection_destroy (sock);
+ return SYSERR;
+ }
+ if (SYSERR == connection_read_result (sock, &ret))
+ {
+ connection_destroy (sock);
+ return SYSERR;
+ }
+ connection_destroy (sock);
return OK;
}
-int connection_request_shutdown(struct ClientServerConnection * sock) {
+int
+connection_request_shutdown (struct ClientServerConnection *sock)
+{
MESSAGE_HEADER csHdr;
int ret;
- csHdr.size
- = htons(sizeof(MESSAGE_HEADER));
- csHdr.type
- = htons(CS_PROTO_SHUTDOWN_REQUEST);
- if (SYSERR == connection_write(sock,
- &csHdr)) {
- connection_close_temporarily(sock);
- return SYSERR;
- }
- if (SYSERR == connection_read_result(sock,
- &ret)) {
- connection_close_temporarily(sock);
- return SYSERR;
- }
+ csHdr.size = htons (sizeof (MESSAGE_HEADER));
+ csHdr.type = htons (CS_PROTO_SHUTDOWN_REQUEST);
+ if (SYSERR == connection_write (sock, &csHdr))
+ {
+ connection_close_temporarily (sock);
+ return SYSERR;
+ }
+ if (SYSERR == connection_read_result (sock, &ret))
+ {
+ connection_close_temporarily (sock);
+ return SYSERR;
+ }
return ret;
}
@@ -85,25 +85,26 @@
* @param timeout how long to wait at most
* @return OK if gnunetd is now running
*/
-int connection_wait_for_running(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- cron_t timeout) {
+int
+connection_wait_for_running (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, cron_t timeout)
+{
cron_t min;
int ret;
- timeout += get_time();
- while (GNUNET_SHUTDOWN_TEST() == 0) {
- ret = connection_test_running(ectx,
- cfg);
- if (ret == OK)
- return OK;
- if (timeout < get_time())
- return SYSERR;
- min = timeout - get_time();
- if (min > 100 * cronMILLIS)
- min = 100 * cronMILLIS;
- PTHREAD_SLEEP(min);
- }
+ timeout += get_time ();
+ while (GNUNET_SHUTDOWN_TEST () == 0)
+ {
+ ret = connection_test_running (ectx, cfg);
+ if (ret == OK)
+ return OK;
+ if (timeout < get_time ())
+ return SYSERR;
+ min = timeout - get_time ();
+ if (min > 100 * cronMILLIS)
+ min = 100 * cronMILLIS;
+ PTHREAD_SLEEP (min);
+ }
return SYSERR;
}
Modified: GNUnet/src/util/network_client/tcpio.c
===================================================================
--- GNUnet/src/util/network_client/tcpio.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/network_client/tcpio.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -51,22 +51,23 @@
* drops the connection, the client automatically tries
* to reconnect (and for that needs connection information).
*/
-typedef struct ClientServerConnection {
+typedef struct ClientServerConnection
+{
/**
* the socket handle, NULL if not life
*/
- struct SocketHandle * sock;
+ struct SocketHandle *sock;
- struct MUTEX * readlock;
+ struct MUTEX *readlock;
- struct MUTEX * writelock;
+ struct MUTEX *writelock;
- struct MUTEX * destroylock;
+ struct MUTEX *destroylock;
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
int dead;
@@ -77,38 +78,42 @@
* Return the port-number (in host byte order)
* @return 0 on error
*/
-static unsigned short getGNUnetPort(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- char * res;
- char * pos;
+static unsigned short
+getGNUnetPort (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ char *res;
+ char *pos;
unsigned int port;
res = NULL;
- if (-1 == GC_get_configuration_value_string(cfg,
- "NETWORK",
- "HOST",
- "localhost:2087",
- &res)) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- _("Could not find valid value for HOST in section NETWORK."));
- return 2087;
- }
- pos = strstr(res, ":");
- if (pos == NULL) {
- FREE(res);
- return 2087;
- }
+ if (-1 == GC_get_configuration_value_string (cfg,
+ "NETWORK",
+ "HOST",
+ "localhost:2087", &res))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ _("Could not find valid value for HOST in section NETWORK."));
+ return 2087;
+ }
+ pos = strstr (res, ":");
+ if (pos == NULL)
+ {
+ FREE (res);
+ return 2087;
+ }
pos++;
- if (1 != SSCANF(pos, "%u", &port)) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- _("Syntax error in configuration entry HOST in section NETWORK: `%s'"),
- pos);
- FREE(res);
- return 2087;
- }
- FREE(res);
+ if (1 != SSCANF (pos, "%u", &port))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ _
+ ("Syntax error in configuration entry HOST in section NETWORK:
`%s'"),
+ pos);
+ FREE (res);
+ return 2087;
+ }
+ FREE (res);
return (unsigned short) port;
}
@@ -119,93 +124,108 @@
* @return the name of the host, NULL on error
*/
static char *
-getGNUnetdHost(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- char * res;
- char * pos;
+getGNUnetdHost (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ char *res;
+ char *pos;
res = NULL;
- if (-1 == GC_get_configuration_value_string(cfg,
- "NETWORK",
- "HOST",
- "localhost:2087",
- &res)) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- _("Could not find valid value for HOST in section NETWORK."));
- return NULL;
- }
- pos = strstr(res, ":");
+ if (-1 == GC_get_configuration_value_string (cfg,
+ "NETWORK",
+ "HOST",
+ "localhost:2087", &res))
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ _("Could not find valid value for HOST in section NETWORK."));
+ return NULL;
+ }
+ pos = strstr (res, ":");
if (pos != NULL)
*pos = '\0';
return res;
}
struct ClientServerConnection *
-client_connection_create(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- ClientServerConnection * result;
+client_connection_create (struct GE_Context *ectx,
+ struct GC_Configuration *cfg)
+{
+ ClientServerConnection *result;
- result = MALLOC(sizeof(ClientServerConnection));
+ result = MALLOC (sizeof (ClientServerConnection));
result->sock = NULL;
- result->readlock = MUTEX_CREATE(NO);
- result->writelock = MUTEX_CREATE(NO);
- result->destroylock = MUTEX_CREATE(YES);
+ result->readlock = MUTEX_CREATE (NO);
+ result->writelock = MUTEX_CREATE (NO);
+ result->destroylock = MUTEX_CREATE (YES);
result->ectx = ectx;
result->cfg = cfg;
return result;
}
-void connection_close_temporarily(struct ClientServerConnection * sock) {
- GE_ASSERT(NULL, sock != NULL);
- MUTEX_LOCK(sock->destroylock);
- if (sock->sock != NULL) {
- socket_close(sock->sock);
- MUTEX_LOCK(sock->readlock);
- MUTEX_LOCK(sock->writelock);
- socket_destroy(sock->sock);
- sock->sock = NULL;
- MUTEX_UNLOCK(sock->writelock);
- MUTEX_UNLOCK(sock->readlock);
- }
- MUTEX_UNLOCK(sock->destroylock);
+void
+connection_close_temporarily (struct ClientServerConnection *sock)
+{
+ GE_ASSERT (NULL, sock != NULL);
+ MUTEX_LOCK (sock->destroylock);
+ if (sock->sock != NULL)
+ {
+ socket_close (sock->sock);
+ MUTEX_LOCK (sock->readlock);
+ MUTEX_LOCK (sock->writelock);
+ socket_destroy (sock->sock);
+ sock->sock = NULL;
+ MUTEX_UNLOCK (sock->writelock);
+ MUTEX_UNLOCK (sock->readlock);
+ }
+ MUTEX_UNLOCK (sock->destroylock);
}
-void connection_close_forever(struct ClientServerConnection * sock) {
- GE_ASSERT(NULL, sock != NULL);
- MUTEX_LOCK(sock->destroylock);
- if (sock->sock != NULL) {
- socket_close(sock->sock);
- MUTEX_LOCK(sock->readlock);
- MUTEX_LOCK(sock->writelock);
- socket_destroy(sock->sock);
- sock->sock = NULL;
- sock->dead = YES;
- MUTEX_UNLOCK(sock->writelock);
- MUTEX_UNLOCK(sock->readlock);
- } else {
- sock->dead = YES;
- }
- MUTEX_UNLOCK(sock->destroylock);
+void
+connection_close_forever (struct ClientServerConnection *sock)
+{
+ GE_ASSERT (NULL, sock != NULL);
+ MUTEX_LOCK (sock->destroylock);
+ if (sock->sock != NULL)
+ {
+ socket_close (sock->sock);
+ MUTEX_LOCK (sock->readlock);
+ MUTEX_LOCK (sock->writelock);
+ socket_destroy (sock->sock);
+ sock->sock = NULL;
+ sock->dead = YES;
+ MUTEX_UNLOCK (sock->writelock);
+ MUTEX_UNLOCK (sock->readlock);
+ }
+ else
+ {
+ sock->dead = YES;
+ }
+ MUTEX_UNLOCK (sock->destroylock);
}
-void connection_destroy(struct ClientServerConnection * sock) {
- GE_ASSERT(NULL, sock != NULL);
- connection_close_forever(sock);
- MUTEX_DESTROY(sock->readlock);
- MUTEX_DESTROY(sock->writelock);
- MUTEX_DESTROY(sock->destroylock);
- FREE(sock);
+void
+connection_destroy (struct ClientServerConnection *sock)
+{
+ GE_ASSERT (NULL, sock != NULL);
+ connection_close_forever (sock);
+ MUTEX_DESTROY (sock->readlock);
+ MUTEX_DESTROY (sock->writelock);
+ MUTEX_DESTROY (sock->destroylock);
+ FREE (sock);
}
-int connection_test_open(struct ClientServerConnection * sock) {
+int
+connection_test_open (struct ClientServerConnection *sock)
+{
return (sock->sock != NULL);
}
/**
* Check a socket, open and connect if it is closed and it is a client-socket.
*/
-int connection_ensure_connected(struct ClientServerConnection * sock) {
+int
+connection_ensure_connected (struct ClientServerConnection *sock)
+{
struct sockaddr_in soaddr;
fd_set rset;
fd_set wset;
@@ -214,138 +234,118 @@
int ret;
int osock;
unsigned short port;
- char * host;
+ char *host;
IPaddr ip;
- GE_ASSERT(NULL, sock != NULL);
+ GE_ASSERT (NULL, sock != NULL);
if (sock->sock != NULL)
return OK;
if (sock->dead == YES)
return SYSERR;
- port = getGNUnetPort(sock->ectx,
- sock->cfg);
+ port = getGNUnetPort (sock->ectx, sock->cfg);
if (port == 0)
return SYSERR;
- host = getGNUnetdHost(sock->ectx,
- sock->cfg);
+ host = getGNUnetdHost (sock->ectx, sock->cfg);
if (host == NULL)
return SYSERR;
- if (SYSERR == get_host_by_name(sock->ectx,
- host,
- &ip)) {
- FREE(host);
- return SYSERR;
- }
- MUTEX_LOCK(sock->destroylock);
- if (sock->sock != NULL) {
- FREE(host);
- MUTEX_UNLOCK(sock->destroylock);
- return OK;
- }
- if (sock->dead == YES) {
- FREE(host);
- MUTEX_UNLOCK(sock->destroylock);
- return SYSERR;
- }
- osock = SOCKET(PF_INET, SOCK_STREAM, 6); /* 6: TCP */
- if (osock == -1) {
- GE_LOG_STRERROR(sock->ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "socket");
- FREE(host);
- MUTEX_UNLOCK(sock->destroylock);
- return SYSERR;
- }
- sock->sock = socket_create(sock->ectx,
- NULL,
- osock);
- socket_set_blocking(sock->sock, NO);
- memset(&soaddr,
- 0,
- sizeof(soaddr));
+ if (SYSERR == get_host_by_name (sock->ectx, host, &ip))
+ {
+ FREE (host);
+ return SYSERR;
+ }
+ MUTEX_LOCK (sock->destroylock);
+ if (sock->sock != NULL)
+ {
+ FREE (host);
+ MUTEX_UNLOCK (sock->destroylock);
+ return OK;
+ }
+ if (sock->dead == YES)
+ {
+ FREE (host);
+ MUTEX_UNLOCK (sock->destroylock);
+ return SYSERR;
+ }
+ osock = SOCKET (PF_INET, SOCK_STREAM, 6); /* 6: TCP */
+ if (osock == -1)
+ {
+ GE_LOG_STRERROR (sock->ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK, "socket");
+ FREE (host);
+ MUTEX_UNLOCK (sock->destroylock);
+ return SYSERR;
+ }
+ sock->sock = socket_create (sock->ectx, NULL, osock);
+ socket_set_blocking (sock->sock, NO);
+ memset (&soaddr, 0, sizeof (soaddr));
soaddr.sin_family = AF_INET;
- GE_ASSERT(sock->ectx,
- sizeof(struct in_addr) == sizeof(IPaddr));
- memcpy(&soaddr.sin_addr,
- &ip,
- sizeof(struct in_addr));
- soaddr.sin_port = htons(port);
- ret = CONNECT(osock,
- (struct sockaddr*)&soaddr,
- sizeof(soaddr));
- if ( (ret != 0) &&
- (errno != EINPROGRESS) && (errno != EWOULDBLOCK)) {
- GE_LOG(sock->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Cannot connect to %s:%u: %s\n"),
- host,
- port,
- STRERROR(errno));
- socket_destroy(sock->sock);
- sock->sock = NULL;
- FREE(host);
- MUTEX_UNLOCK(sock->destroylock);
- return SYSERR;
- }
+ GE_ASSERT (sock->ectx, sizeof (struct in_addr) == sizeof (IPaddr));
+ memcpy (&soaddr.sin_addr, &ip, sizeof (struct in_addr));
+ soaddr.sin_port = htons (port);
+ ret = CONNECT (osock, (struct sockaddr *) &soaddr, sizeof (soaddr));
+ if ((ret != 0) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK))
+ {
+ GE_LOG (sock->ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Cannot connect to %s:%u: %s\n"),
+ host, port, STRERROR (errno));
+ socket_destroy (sock->sock);
+ sock->sock = NULL;
+ FREE (host);
+ MUTEX_UNLOCK (sock->destroylock);
+ return SYSERR;
+ }
/* we call select() first with a timeout of WAIT_SECONDS to
avoid blocking on a later write indefinitely;
Important if a local firewall decides to just drop
- the TCP handshake...*/
- FD_ZERO(&rset);
- FD_ZERO(&wset);
- FD_ZERO(&eset);
- FD_SET(osock, &wset);
- FD_SET(osock, &eset);
+ the TCP handshake... */
+ FD_ZERO (&rset);
+ FD_ZERO (&wset);
+ FD_ZERO (&eset);
+ FD_SET (osock, &wset);
+ FD_SET (osock, &eset);
#define WAIT_SECONDS 1
timeout.tv_sec = WAIT_SECONDS;
timeout.tv_usec = 0;
errno = 0;
- ret = SELECT(osock + 1,
- &rset,
- &wset,
- &eset,
- &timeout);
- if (ret == -1) {
- if (errno != EINTR)
- GE_LOG_STRERROR(sock->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "select");
- socket_destroy(sock->sock);
- sock->sock = NULL;
- FREE(host);
- MUTEX_UNLOCK(sock->destroylock);
- return SYSERR;
- }
- if (FD_ISSET(osock,
- &eset)) {
- GE_LOG(sock->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Error connecting to %s:%u\n"),
- host,
- port);
- socket_destroy(sock->sock);
- sock->sock = NULL;
- FREE(host);
- MUTEX_UNLOCK(sock->destroylock);
- return SYSERR;
- }
- if (! FD_ISSET(osock,
- &wset)) {
- GE_LOG(sock->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- _("Failed to connect to %s:%u in %ds\n"),
- host,
- port,
- WAIT_SECONDS);
- socket_destroy(sock->sock);
- sock->sock = NULL;
- FREE(host);
- MUTEX_UNLOCK(sock->destroylock);
- return SYSERR;
- }
- FREE(host);
- socket_set_blocking(sock->sock, YES);
- MUTEX_UNLOCK(sock->destroylock);
+ ret = SELECT (osock + 1, &rset, &wset, &eset, &timeout);
+ if (ret == -1)
+ {
+ if (errno != EINTR)
+ GE_LOG_STRERROR (sock->ectx,
+ GE_WARNING | GE_USER | GE_BULK, "select");
+ socket_destroy (sock->sock);
+ sock->sock = NULL;
+ FREE (host);
+ MUTEX_UNLOCK (sock->destroylock);
+ return SYSERR;
+ }
+ if (FD_ISSET (osock, &eset))
+ {
+ GE_LOG (sock->ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Error connecting to %s:%u\n"), host, port);
+ socket_destroy (sock->sock);
+ sock->sock = NULL;
+ FREE (host);
+ MUTEX_UNLOCK (sock->destroylock);
+ return SYSERR;
+ }
+ if (!FD_ISSET (osock, &wset))
+ {
+ GE_LOG (sock->ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ _("Failed to connect to %s:%u in %ds\n"),
+ host, port, WAIT_SECONDS);
+ socket_destroy (sock->sock);
+ sock->sock = NULL;
+ FREE (host);
+ MUTEX_UNLOCK (sock->destroylock);
+ return SYSERR;
+ }
+ FREE (host);
+ socket_set_blocking (sock->sock, YES);
+ MUTEX_UNLOCK (sock->destroylock);
return OK;
}
@@ -357,116 +357,117 @@
* @param buffer the buffer to write
* @return OK if the write was sucessful, otherwise SYSERR.
*/
-int connection_write(struct ClientServerConnection * sock,
- const MESSAGE_HEADER * buffer) {
+int
+connection_write (struct ClientServerConnection *sock,
+ const MESSAGE_HEADER * buffer)
+{
size_t size;
size_t sent;
int res;
- MUTEX_LOCK(sock->destroylock);
- MUTEX_LOCK(sock->writelock);
- if (SYSERR == connection_ensure_connected(sock)) {
- MUTEX_UNLOCK(sock->writelock);
- MUTEX_UNLOCK(sock->destroylock);
- return SYSERR;
- }
- MUTEX_UNLOCK(sock->destroylock);
- GE_ASSERT(NULL, sock->sock != NULL);
- size = ntohs(buffer->size);
- res = socket_send(sock->sock,
- NC_Complete,
- buffer,
- size,
- &sent);
- if ( (res != YES) ||
- (sent != size) ) {
- MUTEX_UNLOCK(sock->writelock);
- connection_close_temporarily(sock);
- return SYSERR;
- }
- MUTEX_UNLOCK(sock->writelock);
+ MUTEX_LOCK (sock->destroylock);
+ MUTEX_LOCK (sock->writelock);
+ if (SYSERR == connection_ensure_connected (sock))
+ {
+ MUTEX_UNLOCK (sock->writelock);
+ MUTEX_UNLOCK (sock->destroylock);
+ return SYSERR;
+ }
+ MUTEX_UNLOCK (sock->destroylock);
+ GE_ASSERT (NULL, sock->sock != NULL);
+ size = ntohs (buffer->size);
+ res = socket_send (sock->sock, NC_Complete, buffer, size, &sent);
+ if ((res != YES) || (sent != size))
+ {
+ MUTEX_UNLOCK (sock->writelock);
+ connection_close_temporarily (sock);
+ return SYSERR;
+ }
+ MUTEX_UNLOCK (sock->writelock);
return OK;
}
-int connection_read(struct ClientServerConnection * sock,
- MESSAGE_HEADER ** buffer) {
+int
+connection_read (struct ClientServerConnection *sock,
+ MESSAGE_HEADER ** buffer)
+{
int res;
size_t pos;
- char * buf;
+ char *buf;
unsigned short size;
- RETURN_ERROR_MESSAGE * rem;
+ RETURN_ERROR_MESSAGE *rem;
- MUTEX_LOCK(sock->destroylock);
- MUTEX_LOCK(sock->readlock);
- if (OK != connection_ensure_connected(sock)) {
- MUTEX_UNLOCK(sock->readlock);
- MUTEX_UNLOCK(sock->destroylock);
- return SYSERR;
- }
- MUTEX_UNLOCK(sock->destroylock);
- GE_ASSERT(NULL, sock->sock != NULL);
- while (1) {
- pos = 0;
- res = 0;
- if ( (OK != socket_recv(sock->sock,
- NC_Complete,
- &size,
- sizeof(unsigned short),
- &pos)) ||
- (pos != sizeof(unsigned short)) ) {
- MUTEX_UNLOCK(sock->readlock);
- connection_close_temporarily(sock);
+ MUTEX_LOCK (sock->destroylock);
+ MUTEX_LOCK (sock->readlock);
+ if (OK != connection_ensure_connected (sock))
+ {
+ MUTEX_UNLOCK (sock->readlock);
+ MUTEX_UNLOCK (sock->destroylock);
return SYSERR;
}
- size = ntohs(size);
- if (size < sizeof(MESSAGE_HEADER)) {
- GE_BREAK(sock->ectx, 0);
- MUTEX_UNLOCK(sock->readlock);
- connection_close_temporarily(sock);
- return SYSERR; /* invalid header */
- }
+ MUTEX_UNLOCK (sock->destroylock);
+ GE_ASSERT (NULL, sock->sock != NULL);
+ while (1)
+ {
+ pos = 0;
+ res = 0;
+ if ((OK != socket_recv (sock->sock,
+ NC_Complete,
+ &size,
+ sizeof (unsigned short),
+ &pos)) || (pos != sizeof (unsigned short)))
+ {
+ MUTEX_UNLOCK (sock->readlock);
+ connection_close_temporarily (sock);
+ return SYSERR;
+ }
+ size = ntohs (size);
+ if (size < sizeof (MESSAGE_HEADER))
+ {
+ GE_BREAK (sock->ectx, 0);
+ MUTEX_UNLOCK (sock->readlock);
+ connection_close_temporarily (sock);
+ return SYSERR; /* invalid header */
+ }
- buf = MALLOC(size);
- if ( (OK != socket_recv(sock->sock,
- NC_Complete,
- &buf[pos],
- size - pos,
- &pos)) ||
- (pos + sizeof(unsigned short) != size) ) {
- FREE(buf);
- MUTEX_UNLOCK(sock->readlock);
- connection_close_temporarily(sock);
- return SYSERR;
- }
+ buf = MALLOC (size);
+ if ((OK != socket_recv (sock->sock,
+ NC_Complete,
+ &buf[pos],
+ size - pos,
+ &pos)) ||
+ (pos + sizeof (unsigned short) != size))
+ {
+ FREE (buf);
+ MUTEX_UNLOCK (sock->readlock);
+ connection_close_temporarily (sock);
+ return SYSERR;
+ }
#if DEBUG_TCPIO
- GE_LOG(sock->ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "Successfully received %d bytes from TCP socket.\n",
- size);
+ GE_LOG (sock->ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "Successfully received %d bytes from TCP socket.\n", size);
#endif
- *buffer = (MESSAGE_HEADER*) buf;
- (*buffer)->size = htons(size);
+ *buffer = (MESSAGE_HEADER *) buf;
+ (*buffer)->size = htons (size);
- if (ntohs((*buffer)->type) != CS_PROTO_RETURN_ERROR)
- break; /* got actual message! */
- rem = (RETURN_ERROR_MESSAGE*) *buffer;
- if (ntohs(rem->header.size) < sizeof(RETURN_ERROR_MESSAGE)) {
- GE_BREAK(sock->ectx, 0);
- MUTEX_UNLOCK(sock->readlock);
- connection_close_temporarily(sock);
- FREE(buf);
- return SYSERR;
- }
- size = ntohs(rem->header.size) - sizeof(RETURN_ERROR_MESSAGE);
- GE_LOG(sock->ectx,
- ntohl(rem->kind),
- "%.*s",
- (int) size,
- &rem[1]);
- FREE(rem);
- } /* while (1) */
- MUTEX_UNLOCK(sock->readlock);
- return OK; /* success */
+ if (ntohs ((*buffer)->type) != CS_PROTO_RETURN_ERROR)
+ break; /* got actual message! */
+ rem = (RETURN_ERROR_MESSAGE *) * buffer;
+ if (ntohs (rem->header.size) < sizeof (RETURN_ERROR_MESSAGE))
+ {
+ GE_BREAK (sock->ectx, 0);
+ MUTEX_UNLOCK (sock->readlock);
+ connection_close_temporarily (sock);
+ FREE (buf);
+ return SYSERR;
+ }
+ size = ntohs (rem->header.size) - sizeof (RETURN_ERROR_MESSAGE);
+ GE_LOG (sock->ectx, ntohl (rem->kind), "%.*s", (int) size, &rem[1]);
+ FREE (rem);
+ } /* while (1) */
+ MUTEX_UNLOCK (sock->readlock);
+ return OK; /* success */
}
/**
@@ -477,25 +478,25 @@
* @return SYSERR on error, OK if the return value was read
* successfully
*/
-int connection_read_result(struct ClientServerConnection * sock,
- int * ret) {
- RETURN_VALUE_MESSAGE * rv;
+int
+connection_read_result (struct ClientServerConnection *sock, int *ret)
+{
+ RETURN_VALUE_MESSAGE *rv;
rv = NULL;
- if (SYSERR == connection_read(sock,
- (MESSAGE_HEADER **) &rv))
+ if (SYSERR == connection_read (sock, (MESSAGE_HEADER **) & rv))
return SYSERR;
- if ( (ntohs(rv->header.size) != sizeof(RETURN_VALUE_MESSAGE)) ||
- (ntohs(rv->header.type) != CS_PROTO_RETURN_VALUE) ) {
- GE_LOG(sock->ectx,
- GE_WARNING | GE_DEVELOPER | GE_BULK,
- _("`%s' failed, reply invalid!\n"),
- __FUNCTION__);
- FREE(rv);
- return SYSERR;
- }
- *ret = ntohl(rv->return_value);
- FREE(rv);
+ if ((ntohs (rv->header.size) != sizeof (RETURN_VALUE_MESSAGE)) ||
+ (ntohs (rv->header.type) != CS_PROTO_RETURN_VALUE))
+ {
+ GE_LOG (sock->ectx,
+ GE_WARNING | GE_DEVELOPER | GE_BULK,
+ _("`%s' failed, reply invalid!\n"), __FUNCTION__);
+ FREE (rv);
+ return SYSERR;
+ }
+ *ret = ntohl (rv->return_value);
+ FREE (rv);
return OK;
}
@@ -507,18 +508,15 @@
* @return SYSERR on error, OK if the return value was
* send successfully
*/
-int connection_write_result(struct ClientServerConnection * sock,
- int ret) {
+int
+connection_write_result (struct ClientServerConnection *sock, int ret)
+{
RETURN_VALUE_MESSAGE rv;
- rv.header.size
- = htons(sizeof(RETURN_VALUE_MESSAGE));
- rv.header.type
- = htons(CS_PROTO_RETURN_VALUE);
- rv.return_value
- = htonl(ret);
- return connection_write(sock,
- &rv.header);
+ rv.header.size = htons (sizeof (RETURN_VALUE_MESSAGE));
+ rv.header.type = htons (CS_PROTO_RETURN_VALUE);
+ rv.return_value = htonl (ret);
+ return connection_write (sock, &rv.header);
}
/* end of tcpio.c */
Modified: GNUnet/src/util/network_client/tcpiotest.c
===================================================================
--- GNUnet/src/util/network_client/tcpiotest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/network_client/tcpiotest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -27,182 +27,185 @@
#include "gnunet_util_config_impl.h"
#include "platform.h"
-static struct GC_Configuration * cfg;
+static struct GC_Configuration *cfg;
-static unsigned short getGNUnetPort() {
+static unsigned short
+getGNUnetPort ()
+{
return 2087;
}
-static int openServerSocket() {
+static int
+openServerSocket ()
+{
int listenerFD;
int listenerPort;
struct sockaddr_in serverAddr;
const int on = 1;
- listenerPort = getGNUnetPort();
+ listenerPort = getGNUnetPort ();
/* create the socket */
- listenerFD = SOCKET(PF_INET, SOCK_STREAM, 0);
- if (listenerFD < 0) {
- GE_LOG_STRERROR(NULL,
- GE_BULK | GE_ERROR | GE_USER,
- "socket");
- return -1;
- }
+ listenerFD = SOCKET (PF_INET, SOCK_STREAM, 0);
+ if (listenerFD < 0)
+ {
+ GE_LOG_STRERROR (NULL, GE_BULK | GE_ERROR | GE_USER, "socket");
+ return -1;
+ }
/* fill in the inet address structure */
- memset((char *) &serverAddr,
- 0,
- sizeof(serverAddr));
+ memset ((char *) &serverAddr, 0, sizeof (serverAddr));
serverAddr.sin_family = AF_INET;
- serverAddr.sin_addr.s_addr=htonl(INADDR_ANY);
- serverAddr.sin_port=htons(listenerPort);
+ serverAddr.sin_addr.s_addr = htonl (INADDR_ANY);
+ serverAddr.sin_port = htons (listenerPort);
- if ( SETSOCKOPT(listenerFD,
- SOL_SOCKET,
- SO_REUSEADDR,
- &on, sizeof(on)) < 0 ) {
- GE_LOG_STRERROR(NULL,
- GE_BULK | GE_ERROR | GE_USER,
- "setsockopt");
- CLOSE(listenerFD);
- return -1;
- }
+ if (SETSOCKOPT (listenerFD, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0)
+ {
+ GE_LOG_STRERROR (NULL, GE_BULK | GE_ERROR | GE_USER, "setsockopt");
+ CLOSE (listenerFD);
+ return -1;
+ }
/* bind the socket */
if (BIND (listenerFD,
- (struct sockaddr *) &serverAddr,
- sizeof(serverAddr)) < 0) {
- GE_LOG_STRERROR(NULL,
- GE_BULK | GE_ERROR | GE_USER,
- "bind");
- CLOSE(listenerFD);
- return -1;
- }
+ (struct sockaddr *) &serverAddr, sizeof (serverAddr)) < 0)
+ {
+ GE_LOG_STRERROR (NULL, GE_BULK | GE_ERROR | GE_USER, "bind");
+ CLOSE (listenerFD);
+ return -1;
+ }
/* start listening for new connections */
- if (0 != LISTEN(listenerFD, 5)) {
- GE_LOG_STRERROR(NULL,
- GE_BULK | GE_ERROR | GE_USER,
- "listen");
- CLOSE(listenerFD);
- return -1;
- }
+ if (0 != LISTEN (listenerFD, 5))
+ {
+ GE_LOG_STRERROR (NULL, GE_BULK | GE_ERROR | GE_USER, "listen");
+ CLOSE (listenerFD);
+ return -1;
+ }
return listenerFD;
}
-static int doAccept(int serverSocket) {
+static int
+doAccept (int serverSocket)
+{
int incomingFD;
socklen_t lenOfIncomingAddr;
struct sockaddr_in clientAddr;
incomingFD = -1;
- while (incomingFD < 0) {
- lenOfIncomingAddr = sizeof(clientAddr);
- incomingFD = ACCEPT(serverSocket,
- (struct sockaddr *)&clientAddr,
- &lenOfIncomingAddr);
- if (incomingFD < 0) {
- GE_LOG_STRERROR(NULL,
- GE_BULK | GE_ERROR | GE_USER,
- "accept");
- continue;
+ while (incomingFD < 0)
+ {
+ lenOfIncomingAddr = sizeof (clientAddr);
+ incomingFD = ACCEPT (serverSocket,
+ (struct sockaddr *) &clientAddr,
+ &lenOfIncomingAddr);
+ if (incomingFD < 0)
+ {
+ GE_LOG_STRERROR (NULL, GE_BULK | GE_ERROR | GE_USER, "accept");
+ continue;
+ }
}
- }
return incomingFD;
}
-static int testTransmission(struct ClientServerConnection * a,
- struct SocketHandle * b) {
- MESSAGE_HEADER * hdr;
- MESSAGE_HEADER * buf;
+static int
+testTransmission (struct ClientServerConnection *a, struct SocketHandle *b)
+{
+ MESSAGE_HEADER *hdr;
+ MESSAGE_HEADER *buf;
int i;
int j;
size_t rd;
size_t pos;
- hdr = MALLOC(1024);
- for (i=0;i<1024-sizeof(MESSAGE_HEADER);i+=7) {
- fprintf(stderr, ".");
- for (j=0;j<i;j++)
- ((char*)&hdr[1])[j] = (char)i+j;
- hdr->size = htons(i+sizeof(MESSAGE_HEADER));
- hdr->type = 0;
- if (OK != connection_write(a, hdr)) {
- FREE(hdr);
- return 1;
+ hdr = MALLOC (1024);
+ for (i = 0; i < 1024 - sizeof (MESSAGE_HEADER); i += 7)
+ {
+ fprintf (stderr, ".");
+ for (j = 0; j < i; j++)
+ ((char *) &hdr[1])[j] = (char) i + j;
+ hdr->size = htons (i + sizeof (MESSAGE_HEADER));
+ hdr->type = 0;
+ if (OK != connection_write (a, hdr))
+ {
+ FREE (hdr);
+ return 1;
+ }
+ buf = MALLOC (2048);
+ pos = 0;
+ while (pos < i + sizeof (MESSAGE_HEADER))
+ {
+ rd = 0;
+ if (SYSERR == socket_recv (b,
+ NC_Nonblocking,
+ &buf[pos], 2048 - pos, &rd))
+ {
+ FREE (hdr);
+ FREE (buf);
+ return 2;
+ }
+ pos += rd;
+ }
+ if (pos != i + sizeof (MESSAGE_HEADER))
+ {
+ FREE (buf);
+ FREE (hdr);
+ return 3;
+ }
+ if (0 != memcmp (buf, hdr, i + sizeof (MESSAGE_HEADER)))
+ {
+ FREE (buf);
+ FREE (hdr);
+ return 4;
+ }
+ FREE (buf);
}
- buf = MALLOC(2048);
- pos = 0;
- while (pos < i + sizeof(MESSAGE_HEADER)) {
- rd = 0;
- if (SYSERR == socket_recv(b,
- NC_Nonblocking,
- &buf[pos],
- 2048 - pos,
- &rd)) {
- FREE(hdr);
- FREE(buf);
- return 2;
- }
- pos += rd;
- }
- if (pos != i + sizeof(MESSAGE_HEADER)) {
- FREE(buf);
- FREE(hdr);
- return 3;
- }
- if (0 != memcmp(buf, hdr, i+sizeof(MESSAGE_HEADER))) {
- FREE(buf);
- FREE(hdr);
- return 4;
- }
- FREE(buf);
- }
- FREE(hdr);
+ FREE (hdr);
return 0;
}
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
int i;
int ret;
int serverSocket;
- struct ClientServerConnection * clientSocket;
+ struct ClientServerConnection *clientSocket;
int acceptSocket;
- struct SocketHandle * sh;
+ struct SocketHandle *sh;
- cfg = GC_create_C_impl();
- if (-1 == GC_parse_configuration(cfg,
- "check.conf")) {
- GC_free(cfg);
- return -1;
- }
- serverSocket = openServerSocket();
+ cfg = GC_create_C_impl ();
+ if (-1 == GC_parse_configuration (cfg, "check.conf"))
+ {
+ GC_free (cfg);
+ return -1;
+ }
+ serverSocket = openServerSocket ();
if (serverSocket == -1)
return 1;
- clientSocket = client_connection_create(NULL,
- cfg);
+ clientSocket = client_connection_create (NULL, cfg);
ret = 0;
- for (i=0;i<2;i++) {
- if (OK != connection_ensure_connected(clientSocket)) {
- ret = 42;
- break;
+ for (i = 0; i < 2; i++)
+ {
+ if (OK != connection_ensure_connected (clientSocket))
+ {
+ ret = 42;
+ break;
+ }
+ acceptSocket = doAccept (serverSocket);
+ if (acceptSocket == -1)
+ {
+ ret = 43;
+ break;
+ }
+ sh = socket_create (NULL, NULL, acceptSocket);
+ ret = ret | testTransmission (clientSocket, sh);
+ connection_close_temporarily (clientSocket);
+ socket_destroy (sh);
}
- acceptSocket = doAccept(serverSocket);
- if (acceptSocket == -1) {
- ret = 43;
- break;
- }
- sh = socket_create(NULL, NULL, acceptSocket);
- ret = ret | testTransmission(clientSocket, sh);
- connection_close_temporarily(clientSocket);
- socket_destroy(sh);
- }
- connection_destroy(clientSocket);
- CLOSE(serverSocket);
+ connection_destroy (clientSocket);
+ CLOSE (serverSocket);
if (ret > 0)
- fprintf(stderr,
- "Error %d\n",
- ret);
- GC_free(cfg);
+ fprintf (stderr, "Error %d\n", ret);
+ GC_free (cfg);
return ret;
}
Modified: GNUnet/src/util/os/console.c
===================================================================
--- GNUnet/src/util/os/console.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/console.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -36,14 +36,15 @@
static char *
-getPIDFile(struct GC_Configuration * cfg) {
- char * pif;
+getPIDFile (struct GC_Configuration *cfg)
+{
+ char *pif;
- if (0 != GC_get_configuration_value_filename(cfg,
- "GNUNETD",
- "PIDFILE",
- VAR_DAEMON_DIRECTORY "/gnunetd/pid",
- &pif))
+ if (0 != GC_get_configuration_value_filename (cfg,
+ "GNUNETD",
+ "PIDFILE",
+ VAR_DAEMON_DIRECTORY
+ "/gnunetd/pid", &pif))
return NULL;
return pif;
}
@@ -54,96 +55,83 @@
*
* @return OK on success, SYSERR on error
*/
-int os_write_pid_file(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- unsigned int pid) {
- FILE * pidfd;
- char * pif;
- char * user;
- char * rdir;
+int
+os_write_pid_file (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, unsigned int pid)
+{
+ FILE *pidfd;
+ char *pif;
+ char *user;
+ char *rdir;
int len;
- pif = getPIDFile(cfg);
+ pif = getPIDFile (cfg);
if (pif == NULL)
- return OK; /* no PID file */
- GC_get_configuration_value_string(cfg,
- "GNUNETD",
- "USER",
- "",
- &user);
- rdir = STRDUP(pif);
- len = strlen(rdir);
- while ( (len > 0) &&
- (rdir[len] != DIR_SEPARATOR) )
+ return OK; /* no PID file */
+ GC_get_configuration_value_string (cfg, "GNUNETD", "USER", "", &user);
+ rdir = STRDUP (pif);
+ len = strlen (rdir);
+ while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
len--;
rdir[len] = '\0';
- if (0 != ACCESS(rdir, F_OK)) {
- /* we get to create a directory -- and claim it
- as ours! */
- disk_directory_create(ectx, rdir);
- if (strlen(user))
- os_change_owner(ectx,
- rdir,
- user);
- }
- if (0 != ACCESS(rdir, W_OK | X_OK)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "access",
- rdir);
- FREE(rdir);
- FREE(user);
- return SYSERR;
- }
- FREE(rdir);
- pidfd = FOPEN(pif, "w");
- if (pidfd == NULL) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "fopen",
- pif);
- FREE(pif);
- FREE(user);
- return SYSERR;
- }
- if (0 > FPRINTF(pidfd,
- "%u",
- pid))
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "fprintf",
- pif);
- if (0 != fclose(pidfd))
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "fclose",
- pif);
- if (strlen(user))
- os_change_owner(ectx,
- pif,
- user);
- FREE(user);
- FREE(pif);
+ if (0 != ACCESS (rdir, F_OK))
+ {
+ /* we get to create a directory -- and claim it
+ as ours! */
+ disk_directory_create (ectx, rdir);
+ if (strlen (user))
+ os_change_owner (ectx, rdir, user);
+ }
+ if (0 != ACCESS (rdir, W_OK | X_OK))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "access", rdir);
+ FREE (rdir);
+ FREE (user);
+ return SYSERR;
+ }
+ FREE (rdir);
+ pidfd = FOPEN (pif, "w");
+ if (pidfd == NULL)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_ADMIN | GE_BULK, "fopen", pif);
+ FREE (pif);
+ FREE (user);
+ return SYSERR;
+ }
+ if (0 > FPRINTF (pidfd, "%u", pid))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_ADMIN | GE_BULK, "fprintf", pif);
+ if (0 != fclose (pidfd))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_ADMIN | GE_BULK, "fclose", pif);
+ if (strlen (user))
+ os_change_owner (ectx, pif, user);
+ FREE (user);
+ FREE (pif);
return OK;
}
-int os_delete_pid_file(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- char * pif = getPIDFile(cfg);
+int
+os_delete_pid_file (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
+ char *pif = getPIDFile (cfg);
if (pif == NULL)
- return OK; /* no PID file */
- if (YES == disk_file_test(ectx,
- pif)) {
- if (0 != UNLINK(pif)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "unlink",
- pif);
- FREE(pif);
- return SYSERR;
+ return OK; /* no PID file */
+ if (YES == disk_file_test (ectx, pif))
+ {
+ if (0 != UNLINK (pif))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_ADMIN | GE_BULK,
+ "unlink", pif);
+ FREE (pif);
+ return SYSERR;
+ }
}
- }
- FREE(pif);
+ FREE (pif);
return OK;
}
@@ -155,106 +143,96 @@
* @param filedes pointer to an array of 2 file descriptors
* to complete the detachment protocol (handshake)
*/
-int os_terminal_detach(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- int * filedes) {
+int
+os_terminal_detach (struct GE_Context *ectx,
+ struct GC_Configuration *cfg, int *filedes)
+{
pid_t pid;
int nullfd;
/* Don't hold the wrong FS mounted */
- if (CHDIR("/") < 0) {
- GE_LOG_STRERROR(ectx,
- GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "chdir");
- return SYSERR;
- }
+ if (CHDIR ("/") < 0)
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE, "chdir");
+ return SYSERR;
+ }
#ifndef MINGW
- PIPE(filedes);
- pid = fork();
- if (pid < 0) {
- GE_LOG_STRERROR(ectx,
- GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "fork");
- return SYSERR;
- }
- if (pid) { /* Parent */
- int ok;
- char c;
+ PIPE (filedes);
+ pid = fork ();
+ if (pid < 0)
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE, "fork");
+ return SYSERR;
+ }
+ if (pid)
+ { /* Parent */
+ int ok;
+ char c;
- if (0 != CLOSE(filedes[1]))
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "close");
- ok = SYSERR;
- while (0 < READ(filedes[0],
- &c,
- sizeof(char))) {
- if (c == '.')
- ok = OK;
+ if (0 != CLOSE (filedes[1]))
+ GE_LOG_STRERROR (ectx, GE_WARNING | GE_USER | GE_BULK, "close");
+ ok = SYSERR;
+ while (0 < READ (filedes[0], &c, sizeof (char)))
+ {
+ if (c == '.')
+ ok = OK;
+ }
+ fflush (stdout);
+ if (ok == OK)
+ {
+ os_write_pid_file (ectx, cfg, pid);
+ exit (0);
+ }
+ else
+ {
+ exit (1); /* child reported error */
+ }
}
- fflush(stdout);
- if (ok == OK) {
- os_write_pid_file(ectx,
- cfg,
- pid);
- exit(0);
- } else {
- exit(1); /* child reported error */
+ if (0 != CLOSE (filedes[0]))
+ GE_LOG_STRERROR (ectx, GE_WARNING | GE_USER | GE_BULK, "close");
+ nullfd = disk_file_open (ectx, "/dev/null", O_RDWR | O_APPEND);
+ if (nullfd < 0)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ "fork", "/dev/null");
+ return SYSERR;
}
- }
- if (0 != CLOSE(filedes[0]))
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "close");
- nullfd = disk_file_open(ectx,
- "/dev/null",
- O_RDWR | O_APPEND);
- if (nullfd < 0) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "fork",
- "/dev/null");
- return SYSERR;
- }
/* child - close fds linking to invoking terminal, but
* close usual incoming fds, but redirect them somewhere
* useful so the fds don't get reallocated elsewhere.
*/
- if (dup2(nullfd,0) < 0 ||
- dup2(nullfd,1) < 0 ||
- dup2(nullfd,2) < 0) {
- GE_LOG_STRERROR(ectx,
- GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "dup2");
- return SYSERR;
- }
- pid = setsid(); /* Detach from controlling terminal */
+ if (dup2 (nullfd, 0) < 0 || dup2 (nullfd, 1) < 0 || dup2 (nullfd, 2) < 0)
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE, "dup2");
+ return SYSERR;
+ }
+ pid = setsid (); /* Detach from controlling terminal */
if (pid == -1)
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "setsid");
+ GE_LOG_STRERROR (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE, "setsid");
#else
- FreeConsole();
+ FreeConsole ();
#endif
return OK;
}
-void os_terminal_detach_complete(struct GE_Context * ectx,
- int * filedes,
- int success) {
+void
+os_terminal_detach_complete (struct GE_Context *ectx,
+ int *filedes, int success)
+{
#ifndef MINGW
char c = '.';
- if (! success)
+ if (!success)
c = '!';
- WRITE(filedes[1],
- &c,
- sizeof(char)); /* signal success */
- if (0 != CLOSE(filedes[1]))
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "close");
+ WRITE (filedes[1], &c, sizeof (char)); /* signal success */
+ if (0 != CLOSE (filedes[1]))
+ GE_LOG_STRERROR (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_IMMEDIATE, "close");
#endif
}
-
Modified: GNUnet/src/util/os/cpustatus.c
===================================================================
--- GNUnet/src/util/os/cpustatus.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/cpustatus.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -61,10 +61,10 @@
#define DEBUG_STATUSCALLS NO
#ifdef LINUX
-static FILE * proc_stat;
+static FILE *proc_stat;
#endif
-static struct MUTEX * statusMutex;
+static struct MUTEX *statusMutex;
/**
* Current CPU load, as percentage of CPU cycles not idle or
@@ -82,33 +82,38 @@
static int agedIOLoad = -1;
#ifdef OSX
-static int initMachCpuStats() {
+static int
+initMachCpuStats ()
+{
unsigned int cpu_count;
processor_cpu_load_info_t cpu_load;
mach_msg_type_number_t cpu_msg_count;
kern_return_t kret;
- int i,j;
+ int i, j;
- kret = host_processor_info(mach_host_self(),
- PROCESSOR_CPU_LOAD_INFO,
- &cpu_count,
- (processor_info_array_t *)&cpu_load,
- &cpu_msg_count);
- if (kret != KERN_SUCCESS) {
- GE_LOG(NULL,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "host_processor_info failed.");
- return SYSERR;
- }
- prev_cpu_load = MALLOC(cpu_count * sizeof(*prev_cpu_load));
- for (i = 0; i < cpu_count; i++) {
- for (j = 0; j < CPU_STATE_MAX; j++) {
- prev_cpu_load[i].cpu_ticks[j] = cpu_load[i].cpu_ticks[j];
+ kret = host_processor_info (mach_host_self (),
+ PROCESSOR_CPU_LOAD_INFO,
+ &cpu_count,
+ (processor_info_array_t *) & cpu_load,
+ &cpu_msg_count);
+ if (kret != KERN_SUCCESS)
+ {
+ GE_LOG (NULL,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "host_processor_info failed.");
+ return SYSERR;
}
- }
- vm_deallocate(mach_task_self(),
- (vm_address_t)cpu_load,
- (vm_size_t)(cpu_msg_count * sizeof(*cpu_load)));
+ prev_cpu_load = MALLOC (cpu_count * sizeof (*prev_cpu_load));
+ for (i = 0; i < cpu_count; i++)
+ {
+ for (j = 0; j < CPU_STATE_MAX; j++)
+ {
+ prev_cpu_load[i].cpu_ticks[j] = cpu_load[i].cpu_ticks[j];
+ }
+ }
+ vm_deallocate (mach_task_self (),
+ (vm_address_t) cpu_load,
+ (vm_size_t) (cpu_msg_count * sizeof (*cpu_load)));
return OK;
}
#endif
@@ -119,77 +124,82 @@
* Before its first invocation the method initStatusCalls() must be called.
* If there is an error the method returns -1.
*/
-static int updateUsage(){
+static int
+updateUsage ()
+{
currentIOLoad = -1;
currentCPULoad = -1;
#ifdef LINUX
/* under linux, first try %idle/usage using /proc/stat;
if that does not work, disable /proc/stat for the future
by closing the file and use the next-best method. */
- if (proc_stat != NULL) {
- static unsigned long long last_cpu_results[5] = { 0, 0, 0, 0, 0 };
- static int have_last_cpu = NO;
- int ret;
- char line[256];
- unsigned long long user_read, system_read, nice_read, idle_read,
iowait_read;
- unsigned long long user, system, nice, idle, iowait;
- unsigned long long usage_time=0, total_time=1;
+ if (proc_stat != NULL)
+ {
+ static unsigned long long last_cpu_results[5] = { 0, 0, 0, 0, 0 };
+ static int have_last_cpu = NO;
+ int ret;
+ char line[256];
+ unsigned long long user_read, system_read, nice_read, idle_read,
+ iowait_read;
+ unsigned long long user, system, nice, idle, iowait;
+ unsigned long long usage_time = 0, total_time = 1;
- /* Get the first line with the data */
- rewind(proc_stat);
- fflush(proc_stat);
- if (NULL == fgets(line, 256, proc_stat)) {
- GE_LOG_STRERROR_FILE(NULL,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "fgets",
- "/proc/stat");
- fclose(proc_stat);
- proc_stat = NULL; /* don't try again */
- } else {
- iowait_read = 0;
- ret = sscanf(line, "%*s %llu %llu %llu %llu %llu",
- &user_read,
- &system_read,
- &nice_read,
- &idle_read,
- &iowait_read);
- if (ret < 4) {
- GE_LOG_STRERROR_FILE(NULL,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "fgets-sscanf",
- "/proc/stat");
- fclose(proc_stat);
- proc_stat = NULL; /* don't try again */
- have_last_cpu = NO;
- } else {
- /* Store the current usage*/
- user = user_read - last_cpu_results[0];
- system = system_read - last_cpu_results[1];
- nice = nice_read - last_cpu_results[2];
- idle = idle_read - last_cpu_results[3];
- iowait = iowait_read - last_cpu_results[4];
- /* Calculate the % usage */
- usage_time = user + system + nice;
- total_time = usage_time + idle + iowait;
- if ( (total_time > 0) &&
- (have_last_cpu == YES) ) {
- currentCPULoad = (int) (100L * usage_time / total_time);
- if (ret > 4)
- currentIOLoad = (int) (100L * iowait / total_time);
- else
- currentIOLoad = -1; /* 2.4 kernel */
- }
- /* Store the values for the next calculation*/
- last_cpu_results[0] = user_read;
- last_cpu_results[1] = system_read;
- last_cpu_results[2] = nice_read;
- last_cpu_results[3] = idle_read;
- last_cpu_results[4] = iowait_read;
- have_last_cpu = YES;
- return OK;
- }
+ /* Get the first line with the data */
+ rewind (proc_stat);
+ fflush (proc_stat);
+ if (NULL == fgets (line, 256, proc_stat))
+ {
+ GE_LOG_STRERROR_FILE (NULL,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "fgets", "/proc/stat");
+ fclose (proc_stat);
+ proc_stat = NULL; /* don't try again */
+ }
+ else
+ {
+ iowait_read = 0;
+ ret = sscanf (line, "%*s %llu %llu %llu %llu %llu",
+ &user_read,
+ &system_read, &nice_read, &idle_read, &iowait_read);
+ if (ret < 4)
+ {
+ GE_LOG_STRERROR_FILE (NULL,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "fgets-sscanf", "/proc/stat");
+ fclose (proc_stat);
+ proc_stat = NULL; /* don't try again */
+ have_last_cpu = NO;
+ }
+ else
+ {
+ /* Store the current usage */
+ user = user_read - last_cpu_results[0];
+ system = system_read - last_cpu_results[1];
+ nice = nice_read - last_cpu_results[2];
+ idle = idle_read - last_cpu_results[3];
+ iowait = iowait_read - last_cpu_results[4];
+ /* Calculate the % usage */
+ usage_time = user + system + nice;
+ total_time = usage_time + idle + iowait;
+ if ((total_time > 0) && (have_last_cpu == YES))
+ {
+ currentCPULoad = (int) (100L * usage_time / total_time);
+ if (ret > 4)
+ currentIOLoad = (int) (100L * iowait / total_time);
+ else
+ currentIOLoad = -1; /* 2.4 kernel */
+ }
+ /* Store the values for the next calculation */
+ last_cpu_results[0] = user_read;
+ last_cpu_results[1] = system_read;
+ last_cpu_results[2] = nice_read;
+ last_cpu_results[3] = idle_read;
+ last_cpu_results[4] = iowait_read;
+ have_last_cpu = YES;
+ return OK;
+ }
+ }
}
- }
#endif
#ifdef OSX
@@ -203,75 +213,93 @@
int i, j;
t_idle_all = t_total_all = 0;
- kret = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO,
- &cpu_count,
- (processor_info_array_t *)&cpu_load,
- &cpu_msg_count);
- if (kret == KERN_SUCCESS) {
- for (i = 0; i < cpu_count; i++) {
- if (cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] >=
- prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM]) {
- t_sys = cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] -
+ kret = host_processor_info (mach_host_self (), PROCESSOR_CPU_LOAD_INFO,
+ &cpu_count,
+ (processor_info_array_t *) & cpu_load,
+ &cpu_msg_count);
+ if (kret == KERN_SUCCESS)
+ {
+ for (i = 0; i < cpu_count; i++)
+ {
+ if (cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] >=
+ prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM])
+ {
+ t_sys = cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] -
prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM];
- }
- else {
- t_sys = cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] +
- (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM]+1);
- }
+ }
+ else
+ {
+ t_sys = cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] +
+ (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] +
+ 1);
+ }
- if (cpu_load[i].cpu_ticks[CPU_STATE_USER] >=
- prev_cpu_load[i].cpu_ticks[CPU_STATE_USER]) {
- t_user = cpu_load[i].cpu_ticks[CPU_STATE_USER] -
- prev_cpu_load[i].cpu_ticks[CPU_STATE_USER];
- }
- else {
- t_user = cpu_load[i].cpu_ticks[CPU_STATE_USER] +
- (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_USER] +
1);
- }
+ if (cpu_load[i].cpu_ticks[CPU_STATE_USER] >=
+ prev_cpu_load[i].cpu_ticks[CPU_STATE_USER])
+ {
+ t_user = cpu_load[i].cpu_ticks[CPU_STATE_USER] -
+ prev_cpu_load[i].cpu_ticks[CPU_STATE_USER];
+ }
+ else
+ {
+ t_user = cpu_load[i].cpu_ticks[CPU_STATE_USER] +
+ (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_USER] +
+ 1);
+ }
- if (cpu_load[i].cpu_ticks[CPU_STATE_NICE] >=
- prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE]) {
- t_nice = cpu_load[i].cpu_ticks[CPU_STATE_NICE] -
- prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE];
- }
- else {
- t_nice = cpu_load[i].cpu_ticks[CPU_STATE_NICE] +
- (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE] +
1);
- }
+ if (cpu_load[i].cpu_ticks[CPU_STATE_NICE] >=
+ prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE])
+ {
+ t_nice = cpu_load[i].cpu_ticks[CPU_STATE_NICE] -
+ prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE];
+ }
+ else
+ {
+ t_nice = cpu_load[i].cpu_ticks[CPU_STATE_NICE] +
+ (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE] +
+ 1);
+ }
- if (cpu_load[i].cpu_ticks[CPU_STATE_IDLE] >=
- prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE]) {
- t_idle = cpu_load[i].cpu_ticks[CPU_STATE_IDLE] -
- prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE];
- }
- else {
- t_idle = cpu_load[i].cpu_ticks[CPU_STATE_IDLE] +
- (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE] +
1);
- }
- t_total = t_sys + t_user + t_nice + t_idle;
- t_idle_all += t_idle;
- t_total_all += t_total;
+ if (cpu_load[i].cpu_ticks[CPU_STATE_IDLE] >=
+ prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE])
+ {
+ t_idle = cpu_load[i].cpu_ticks[CPU_STATE_IDLE] -
+ prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE];
+ }
+ else
+ {
+ t_idle = cpu_load[i].cpu_ticks[CPU_STATE_IDLE] +
+ (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE] +
+ 1);
+ }
+ t_total = t_sys + t_user + t_nice + t_idle;
+ t_idle_all += t_idle;
+ t_total_all += t_total;
+ }
+ for (i = 0; i < cpu_count; i++)
+ {
+ for (j = 0; j < CPU_STATE_MAX; j++)
+ {
+ prev_cpu_load[i].cpu_ticks[j] = cpu_load[i].cpu_ticks[j];
+ }
+ }
+ if (t_total_all > 0)
+ currentCPULoad = 100 - (100 * t_idle_all) / t_total_all;
+ else
+ currentCPULoad = -1;
+ vm_deallocate (mach_task_self (),
+ (vm_address_t) cpu_load,
+ (vm_size_t) (cpu_msg_count * sizeof (*cpu_load)));
+ currentIOLoad = -1; /* FIXME-OSX! */
+ return OK;
}
- for (i = 0; i < cpu_count; i++) {
- for (j = 0; j < CPU_STATE_MAX; j++) {
- prev_cpu_load[i].cpu_ticks[j] = cpu_load[i].cpu_ticks[j];
- }
+ else
+ {
+ GE_LOG (NULL,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "host_processor_info failed.");
+ return SYSERR;
}
- if (t_total_all > 0)
- currentCPULoad = 100 - (100 * t_idle_all) / t_total_all;
- else
- currentCPULoad = -1;
- vm_deallocate(mach_task_self(),
- (vm_address_t)cpu_load,
- (vm_size_t)(cpu_msg_count * sizeof(*cpu_load)));
- currentIOLoad = -1; /* FIXME-OSX! */
- return OK;
- } else {
- GE_LOG(NULL,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "host_processor_info failed.");
- return SYSERR;
- }
}
#endif
/* try kstat (Solaris only) */
@@ -279,10 +307,10 @@
{
static long long last_idlecount;
static long long last_totalcount;
- static int kstat_once; /* if open fails, don't keep
- trying */
- kstat_ctl_t * kc;
- kstat_t * khelper;
+ static int kstat_once; /* if open fails, don't keep
+ trying */
+ kstat_ctl_t *kc;
+ kstat_t *khelper;
long long idlecount;
long long totalcount;
long long deltaidle;
@@ -290,62 +318,60 @@
if (kstat_once == 1)
goto ABORT_KSTAT;
- kc = kstat_open();
- if (kc == NULL) {
- GE_LOG_STRERROR(NULL,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "kstat_open");
- goto ABORT_KSTAT;
- }
+ kc = kstat_open ();
+ if (kc == NULL)
+ {
+ GE_LOG_STRERROR (NULL,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "kstat_open");
+ goto ABORT_KSTAT;
+ }
idlecount = 0;
totalcount = 0;
- for (khelper = kc->kc_chain;
- khelper != NULL;
- khelper = khelper->ks_next) {
- cpu_stat_t stats;
+ for (khelper = kc->kc_chain; khelper != NULL; khelper = khelper->ks_next)
+ {
+ cpu_stat_t stats;
- if (0 != strncmp(khelper->ks_name,
- "cpu_stat",
- strlen("cpu_stat")) )
- continue;
- if (khelper->ks_data_size > sizeof(cpu_stat_t))
- continue; /* better save then sorry! */
- if (-1 != kstat_read(kc, khelper, &stats)) {
- idlecount
- += stats.cpu_sysinfo.cpu[CPU_IDLE];
- totalcount
- += stats.cpu_sysinfo.cpu[CPU_IDLE] +
- stats.cpu_sysinfo.cpu[CPU_USER] +
- stats.cpu_sysinfo.cpu[CPU_KERNEL] +
- stats.cpu_sysinfo.cpu[CPU_WAIT];
+ if (0 != strncmp (khelper->ks_name, "cpu_stat", strlen ("cpu_stat")))
+ continue;
+ if (khelper->ks_data_size > sizeof (cpu_stat_t))
+ continue; /* better save then sorry! */
+ if (-1 != kstat_read (kc, khelper, &stats))
+ {
+ idlecount += stats.cpu_sysinfo.cpu[CPU_IDLE];
+ totalcount
+ += stats.cpu_sysinfo.cpu[CPU_IDLE] +
+ stats.cpu_sysinfo.cpu[CPU_USER] +
+ stats.cpu_sysinfo.cpu[CPU_KERNEL] +
+ stats.cpu_sysinfo.cpu[CPU_WAIT];
+ }
}
- }
- if (0 != kstat_close(kc))
- GE_LOG_STRERROR(NULL,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "kstat_close");
- if ( (idlecount == 0) &&
- (totalcount == 0) )
- goto ABORT_KSTAT; /* no stats found => abort */
+ if (0 != kstat_close (kc))
+ GE_LOG_STRERROR (NULL,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "kstat_close");
+ if ((idlecount == 0) && (totalcount == 0))
+ goto ABORT_KSTAT; /* no stats found => abort */
deltaidle = idlecount - last_idlecount;
deltatotal = totalcount - last_totalcount;
- if ( (deltatotal > 0) &&
- (last_totalcount > 0) ) {
- currentCPULoad = (unsigned int) (100.0 * deltaidle / deltatotal);
- if (currentCPULoad > 100)
- currentCPULoad = 100; /* odd */
- if (currentCPULoad < 0)
- currentCPULoad = 0; /* odd */
- currentCPULoad = 100 - currentCPULoad; /* computed idle-load before! */
- } else
+ if ((deltatotal > 0) && (last_totalcount > 0))
+ {
+ currentCPULoad = (unsigned int) (100.0 * deltaidle / deltatotal);
+ if (currentCPULoad > 100)
+ currentCPULoad = 100; /* odd */
+ if (currentCPULoad < 0)
+ currentCPULoad = 0; /* odd */
+ currentCPULoad = 100 - currentCPULoad; /* computed idle-load before!
*/
+ }
+ else
currentCPULoad = -1;
- currentIOLoad = -1; /* FIXME-SOLARIS! */
+ currentIOLoad = -1; /* FIXME-SOLARIS! */
last_idlecount = idlecount;
last_totalcount = totalcount;
return OK;
ABORT_KSTAT:
- kstat_once = 1; /* failed, don't try again */
+ kstat_once = 1; /* failed, don't try again */
return SYSERR;
}
#endif
@@ -358,153 +384,143 @@
{
static int warnOnce = 0;
double loadavg;
- if (1 != getloadavg(&loadavg, 1)) {
- /* only warn once, if there is a problem with
- getloadavg, we're going to hit it frequently... */
- if (warnOnce == 0) {
- warnOnce = 1;
- GE_LOG_STRERROR(NULL,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "getloadavg");
+ if (1 != getloadavg (&loadavg, 1))
+ {
+ /* only warn once, if there is a problem with
+ getloadavg, we're going to hit it frequently... */
+ if (warnOnce == 0)
+ {
+ warnOnce = 1;
+ GE_LOG_STRERROR (NULL,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "getloadavg");
+ }
+ return SYSERR;
}
- return SYSERR;
- } else {
- /* success with getloadavg */
- currentCPULoad = (int) (100 * loadavg);
- currentIOLoad = -1; /* FIXME */
- return OK;
- }
+ else
+ {
+ /* success with getloadavg */
+ currentCPULoad = (int) (100 * loadavg);
+ currentIOLoad = -1; /* FIXME */
+ return OK;
+ }
}
#endif
#if MINGW
/* Win NT? */
- if (GNNtQuerySystemInformation) {
- static double dLastKernel;
- static double dLastIdle;
- static double dLastUser;
- double dKernel;
- double dIdle;
- double dUser;
- double dDiffKernel;
- double dDiffIdle;
- double dDiffUser;
- SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION theInfo;
+ if (GNNtQuerySystemInformation)
+ {
+ static double dLastKernel;
+ static double dLastIdle;
+ static double dLastUser;
+ double dKernel;
+ double dIdle;
+ double dUser;
+ double dDiffKernel;
+ double dDiffIdle;
+ double dDiffUser;
+ SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION theInfo;
- if (GNNtQuerySystemInformation(SystemProcessorPerformanceInformation,
- &theInfo,
- sizeof(theInfo),
- NULL) == NO_ERROR) {
- /* PORT-ME MINGW: Multi-processor? */
- dKernel = Li2Double(theInfo.KernelTime);
- dIdle = Li2Double(theInfo.IdleTime);
- dUser = Li2Double(theInfo.UserTime);
- dDiffKernel = dKernel - dLastKernel;
- dDiffIdle = dIdle - dLastIdle;
- dDiffUser = dUser - dLastUser;
+ if (GNNtQuerySystemInformation (SystemProcessorPerformanceInformation,
+ &theInfo,
+ sizeof (theInfo), NULL) == NO_ERROR)
+ {
+ /* PORT-ME MINGW: Multi-processor? */
+ dKernel = Li2Double (theInfo.KernelTime);
+ dIdle = Li2Double (theInfo.IdleTime);
+ dUser = Li2Double (theInfo.UserTime);
+ dDiffKernel = dKernel - dLastKernel;
+ dDiffIdle = dIdle - dLastIdle;
+ dDiffUser = dUser - dLastUser;
- if ( ( (dDiffKernel + dDiffUser) > 0) &&
- (dLastIdle + dLastKernel + dLastUser > 0) )
- currentCPULoad = 100.0 - (dDiffIdle / (dDiffKernel + dDiffUser)) *
100.0;
- else
- currentCPULoad = -1; /* don't know (yet) */
+ if (((dDiffKernel + dDiffUser) > 0) &&
+ (dLastIdle + dLastKernel + dLastUser > 0))
+ currentCPULoad =
+ 100.0 - (dDiffIdle / (dDiffKernel + dDiffUser)) * 100.0;
+ else
+ currentCPULoad = -1; /* don't know (yet) */
- dLastKernel = dKernel;
- dLastIdle = dIdle;
- dLastUser = dUser;
+ dLastKernel = dKernel;
+ dLastIdle = dIdle;
+ dLastUser = dUser;
- currentIOLoad = -1; /* FIXME-MINGW */
- return OK;
- } else {
- /* only warn once, if there is a problem with
- NtQuery..., we're going to hit it frequently... */
- static int once;
- if (once == 0) {
- once = 1;
- GE_LOG(NULL,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- _("Cannot query the CPU usage (Windows NT).\n"));
- }
- return SYSERR;
+ currentIOLoad = -1; /* FIXME-MINGW */
+ return OK;
+ }
+ else
+ {
+ /* only warn once, if there is a problem with
+ NtQuery..., we're going to hit it frequently... */
+ static int once;
+ if (once == 0)
+ {
+ once = 1;
+ GE_LOG (NULL,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ _("Cannot query the CPU usage (Windows NT).\n"));
+ }
+ return SYSERR;
+ }
}
- } else { /* Win 9x */
- HKEY hKey;
- DWORD dwDataSize, dwType, dwDummy;
+ else
+ { /* Win 9x */
+ HKEY hKey;
+ DWORD dwDataSize, dwType, dwDummy;
- /* Start query */
- if (RegOpenKeyEx(HKEY_DYN_DATA,
- "PerfStats\\StartSrv",
- 0,
- KEY_ALL_ACCESS,
- &hKey) != ERROR_SUCCESS) {
- /* only warn once */
- static int once = 0;
- if (once == 0) {
- once = 1;
- GE_LOG(NULL,
- GE_USER | GE_ADMIN | GE_ERROR | GE_BULK,
- _("Cannot query the CPU usage (Win 9x)\n"));
- }
- }
+ /* Start query */
+ if (RegOpenKeyEx (HKEY_DYN_DATA,
+ "PerfStats\\StartSrv",
+ 0, KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
+ {
+ /* only warn once */
+ static int once = 0;
+ if (once == 0)
+ {
+ once = 1;
+ GE_LOG (NULL,
+ GE_USER | GE_ADMIN | GE_ERROR | GE_BULK,
+ _("Cannot query the CPU usage (Win 9x)\n"));
+ }
+ }
- RegOpenKeyEx(HKEY_DYN_DATA,
- "PerfStats\\StartStat",
- 0,
- KEY_ALL_ACCESS,
- &hKey);
- dwDataSize = sizeof(dwDummy);
- RegQueryValueEx(hKey,
- "KERNEL\\CPUUsage",
- NULL,
- &dwType,
- (LPBYTE) &dwDummy,
- &dwDataSize);
- RegCloseKey(hKey);
+ RegOpenKeyEx (HKEY_DYN_DATA,
+ "PerfStats\\StartStat", 0, KEY_ALL_ACCESS, &hKey);
+ dwDataSize = sizeof (dwDummy);
+ RegQueryValueEx (hKey,
+ "KERNEL\\CPUUsage",
+ NULL, &dwType, (LPBYTE) & dwDummy, &dwDataSize);
+ RegCloseKey (hKey);
- /* Get CPU usage */
- RegOpenKeyEx(HKEY_DYN_DATA,
- "PerfStats\\StatData",
- 0,
- KEY_ALL_ACCESS,
- &hKey);
- dwDataSize = sizeof(currentCPULoad);
- RegQueryValueEx(hKey,
- "KERNEL\\CPUUsage",
- NULL,
- &dwType,
- (LPBYTE) ¤tCPULoad,
- &dwDataSize);
- RegCloseKey(hKey);
- currentIOLoad = -1; /* FIXME-MINGW! */
+ /* Get CPU usage */
+ RegOpenKeyEx (HKEY_DYN_DATA,
+ "PerfStats\\StatData", 0, KEY_ALL_ACCESS, &hKey);
+ dwDataSize = sizeof (currentCPULoad);
+ RegQueryValueEx (hKey,
+ "KERNEL\\CPUUsage",
+ NULL, &dwType, (LPBYTE) & currentCPULoad, &dwDataSize);
+ RegCloseKey (hKey);
+ currentIOLoad = -1; /* FIXME-MINGW! */
- /* Stop query */
- RegOpenKeyEx(HKEY_DYN_DATA,
- "PerfStats\\StopStat",
- 0,
- KEY_ALL_ACCESS,
- &hKey);
- RegOpenKeyEx(HKEY_DYN_DATA,
- "PerfStats\\StopSrv",
- 0,
- KEY_ALL_ACCESS,
- &hKey);
- dwDataSize = sizeof(dwDummy);
- RegQueryValueEx(hKey,
- "KERNEL\\CPUUsage",
- NULL,
- &dwType,
- (LPBYTE)&dwDummy,
- &dwDataSize);
- RegCloseKey(hKey);
+ /* Stop query */
+ RegOpenKeyEx (HKEY_DYN_DATA,
+ "PerfStats\\StopStat", 0, KEY_ALL_ACCESS, &hKey);
+ RegOpenKeyEx (HKEY_DYN_DATA,
+ "PerfStats\\StopSrv", 0, KEY_ALL_ACCESS, &hKey);
+ dwDataSize = sizeof (dwDummy);
+ RegQueryValueEx (hKey,
+ "KERNEL\\CPUUsage",
+ NULL, &dwType, (LPBYTE) & dwDummy, &dwDataSize);
+ RegCloseKey (hKey);
- return OK;
- }
+ return OK;
+ }
#endif
/* loadaverage not defined and no platform
specific alternative defined
=> default: error
- */
+ */
return SYSERR;
}
@@ -513,43 +529,56 @@
* including computation of averages. Code assumes
* that lock has already been obtained.
*/
-static void updateAgedLoad(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
+static void
+updateAgedLoad (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
static cron_t lastCall;
cron_t now;
- now = get_time();
- if ( (agedCPULoad == -1) ||
- (now - lastCall > 500 * cronMILLIS) ) {
- /* use smoothing, but do NOT update lastRet at frequencies higher
- than 500ms; this makes the smoothing (mostly) independent from
- the frequency at which getCPULoad is called (and we don't spend
- more time measuring CPU than actually computing something). */
- lastCall = now;
- updateUsage();
- if (currentCPULoad == -1) {
- agedCPULoad = -1;
- } else {
- if (agedCPULoad == -1) {
- agedCPULoad = currentCPULoad;
- } else {
- /* for CPU, we don't do the 'fast increase' since CPU is much
- more jitterish to begin with */
- agedCPULoad = (agedCPULoad * 31 + currentCPULoad) / 32;
- }
+ now = get_time ();
+ if ((agedCPULoad == -1) || (now - lastCall > 500 * cronMILLIS))
+ {
+ /* use smoothing, but do NOT update lastRet at frequencies higher
+ than 500ms; this makes the smoothing (mostly) independent from
+ the frequency at which getCPULoad is called (and we don't spend
+ more time measuring CPU than actually computing something). */
+ lastCall = now;
+ updateUsage ();
+ if (currentCPULoad == -1)
+ {
+ agedCPULoad = -1;
+ }
+ else
+ {
+ if (agedCPULoad == -1)
+ {
+ agedCPULoad = currentCPULoad;
+ }
+ else
+ {
+ /* for CPU, we don't do the 'fast increase' since CPU is much
+ more jitterish to begin with */
+ agedCPULoad = (agedCPULoad * 31 + currentCPULoad) / 32;
+ }
+ }
+ if (currentIOLoad == -1)
+ {
+ agedIOLoad = -1;
+ }
+ else
+ {
+ if (agedIOLoad == -1)
+ {
+ agedIOLoad = currentIOLoad;
+ }
+ else
+ {
+ /* for IO, we don't do the 'fast increase' since IO is much
+ more jitterish to begin with */
+ agedIOLoad = (agedIOLoad * 31 + currentIOLoad) / 32;
+ }
+ }
}
- if (currentIOLoad == -1) {
- agedIOLoad = -1;
- } else {
- if (agedIOLoad == -1) {
- agedIOLoad = currentIOLoad;
- } else {
- /* for IO, we don't do the 'fast increase' since IO is much
- more jitterish to begin with */
- agedIOLoad = (agedIOLoad * 31 + currentIOLoad) / 32;
- }
- }
- }
}
/**
@@ -557,24 +586,20 @@
* @return the CPU load as a percentage of allowed
* (100 is equivalent to full load)
*/
-int os_cpu_get_load(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
+int
+os_cpu_get_load (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
unsigned long long maxCPULoad;
int ret;
- MUTEX_LOCK(statusMutex);
- updateAgedLoad(ectx, cfg);
+ MUTEX_LOCK (statusMutex);
+ updateAgedLoad (ectx, cfg);
ret = agedCPULoad;
- MUTEX_UNLOCK(statusMutex);
+ MUTEX_UNLOCK (statusMutex);
if (ret == -1)
return -1;
- if (-1 == GC_get_configuration_value_number(cfg,
- "LOAD",
- "MAXCPULOAD",
- 0,
- 10000, /* more than 1 CPU possible */
- 100,
- &maxCPULoad))
+ if (-1 == GC_get_configuration_value_number (cfg, "LOAD", "MAXCPULOAD", 0,
10000, /* more than 1 CPU possible */
+ 100, &maxCPULoad))
return SYSERR;
return (100 * ret) / maxCPULoad;
}
@@ -585,24 +610,20 @@
* @return the CPU load as a percentage of allowed
* (100 is equivalent to full load)
*/
-int os_disk_get_load(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
+int
+os_disk_get_load (struct GE_Context *ectx, struct GC_Configuration *cfg)
+{
unsigned long long maxIOLoad;
int ret;
- MUTEX_LOCK(statusMutex);
- updateAgedLoad(ectx, cfg);
+ MUTEX_LOCK (statusMutex);
+ updateAgedLoad (ectx, cfg);
ret = agedIOLoad;
- MUTEX_UNLOCK(statusMutex);
+ MUTEX_UNLOCK (statusMutex);
if (ret == -1)
return -1;
- if (-1 == GC_get_configuration_value_number(cfg,
- "LOAD",
- "MAXIOLOAD",
- 0,
- 10000, /* more than 1 CPU possible */
- 100,
- &maxIOLoad))
+ if (-1 == GC_get_configuration_value_number (cfg, "LOAD", "MAXIOLOAD", 0,
10000, /* more than 1 CPU possible */
+ 100, &maxIOLoad))
return SYSERR;
return (100 * ret) / maxIOLoad;
}
@@ -612,38 +633,40 @@
* routines. After that it is safe to call each of the status calls separately
* @return OK on success and SYSERR on error (or calls errexit).
*/
-void __attribute__ ((constructor)) gnunet_cpustats_ltdl_init() {
- statusMutex = MUTEX_CREATE(NO);
+void __attribute__ ((constructor)) gnunet_cpustats_ltdl_init ()
+{
+ statusMutex = MUTEX_CREATE (NO);
#ifdef LINUX
- proc_stat = fopen("/proc/stat", "r");
+ proc_stat = fopen ("/proc/stat", "r");
if (NULL == proc_stat)
- GE_LOG_STRERROR_FILE(NULL,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "fopen",
- "/proc/stat");
+ GE_LOG_STRERROR_FILE (NULL,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "fopen", "/proc/stat");
#elif OSX
- initMachCpuStats();
+ initMachCpuStats ();
#elif MINGW
- InitWinEnv(NULL);
+ InitWinEnv (NULL);
#endif
- updateUsage(); /* initialize */
+ updateUsage (); /* initialize */
}
/**
* Shutdown the status calls module.
*/
-void __attribute__ ((destructor)) gnunet_cpustats_ltdl_fini() {
+void __attribute__ ((destructor)) gnunet_cpustats_ltdl_fini ()
+{
#ifdef LINUX
- if (proc_stat != NULL) {
- fclose(proc_stat);
- proc_stat = NULL;
- }
+ if (proc_stat != NULL)
+ {
+ fclose (proc_stat);
+ proc_stat = NULL;
+ }
#elif OSX
- FREENONNULL(prev_cpu_load);
+ FREENONNULL (prev_cpu_load);
#elif MINGW
- ShutdownWinEnv();
+ ShutdownWinEnv ();
#endif
- MUTEX_DESTROY(statusMutex);
+ MUTEX_DESTROY (statusMutex);
}
Modified: GNUnet/src/util/os/daemon.c
===================================================================
--- GNUnet/src/util/os/daemon.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/daemon.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -36,110 +36,116 @@
* @return pid_t of gnunetd if NOT daemonized, 0 if
* daemonized sucessfully, -1 on error
*/
-static pid_t launchWithExec(struct GE_Context * ectx,
- const char * cfgFile,
- int daemonize) {
+static pid_t
+launchWithExec (struct GE_Context *ectx, const char *cfgFile, int daemonize)
+{
pid_t pid;
#ifndef MINGW
- pid = fork();
+ pid = fork ();
if (pid == 0)
#endif
- {
- const char * args[6];
- char * path;
- char * cp;
- int i;
+ {
+ const char *args[6];
+ char *path;
+ char *cp;
+ int i;
- path = NULL;
- cp = os_get_installation_path(IPK_BINDIR);
- i = strlen(cp);
- path = MALLOC(i+2+strlen("gnunetd.exe"));
- strcpy(path, cp);
- strcat(path, "gnunetd");
+ path = NULL;
+ cp = os_get_installation_path (IPK_BINDIR);
+ i = strlen (cp);
+ path = MALLOC (i + 2 + strlen ("gnunetd.exe"));
+ strcpy (path, cp);
+ strcat (path, "gnunetd");
#ifdef MINGW
- strcat(path, ".exe");
+ strcat (path, ".exe");
#endif
- if (ACCESS(path, X_OK) == 0) {
- args[0] = path;
- } else {
- FREE(path);
- path = NULL;
- args[0] = "gnunetd";
- }
- FREE(cp);
- if (cfgFile != NULL) {
- args[1] = "-c";
- args[2] = cfgFile;
- if (NO == daemonize) {
- args[3] = "-d";
- args[4] = NULL;
- } else
- args[3] = NULL;
- } else {
- if (NO == daemonize) {
- args[1] = "-d";
- args[2] = NULL;
- } else
- args[1] = NULL;
- }
- errno = 0;
+ if (ACCESS (path, X_OK) == 0)
+ {
+ args[0] = path;
+ }
+ else
+ {
+ FREE (path);
+ path = NULL;
+ args[0] = "gnunetd";
+ }
+ FREE (cp);
+ if (cfgFile != NULL)
+ {
+ args[1] = "-c";
+ args[2] = cfgFile;
+ if (NO == daemonize)
+ {
+ args[3] = "-d";
+ args[4] = NULL;
+ }
+ else
+ args[3] = NULL;
+ }
+ else
+ {
+ if (NO == daemonize)
+ {
+ args[1] = "-d";
+ args[2] = NULL;
+ }
+ else
+ args[1] = NULL;
+ }
+ errno = 0;
#ifndef MINGW
- nice(10); /* return value is not well-defined */
- if (errno != 0)
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "nice");
+ nice (10); /* return value is not well-defined */
+ if (errno != 0)
+ GE_LOG_STRERROR (ectx, GE_WARNING | GE_USER | GE_BULK, "nice");
- if (path != NULL)
- i = execv(path,
- (char**) args);
- else
- i = execvp("gnunetd",
- (char**) args);
+ if (path != NULL)
+ i = execv (path, (char **) args);
+ else
+ i = execvp ("gnunetd", (char **) args);
#else
- if (path != NULL)
- pid = i = spawnv(_P_NOWAIT, path, (const char *const *) args);
- else
- pid = i = spawnvp(_P_NOWAIT, "gnunetd", (const char *const *) args);
+ if (path != NULL)
+ pid = i = spawnv (_P_NOWAIT, path, (const char *const *) args);
+ else
+ pid = i = spawnvp (_P_NOWAIT, "gnunetd", (const char *const *) args);
#endif
- FREENONNULL(path);
- if (i == -1)
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- "exec",
- path == NULL ? "gnunetd" : path);
+ FREENONNULL (path);
+ if (i == -1)
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ "exec", path == NULL ? "gnunetd" : path);
#ifndef MINGW
- _exit(-1);
+ _exit (-1);
#endif
- }
+ }
#ifndef MINGW
- else if (daemonize) {
- pid_t ret;
- int status;
+ else if (daemonize)
+ {
+ pid_t ret;
+ int status;
- ret = waitpid(pid, &status, 0);
- if (ret == -1) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- "waitpid");
- return SYSERR;
- }
- if ( (WIFEXITED(status) &&
- (0 != WEXITSTATUS(status)) ) ) {
- return SYSERR;
- }
+ ret = waitpid (pid, &status, 0);
+ if (ret == -1)
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_USER | GE_BULK, "waitpid");
+ return SYSERR;
+ }
+ if ((WIFEXITED (status) && (0 != WEXITSTATUS (status))))
+ {
+ return SYSERR;
+ }
#ifdef WCOREDUMP
- if (WCOREDUMP(status)) {
- return SYSERR;
- }
+ if (WCOREDUMP (status))
+ {
+ return SYSERR;
+ }
#endif
- if (WIFSIGNALED(status) ||
- WTERMSIG(status) ) {
- return SYSERR;
+ if (WIFSIGNALED (status) || WTERMSIG (status))
+ {
+ return SYSERR;
+ }
+ return 0;
}
- return 0;
- }
#endif /* MINGW */
return pid;
}
@@ -152,43 +158,45 @@
* @return pid_t of gnunetd if NOT daemonized, 0 if
* daemonized sucessfully, -1 on error
*/
-int os_daemon_start(struct GE_Context * ectx,
- struct GC_Configuration * cfg,
- const char * cfgFile,
- int daemonize) {
+int
+os_daemon_start (struct GE_Context *ectx,
+ struct GC_Configuration *cfg,
+ const char *cfgFile, int daemonize)
+{
#if LINUX || OSX || SOLARIS || SOMEBSD || MINGW
- return launchWithExec(ectx,
- cfgFile,
- daemonize);
+ return launchWithExec (ectx, cfgFile, daemonize);
#else
/* any system out there that does not support THIS!? */
- if (-1 == system("gnunetd")) /* we may not have nice,
- so let's be minimalistic here. */
+ if (-1 == system ("gnunetd")) /* we may not have nice,
+ so let's be minimalistic here. */
return -1;
return 0;
#endif
}
-static int termProcess(int pid) {
+static int
+termProcess (int pid)
+{
#ifndef MINGW
- return kill(pid, SIGTERM) == 0;
+ return kill (pid, SIGTERM) == 0;
#else
int ret;
DWORD dwExitCode = 0;
- HANDLE hProc = OpenProcess(1, 0, pid);
- GenerateConsoleCtrlEvent(CTRL_C_EVENT, pid);
+ HANDLE hProc = OpenProcess (1, 0, pid);
+ GenerateConsoleCtrlEvent (CTRL_C_EVENT, pid);
- WaitForSingleObject(hProc, 3000);
+ WaitForSingleObject (hProc, 3000);
- GetExitCodeProcess(hProc, &dwExitCode);
- if(dwExitCode == STILL_ACTIVE) {
- ret = TerminateProcess(hProc, 0);
- }
+ GetExitCodeProcess (hProc, &dwExitCode);
+ if (dwExitCode == STILL_ACTIVE)
+ {
+ ret = TerminateProcess (hProc, 0);
+ }
else
ret = 1;
- CloseHandle(hProc);
+ CloseHandle (hProc);
return ret;
#endif
@@ -207,20 +215,20 @@
* failed, NO if gnunetd shutdown with
* some error
*/
-int os_daemon_stop(struct GE_Context * ectx,
- int pid) {
+int
+os_daemon_stop (struct GE_Context *ectx, int pid)
+{
pid_t p;
int status;
- termProcess(pid);
+ termProcess (pid);
p = pid;
- if (p != WAITPID(p, &status, 0)) {
- GE_LOG_STRERROR(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- "waitpid");
- return SYSERR;
- }
- if (WEXITSTATUS(status) == 0)
+ if (p != WAITPID (p, &status, 0))
+ {
+ GE_LOG_STRERROR (ectx, GE_ERROR | GE_USER | GE_BULK, "waitpid");
+ return SYSERR;
+ }
+ if (WEXITSTATUS (status) == 0)
return YES;
else
return NO;
Modified: GNUnet/src/util/os/daemontest.c
===================================================================
--- GNUnet/src/util/os/daemontest.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/daemontest.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -29,52 +29,48 @@
#include "gnunet_util_error_loggers.h"
#include "platform.h"
-int main(int argc,
- const char *argv[]) {
+int
+main (int argc, const char *argv[])
+{
int daemon;
- struct GE_Context * ectx;
- struct GC_Configuration * cfg;
+ struct GE_Context *ectx;
+ struct GC_Configuration *cfg;
- ectx = GE_create_context_stderr(NO,
- GE_WARNING | GE_ERROR | GE_FATAL |
- GE_USER | GE_ADMIN | GE_DEVELOPER |
- GE_IMMEDIATE | GE_BULK);
- GE_setDefaultContext(ectx);
- cfg = GC_create_C_impl();
- GE_ASSERT(ectx, cfg != NULL);
- os_init(ectx);
- daemon = os_daemon_start(ectx,
- cfg,
- "check.conf",
- NO);
- if (daemon <= 0) {
- fprintf(stderr,
- "Failed to start daemon.\n");
- GC_free(cfg);
- GE_free_context(ectx);
- return 1;
- }
- if (OK != connection_wait_for_running(ectx,
- cfg,
- 30 * cronSECONDS)) {
- fprintf(stderr,
- "Failed to confirm daemon running (after 30s).\n");
- /* try killing anyway, just to be sure */
- os_daemon_stop(ectx, daemon);
- GC_free(cfg);
- GE_free_context(ectx);
- return 1;
- }
- if (OK != os_daemon_stop(ectx, daemon)) {
- fprintf(stderr,
- "Failed to stop daemon.\n");
- GC_free(cfg);
- GE_free_context(ectx);
- return 1;
- }
+ ectx = GE_create_context_stderr (NO,
+ GE_WARNING | GE_ERROR | GE_FATAL |
+ GE_USER | GE_ADMIN | GE_DEVELOPER |
+ GE_IMMEDIATE | GE_BULK);
+ GE_setDefaultContext (ectx);
+ cfg = GC_create_C_impl ();
+ GE_ASSERT (ectx, cfg != NULL);
+ os_init (ectx);
+ daemon = os_daemon_start (ectx, cfg, "check.conf", NO);
+ if (daemon <= 0)
+ {
+ fprintf (stderr, "Failed to start daemon.\n");
+ GC_free (cfg);
+ GE_free_context (ectx);
+ return 1;
+ }
+ if (OK != connection_wait_for_running (ectx, cfg, 30 * cronSECONDS))
+ {
+ fprintf (stderr, "Failed to confirm daemon running (after 30s).\n");
+ /* try killing anyway, just to be sure */
+ os_daemon_stop (ectx, daemon);
+ GC_free (cfg);
+ GE_free_context (ectx);
+ return 1;
+ }
+ if (OK != os_daemon_stop (ectx, daemon))
+ {
+ fprintf (stderr, "Failed to stop daemon.\n");
+ GC_free (cfg);
+ GE_free_context (ectx);
+ return 1;
+ }
- GC_free(cfg);
- GE_free_context(ectx);
+ GC_free (cfg);
+ GE_free_context (ectx);
return 0;
}
Modified: GNUnet/src/util/os/dso.c
===================================================================
--- GNUnet/src/util/os/dso.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/dso.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -28,133 +28,138 @@
#include "gnunet_util_os.h"
#include "gnunet_util_string.h"
-typedef struct PluginHandle {
- struct GE_Context * ectx;
- char * libprefix;
- char * dsoname;
- void * handle;
+typedef struct PluginHandle
+{
+ struct GE_Context *ectx;
+ char *libprefix;
+ char *dsoname;
+ void *handle;
} Plugin;
-static char * old_dlsearchpath;
+static char *old_dlsearchpath;
/* using libtool, needs init! */
-void __attribute__ ((constructor)) gnc_ltdl_init() {
+void __attribute__ ((constructor)) gnc_ltdl_init ()
+{
int err;
- const char * opath;
- char * path;
- char * cpath;
+ const char *opath;
+ char *path;
+ char *cpath;
#ifdef MINGW
- InitWinEnv(NULL);
+ InitWinEnv (NULL);
#endif
- err = lt_dlinit();
- if (err > 0) {
- fprintf(stderr,
- _("Initialization of plugin mechanism failed: %s!\n"),
- lt_dlerror());
- return;
- }
- opath = lt_dlgetsearchpath();
+ err = lt_dlinit ();
+ if (err > 0)
+ {
+ fprintf (stderr,
+ _("Initialization of plugin mechanism failed: %s!\n"),
+ lt_dlerror ());
+ return;
+ }
+ opath = lt_dlgetsearchpath ();
if (opath != NULL)
- old_dlsearchpath = STRDUP(opath);
- path = os_get_installation_path(IPK_LIBDIR);
- if (path != NULL) {
- if (opath != NULL) {
- cpath = MALLOC(strlen(path) + strlen(opath) + 4);
- strcpy(cpath, opath);
- strcat(cpath, ":");
- strcat(cpath, path);
- lt_dlsetsearchpath(cpath);
- FREE(path);
- FREE(cpath);
- } else {
- lt_dlsetsearchpath(path);
- FREE(path);
+ old_dlsearchpath = STRDUP (opath);
+ path = os_get_installation_path (IPK_LIBDIR);
+ if (path != NULL)
+ {
+ if (opath != NULL)
+ {
+ cpath = MALLOC (strlen (path) + strlen (opath) + 4);
+ strcpy (cpath, opath);
+ strcat (cpath, ":");
+ strcat (cpath, path);
+ lt_dlsetsearchpath (cpath);
+ FREE (path);
+ FREE (cpath);
+ }
+ else
+ {
+ lt_dlsetsearchpath (path);
+ FREE (path);
+ }
}
- }
}
-void __attribute__ ((destructor)) gnc_ltdl_fini() {
- lt_dlsetsearchpath(old_dlsearchpath);
- if (old_dlsearchpath != NULL) {
- FREE(old_dlsearchpath);
- old_dlsearchpath = NULL;
- }
+void __attribute__ ((destructor)) gnc_ltdl_fini ()
+{
+ lt_dlsetsearchpath (old_dlsearchpath);
+ if (old_dlsearchpath != NULL)
+ {
+ FREE (old_dlsearchpath);
+ old_dlsearchpath = NULL;
+ }
#ifdef MINGW
- ShutdownWinEnv();
+ ShutdownWinEnv ();
#endif
// lt_dlexit();
}
struct PluginHandle *
-os_plugin_load(struct GE_Context * ectx,
- const char * libprefix,
- const char * dsoname) {
- void * libhandle;
- char * libname;
- Plugin * plug;
+os_plugin_load (struct GE_Context *ectx,
+ const char *libprefix, const char *dsoname)
+{
+ void *libhandle;
+ char *libname;
+ Plugin *plug;
- libname = MALLOC(strlen(dsoname) +
- strlen(libprefix) + 1);
- strcpy(libname, libprefix);
- strcat(libname, dsoname);
- libhandle = lt_dlopenext(libname);
- if (libhandle == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- _("`%s' failed for library `%s' with error: %s\n"),
- "lt_dlopenext",
- libname,
- lt_dlerror());
- FREE(libname);
- return NULL;
- }
- FREE(libname);
- plug = MALLOC(sizeof(Plugin));
+ libname = MALLOC (strlen (dsoname) + strlen (libprefix) + 1);
+ strcpy (libname, libprefix);
+ strcat (libname, dsoname);
+ libhandle = lt_dlopenext (libname);
+ if (libhandle == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ _("`%s' failed for library `%s' with error: %s\n"),
+ "lt_dlopenext", libname, lt_dlerror ());
+ FREE (libname);
+ return NULL;
+ }
+ FREE (libname);
+ plug = MALLOC (sizeof (Plugin));
plug->handle = libhandle;
- plug->libprefix = STRDUP(libprefix);
- plug->dsoname = STRDUP(dsoname);
+ plug->libprefix = STRDUP (libprefix);
+ plug->dsoname = STRDUP (dsoname);
plug->ectx = ectx;
return plug;
}
-void os_plugin_unload(struct PluginHandle * plugin) {
+void
+os_plugin_unload (struct PluginHandle *plugin)
+{
// lt_dlclose(plugin->handle);
- FREE(plugin->libprefix);
- FREE(plugin->dsoname);
- FREE(plugin);
+ FREE (plugin->libprefix);
+ FREE (plugin->dsoname);
+ FREE (plugin);
}
void *
-os_plugin_resolve_function(struct PluginHandle * plug,
- const char * methodprefix,
- int logError) {
- char * initName;
- void * mptr;
+os_plugin_resolve_function (struct PluginHandle *plug,
+ const char *methodprefix, int logError)
+{
+ char *initName;
+ void *mptr;
- initName = MALLOC(strlen(plug->dsoname) +
- strlen(methodprefix) + 2);
- strcpy(initName, "_");
- strcat(initName, methodprefix);
- strcat(initName, plug->dsoname);
- mptr = lt_dlsym(plug->handle, &initName[1]);
+ initName = MALLOC (strlen (plug->dsoname) + strlen (methodprefix) + 2);
+ strcpy (initName, "_");
+ strcat (initName, methodprefix);
+ strcat (initName, plug->dsoname);
+ mptr = lt_dlsym (plug->handle, &initName[1]);
if (mptr == NULL)
- mptr = lt_dlsym(plug->handle, initName);
- if ( (mptr == NULL) &&
- (logError) )
- GE_LOG(plug->ectx,
- GE_ERROR | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
- _("`%s' failed to resolve method '%s' with error: %s\n"),
- "lt_dlsym",
- &initName[1],
- lt_dlerror());
- FREE(initName);
+ mptr = lt_dlsym (plug->handle, initName);
+ if ((mptr == NULL) && (logError))
+ GE_LOG (plug->ectx,
+ GE_ERROR | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
+ _("`%s' failed to resolve method '%s' with error: %s\n"),
+ "lt_dlsym", &initName[1], lt_dlerror ());
+ FREE (initName);
return mptr;
}
-/* end of dso.c */
+/* end of dso.c */
Modified: GNUnet/src/util/os/init.c
===================================================================
--- GNUnet/src/util/os/init.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/init.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -32,10 +32,11 @@
* @param ectx logging context, NULL means stderr
* @returns OK on success, SYSERR otherwise
*/
-int os_init(struct GE_Context *ectx)
+int
+os_init (struct GE_Context *ectx)
{
#ifdef MINGW
- if (InitWinEnv(ectx) != ERROR_SUCCESS)
+ if (InitWinEnv (ectx) != ERROR_SUCCESS)
return SYSERR;
else
#endif
@@ -45,10 +46,10 @@
/**
* @brief Perform OS specific cleanup
*/
-void __attribute__ ((destructor)) os_fini()
+void __attribute__ ((destructor)) os_fini ()
{
#ifdef MINGW
- ShutdownWinEnv();
+ ShutdownWinEnv ();
#endif
}
Modified: GNUnet/src/util/os/installpath.c
===================================================================
--- GNUnet/src/util/os/installpath.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/installpath.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -25,8 +25,9 @@
*/
#ifdef __cplusplus
-extern "C" {
-#if 0 /* keep Emacsens' auto-indent happy */
+extern "C"
+{
+#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
@@ -47,35 +48,32 @@
* Try to determine path by reading /proc/PID/exe
*/
static char *
-get_path_from_proc_exe() {
+get_path_from_proc_exe ()
+{
char fn[64];
- char * lnk;
+ char *lnk;
size_t size;
- SNPRINTF(fn,
- 64,
- "/proc/%u/exe",
- getpid());
- lnk = MALLOC(1024);
- size = readlink(fn, lnk, 1023);
- if ( (size == 0) || (size >= 1024) ) {
- GE_LOG_STRERROR_FILE(NULL,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "readlink",
- fn);
- FREE(lnk);
- return NULL;
- }
+ SNPRINTF (fn, 64, "/proc/%u/exe", getpid ());
+ lnk = MALLOC (1024);
+ size = readlink (fn, lnk, 1023);
+ if ((size == 0) || (size >= 1024))
+ {
+ GE_LOG_STRERROR_FILE (NULL,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ "readlink", fn);
+ FREE (lnk);
+ return NULL;
+ }
lnk[size] = '\0';
- while ( (lnk[size] != '/') &&
- (size > 0) )
+ while ((lnk[size] != '/') && (size > 0))
size--;
- if ( (size < 4) ||
- (lnk[size-4] != '/') ) {
- /* not installed in "/bin/" -- binary path probably useless */
- FREE(lnk);
- return NULL;
- }
+ if ((size < 4) || (lnk[size - 4] != '/'))
+ {
+ /* not installed in "/bin/" -- binary path probably useless */
+ FREE (lnk);
+ return NULL;
+ }
lnk[size] = '\0';
return lnk;
}
@@ -85,16 +83,16 @@
/**
* Try to determine path with win32-specific function
*/
-static char * get_path_from_module_filename() {
- char * path;
- char * idx;
+static char *
+get_path_from_module_filename ()
+{
+ char *path;
+ char *idx;
- path = MALLOC(4097);
- GetModuleFileName(NULL, path, 4096);
- idx = path + strlen(path);
- while ( (idx > path) &&
- (*idx != '\\') &&
- (*idx != '/') )
+ path = MALLOC (4097);
+ GetModuleFileName (NULL, path, 4096);
+ idx = path + strlen (path);
+ while ((idx > path) && (*idx != '\\') && (*idx != '/'))
idx--;
*idx = '\0';
return path;
@@ -102,9 +100,11 @@
#endif
#if OSX
-typedef int (*MyNSGetExecutablePathProto)(char *buf, size_t *bufsize);
+typedef int (*MyNSGetExecutablePathProto) (char *buf, size_t * bufsize);
-static char * get_path_from_NSGetExecutablePath() {
+static char *
+get_path_from_NSGetExecutablePath ()
+{
char *path;
char zero = '\0';
size_t len;
@@ -112,79 +112,88 @@
int ret;
path = NULL;
- func = dlsym(RTLD_DEFAULT, "_NSGetExecutablePath");
- if (func) {
- path = &zero;
- len = 0;
- ret = ((MyNSGetExecutablePathProto)func)(path, &len);
- if (len == 0)
- path = NULL;
- else {
- len++;
- path = (char *)MALLOC(len);
- ret = ((MyNSGetExecutablePathProto)func)(path, &len);
- if (ret != 0) {
- FREE(path);
+ func = dlsym (RTLD_DEFAULT, "_NSGetExecutablePath");
+ if (func)
+ {
+ path = &zero;
+ len = 0;
+ ret = ((MyNSGetExecutablePathProto) func) (path, &len);
+ if (len == 0)
path = NULL;
- }
- else {
- while ((path[len] != '/') && (len > 0))
- len--;
- path[len] = '\0';
- }
+ else
+ {
+ len++;
+ path = (char *) MALLOC (len);
+ ret = ((MyNSGetExecutablePathProto) func) (path, &len);
+ if (ret != 0)
+ {
+ FREE (path);
+ path = NULL;
+ }
+ else
+ {
+ while ((path[len] != '/') && (len > 0))
+ len--;
+ path[len] = '\0';
+ }
+ }
}
- }
return path;
}
#endif
static char *
-get_path_from_PATH() {
- char * path;
- char * pos;
- char * end;
- char * buf;
- const char * p;
+get_path_from_PATH ()
+{
+ char *path;
+ char *pos;
+ char *end;
+ char *buf;
+ const char *p;
size_t size;
- p = getenv("PATH");
+ p = getenv ("PATH");
if (p == NULL)
return NULL;
- path = STRDUP(p); /* because we write on it */
- buf = MALLOC(strlen(path) + 20);
- size = strlen(path);
+ path = STRDUP (p); /* because we write on it */
+ buf = MALLOC (strlen (path) + 20);
+ size = strlen (path);
pos = path;
- while (NULL != (end = strchr(pos, ':'))) {
- *end = '\0';
- sprintf(buf, "%s/%s", pos, "gnunetd");
- if (disk_file_test(NULL, buf) == YES) {
- pos = STRDUP(pos);
- FREE(buf);
- FREE(path);
+ while (NULL != (end = strchr (pos, ':')))
+ {
+ *end = '\0';
+ sprintf (buf, "%s/%s", pos, "gnunetd");
+ if (disk_file_test (NULL, buf) == YES)
+ {
+ pos = STRDUP (pos);
+ FREE (buf);
+ FREE (path);
+ return pos;
+ }
+ pos = end + 1;
+ }
+ sprintf (buf, "%s/%s", pos, "gnunetd");
+ if (disk_file_test (NULL, buf) == YES)
+ {
+ pos = STRDUP (pos);
+ FREE (buf);
+ FREE (path);
return pos;
}
- pos = end + 1;
- }
- sprintf(buf, "%s/%s", pos, "gnunetd");
- if (disk_file_test(NULL, buf) == YES) {
- pos = STRDUP(pos);
- FREE(buf);
- FREE(path);
- return pos;
- }
- FREE(buf);
- FREE(path);
+ FREE (buf);
+ FREE (path);
return NULL;
}
static char *
-get_path_from_GNUNET_PREFIX() {
- const char * p;
+get_path_from_GNUNET_PREFIX ()
+{
+ const char *p;
- p = getenv("GNUNET_PREFIX");
+ p = getenv ("GNUNET_PREFIX");
if (p != NULL)
- return STRDUP(p);
+ return STRDUP (p);
return NULL;
}
@@ -195,28 +204,29 @@
* @return a pointer to the executable path, or NULL on error
*/
static char *
-os_get_exec_path() {
- char * ret;
+os_get_exec_path ()
+{
+ char *ret;
- ret = get_path_from_GNUNET_PREFIX();
+ ret = get_path_from_GNUNET_PREFIX ();
if (ret != NULL)
return ret;
#if LINUX
- ret = get_path_from_proc_exe();
+ ret = get_path_from_proc_exe ();
if (ret != NULL)
return ret;
#endif
#if WINDOWS
- ret = get_path_from_module_filename();
+ ret = get_path_from_module_filename ();
if (ret != NULL)
return ret;
#endif
#if OSX
- ret = get_path_from_NSGetExecutablePath();
+ ret = get_path_from_NSGetExecutablePath ();
if (ret != NULL)
return ret;
#endif
- ret = get_path_from_PATH();
+ ret = get_path_from_PATH ();
if (ret != NULL)
return ret;
/* other attempts here */
@@ -230,61 +240,67 @@
* @author Milan
* @return a pointer to the dir path (to be freed by the caller)
*/
-char * os_get_installation_path(enum InstallPathKind dirkind) {
+char *
+os_get_installation_path (enum InstallPathKind dirkind)
+{
size_t n;
- const char * dirname;
- char * execpath;
- char * tmp;
+ const char *dirname;
+ char *execpath;
+ char *tmp;
- execpath = os_get_exec_path();
+ execpath = os_get_exec_path ();
if (execpath == NULL)
return NULL;
- n = strlen(execpath);
- if (n == 0) {
- /* should never happen, but better safe than sorry */
- FREE(execpath);
- return NULL;
- }
- if (execpath[n-1] == DIR_SEPARATOR)
+ n = strlen (execpath);
+ if (n == 0)
+ {
+ /* should never happen, but better safe than sorry */
+ FREE (execpath);
+ return NULL;
+ }
+ if (execpath[n - 1] == DIR_SEPARATOR)
execpath[--n] = '\0';
- if ( (n > 3) &&
- (0 == strcasecmp(&execpath[n-3], "bin")) ) {
- /* good, strip of '/bin'! */
- execpath[n-3] = '\0';
- n -= 3;
- }
- switch(dirkind) {
- case IPK_PREFIX:
- dirname = "";
- break;
- case IPK_BINDIR:
- dirname = DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR;
- break;
- case IPK_LIBDIR:
- dirname = DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR "GNUnet"
DIR_SEPARATOR_STR;
- break;
- case IPK_DATADIR:
- dirname = DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "GNUnet"
DIR_SEPARATOR_STR;
- break;
- case IPK_LOCALEDIR:
- dirname = DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale"
DIR_SEPARATOR_STR ;
- break;
- default:
- FREE(execpath);
- return NULL;
- }
- tmp = MALLOC(strlen(execpath)+strlen(dirname)+1);
- sprintf(tmp,
- "%s%s",
- execpath,
- dirname);
- FREE(execpath);
+ if ((n > 3) && (0 == strcasecmp (&execpath[n - 3], "bin")))
+ {
+ /* good, strip of '/bin'! */
+ execpath[n - 3] = '\0';
+ n -= 3;
+ }
+ switch (dirkind)
+ {
+ case IPK_PREFIX:
+ dirname = "";
+ break;
+ case IPK_BINDIR:
+ dirname = DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR;
+ break;
+ case IPK_LIBDIR:
+ dirname =
+ DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR "GNUnet" DIR_SEPARATOR_STR;
+ break;
+ case IPK_DATADIR:
+ dirname =
+ DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "GNUnet"
+ DIR_SEPARATOR_STR;
+ break;
+ case IPK_LOCALEDIR:
+ dirname =
+ DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale"
+ DIR_SEPARATOR_STR;
+ break;
+ default:
+ FREE (execpath);
+ return NULL;
+ }
+ tmp = MALLOC (strlen (execpath) + strlen (dirname) + 1);
+ sprintf (tmp, "%s%s", execpath, dirname);
+ FREE (execpath);
return tmp;
}
-#if 0 /* keep Emacsens' auto-indent happy */
+#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
Modified: GNUnet/src/util/os/osconfig.c
===================================================================
--- GNUnet/src/util/os/osconfig.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/osconfig.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -34,63 +34,64 @@
* @brief Enumerate all network interfaces
* @param callback the callback function
*/
-void os_list_network_interfaces(struct GE_Context *ectx,
- NetworkIfcProcessor proc, void *cls)
+void
+os_list_network_interfaces (struct GE_Context *ectx,
+ NetworkIfcProcessor proc, void *cls)
{
#ifdef MINGW
- ListNICs(proc, cls);
+ ListNICs (proc, cls);
#else
char entry[11], *dst;
FILE *f;
- if(system("ifconfig > /dev/null 2> /dev/null"))
- if(system("/sbin/ifconfig > /dev/null 2> /dev/null") == 0)
- f = popen("/sbin/ifconfig 2> /dev/null", "r");
+ if (system ("ifconfig > /dev/null 2> /dev/null"))
+ if (system ("/sbin/ifconfig > /dev/null 2> /dev/null") == 0)
+ f = popen ("/sbin/ifconfig 2> /dev/null", "r");
else
f = NULL;
else
- f = popen("ifconfig 2> /dev/null", "r");
- if(!f)
- {
- GE_LOG_STRERROR_FILE(ectx,
- GE_USER | GE_ADMIN | GE_BULK | GE_WARNING,
- "popen", "ifconfig");
- return;
- }
+ f = popen ("ifconfig 2> /dev/null", "r");
+ if (!f)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_USER | GE_ADMIN | GE_BULK | GE_WARNING,
+ "popen", "ifconfig");
+ return;
+ }
- while(1)
- {
- int i = 0;
- int c = fgetc(f);
+ while (1)
+ {
+ int i = 0;
+ int c = fgetc (f);
- if(c == EOF)
- break;
+ if (c == EOF)
+ break;
- dst = entry;
+ dst = entry;
- /* Read interface name until the first space (or colon under OS X) */
- while(c != EOF && c != '\n' &&
+ /* Read interface name until the first space (or colon under OS X) */
+ while (c != EOF && c != '\n' &&
#ifdef OSX
- c != ':'
+ c != ':'
#else
- c != ' '
+ c != ' '
#endif
- && i < 10)
- {
- *dst++ = c;
- i++;
- c = fgetc(f);
- }
- *dst = 0;
+ && i < 10)
+ {
+ *dst++ = c;
+ i++;
+ c = fgetc (f);
+ }
+ *dst = 0;
- if((entry[0] != '\0') &&
- (OK != proc(entry, strcmp(entry, "eth0") == 0, cls)))
- break;
+ if ((entry[0] != '\0') &&
+ (OK != proc (entry, strcmp (entry, "eth0") == 0, cls)))
+ break;
- while((c != '\n') && (c != EOF))
- c = fgetc(f);
- }
- pclose(f);
+ while ((c != '\n') && (c != EOF))
+ c = fgetc (f);
+ }
+ pclose (f);
#endif
}
@@ -98,8 +99,9 @@
* @brief Set maximum number of open file descriptors
* @return OK on success, SYSERR on error
*/
-int os_set_fd_limit(struct GE_Context * ectx,
- int n) {
+int
+os_set_fd_limit (struct GE_Context *ectx, int n)
+{
if (n == 0)
return OK;
#if HAVE_SETRLIMIT
@@ -108,17 +110,18 @@
rlim.rlim_cur = n;
rlim.rlim_max = n;
- ret = setrlimit(RLIMIT_NOFILE, &rlim);
- if (ret != 0) {
- GE_LOG_STRERROR(ectx,
- GE_INFO | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "setrlimit");
- return SYSERR;
- }
+ ret = setrlimit (RLIMIT_NOFILE, &rlim);
+ if (ret != 0)
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_INFO | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ "setrlimit");
+ return SYSERR;
+ }
#else
- GE_LOG(ectx,
- GE_INFO | GE_USER | GE_ADMIN,
- _("Setting open descriptor limit not supported.\n"));
+ GE_LOG (ectx,
+ GE_INFO | GE_USER | GE_ADMIN,
+ _("Setting open descriptor limit not supported.\n"));
#endif
return OK;
}
@@ -127,19 +130,20 @@
* @brief Checks if we can start GNUnet automatically
* @return YES if yes, NO otherwise
*/
-static int isOSAutostartCapable()
+static int
+isOSAutostartCapable ()
{
#ifdef LINUX
- if(ACCESS("/usr/sbin/update-rc.d", X_OK) == 0)
- {
- /* Debian */
- if(ACCESS("/etc/init.d/", W_OK) == 0)
- return YES;
- }
+ if (ACCESS ("/usr/sbin/update-rc.d", X_OK) == 0)
+ {
+ /* Debian */
+ if (ACCESS ("/etc/init.d/", W_OK) == 0)
+ return YES;
+ }
return NO;
#else
#ifdef WINDOWS
- return IsWinNT() ? YES : NO;
+ return IsWinNT ()? YES : NO;
#else
return NO;
#endif
@@ -176,114 +180,116 @@
* Unix
* 2 startup script could not be opened
*/
-int os_modify_autostart(struct GE_Context *ectx,
- int testCapability,
- int doAutoStart,
- const char *application,
- const char *username, const char *groupname)
+int
+os_modify_autostart (struct GE_Context *ectx,
+ int testCapability,
+ int doAutoStart,
+ const char *application,
+ const char *username, const char *groupname)
{
- if(testCapability)
- {
- /* TODO: check that user/group/application
- exist! */
- return isOSAutostartCapable();
- }
+ if (testCapability)
+ {
+ /* TODO: check that user/group/application
+ exist! */
+ return isOSAutostartCapable ();
+ }
#ifdef WINDOWS
- if(doAutoStart)
- {
- if(IsWinNT())
+ if (doAutoStart)
{
- char *err = NULL;
- DWORD dwErr = 0;
+ if (IsWinNT ())
+ {
+ char *err = NULL;
+ DWORD dwErr = 0;
- if(username && !strlen(username))
- username = NULL;
+ if (username && !strlen (username))
+ username = NULL;
- /* Install service */
- switch (InstallAsService(username))
- {
- case 0:
- break;
- case 1:
- return NO;
- case 2:
- return 2;
- case 3:
- if(GetLastError() != ERROR_SERVICE_EXISTS)
- return 3;
- break;
- default:
- return SYSERR;
- }
+ /* Install service */
+ switch (InstallAsService (username))
+ {
+ case 0:
+ break;
+ case 1:
+ return NO;
+ case 2:
+ return 2;
+ case 3:
+ if (GetLastError () != ERROR_SERVICE_EXISTS)
+ return 3;
+ break;
+ default:
+ return SYSERR;
+ }
- /* Grant permissions to the GNUnet directory */
- if((!err || dwErr == ERROR_SERVICE_EXISTS) && username)
- {
- char szHome[_MAX_PATH + 1];
+ /* Grant permissions to the GNUnet directory */
+ if ((!err || dwErr == ERROR_SERVICE_EXISTS) && username)
+ {
+ char szHome[_MAX_PATH + 1];
- plibc_conv_to_win_path("/", szHome);
+ plibc_conv_to_win_path ("/", szHome);
- if(!AddPathAccessRights(szHome, username, GENERIC_ALL))
- return 4;
- }
- }
- else
- {
- char szPath[_MAX_PATH + 1];
- HKEY hKey;
+ if (!AddPathAccessRights (szHome, username, GENERIC_ALL))
+ return 4;
+ }
+ }
+ else
+ {
+ char szPath[_MAX_PATH + 1];
+ HKEY hKey;
- plibc_conv_to_win_path(application, szPath);
+ plibc_conv_to_win_path (application, szPath);
- if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,
- "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0,
- KEY_EXECUTE, &hKey) == ERROR_SUCCESS)
- {
- if(RegSetValueEx(hKey,
- "GNUnet",
- 0, REG_SZ, szPath, strlen(szPath)) != ERROR_SUCCESS)
- return 5;
+ if (RegOpenKeyEx (HKEY_LOCAL_MACHINE,
+
"Software\\Microsoft\\Windows\\CurrentVersion\\Run",
+ 0, KEY_EXECUTE, &hKey) == ERROR_SUCCESS)
+ {
+ if (RegSetValueEx (hKey,
+ "GNUnet",
+ 0, REG_SZ, szPath,
+ strlen (szPath)) != ERROR_SUCCESS)
+ return 5;
- RegCloseKey(hKey);
- }
- else
- return 5;
+ RegCloseKey (hKey);
+ }
+ else
+ return 5;
+ }
}
- }
else
- {
- if(IsWinNT())
{
- switch (UninstallService())
- {
- case 0:
- break;
- case 1:
- return NO;
- case 2:
- return 2;
- case 3:
- return 6;
- case 4:
- return 3;
- default:
- return SYSERR;
- }
- }
- else
- {
- HKEY hKey;
+ if (IsWinNT ())
+ {
+ switch (UninstallService ())
+ {
+ case 0:
+ break;
+ case 1:
+ return NO;
+ case 2:
+ return 2;
+ case 3:
+ return 6;
+ case 4:
+ return 3;
+ default:
+ return SYSERR;
+ }
+ }
+ else
+ {
+ HKEY hKey;
- if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,
- "Software\\Microsoft\\Windows\\CurrentVersion\\Run",
- 0, KEY_SET_VALUE, &hKey) == ERROR_SUCCESS)
- {
- RegDeleteValue(hKey, "GNUnet");
- RegCloseKey(hKey);
- }
- else
- return 5;
+ if (RegOpenKeyEx (HKEY_LOCAL_MACHINE,
+
"Software\\Microsoft\\Windows\\CurrentVersion\\Run",
+ 0, KEY_SET_VALUE, &hKey) == ERROR_SUCCESS)
+ {
+ RegDeleteValue (hKey, "GNUnet");
+ RegCloseKey (hKey);
+ }
+ else
+ return 5;
+ }
}
- }
return YES;
#else
@@ -291,118 +297,127 @@
int ret;
/* Unix */
- if ((ACCESS("/usr/sbin/update-rc.d",
- X_OK) != 0)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "access",
- "/usr/sbin/update-rc.d");
- return SYSERR;
- }
+ if ((ACCESS ("/usr/sbin/update-rc.d", X_OK) != 0))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ "access", "/usr/sbin/update-rc.d");
+ return SYSERR;
+ }
/* Debian */
- if (doAutoStart) {
+ if (doAutoStart)
+ {
- if (ACCESS(application, X_OK) != 0) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "access",
- application);
- }
- if (STAT("/etc/init.d/gnunetd", &buf) == -1) {
- /* create init file */
- FILE *f = FOPEN("/etc/init.d/gnunetd", "w");
- if (f == NULL) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "fopen",
- "/etc/init.d/gnunetd");
- return 2;
- }
+ if (ACCESS (application, X_OK) != 0)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ "access", application);
+ }
+ if (STAT ("/etc/init.d/gnunetd", &buf) == -1)
+ {
+ /* create init file */
+ FILE *f = FOPEN ("/etc/init.d/gnunetd", "w");
+ if (f == NULL)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN |
+ GE_IMMEDIATE, "fopen",
+ "/etc/init.d/gnunetd");
+ return 2;
+ }
- fprintf(f,
- "#!/bin/sh\n"
- "#\n"
- "# Automatically created by %s\n"
- "#\n"
- "\n"
- "PIDFILE=/var/run/gnunetd/gnunetd.pid\n"
- "\n"
- "case \"$1\" in\n"
- " start)\n"
- " echo -n \"Starting GNUnet: \"\n"
- " %s\n && echo ok || echo failed\n"
- " ;;\n"
- " stop)\n"
- " echo -n \"Stopping GNUnet: \"\n"
- " kill `cat $PIDFILE`\n && echo ok || echo failed\n"
- " ;;\n"
- " reload)\n"
- " echo -n \"Reloading GNUnet: \"\n"
- " kill -HUP `cat $PIDFILE`\n && echo ok || echo failed\n"
- " ;;\n"
- " restart|force-reload)\n"
- " echo \"Restarting GNUnet: gnunetd...\"\n"
- " $0 stop\n"
- " sleep 1\n"
- " $0 start\n"
- " ;;\n"
- " *)\n"
- " echo \"Usage: /etc/init.d/gnunetd
{start|stop|reload|restart|force-reload}\" >&2\n"
- " exit 1\n"
- " ;;\n"
- "\n" "esac\n" "exit 0\n",
- "gnunet-setup",
- application);
- fclose(f);
- if (0 != CHMOD("/etc/init.d/gnunetd",
- S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "chmod",
- "/etc/init.d/gnunetd");
- return SYSERR;
- }
+ fprintf (f,
+ "#!/bin/sh\n"
+ "#\n"
+ "# Automatically created by %s\n"
+ "#\n"
+ "\n"
+ "PIDFILE=/var/run/gnunetd/gnunetd.pid\n"
+ "\n"
+ "case \"$1\" in\n"
+ " start)\n"
+ " echo -n \"Starting GNUnet: \"\n"
+ " %s\n && echo ok || echo failed\n"
+ " ;;\n"
+ " stop)\n"
+ " echo -n \"Stopping GNUnet: \"\n"
+ " kill `cat $PIDFILE`\n && echo ok || echo failed\n"
+ " ;;\n"
+ " reload)\n"
+ " echo -n \"Reloading GNUnet: \"\n"
+ " kill -HUP `cat $PIDFILE`\n && echo ok || echo failed\n"
+ " ;;\n"
+ " restart|force-reload)\n"
+ " echo \"Restarting GNUnet: gnunetd...\"\n"
+ " $0 stop\n"
+ " sleep 1\n"
+ " $0 start\n"
+ " ;;\n"
+ " *)\n"
+ " echo \"Usage: /etc/init.d/gnunetd
{start|stop|reload|restart|force-reload}\" >&2\n"
+ " exit 1\n"
+ " ;;\n"
+ "\n" "esac\n" "exit 0\n", "gnunet-setup", application);
+ fclose (f);
+ if (0 != CHMOD ("/etc/init.d/gnunetd",
+ S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN |
+ GE_IMMEDIATE, "chmod",
+ "/etc/init.d/gnunetd");
+ return SYSERR;
+ }
+ }
+ if (STAT ("/etc/init.d/gnunetd", &buf) != -1)
+ {
+ errno = 0;
+ ret = system ("/usr/sbin/update-rc.d gnunetd defaults");
+ if (ret != 0)
+ {
+ if (errno != 0)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN |
+ GE_IMMEDIATE, "system",
+ "/usr/sbin/update-rc.d");
+ }
+ else
+ {
+ GE_LOG (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ _("Command `%s' failed with error code %u\n"),
+ "/usr/sbin/update-rc.d gnunetd defaults",
+ WEXITSTATUS (ret));
+ }
+ return SYSERR;
+ }
+ }
+ return YES;
}
- if (STAT("/etc/init.d/gnunetd", &buf) != -1) {
+ else
+ { /* REMOVE autostart */
+ if ((UNLINK ("/etc/init.d/gnunetd") == -1) && (errno != ENOENT))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN |
+ GE_IMMEDIATE, "unlink",
+ "/etc/init.d/gnunetd");
+ return SYSERR;
+ }
errno = 0;
- ret = system("/usr/sbin/update-rc.d gnunetd defaults");
- if (ret != 0) {
- if (errno != 0) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "system",
- "/usr/sbin/update-rc.d");
- } else {
- GE_LOG(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- _("Command `%s' failed with error code %u\n"),
- "/usr/sbin/update-rc.d gnunetd defaults",
- WEXITSTATUS(ret));
- }
- return SYSERR;
- }
+ if (-1 != system ("/usr/sbin/update-rc.d gnunetd remove"))
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_ADMIN |
+ GE_IMMEDIATE, "system",
+ "/usr/sbin/update-rc.d");
+ return SYSERR;
+ }
+ return YES;
}
- return YES;
- } else { /* REMOVE autostart */
- if ( (UNLINK("/etc/init.d/gnunetd") == -1) &&
- (errno != ENOENT)) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "unlink",
- "/etc/init.d/gnunetd");
- return SYSERR;
- }
- errno = 0;
- if(-1 != system("/usr/sbin/update-rc.d gnunetd remove")) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "system",
- "/usr/sbin/update-rc.d");
- return SYSERR;
- }
- return YES;
- }
#endif
return SYSERR;
}
Modified: GNUnet/src/util/os/priority.c
===================================================================
--- GNUnet/src/util/os/priority.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/priority.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -31,83 +31,80 @@
/**
* Set our process priority
*/
-int os_set_process_priority(struct GE_Context * ectx,
- const char * str) {
+int
+os_set_process_priority (struct GE_Context *ectx, const char *str)
+{
int prio = 0;
- GE_ASSERT(ectx,
- str != NULL);
+ GE_ASSERT (ectx, str != NULL);
/* We support four levels (NORMAL, ABOVE NORMAL, BELOW NORMAL, HIGH and IDLE)
* and the usual numeric nice() increments */
- if (strcmp(str, "NORMAL") == 0)
+ if (strcmp (str, "NORMAL") == 0)
#ifdef MINGW
prio = NORMAL_PRIORITY_CLASS;
#else
- prio = 0;
+ prio = 0;
#endif
- else if (strcmp(str, "ABOVE NORMAL") == 0)
+ else if (strcmp (str, "ABOVE NORMAL") == 0)
#ifdef MINGW
prio = ABOVE_NORMAL_PRIORITY_CLASS;
#else
- prio = -5;
+ prio = -5;
#endif
- else if (strcmp(str, "BELOW NORMAL") == 0)
+ else if (strcmp (str, "BELOW NORMAL") == 0)
#ifdef MINGW
prio = BELOW_NORMAL_PRIORITY_CLASS;
#else
- prio = 10;
+ prio = 10;
#endif
- else if (strcmp(str, "HIGH") == 0)
+ else if (strcmp (str, "HIGH") == 0)
#ifdef MINGW
prio = HIGH_PRIORITY_CLASS;
#else
- prio = -10;
+ prio = -10;
#endif
- else if (strcmp(str, "IDLE") == 0)
+ else if (strcmp (str, "IDLE") == 0)
#ifdef MINGW
prio = IDLE_PRIORITY_CLASS;
#else
- prio = 19;
+ prio = 19;
#endif
- else {
- if (1 != sscanf(str,
- "%d",
- &prio)) {
- GE_LOG(ectx,
- GE_USER | GE_BULK | GE_ERROR,
- _("Invalid process priority `%s'\n"),
- str);
- return SYSERR;
- }
+ else
+ {
+ if (1 != sscanf (str, "%d", &prio))
+ {
+ GE_LOG (ectx,
+ GE_USER | GE_BULK | GE_ERROR,
+ _("Invalid process priority `%s'\n"), str);
+ return SYSERR;
+ }
#ifdef MINGW
- /* Convert the nice increment to a priority class */
- if (prio == 0)
- prio = NORMAL_PRIORITY_CLASS;
- else if (prio > 0 && prio <= 10)
- prio = BELOW_NORMAL_PRIORITY_CLASS;
- else if (prio > 0)
- prio = IDLE_PRIORITY_CLASS;
- else if (prio < 0 && prio >= -10)
- prio = ABOVE_NORMAL_PRIORITY_CLASS;
- else if (prio < 0)
- prio = HIGH_PRIORITY_CLASS;
+ /* Convert the nice increment to a priority class */
+ if (prio == 0)
+ prio = NORMAL_PRIORITY_CLASS;
+ else if (prio > 0 && prio <= 10)
+ prio = BELOW_NORMAL_PRIORITY_CLASS;
+ else if (prio > 0)
+ prio = IDLE_PRIORITY_CLASS;
+ else if (prio < 0 && prio >= -10)
+ prio = ABOVE_NORMAL_PRIORITY_CLASS;
+ else if (prio < 0)
+ prio = HIGH_PRIORITY_CLASS;
#endif
- }
+ }
/* Set process priority */
#ifdef MINGW
- SetPriorityClass(GetCurrentProcess(), prio);
+ SetPriorityClass (GetCurrentProcess (), prio);
#else
errno = 0;
- nice(prio);
- if (errno != 0) {
- GE_LOG_STRERROR(ectx,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "nice");
- return SYSERR;
- }
+ nice (prio);
+ if (errno != 0)
+ {
+ GE_LOG_STRERROR (ectx, GE_WARNING | GE_ADMIN | GE_BULK, "nice");
+ return SYSERR;
+ }
#endif
return OK;
}
-
Modified: GNUnet/src/util/os/semaphore.c
===================================================================
--- GNUnet/src/util/os/semaphore.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/semaphore.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -52,23 +52,24 @@
*/
#define USE_CHECKING_MUTEX 1
-typedef struct IPC_SEMAPHORE {
- struct GE_Context * ectx;
+typedef struct IPC_SEMAPHORE
+{
+ struct GE_Context *ectx;
#if SOLARIS || FREEBSD5 || OSX
- sem_t * internal;
+ sem_t *internal;
#elif WINDOWS
HANDLE internal;
#elif LINUX
int internal;
- char * filename;
+ char *filename;
#elif SOMEBSD
int initialValue;
int fd;
- struct MUTEX * internalLock;
- char * filename;
+ struct MUTEX *internalLock;
+ char *filename;
#elif _MSC_VER
- int internal; /* KLB_FIX */
- char * filename;
+ int internal; /* KLB_FIX */
+ char *filename;
#else
/* PORT-ME! */
#endif
@@ -91,456 +92,385 @@
/* Various operations */
static struct sembuf op_lock[2] = {
- {2, 0, 0}, /* wait for [2] (lock) to equal 0 */
- {2, 1, SEM_UNDO} /* then increment [2] to 1 - this locks it */
- /* UNDO to release the lock if processes exits */
/* before explicitly unlocking */
+ {2, 0, 0}, /* wait for [2] (lock) to equal 0 */
+ {2, 1, SEM_UNDO} /* then increment [2] to 1 - this locks it */
+ /* UNDO to release the lock if processes exits *//* before explicitly
unlocking */
};
static struct sembuf op_unlock[1] = {
- {2, -1, SEM_UNDO} /* decrement [2] (lock) back to 0 */
+ {2, -1, SEM_UNDO} /* decrement [2] (lock) back to 0 */
};
-static struct sembuf op_endcreate[2] = {
- {1, -1, SEM_UNDO},/* decrement [1] (proc counter) with undo on exit */
+static struct sembuf op_endcreate[2] = {
+ {1, -1, SEM_UNDO}, /* decrement [1] (proc counter) with undo on
exit */
/* UNDO to adjust proc counter if process exits
before explicitly calling sem_close() */
- {2, -1, SEM_UNDO} /* then decrement [2] (lock) back to 0 */
+ {2, -1, SEM_UNDO} /* then decrement [2] (lock) back to 0 */
};
-static struct sembuf op_close[3] = {
- {2, 0, 0}, /* wait for [2] (lock) to equal 0 */
- {2, 1, SEM_UNDO}, /* then increment [2] to 1 - this locks it */
- {1, 1, SEM_UNDO} /* then increment [1] (proc counter) */
+static struct sembuf op_close[3] = {
+ {2, 0, 0}, /* wait for [2] (lock) to equal 0 */
+ {2, 1, SEM_UNDO}, /* then increment [2] to 1 - this locks it */
+ {1, 1, SEM_UNDO} /* then increment [1] (proc counter) */
};
#endif
#if SOMEBSD
-static void FLOCK(int fd,
- int operation) {
+static void
+FLOCK (int fd, int operation)
+{
int ret;
ret = -1;
- while (ret == -1) {
- ret = flock(fd,
- operation);
- if (ret == -1) {
- if (errno != EINTR) {
- GE_LOG_STRERROR(NULL,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "flock");
- return;
- }
+ while (ret == -1)
+ {
+ ret = flock (fd, operation);
+ if (ret == -1)
+ {
+ if (errno != EINTR)
+ {
+ GE_LOG_STRERROR (NULL,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
+ "flock");
+ return;
+ }
+ }
}
- }
- fsync(fd);
+ fsync (fd);
}
-static int LSEEK(int fd,
- off_t pos,
- int mode) {
+static int
+LSEEK (int fd, off_t pos, int mode)
+{
int ret;
- ret = lseek(fd,
- pos,
- mode);
+ ret = lseek (fd, pos, mode);
if (ret == -1)
- GE_LOG_STRERROR(NULL,
- GE_ERROR | GE_USER | GE_ADMIN | GE_BULK,
- "lseek");
+ GE_LOG_STRERROR (NULL, GE_ERROR | GE_USER | GE_ADMIN | GE_BULK, "lseek");
return ret;
}
#endif
struct IPC_SEMAPHORE *
-IPC_SEMAPHORE_CREATE(struct GE_Context * ectx,
- const char * basename,
- const unsigned int initialValue) {
+IPC_SEMAPHORE_CREATE (struct GE_Context *ectx,
+ const char *basename, const unsigned int initialValue)
+{
/* Could older FreeBSD use this too since this code can shorten the IPC name
*/
#if SOLARIS || OSX || FREEBSD5
- char * noslashBasename;
+ char *noslashBasename;
int i;
- struct IPC_SEMAPHORE * ret;
+ struct IPC_SEMAPHORE *ret;
- ret = MALLOC(sizeof(struct IPC_SEMAPHORE));
+ ret = MALLOC (sizeof (struct IPC_SEMAPHORE));
ret->ectx = ectx;
- noslashBasename = string_expandFileName(ectx, basename);
- for (i=strlen(noslashBasename);i>0;i--)
+ noslashBasename = string_expandFileName (ectx, basename);
+ for (i = strlen (noslashBasename); i > 0; i--)
if (noslashBasename[i] == '/')
noslashBasename[i] = '.'; /* first character MUST be /, but Solaris
- forbids it afterwards */
+ forbids it afterwards */
noslashBasename[0] = '/';
- ret->internal = sem_open(noslashBasename,
- O_CREAT,
- S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP, /* 660 */
- initialValue);
- while ( (ret->internal == (void *) SEM_FAILED)
- && (errno == ENAMETOOLONG) ) {
- char * halfBasename;
+ ret->internal = sem_open (noslashBasename, O_CREAT, S_IRUSR | S_IWUSR |
S_IRGRP | S_IWGRP, /* 660 */
+ initialValue);
+ while ((ret->internal == (void *) SEM_FAILED) && (errno == ENAMETOOLONG))
+ {
+ char *halfBasename;
- if (strlen(noslashBasename) < 4)
- break; /* definitely OS error... */
- /* FIXME: this might cause unintended mapping to same names */
- halfBasename = noslashBasename+strlen(noslashBasename)/2; /* cut in half */
- halfBasename[0] = '/';
- ret->internal = sem_open(halfBasename,
- O_CREAT,
- S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP, /* 660 */
- initialValue);
- }
+ if (strlen (noslashBasename) < 4)
+ break; /* definitely OS error... */
+ /* FIXME: this might cause unintended mapping to same names */
+ halfBasename = noslashBasename + strlen (noslashBasename) / 2; /* cut
in half */
+ halfBasename[0] = '/';
+ ret->internal = sem_open (halfBasename, O_CREAT, S_IRUSR | S_IWUSR |
S_IRGRP | S_IWGRP, /* 660 */
+ initialValue);
+ }
if (ret->internal == (void *) SEM_FAILED)
- GE_DIE_STRERROR_FILE(ectx,
- GE_FATAL | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
- "sem_open",
- noslashBasename);
- FREE(noslashBasename);
+ GE_DIE_STRERROR_FILE (ectx,
+ GE_FATAL | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
+ "sem_open", noslashBasename);
+ FREE (noslashBasename);
return ret;
#elif WINDOWS
- char * noslashBasename;
+ char *noslashBasename;
int i;
- struct IPC_SEMAPHORE * ret;
+ struct IPC_SEMAPHORE *ret;
SECURITY_ATTRIBUTES sec;
DWORD dwErr;
- ret = MALLOC(sizeof(struct IPC_SEMAPHORE));
+ ret = MALLOC (sizeof (struct IPC_SEMAPHORE));
ret->ectx = ectx;
- noslashBasename = string_expandFileName(ectx, basename);
- for (i=strlen(noslashBasename);i>0;i--)
+ noslashBasename = string_expandFileName (ectx, basename);
+ for (i = strlen (noslashBasename); i > 0; i--)
if (noslashBasename[i] == '\\')
noslashBasename[i] = '.'; /* must not contain backslashes */
- sec.nLength = sizeof(SECURITY_ATTRIBUTES);
+ sec.nLength = sizeof (SECURITY_ATTRIBUTES);
sec.bInheritHandle = TRUE;
sec.lpSecurityDescriptor = NULL;
- ret->internal = CreateSemaphore(&sec, initialValue, LONG_MAX,
noslashBasename);
- dwErr = GetLastError();
- if (! ret->internal && dwErr == ERROR_ALREADY_EXISTS) {
- ret->internal = OpenSemaphore(SEMAPHORE_MODIFY_STATE, TRUE,
noslashBasename);
- dwErr = GetLastError();
- }
- if (! ret->internal) {
- GE_LOG(ectx,
- GE_FATAL | GE_USER | GE_DEVELOPER | GE_BULK,
- _("Can't create semaphore: %i"),
- dwErr);
- GE_DIE_STRERROR_FILE(ectx,
- GE_FATAL | GE_USER | GE_DEVELOPER | GE_BULK,
- "OpenSemaphore", noslashBasename);
- }
- FREE(noslashBasename);
+ ret->internal =
+ CreateSemaphore (&sec, initialValue, LONG_MAX, noslashBasename);
+ dwErr = GetLastError ();
+ if (!ret->internal && dwErr == ERROR_ALREADY_EXISTS)
+ {
+ ret->internal =
+ OpenSemaphore (SEMAPHORE_MODIFY_STATE, TRUE, noslashBasename);
+ dwErr = GetLastError ();
+ }
+ if (!ret->internal)
+ {
+ GE_LOG (ectx,
+ GE_FATAL | GE_USER | GE_DEVELOPER | GE_BULK,
+ _("Can't create semaphore: %i"), dwErr);
+ GE_DIE_STRERROR_FILE (ectx,
+ GE_FATAL | GE_USER | GE_DEVELOPER | GE_BULK,
+ "OpenSemaphore", noslashBasename);
+ }
+ FREE (noslashBasename);
return ret;
#elif LINUX
- union semun {
- int val;
- struct semid_ds *buf;
- ushort *array;
+ union semun
+ {
+ int val;
+ struct semid_ds *buf;
+ ushort *array;
} semctl_arg;
- struct IPC_SEMAPHORE * ret;
+ struct IPC_SEMAPHORE *ret;
key_t key;
- FILE * fp;
+ FILE *fp;
int pcount;
- char * ebasename;
+ char *ebasename;
- ret = MALLOC(sizeof(struct IPC_SEMAPHORE));
+ ret = MALLOC (sizeof (struct IPC_SEMAPHORE));
ret->ectx = ectx;
- ebasename = string_expandFileName(ectx, basename);
- disk_directory_create_for_file(ectx,
- ebasename);
- fp = FOPEN(ebasename, "a+");
- if (NULL == fp) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- "fopen",
- ebasename);
- FREE(ret);
- FREE(ebasename);
- return NULL;
- }
- fclose(fp);
+ ebasename = string_expandFileName (ectx, basename);
+ disk_directory_create_for_file (ectx, ebasename);
+ fp = FOPEN (ebasename, "a+");
+ if (NULL == fp)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_BULK, "fopen", ebasename);
+ FREE (ret);
+ FREE (ebasename);
+ return NULL;
+ }
+ fclose (fp);
- key = ftok(ebasename,'g');
+ key = ftok (ebasename, 'g');
again:
- ret->internal = semget(key,
- 3,
- IPC_CREAT|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP);
+ ret->internal = semget (key,
+ 3,
+ IPC_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
if (ret->internal == -1)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_USER | GE_IMMEDIATE,
- "semget");
- if (semop(ret->internal, &op_lock[0], 2) < 0) {
- if (errno == EINVAL)
- goto again;
- else
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_USER | GE_IMMEDIATE,
- "semop");
- }
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_USER | GE_IMMEDIATE, "semget");
+ if (semop (ret->internal, &op_lock[0], 2) < 0)
+ {
+ if (errno == EINVAL)
+ goto again;
+ else
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_USER | GE_IMMEDIATE, "semop");
+ }
/* get process count */
- if ( (pcount = semctl(ret->internal,
- 1,
- GETVAL,
- 0)) < 0)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_USER | GE_IMMEDIATE,
- "semctl");
- if (pcount==0) {
- semctl_arg.val = initialValue;
- if (semctl(ret->internal,
- 0,
- SETVAL,
- semctl_arg) < 0)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_USER | GE_IMMEDIATE,
- "semtcl");
- semctl_arg.val = PROCCOUNT;
- if (semctl(ret->internal,
- 1,
- SETVAL,
- semctl_arg) < 0)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_USER | GE_IMMEDIATE,
- "semtcl");
- }
+ if ((pcount = semctl (ret->internal, 1, GETVAL, 0)) < 0)
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_USER | GE_IMMEDIATE, "semctl");
+ if (pcount == 0)
+ {
+ semctl_arg.val = initialValue;
+ if (semctl (ret->internal, 0, SETVAL, semctl_arg) < 0)
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_USER | GE_IMMEDIATE, "semtcl");
+ semctl_arg.val = PROCCOUNT;
+ if (semctl (ret->internal, 1, SETVAL, semctl_arg) < 0)
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_USER | GE_IMMEDIATE, "semtcl");
+ }
- if (semop(ret->internal,
- &op_endcreate[0],
- 2) < 0)
- GE_DIE_STRERROR(ectx,
- GE_FATAL | GE_USER | GE_IMMEDIATE,
- "semop");
+ if (semop (ret->internal, &op_endcreate[0], 2) < 0)
+ GE_DIE_STRERROR (ectx, GE_FATAL | GE_USER | GE_IMMEDIATE, "semop");
ret->filename = ebasename;
return ret;
#elif SOMEBSD
int fd;
int cnt;
- struct IPC_SEMAPHORE * ret;
+ struct IPC_SEMAPHORE *ret;
- ret = MALLOC(sizeof(struct IPC_SEMAPHORE));
+ ret = MALLOC (sizeof (struct IPC_SEMAPHORE));
ret->ectx = ectx;
- MUTEX_CREATE(&ret->internalLock);
- ret->filename = STRDUP(basename);
+ MUTEX_CREATE (&ret->internalLock);
+ ret->filename = STRDUP (basename);
fd = -1;
- while (fd == -1) {
- fd = disk_file_open(ectx,
- basename,
- O_CREAT|O_RDWR|O_EXCL,
- S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP /* 660 */);
- if ( (fd == -1) &&
- (errno == EEXIST) ) {
- /* try without creation */
- fd = disk_file_open(ectx,
- basename,
- O_RDWR,
- S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP /* 660 */);
- /* possibly the file was deleted in the meantime,
- then try again with O_CREAT! */
- if ( (fd == -1) &&
- (errno != ENOENT) )
- break;
+ while (fd == -1)
+ {
+ fd = disk_file_open (ectx,
+ basename,
+ O_CREAT | O_RDWR | O_EXCL,
+ S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP /* 660 */ );
+ if ((fd == -1) && (errno == EEXIST))
+ {
+ /* try without creation */
+ fd = disk_file_open (ectx, basename, O_RDWR, S_IRUSR | S_IWUSR |
S_IRGRP | S_IWGRP /* 660 */
+ );
+ /* possibly the file was deleted in the meantime,
+ then try again with O_CREAT! */
+ if ((fd == -1) && (errno != ENOENT))
+ break;
+ }
}
- }
- if (fd == -1) {
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- "open",
- ret->filename);
- MUTEX_DESTROY(&ret->internalLock);
- FREE(ret->filename);
- FREE(ret);
- return NULL;
- }
- FLOCK(fd, LOCK_EX);
- if (sizeof(int) != READ(fd,
- &cnt,
- sizeof(int))) {
- cnt = htonl(initialValue);
- LSEEK(fd,
- 0,
- SEEK_SET);
- if (sizeof(int) != WRITE(fd,
- &cnt,
- sizeof(int)))
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- "write",
- basename);
- }
- LSEEK(fd,
- sizeof(int),
- SEEK_SET);
- if (sizeof(int) != READ(fd,
- &cnt,
- sizeof(int)))
- cnt = htonl(1);
+ if (fd == -1)
+ {
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ "open", ret->filename);
+ MUTEX_DESTROY (&ret->internalLock);
+ FREE (ret->filename);
+ FREE (ret);
+ return NULL;
+ }
+ FLOCK (fd, LOCK_EX);
+ if (sizeof (int) != READ (fd, &cnt, sizeof (int)))
+ {
+ cnt = htonl (initialValue);
+ LSEEK (fd, 0, SEEK_SET);
+ if (sizeof (int) != WRITE (fd, &cnt, sizeof (int)))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ "write", basename);
+ }
+ LSEEK (fd, sizeof (int), SEEK_SET);
+ if (sizeof (int) != READ (fd, &cnt, sizeof (int)))
+ cnt = htonl (1);
else
- cnt = htonl(ntohl(cnt)+1);
- LSEEK(fd, sizeof(int), SEEK_SET);
- if (sizeof(int) != WRITE(fd,
- &cnt,
- sizeof(int)))
- GE_LOG_STRERROR_FILE(ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "write",
- basename);
- FLOCK(fd, LOCK_UN);
+ cnt = htonl (ntohl (cnt) + 1);
+ LSEEK (fd, sizeof (int), SEEK_SET);
+ if (sizeof (int) != WRITE (fd, &cnt, sizeof (int)))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_WARNING | GE_USER | GE_BULK, "write", basename);
+ FLOCK (fd, LOCK_UN);
ret->fd = fd;
ret->initialValue = initialValue;
return ret;
#else
- #ifndef _MSC_VER
- #warning Port IPC.
- return NULL;
- #else
- return NULL;
- #endif
+#ifndef _MSC_VER
+#warning Port IPC.
+ return NULL;
+#else
+ return NULL;
#endif
+#endif
}
-void IPC_SEMAPHORE_UP(struct IPC_SEMAPHORE * sem) {
- if (sem == NULL) /* error on creation, optimistic execution; good luck */
+void
+IPC_SEMAPHORE_UP (struct IPC_SEMAPHORE *sem)
+{
+ if (sem == NULL) /* error on creation, optimistic execution;
good luck */
return;
#if SOLARIS || OSX || FREEBSD5
- if (0 != sem_post(sem->internal))
- GE_LOG_STRERROR(sem->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "sem_post");
+ if (0 != sem_post (sem->internal))
+ GE_LOG_STRERROR (sem->ectx, GE_WARNING | GE_USER | GE_BULK, "sem_post");
#elif WINDOWS
- if (!ReleaseSemaphore(sem->internal, 1, NULL))
- GE_LOG(sem->ectx, GE_WARNING | GE_USER | GE_BULK,
- "ReleaseSemaphore signaled error: %i\n",
- GetLastError());
+ if (!ReleaseSemaphore (sem->internal, 1, NULL))
+ GE_LOG (sem->ectx, GE_WARNING | GE_USER | GE_BULK,
+ "ReleaseSemaphore signaled error: %i\n", GetLastError ());
#elif LINUX
{
- struct sembuf sops = {0,1,SEM_UNDO};
+ struct sembuf sops = { 0, 1, SEM_UNDO };
- if (0 != semop(sem->internal,&sops,1))
- GE_LOG_STRERROR(sem->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "semop");
+ if (0 != semop (sem->internal, &sops, 1))
+ GE_LOG_STRERROR (sem->ectx, GE_WARNING | GE_USER | GE_BULK, "semop");
}
#elif SOMEBSD
{
int cnt;
- MUTEX_LOCK(&sem->internalLock);
- FLOCK(sem->fd,
- LOCK_EX);
- LSEEK(sem->fd,
- 0,
- SEEK_SET);
- if (sizeof(int) != READ(sem->fd,
- &cnt,
- sizeof(int))) {
- GE_LOG_STRERROR_FILE(sem->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "read",
- sem->filename);
- FLOCK(sem->fd,
- LOCK_UN);
- MUTEX_UNLOCK(&sem->internalLock);
- return;
- }
- cnt = htonl(ntohl(cnt)+1);
- LSEEK(sem->fd,
- 0,
- SEEK_SET);
- if (sizeof(int) != WRITE(sem->fd,
- &cnt,
- sizeof(int)))
- GE_LOG_STRERROR_FILE(sem->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "write",
- sem->filename);
- FLOCK(sem->fd,
- LOCK_UN);
- MUTEX_UNLOCK(&sem->internalLock);
+ MUTEX_LOCK (&sem->internalLock);
+ FLOCK (sem->fd, LOCK_EX);
+ LSEEK (sem->fd, 0, SEEK_SET);
+ if (sizeof (int) != READ (sem->fd, &cnt, sizeof (int)))
+ {
+ GE_LOG_STRERROR_FILE (sem->ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ "read", sem->filename);
+ FLOCK (sem->fd, LOCK_UN);
+ MUTEX_UNLOCK (&sem->internalLock);
+ return;
+ }
+ cnt = htonl (ntohl (cnt) + 1);
+ LSEEK (sem->fd, 0, SEEK_SET);
+ if (sizeof (int) != WRITE (sem->fd, &cnt, sizeof (int)))
+ GE_LOG_STRERROR_FILE (sem->ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ "write", sem->filename);
+ FLOCK (sem->fd, LOCK_UN);
+ MUTEX_UNLOCK (&sem->internalLock);
}
#endif
}
/* FIXME: add support for mayBlock! */
-int IPC_SEMAPHORE_DOWN(struct IPC_SEMAPHORE * sem,
- int mayBlock) {
- if (sem == NULL) /* error on creation, optimistic execution; good luck */
+int
+IPC_SEMAPHORE_DOWN (struct IPC_SEMAPHORE *sem, int mayBlock)
+{
+ if (sem == NULL) /* error on creation, optimistic execution;
good luck */
return OK;
#if OSX || SOLARIS || FREEBSD5
- while (0 != sem_wait(sem->internal)) {
- if ( (errno == EINTR) ||
- (errno == EAGAIN) )
- continue;
- GE_DIE_STRERROR(sem->ectx,
- GE_FATAL | GE_USER | GE_IMMEDIATE,
- "sem_wait");
- }
+ while (0 != sem_wait (sem->internal))
+ {
+ if ((errno == EINTR) || (errno == EAGAIN))
+ continue;
+ GE_DIE_STRERROR (sem->ectx,
+ GE_FATAL | GE_USER | GE_IMMEDIATE, "sem_wait");
+ }
return OK;
#elif WINDOWS
- if (WaitForSingleObject(sem->internal,
- INFINITE) == WAIT_FAILED)
- GE_LOG_STRERROR(sem->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "WaitForSingleObject");
+ if (WaitForSingleObject (sem->internal, INFINITE) == WAIT_FAILED)
+ GE_LOG_STRERROR (sem->ectx,
+ GE_WARNING | GE_USER | GE_BULK, "WaitForSingleObject");
return OK;
#elif LINUX
{
- struct sembuf sops = {0,-1,SEM_UNDO};
+ struct sembuf sops = { 0, -1, SEM_UNDO };
- while (0 != semop(sem->internal,
- &sops,
- 1)) {
- if ( (errno == EINTR) ||
- (errno == EAGAIN) )
- continue;
- GE_DIE_STRERROR(sem->ectx,
- GE_FATAL | GE_USER | GE_IMMEDIATE,
- "semop");
- }
+ while (0 != semop (sem->internal, &sops, 1))
+ {
+ if ((errno == EINTR) || (errno == EAGAIN))
+ continue;
+ GE_DIE_STRERROR (sem->ectx,
+ GE_FATAL | GE_USER | GE_IMMEDIATE, "semop");
+ }
return OK;
}
#elif SOMEBSD
{
int cnt;
- MUTEX_LOCK(&sem->internalLock);
- FLOCK(sem->fd,
- LOCK_EX);
- cnt = ntohl(0);
- while (htonl(cnt) == 0) {
- LSEEK(sem->fd,
- 0,
- SEEK_SET);
- if (sizeof(int) != READ(sem->fd,
- &cnt,
- sizeof(int))) {
- GE_LOG_STRERROR_FILE(sem->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "read",
- sem->filename);
- FLOCK(sem->fd,
- LOCK_UN);
- MUTEX_UNLOCK(&sem->internalLock);
- return SYSERR;
+ MUTEX_LOCK (&sem->internalLock);
+ FLOCK (sem->fd, LOCK_EX);
+ cnt = ntohl (0);
+ while (htonl (cnt) == 0)
+ {
+ LSEEK (sem->fd, 0, SEEK_SET);
+ if (sizeof (int) != READ (sem->fd, &cnt, sizeof (int)))
+ {
+ GE_LOG_STRERROR_FILE (sem->ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ "read", sem->filename);
+ FLOCK (sem->fd, LOCK_UN);
+ MUTEX_UNLOCK (&sem->internalLock);
+ return SYSERR;
+ }
+ if (htonl (cnt) == 0)
+ {
+ /* busy wait! */
+ FLOCK (sem->fd, LOCK_UN);
+ PTHREAD_SLEEP (50 * cronMILLIS);
+ FLOCK (sem->fd, LOCK_EX);
+ }
}
- if (htonl(cnt) == 0) {
- /* busy wait! */
- FLOCK(sem->fd,
- LOCK_UN);
- PTHREAD_SLEEP(50 * cronMILLIS);
- FLOCK(sem->fd,
- LOCK_EX);
- }
- }
- cnt = htonl(ntohl(cnt)-1);
- LSEEK(sem->fd, 0, SEEK_SET);
- if (sizeof(int) != WRITE(sem->fd,
- &cnt,
- sizeof(int)))
- GE_LOG_STRERROR_FILE(sem->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "write",
- sem->filename);
- FLOCK(sem->fd,
- LOCK_UN);
- MUTEX_UNLOCK(&sem->internalLock);
+ cnt = htonl (ntohl (cnt) - 1);
+ LSEEK (sem->fd, 0, SEEK_SET);
+ if (sizeof (int) != WRITE (sem->fd, &cnt, sizeof (int)))
+ GE_LOG_STRERROR_FILE (sem->ectx,
+ GE_WARNING | GE_USER | GE_BULK,
+ "write", sem->filename);
+ FLOCK (sem->fd, LOCK_UN);
+ MUTEX_UNLOCK (&sem->internalLock);
}
return OK;
#else
@@ -548,82 +478,72 @@
#endif
}
-void IPC_SEMAPHORE_DESTROY(struct IPC_SEMAPHORE * sem) {
- if (sem == NULL) /* error on creation, optimistic execution; good luck */
+void
+IPC_SEMAPHORE_DESTROY (struct IPC_SEMAPHORE *sem)
+{
+ if (sem == NULL) /* error on creation, optimistic execution;
good luck */
return;
#if SOLARIS || OSX || FREEBSD5
- if (0 != sem_close(sem->internal))
- GE_LOG_STRERROR(sem->ectx,
- GE_USER | GE_WARNING | GE_BULK,
- "sem_close");
+ if (0 != sem_close (sem->internal))
+ GE_LOG_STRERROR (sem->ectx, GE_USER | GE_WARNING | GE_BULK, "sem_close");
#elif WINDOWS
- if (!CloseHandle(sem->internal))
- GE_LOG(sem->ectx,
- GE_USER | GE_WARNING | GE_BULK,
- "CloseHandle signaled error: %i\n",
- GetLastError());
+ if (!CloseHandle (sem->internal))
+ GE_LOG (sem->ectx,
+ GE_USER | GE_WARNING | GE_BULK,
+ "CloseHandle signaled error: %i\n", GetLastError ());
#elif LINUX
{
int pcount;
- if (semop(sem->internal, &op_close[0], 3) < 0)
- GE_LOG_STRERROR(sem->ectx,
- GE_USER | GE_WARNING | GE_BULK,
- "semop");
- if ( (pcount = semctl(sem->internal, 1, GETVAL, 0)) < 0)
- GE_LOG_STRERROR(sem->ectx,
- GE_USER | GE_WARNING | GE_BULK,
- "semctl");
- if (pcount > PROCCOUNT) {
- GE_BREAK(sem->ectx, 0);
- } else if (pcount == PROCCOUNT) {
- if (0 != semctl(sem->internal,
- 0,
- IPC_RMID,
- 0))
- GE_LOG_STRERROR(sem->ectx,
- GE_USER | GE_WARNING | GE_BULK,
- "semctl");
- UNLINK(sem->filename);
- } else {
- if (semop(sem->internal,
- &op_unlock[0],
- 1) < 0)
- GE_LOG_STRERROR(sem->ectx,
- GE_USER | GE_WARNING | GE_BULK,
- "semop");
- }
- FREE(sem->filename);
+ if (semop (sem->internal, &op_close[0], 3) < 0)
+ GE_LOG_STRERROR (sem->ectx, GE_USER | GE_WARNING | GE_BULK, "semop");
+ if ((pcount = semctl (sem->internal, 1, GETVAL, 0)) < 0)
+ GE_LOG_STRERROR (sem->ectx, GE_USER | GE_WARNING | GE_BULK, "semctl");
+ if (pcount > PROCCOUNT)
+ {
+ GE_BREAK (sem->ectx, 0);
+ }
+ else if (pcount == PROCCOUNT)
+ {
+ if (0 != semctl (sem->internal, 0, IPC_RMID, 0))
+ GE_LOG_STRERROR (sem->ectx,
+ GE_USER | GE_WARNING | GE_BULK, "semctl");
+ UNLINK (sem->filename);
+ }
+ else
+ {
+ if (semop (sem->internal, &op_unlock[0], 1) < 0)
+ GE_LOG_STRERROR (sem->ectx,
+ GE_USER | GE_WARNING | GE_BULK, "semop");
+ }
+ FREE (sem->filename);
}
#elif SOMEBSD
{
int cnt;
- MUTEX_DESTROY(&sem->internalLock);
- FLOCK(sem->fd, LOCK_EX);
- LSEEK(sem->fd, sizeof(int), SEEK_SET);
- if (sizeof(int) == READ(sem->fd, &cnt, sizeof(int))) {
- cnt = htonl(ntohl(cnt)-1);
- LSEEK(sem->fd, sizeof(int), SEEK_SET);
- if (sizeof(int) != WRITE(sem->fd, &cnt, sizeof(int)))
- GE_LOG_STRERROR(sem->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "write");
- if (ntohl(cnt) == 0)
- UNLINK(sem->filename);
- } else
- GE_LOG_STRERROR(sem->ectx,
- GE_WARNING | GE_USER | GE_BULK,
- "read");
- FLOCK(sem->fd, LOCK_UN);
- disk_file_close(sem->ectx,
- sem->filename,
- sem->fd);
- FREE(sem->filename);
+ MUTEX_DESTROY (&sem->internalLock);
+ FLOCK (sem->fd, LOCK_EX);
+ LSEEK (sem->fd, sizeof (int), SEEK_SET);
+ if (sizeof (int) == READ (sem->fd, &cnt, sizeof (int)))
+ {
+ cnt = htonl (ntohl (cnt) - 1);
+ LSEEK (sem->fd, sizeof (int), SEEK_SET);
+ if (sizeof (int) != WRITE (sem->fd, &cnt, sizeof (int)))
+ GE_LOG_STRERROR (sem->ectx,
+ GE_WARNING | GE_USER | GE_BULK, "write");
+ if (ntohl (cnt) == 0)
+ UNLINK (sem->filename);
+ }
+ else
+ GE_LOG_STRERROR (sem->ectx, GE_WARNING | GE_USER | GE_BULK, "read");
+ FLOCK (sem->fd, LOCK_UN);
+ disk_file_close (sem->ectx, sem->filename, sem->fd);
+ FREE (sem->filename);
}
#else
#endif
- FREE(sem);
+ FREE (sem);
}
Modified: GNUnet/src/util/os/semaphoretest.c
===================================================================
--- GNUnet/src/util/os/semaphoretest.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/semaphoretest.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -28,122 +28,132 @@
#include <sys/types.h>
-static struct IPC_SEMAPHORE * ipc;
+static struct IPC_SEMAPHORE *ipc;
-static struct GE_Context * ectx;
+static struct GE_Context *ectx;
-static int testIPCSemaphore() {
+static int
+testIPCSemaphore ()
+{
pid_t me;
int cnt;
int i;
int j;
- FILE * fd;
+ FILE *fd;
int ret;
int si;
int sw;
ret = 0;
- REMOVE("/tmp/gnunet_ipc_xchange");
- REMOVE("/tmp/gnunet_ipc_semtest");
- me = fork();
+ REMOVE ("/tmp/gnunet_ipc_xchange");
+ REMOVE ("/tmp/gnunet_ipc_semtest");
+ me = fork ();
sw = me;
- ipc = IPC_SEMAPHORE_CREATE(ectx,
- "/tmp/gnunet_ipc_semtest",
- 0);
- for (cnt=0;cnt<3;cnt++) {
- if (sw == 0) {
- for (i=0;i<6;i++) {
- IPC_SEMAPHORE_DOWN(ipc,
- YES);
- fd = FOPEN("/tmp/gnunet_ipc_xchange",
- "a+");
- if (fd == NULL) {
- printf("Could not open testfile for reading: %s\n",
- STRERROR(errno));
- ret = 1;
- goto END;
- }
- fseek(fd, 4*i, SEEK_SET);
- si = GN_FREAD(&j, 4, 1, fd);
- if (si != 1) {
- printf("Could not read from testfile: %d - %s at %s:%d\n",
- si,
- STRERROR(errno),
- __FILE__,
- __LINE__);
- ret = 1;
- goto END;
- }
- fclose(fd);
- if (j != i+cnt) {
- printf("IPC test failed at cnt=%d i=%d j=%d %s:%u\n",
- cnt, i, j, __FILE__, __LINE__);
- ret = 1;
- goto END;
- } else
- fprintf(stderr, ".");
- }
- REMOVE("/tmp/gnunet_ipc_xchange");
- sw = 1;
- } else {
- for (i=0;i<6;i++) {
- PTHREAD_SLEEP(50 + i*50);
- fd = FOPEN("/tmp/gnunet_ipc_xchange",
- "a+");
- if (fd == NULL) {
- printf("Could not open testfile for writing: %s\n",
- STRERROR(errno));
- ret = 1;
- goto END;
- }
- fseek(fd, 4*i, SEEK_SET);
- j=cnt+i;
- if (1 != GN_FWRITE(&j, 4, 1, fd)) {
- printf("Could not write to testfile: %s\n",
- STRERROR(errno));
- ret = 1;
- goto END;
- }
- fclose(fd);
- IPC_SEMAPHORE_UP(ipc);
- }
- fprintf(stderr, ".");
- sleep(1); /* give reader ample time to finish */
- sw = 0;
+ ipc = IPC_SEMAPHORE_CREATE (ectx, "/tmp/gnunet_ipc_semtest", 0);
+ for (cnt = 0; cnt < 3; cnt++)
+ {
+ if (sw == 0)
+ {
+ for (i = 0; i < 6; i++)
+ {
+ IPC_SEMAPHORE_DOWN (ipc, YES);
+ fd = FOPEN ("/tmp/gnunet_ipc_xchange", "a+");
+ if (fd == NULL)
+ {
+ printf ("Could not open testfile for reading: %s\n",
+ STRERROR (errno));
+ ret = 1;
+ goto END;
+ }
+ fseek (fd, 4 * i, SEEK_SET);
+ si = GN_FREAD (&j, 4, 1, fd);
+ if (si != 1)
+ {
+ printf ("Could not read from testfile: %d - %s at %s:%d\n",
+ si, STRERROR (errno), __FILE__, __LINE__);
+ ret = 1;
+ goto END;
+ }
+ fclose (fd);
+ if (j != i + cnt)
+ {
+ printf ("IPC test failed at cnt=%d i=%d j=%d %s:%u\n",
+ cnt, i, j, __FILE__, __LINE__);
+ ret = 1;
+ goto END;
+ }
+ else
+ fprintf (stderr, ".");
+ }
+ REMOVE ("/tmp/gnunet_ipc_xchange");
+ sw = 1;
+ }
+ else
+ {
+ for (i = 0; i < 6; i++)
+ {
+ PTHREAD_SLEEP (50 + i * 50);
+ fd = FOPEN ("/tmp/gnunet_ipc_xchange", "a+");
+ if (fd == NULL)
+ {
+ printf ("Could not open testfile for writing: %s\n",
+ STRERROR (errno));
+ ret = 1;
+ goto END;
+ }
+ fseek (fd, 4 * i, SEEK_SET);
+ j = cnt + i;
+ if (1 != GN_FWRITE (&j, 4, 1, fd))
+ {
+ printf ("Could not write to testfile: %s\n",
+ STRERROR (errno));
+ ret = 1;
+ goto END;
+ }
+ fclose (fd);
+ IPC_SEMAPHORE_UP (ipc);
+ }
+ fprintf (stderr, ".");
+ sleep (1); /* give reader ample time to finish */
+ sw = 0;
+ }
}
- }
- END:
- IPC_SEMAPHORE_DESTROY(ipc);
- REMOVE("/tmp/gnunet_ipc_xchange");
- if (me == 0) {
- exit(ret);
- } else {
- GE_LOG(ectx,
- GE_DEBUG | GE_REQUEST | GE_USER,
- "waiting for other process to exit.\n");
- if (-1 == waitpid(me, &j, 0))
- GE_LOG(ectx,
- GE_ERROR | GE_BULK | GE_USER,
- "waitpid failed: %s\n",
- STRERROR(errno));
- if ((! WIFEXITED(j)) || WEXITSTATUS(j) == 1)
- ret = 1; /* error in child */
- }
+END:
+ IPC_SEMAPHORE_DESTROY (ipc);
+ REMOVE ("/tmp/gnunet_ipc_xchange");
+ if (me == 0)
+ {
+ exit (ret);
+ }
+ else
+ {
+ GE_LOG (ectx,
+ GE_DEBUG | GE_REQUEST | GE_USER,
+ "waiting for other process to exit.\n");
+ if (-1 == waitpid (me, &j, 0))
+ GE_LOG (ectx,
+ GE_ERROR | GE_BULK | GE_USER,
+ "waitpid failed: %s\n", STRERROR (errno));
+ if ((!WIFEXITED (j)) || WEXITSTATUS (j) == 1)
+ ret = 1; /* error in child */
+ }
return ret;
}
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
int ret = 0;
- ectx = GE_create_context_stderr(NO,
- GE_WARNING | GE_ERROR | GE_FATAL |
- GE_USER | GE_ADMIN | GE_DEVELOPER |
- GE_IMMEDIATE | GE_BULK);
- GE_setDefaultContext(ectx);
- os_init(ectx);
- ret += testIPCSemaphore();
- fprintf(stderr, "\n");
- GE_free_context(ectx);
+ ectx = GE_create_context_stderr (NO,
+ GE_WARNING | GE_ERROR | GE_FATAL |
+ GE_USER | GE_ADMIN | GE_DEVELOPER |
+ GE_IMMEDIATE | GE_BULK);
+ GE_setDefaultContext (ectx);
+ os_init (ectx);
+ ret += testIPCSemaphore ();
+ fprintf (stderr, "\n");
+ GE_free_context (ectx);
return ret;
}
Modified: GNUnet/src/util/os/statuscalls.c
===================================================================
--- GNUnet/src/util/os/statuscalls.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/statuscalls.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -64,16 +64,18 @@
*/
#define PROC_NET_DEV "/proc/net/dev"
-typedef struct {
+typedef struct
+{
- char * name;
+ char *name;
unsigned long long last_in;
unsigned long long last_out;
} NetworkStats;
-typedef struct {
+typedef struct
+{
unsigned long long overload;
unsigned long long lastSum;
@@ -95,7 +97,8 @@
} DirectionInfo;
-typedef struct LoadMonitor {
+typedef struct LoadMonitor
+{
/**
* Traffic counter for only gnunetd traffic.
@@ -105,7 +108,7 @@
/**
* tracking
*/
- NetworkStats * ifcs;
+ NetworkStats *ifcs;
/**
* how many interfaces do we have?
@@ -119,17 +122,17 @@
int useBasicMethod;
#ifdef LINUX
- FILE * proc_net_dev;
+ FILE *proc_net_dev;
#endif
/**
* Lock.
*/
- struct MUTEX * statusMutex;
+ struct MUTEX *statusMutex;
- struct GE_Context * ectx;
+ struct GE_Context *ectx;
- struct GC_Configuration * cfg;
+ struct GC_Configuration *cfg;
DirectionInfo upload_info;
@@ -139,70 +142,77 @@
} LoadMonitor;
-void os_network_monitor_notify_transmission(struct LoadMonitor * monitor,
- NetworkDirection dir,
- unsigned long long delta) {
- MUTEX_LOCK(monitor->statusMutex);
+void
+os_network_monitor_notify_transmission (struct LoadMonitor *monitor,
+ NetworkDirection dir,
+ unsigned long long delta)
+{
+ MUTEX_LOCK (monitor->statusMutex);
if (dir == Download)
monitor->globalTrafficBetweenProc.last_in += delta;
else
monitor->globalTrafficBetweenProc.last_out += delta;
- MUTEX_UNLOCK(monitor->statusMutex);
+ MUTEX_UNLOCK (monitor->statusMutex);
}
#define MAX_PROC_LINE 5000
-static void updateInterfaceTraffic(struct LoadMonitor * monitor) {
+static void
+updateInterfaceTraffic (struct LoadMonitor *monitor)
+{
#ifdef LINUX
unsigned long long rxnew;
unsigned long long txnew;
int i;
char line[MAX_PROC_LINE];
- NetworkStats * ifc;
- char * data;
+ NetworkStats *ifc;
+ char *data;
- if (monitor->proc_net_dev != NULL) {
- rewind(monitor->proc_net_dev);
- fflush(monitor->proc_net_dev);
- /* Parse the line matching the interface ('eth0') */
- while (! feof(monitor->proc_net_dev) ) {
- if (NULL == fgets(line,
- MAX_PROC_LINE,
- monitor->proc_net_dev))
- break;
- for (i=0;i<monitor->ifcsSize;i++) {
- ifc = &monitor->ifcs[i];
- if (NULL != strstr(line, ifc->name) ) {
- data = strchr(line, ':');
- if (data == NULL)
- continue;
- data++;
- if (2 != SSCANF(data,
- "%llu %*s %*s %*s %*s %*s %*s %*s %llu",
- &rxnew,
- &txnew)) {
- GE_LOG(monitor->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- _("Failed to parse interface data from `%s'.\n"),
- PROC_NET_DEV);
- continue;
+ if (monitor->proc_net_dev != NULL)
+ {
+ rewind (monitor->proc_net_dev);
+ fflush (monitor->proc_net_dev);
+ /* Parse the line matching the interface ('eth0') */
+ while (!feof (monitor->proc_net_dev))
+ {
+ if (NULL == fgets (line, MAX_PROC_LINE, monitor->proc_net_dev))
+ break;
+ for (i = 0; i < monitor->ifcsSize; i++)
+ {
+ ifc = &monitor->ifcs[i];
+ if (NULL != strstr (line, ifc->name))
+ {
+ data = strchr (line, ':');
+ if (data == NULL)
+ continue;
+ data++;
+ if (2 != SSCANF (data,
+ "%llu %*s %*s %*s %*s %*s %*s %*s %llu",
+ &rxnew, &txnew))
+ {
+ GE_LOG (monitor->ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK,
+ _
+ ("Failed to parse interface data from `%s'.\n"),
+ PROC_NET_DEV);
+ continue;
+ }
+ ifc->last_in = rxnew;
+ ifc->last_out = txnew;
+ monitor->globalTrafficBetweenProc.last_in = 0;
+ monitor->globalTrafficBetweenProc.last_out = 0;
+ break;
+ }
+ }
+ }
}
- ifc->last_in = rxnew;
- ifc->last_out = txnew;
- monitor->globalTrafficBetweenProc.last_in = 0;
- monitor->globalTrafficBetweenProc.last_out = 0;
- break;
- }
- }
- }
- }
#elif OSX
int name[6];
size_t len;
int rows;
int j;
int i;
- NetworkStats * ifc;
+ NetworkStats *ifc;
name[0] = CTL_NET;
name[1] = PF_LINK;
@@ -210,124 +220,128 @@
name[3] = IFMIB_SYSTEM;
name[4] = IFMIB_IFCOUNT;
- len = sizeof(rows);
+ len = sizeof (rows);
- if (sysctl(name, 5, &rows, &len, (void *)0, 0) == 0) {
- for (j=1;j<=rows;j++) {
- struct ifmibdata ifmd;
+ if (sysctl (name, 5, &rows, &len, (void *) 0, 0) == 0)
+ {
+ for (j = 1; j <= rows; j++)
+ {
+ struct ifmibdata ifmd;
- name[0] = CTL_NET;
- name[1] = PF_LINK;
- name[2] = NETLINK_GENERIC;
- name[3] = IFMIB_IFDATA;
- name[4] = j;
- name[5] = IFDATA_GENERAL;
+ name[0] = CTL_NET;
+ name[1] = PF_LINK;
+ name[2] = NETLINK_GENERIC;
+ name[3] = IFMIB_IFDATA;
+ name[4] = j;
+ name[5] = IFDATA_GENERAL;
- len = sizeof(ifmd);
- if (sysctl(name, 6, &ifmd, &len, (void*)0, 0) != 0) {
- if (errno == ENOENT)
- continue;
- else {
- GE_LOG_STRERROR(monitor->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "sysctl");
- break;
+ len = sizeof (ifmd);
+ if (sysctl (name, 6, &ifmd, &len, (void *) 0, 0) != 0)
+ {
+ if (errno == ENOENT)
+ continue;
+ else
+ {
+ GE_LOG_STRERROR (monitor->ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK, "sysctl");
+ break;
+ }
+ }
+ for (i = 0; i < monitor->ifcsSize; i++)
+ {
+ ifc = &monitor->ifcs[i];
+ if (strcmp (ifc->name, ifmd.ifmd_name) == 0)
+ {
+ ifc->last_in = ifmd.ifmd_data.ifi_ibytes;
+ ifc->last_out = ifmd.ifmd_data.ifi_obytes;
+ monitor->globalTrafficBetweenProc.last_in = 0;
+ monitor->globalTrafficBetweenProc.last_out = 0;
+ break;
+ }
+ }
}
- }
- for (i=0;i<monitor->ifcsSize;i++) {
- ifc = &monitor->ifcs[i];
- if (strcmp(ifc->name, ifmd.ifmd_name) == 0) {
- ifc->last_in = ifmd.ifmd_data.ifi_ibytes;
- ifc->last_out = ifmd.ifmd_data.ifi_obytes;
- monitor->globalTrafficBetweenProc.last_in = 0;
- monitor->globalTrafficBetweenProc.last_out = 0;
- break;
- }
- }
}
- }
- else {
- GE_LOG_STRERROR(monitor->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "sysctl");
- }
+ else
+ {
+ GE_LOG_STRERROR (monitor->ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK, "sysctl");
+ }
#elif MINGW
- NetworkStats * ifc;
+ NetworkStats *ifc;
PMIB_IFTABLE pTable;
DWORD dwIfIdx;
unsigned long long l;
BYTE bPhysAddr[MAXLEN_PHYSADDR];
int iLine = 0;
- FILE * command;
+ FILE *command;
unsigned long long rxnew;
unsigned long long txnew;
int i;
char line[MAX_PROC_LINE];
/* Win 98 and NT SP 4 */
- if (GNGetIfEntry) {
- EnumNICs(&pTable, NULL);
- for (i=0;i<monitor->ifcsSize;i++) {
- ifc = &monitor->ifcs[i];
- for (dwIfIdx=0; dwIfIdx < pTable->dwNumEntries; dwIfIdx++) {
- l = _atoi64(ifc->name);
- memset(bPhysAddr,
- 0,
- MAXLEN_PHYSADDR);
- memcpy(bPhysAddr,
- pTable->table[dwIfIdx].bPhysAddr,
- pTable->table[dwIfIdx].dwPhysAddrLen);
- if (0 == memcmp(bPhysAddr,
- &l,
- sizeof(unsigned long long))) {
- ifc->last_in
- = pTable->table[dwIfIdx].dwInOctets;
- ifc->last_out
- = pTable->table[dwIfIdx].dwOutOctets;
- monitor->globalTrafficBetweenProc.last_in = 0;
- monitor->globalTrafficBetweenProc.last_out = 0;
- break;
+ if (GNGetIfEntry)
+ {
+ EnumNICs (&pTable, NULL);
+ for (i = 0; i < monitor->ifcsSize; i++)
+ {
+ ifc = &monitor->ifcs[i];
+ for (dwIfIdx = 0; dwIfIdx < pTable->dwNumEntries; dwIfIdx++)
+ {
+ l = _atoi64 (ifc->name);
+ memset (bPhysAddr, 0, MAXLEN_PHYSADDR);
+ memcpy (bPhysAddr,
+ pTable->table[dwIfIdx].bPhysAddr,
+ pTable->table[dwIfIdx].dwPhysAddrLen);
+ if (0 == memcmp (bPhysAddr, &l, sizeof (unsigned long long)))
+ {
+ ifc->last_in = pTable->table[dwIfIdx].dwInOctets;
+ ifc->last_out = pTable->table[dwIfIdx].dwOutOctets;
+ monitor->globalTrafficBetweenProc.last_in = 0;
+ monitor->globalTrafficBetweenProc.last_out = 0;
+ break;
+ }
+ }
}
- }
+ GlobalFree (pTable);
}
- GlobalFree(pTable);
- } else { /* Win 95 */
- if ( ( command = popen("netstat -e", "rt") ) == NULL ) {
- GE_LOG_STRERROR_FILE(monitor->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- "popen",
- "netstat -e");
- return;
+ else
+ { /* Win 95 */
+ if ((command = popen ("netstat -e", "rt")) == NULL)
+ {
+ GE_LOG_STRERROR_FILE (monitor->ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK,
+ "popen", "netstat -e");
+ return;
+ }
+ ifc = &monitor->ifcs[0];
+ while (!feof (command))
+ {
+ if (NULL == fgets (line, MAX_PROC_LINE, command))
+ break;
+ /* PORT-ME: any way to do this per-ifc? */
+ if (iLine == 1)
+ {
+ if (2 == sscanf ("%*s%i%i", &rxnew, &txnew))
+ {
+ ifc->last_in = rxnew;
+ ifc->last_out = txnew;
+ monitor->globalTrafficBetweenProc.last_in = 0;
+ monitor->globalTrafficBetweenProc.last_out = 0;
+ break;
+ }
+ else
+ {
+ GE_LOG (monitor->ectx,
+ GE_ERROR | GE_ADMIN | GE_BULK,
+ _("Failed to parse interface data from `%s'.\n"),
+ PROC_NET_DEV);
+ }
+ }
+ iLine++;
+ }
+ pclose (command);
}
- ifc = &monitor->ifcs[0];
- while (!feof(command)) {
- if (NULL == fgets(line,
- MAX_PROC_LINE,
- command))
- break;
- /* PORT-ME: any way to do this per-ifc? */
- if (iLine == 1) {
- if (2 == sscanf("%*s%i%i",
- &rxnew,
- &txnew)) {
- ifc->last_in
- = rxnew;
- ifc->last_out
- = txnew;
- monitor->globalTrafficBetweenProc.last_in = 0;
- monitor->globalTrafficBetweenProc.last_out = 0;
- break;
- } else {
- GE_LOG(monitor->ectx,
- GE_ERROR | GE_ADMIN | GE_BULK,
- _("Failed to parse interface data from `%s'.\n"),
- PROC_NET_DEV);
- }
- }
- iLine++;
- }
- pclose(command);
- }
#else
/* PORT-ME! */
#endif
@@ -336,97 +350,94 @@
/**
* Re-read the configuration for statuscalls.
*/
-static int resetStatusCalls(void * cls,
- struct GC_Configuration * cfg,
- struct GE_Context * ectx,
- const char * sect,
- const char * op) {
- struct LoadMonitor * monitor = cls;
- char * interfaces;
+static int
+resetStatusCalls (void *cls,
+ struct GC_Configuration *cfg,
+ struct GE_Context *ectx, const char *sect, const char *op)
+{
+ struct LoadMonitor *monitor = cls;
+ char *interfaces;
int i;
int numInterfaces;
int basic;
- if (0 != strcmp(sect,
- "LOAD"))
- return 0; /* fast path */
- basic = GC_get_configuration_value_yesno(cfg,
- "LOAD",
- "BASICLIMITING",
- YES);
+ if (0 != strcmp (sect, "LOAD"))
+ return 0; /* fast path */
+ basic = GC_get_configuration_value_yesno (cfg,
+ "LOAD", "BASICLIMITING", YES);
if (basic == SYSERR)
return SYSERR;
- if (-1 == GC_get_configuration_value_string(cfg,
- "LOAD",
- "INTERFACES",
- "eth0",
- &interfaces))
+ if (-1 == GC_get_configuration_value_string (cfg,
+ "LOAD",
+ "INTERFACES",
+ "eth0", &interfaces))
return SYSERR;
- if (interfaces == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- _("No network interfaces defined in configuration section `%s' under
`%s'!\n"),
- "LOAD",
- "INTERFACES");
- return SYSERR;
- }
- if (strlen(interfaces) == 0) {
- FREE(interfaces);
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_BULK,
- _("No network interfaces defined in configuration section `%s' under
`%s'!\n"),
- "LOAD",
- "INTERFACES");
- return SYSERR;
- }
- MUTEX_LOCK(monitor->statusMutex);
- for (i=0;i<monitor->ifcsSize;i++)
- FREE(monitor->ifcs[i].name);
+ if (interfaces == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ _
+ ("No network interfaces defined in configuration section `%s'
under `%s'!\n"),
+ "LOAD", "INTERFACES");
+ return SYSERR;
+ }
+ if (strlen (interfaces) == 0)
+ {
+ FREE (interfaces);
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_BULK,
+ _
+ ("No network interfaces defined in configuration section `%s'
under `%s'!\n"),
+ "LOAD", "INTERFACES");
+ return SYSERR;
+ }
+ MUTEX_LOCK (monitor->statusMutex);
+ for (i = 0; i < monitor->ifcsSize; i++)
+ FREE (monitor->ifcs[i].name);
numInterfaces = 1;
- for (i=strlen(interfaces)-1;i>=0;i--)
+ for (i = strlen (interfaces) - 1; i >= 0; i--)
if (interfaces[i] == ',')
numInterfaces++;
- GROW(monitor->ifcs,
- monitor->ifcsSize,
- numInterfaces);
- for (i=strlen(interfaces)-1;i>=0;i--) {
- if (interfaces[i] == ',') {
- monitor->ifcs[--numInterfaces].name = STRDUP(&interfaces[i+1]);
- numInterfaces++;
- interfaces[i] = '\0';
+ GROW (monitor->ifcs, monitor->ifcsSize, numInterfaces);
+ for (i = strlen (interfaces) - 1; i >= 0; i--)
+ {
+ if (interfaces[i] == ',')
+ {
+ monitor->ifcs[--numInterfaces].name = STRDUP (&interfaces[i + 1]);
+ numInterfaces++;
+ interfaces[i] = '\0';
+ }
}
- }
- monitor->ifcs[--numInterfaces].name = STRDUP(interfaces);
- GE_ASSERT(ectx, numInterfaces == 0);
- for (i=0;i<monitor->ifcsSize;i++) {
- monitor->ifcs[i].last_in = 0;
- monitor->ifcs[i].last_out = 0;
- }
+ monitor->ifcs[--numInterfaces].name = STRDUP (interfaces);
+ GE_ASSERT (ectx, numInterfaces == 0);
+ for (i = 0; i < monitor->ifcsSize; i++)
+ {
+ monitor->ifcs[i].last_in = 0;
+ monitor->ifcs[i].last_out = 0;
+ }
monitor->upload_info.have_last = NO;
monitor->upload_info.lastCall = 0;
monitor->upload_info.overload = 0;
monitor->download_info.have_last = NO;
monitor->download_info.lastCall = 0;
monitor->download_info.overload = 0;
- FREE(interfaces);
+ FREE (interfaces);
monitor->useBasicMethod = basic;
- GC_get_configuration_value_number(cfg,
- "LOAD",
- "MAXNETDOWNBPSTOTAL",
- 0,
- (unsigned long long)-1,
- 50000,
- &monitor->download_info.max);
- GC_get_configuration_value_number(cfg,
- "LOAD",
- "MAXNETUPBPSTOTAL",
- 0,
- (unsigned long long)-1,
- 50000,
- &monitor->upload_info.max);
- monitor->last_ifc_update = get_time();
- updateInterfaceTraffic(monitor);
- MUTEX_UNLOCK(monitor->statusMutex);
+ GC_get_configuration_value_number (cfg,
+ "LOAD",
+ "MAXNETDOWNBPSTOTAL",
+ 0,
+ (unsigned long long) -1,
+ 50000, &monitor->download_info.max);
+ GC_get_configuration_value_number (cfg,
+ "LOAD",
+ "MAXNETUPBPSTOTAL",
+ 0,
+ (unsigned long long) -1,
+ 50000, &monitor->upload_info.max);
+ monitor->last_ifc_update = get_time ();
+ updateInterfaceTraffic (monitor);
+ MUTEX_UNLOCK (monitor->statusMutex);
return 0;
}
@@ -436,8 +447,10 @@
*
* @return the maximum bandwidth in bytes per second, -1 for no limit
*/
-unsigned long long os_network_monitor_get_limit(struct LoadMonitor * monitor,
- NetworkDirection dir) {
+unsigned long long
+os_network_monitor_get_limit (struct LoadMonitor *monitor,
+ NetworkDirection dir)
+{
if (monitor == NULL)
return -1;
if (dir == Upload)
@@ -454,9 +467,11 @@
* @return the network load as a percentage of allowed
* (100 is equivalent to full load)
*/
-int os_network_monitor_get_load(struct LoadMonitor * monitor,
- NetworkDirection dir) {
- DirectionInfo * di;
+int
+os_network_monitor_get_load (struct LoadMonitor *monitor,
+ NetworkDirection dir)
+{
+ DirectionInfo *di;
cron_t now;
unsigned long long maxExpect;
unsigned long long currentLoadSum;
@@ -466,57 +481,67 @@
int weight;
if (monitor == NULL)
- return 0; /* no limits */
+ return 0; /* no limits */
if (dir == Upload)
di = &monitor->upload_info;
else
di = &monitor->download_info;
- MUTEX_LOCK(monitor->statusMutex);
- now = get_time();
- if ( (monitor->useBasicMethod == NO) &&
- (now - monitor->last_ifc_update > 10 * cronSECONDS) ) {
- monitor->last_ifc_update = now;
- updateInterfaceTraffic(monitor);
- }
- if (dir == Upload) {
- currentTotal = monitor->globalTrafficBetweenProc.last_out;
- for (i=0;i<monitor->ifcsSize;i++)
- currentTotal += monitor->ifcs[i].last_out;
- } else {
- currentTotal = monitor->globalTrafficBetweenProc.last_in;
- for (i=0;i<monitor->ifcsSize;i++)
- currentTotal += monitor->ifcs[i].last_in;
- }
- if ( (di->lastSum > currentTotal) ||
- (di->have_last == NO) ||
- (now < di->lastCall) ) {
- /* integer overflow or first datapoint; since we cannot tell where
- / by how much the overflow happened, all we can do is ignore
- this datapoint. So we return -1 -- AND reset lastSum / lastCall. */
- di->lastSum = currentTotal;
- di->lastCall = now;
- di->have_last = YES;
- MUTEX_UNLOCK(monitor->statusMutex);
- return -1;
- }
- if (di->max == 0) {
- MUTEX_UNLOCK(monitor->statusMutex);
- return -1;
- }
+ MUTEX_LOCK (monitor->statusMutex);
+ now = get_time ();
+ if ((monitor->useBasicMethod == NO) &&
+ (now - monitor->last_ifc_update > 10 * cronSECONDS))
+ {
+ monitor->last_ifc_update = now;
+ updateInterfaceTraffic (monitor);
+ }
+ if (dir == Upload)
+ {
+ currentTotal = monitor->globalTrafficBetweenProc.last_out;
+ for (i = 0; i < monitor->ifcsSize; i++)
+ currentTotal += monitor->ifcs[i].last_out;
+ }
+ else
+ {
+ currentTotal = monitor->globalTrafficBetweenProc.last_in;
+ for (i = 0; i < monitor->ifcsSize; i++)
+ currentTotal += monitor->ifcs[i].last_in;
+ }
+ if ((di->lastSum > currentTotal) ||
+ (di->have_last == NO) || (now < di->lastCall))
+ {
+ /* integer overflow or first datapoint; since we cannot tell where
+ / by how much the overflow happened, all we can do is ignore
+ this datapoint. So we return -1 -- AND reset lastSum / lastCall. */
+ di->lastSum = currentTotal;
+ di->lastCall = now;
+ di->have_last = YES;
+ MUTEX_UNLOCK (monitor->statusMutex);
+ return -1;
+ }
+ if (di->max == 0)
+ {
+ MUTEX_UNLOCK (monitor->statusMutex);
+ return -1;
+ }
maxExpect = (now - di->lastCall) * di->max / cronSECONDS;
- if (now - di->lastCall < INCREMENTAL_INTERVAL) {
- /* return weighted average between last return value and
- load in the last interval */
- weight = (now - di->lastCall) * 100 / INCREMENTAL_INTERVAL; /* how close
are we to lastCall? */
- if (maxExpect == 0)
- ret = di->lastValue;
- else
- ret = di->lastValue * (100-weight) / 100 + weight * (currentTotal -
di->lastSum + di->overload) / maxExpect;
- MUTEX_UNLOCK(monitor->statusMutex);
- return ret;
- }
+ if (now - di->lastCall < INCREMENTAL_INTERVAL)
+ {
+ /* return weighted average between last return value and
+ load in the last interval */
+ weight = (now - di->lastCall) * 100 / INCREMENTAL_INTERVAL; /* how
close are we to lastCall? */
+ if (maxExpect == 0)
+ ret = di->lastValue;
+ else
+ ret =
+ di->lastValue * (100 - weight) / 100 + weight * (currentTotal -
+ di->lastSum +
+ di->overload) /
+ maxExpect;
+ MUTEX_UNLOCK (monitor->statusMutex);
+ return ret;
+ }
currentLoadSum = currentTotal - di->lastSum + di->overload;
di->lastSum = currentTotal;
@@ -527,56 +552,51 @@
di->overload = currentLoadSum - maxExpect;
ret = currentLoadSum * 100 / maxExpect;
di->lastValue = ret;
- MUTEX_UNLOCK(monitor->statusMutex);
+ MUTEX_UNLOCK (monitor->statusMutex);
return ret;
}
struct LoadMonitor *
-os_network_monitor_create(struct GE_Context * ectx,
- struct GC_Configuration * cfg) {
- struct LoadMonitor * monitor;
+os_network_monitor_create (struct GE_Context *ectx,
+ struct GC_Configuration *cfg)
+{
+ struct LoadMonitor *monitor;
- monitor = MALLOC(sizeof(struct LoadMonitor));
- memset(monitor,
- 0,
- sizeof(struct LoadMonitor));
+ monitor = MALLOC (sizeof (struct LoadMonitor));
+ memset (monitor, 0, sizeof (struct LoadMonitor));
monitor->ectx = ectx;
monitor->cfg = cfg;
#ifdef LINUX
- monitor->proc_net_dev = fopen(PROC_NET_DEV, "r");
+ monitor->proc_net_dev = fopen (PROC_NET_DEV, "r");
if (NULL == monitor->proc_net_dev)
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
- "fopen",
- PROC_NET_DEV);
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_ADMIN | GE_USER | GE_BULK,
+ "fopen", PROC_NET_DEV);
#endif
- monitor->statusMutex = MUTEX_CREATE(NO);
- if (-1 == GC_attach_change_listener(cfg,
- &resetStatusCalls,
- monitor)) {
- os_network_monitor_destroy(monitor);
- return NULL;
- }
+ monitor->statusMutex = MUTEX_CREATE (NO);
+ if (-1 == GC_attach_change_listener (cfg, &resetStatusCalls, monitor))
+ {
+ os_network_monitor_destroy (monitor);
+ return NULL;
+ }
return monitor;
}
-void os_network_monitor_destroy(struct LoadMonitor * monitor) {
+void
+os_network_monitor_destroy (struct LoadMonitor *monitor)
+{
int i;
- GC_detach_change_listener(monitor->cfg,
- &resetStatusCalls,
- monitor);
+ GC_detach_change_listener (monitor->cfg, &resetStatusCalls, monitor);
#ifdef LINUX
if (monitor->proc_net_dev != NULL)
- fclose(monitor->proc_net_dev);
+ fclose (monitor->proc_net_dev);
#endif
- for (i=0;i<monitor->ifcsSize;i++)
- FREE(monitor->ifcs[i].name);
- GROW(monitor->ifcs,
- monitor->ifcsSize,
- 0);
- MUTEX_DESTROY(monitor->statusMutex);
- FREE(monitor);
+ for (i = 0; i < monitor->ifcsSize; i++)
+ FREE (monitor->ifcs[i].name);
+ GROW (monitor->ifcs, monitor->ifcsSize, 0);
+ MUTEX_DESTROY (monitor->statusMutex);
+ FREE (monitor);
}
/* end of statuscalls.c */
Modified: GNUnet/src/util/os/statuscallstest.c
===================================================================
--- GNUnet/src/util/os/statuscallstest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/os/statuscallstest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -27,41 +27,42 @@
#include "gnunet_util_error_loggers.h"
#include "platform.h"
-int main(int argc, char * argv[]){
+int
+main (int argc, char *argv[])
+{
int ret;
cron_t start;
- struct GE_Context * ectx;
- struct GC_Configuration * cfg;
+ struct GE_Context *ectx;
+ struct GC_Configuration *cfg;
- ectx = GE_create_context_stderr(NO,
- GE_WARNING | GE_ERROR | GE_FATAL |
- GE_USER | GE_ADMIN | GE_DEVELOPER |
- GE_IMMEDIATE | GE_BULK);
- GE_setDefaultContext(ectx);
- cfg = GC_create_C_impl();
- GE_ASSERT(ectx, cfg != NULL);
- os_init(ectx);
+ ectx = GE_create_context_stderr (NO,
+ GE_WARNING | GE_ERROR | GE_FATAL |
+ GE_USER | GE_ADMIN | GE_DEVELOPER |
+ GE_IMMEDIATE | GE_BULK);
+ GE_setDefaultContext (ectx);
+ cfg = GC_create_C_impl ();
+ GE_ASSERT (ectx, cfg != NULL);
+ os_init (ectx);
/* need to run each phase for more than 10s since
statuscalls only refreshes that often... */
- start = get_time();
- while (start + 12 * cronSECONDS > get_time())
- PTHREAD_SLEEP(1);
- start = get_time();
- ret = os_cpu_get_load(ectx,
- cfg);
- while (start + 60 * cronSECONDS > get_time())
- sqrt(245.2523); /* do some processing to drive load up */
- if (ret > os_cpu_get_load(ectx,
- cfg)) {
- printf("busy loop decreased CPU load: %d < %d.\n",
- ret,
- os_cpu_get_load(ectx,
- cfg));
- ret = 1;
- } else {
- ret = 0;
- }
- GC_free(cfg);
- GE_free_context(ectx);
+ start = get_time ();
+ while (start + 12 * cronSECONDS > get_time ())
+ PTHREAD_SLEEP (1);
+ start = get_time ();
+ ret = os_cpu_get_load (ectx, cfg);
+ while (start + 60 * cronSECONDS > get_time ())
+ sqrt (245.2523); /* do some processing to drive load up */
+ if (ret > os_cpu_get_load (ectx, cfg))
+ {
+ printf ("busy loop decreased CPU load: %d < %d.\n",
+ ret, os_cpu_get_load (ectx, cfg));
+ ret = 1;
+ }
+ else
+ {
+ ret = 0;
+ }
+ GC_free (cfg);
+ GE_free_context (ectx);
return ret;
}
Modified: GNUnet/src/util/os/time.c
===================================================================
--- GNUnet/src/util/os/time.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/time.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -31,10 +31,12 @@
/**
* TIME prototype. "man time".
*/
-TIME_T TIME(TIME_T * t) {
+TIME_T
+TIME (TIME_T * t)
+{
TIME_T now;
- now = (TIME_T) time(NULL); /* potential 64-bit to 32-bit conversion!*/
+ now = (TIME_T) time (NULL); /* potential 64-bit to 32-bit conversion! */
if (t != NULL)
*t = now;
return now;
@@ -45,16 +47,18 @@
* GNUnet time value to a 64-bit value of the current
* epoc if needed.
*/
-char * GN_CTIME(const TIME_T * t) {
+char *
+GN_CTIME (const TIME_T * t)
+{
TIME_T now;
time_t tnow;
- tnow = time(NULL);
+ tnow = time (NULL);
now = (TIME_T) tnow;
tnow = tnow - now + *t;
#ifdef ctime_r
- return ctime_r(&tnow, MALLOC(32));
+ return ctime_r (&tnow, MALLOC (32));
#else
- return STRDUP(ctime(&tnow));
+ return STRDUP (ctime (&tnow));
#endif
}
Modified: GNUnet/src/util/os/user.c
===================================================================
--- GNUnet/src/util/os/user.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/os/user.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -28,81 +28,85 @@
#include "gnunet_util_string.h"
#include "platform.h"
-int os_modify_user(int testCapability,
- int doAdd,
- const char *group_name,
- const char *user_name) {
+int
+os_modify_user (int testCapability,
+ int doAdd, const char *group_name, const char *user_name)
+{
int haveGroup;
- if (testCapability) {
- /* TODO: actually check that group/user
- exists/does not yet exist */
+ if (testCapability)
+ {
+ /* TODO: actually check that group/user
+ exists/does not yet exist */
#ifdef WINDOWS
- return IsWinNT() ? OK : SYSERR;
+ return IsWinNT ()? OK : SYSERR;
#endif
#ifdef LINUX
- if (geteuid() != 0)
+ if (geteuid () != 0)
+ return SYSERR;
+ if (doAdd == YES)
+ {
+ if (((ACCESS ("/usr/sbin/adduser", X_OK) == 0) ||
+ (ACCESS ("/usr/sbin/useradd", X_OK) == 0)) &&
+ ((ACCESS ("/usr/sbin/addgroup", X_OK) == 0) ||
+ (ACCESS ("/usr/sbin/groupadd", X_OK) == 0)))
+ return OK;
+ return SYSERR;
+ }
+ else if (doAdd == NO)
+ {
+ if ((ACCESS ("/usr/sbin/deluser", X_OK) == 0) ||
+ (ACCESS ("/usr/sbin/userdel", X_OK) == 0))
+ return OK;
+ return SYSERR;
+ }
+ else if (doAdd == SYSERR)
+ {
+ if (((ACCESS ("/usr/sbin/dleuser", X_OK) == 0) ||
+ (ACCESS ("/usr/sbin/userdel", X_OK) == 0)) &&
+ ((ACCESS ("/usr/sbin/delgroup", X_OK) == 0) ||
+ (ACCESS ("/usr/sbin/groupdel", X_OK) == 0)))
+ return OK;
+ return SYSERR;
+ }
+#endif
return SYSERR;
- if (doAdd == YES) {
- if ( ( (ACCESS("/usr/sbin/adduser", X_OK) == 0) ||
- (ACCESS("/usr/sbin/useradd", X_OK) == 0) ) &&
- ( (ACCESS("/usr/sbin/addgroup", X_OK) == 0) ||
- (ACCESS("/usr/sbin/groupadd", X_OK) == 0) ) )
- return OK;
- return SYSERR;
- } else if (doAdd == NO) {
- if ( (ACCESS("/usr/sbin/deluser", X_OK) == 0) ||
- (ACCESS("/usr/sbin/userdel", X_OK) == 0) )
- return OK;
- return SYSERR;
- } else if (doAdd == SYSERR) {
- if ( ( (ACCESS("/usr/sbin/dleuser", X_OK) == 0) ||
- (ACCESS("/usr/sbin/userdel", X_OK) == 0) ) &&
- ( (ACCESS("/usr/sbin/delgroup", X_OK) == 0) ||
- (ACCESS("/usr/sbin/groupdel", X_OK) == 0) ) )
- return OK;
- return SYSERR;
}
-#endif
- return SYSERR;
- }
- if ( (user_name == NULL) ||
- (0 == strlen(user_name)) )
+ if ((user_name == NULL) || (0 == strlen (user_name)))
return 0;
#ifdef WINDOWS
- if (IsWinNT())
- return CreateServiceAccount(user_name,
- "GNUnet service account");
+ if (IsWinNT ())
+ return CreateServiceAccount (user_name, "GNUnet service account");
#elif OSX
- return SYSERR; /* TODO */
+ return SYSERR; /* TODO */
#else
- if (ACCESS("/usr/sbin/adduser",
- X_OK) == 0) {
- /* Debian */
- /* TODO: FreeBSD?
http://www.freebsd.org/cgi/man.cgi?query=adduser&sektion=8 */
- char * cmd;
+ if (ACCESS ("/usr/sbin/adduser", X_OK) == 0)
+ {
+ /* Debian */
+ /* TODO: FreeBSD?
http://www.freebsd.org/cgi/man.cgi?query=adduser&sektion=8 */
+ char *cmd;
- haveGroup = group_name && strlen(group_name) > 0;
- cmd = MALLOC(256 + (haveGroup ? strlen(group_name) : 0) +
strlen(user_name));
+ haveGroup = group_name && strlen (group_name) > 0;
+ cmd =
+ MALLOC (256 + (haveGroup ? strlen (group_name) : 0) +
+ strlen (user_name));
- if (haveGroup) {
- sprintf(cmd,
- "/usr/sbin/addgroup --quiet --system %s",
- group_name);
- system(cmd);
+ if (haveGroup)
+ {
+ sprintf (cmd, "/usr/sbin/addgroup --quiet --system %s", group_name);
+ system (cmd);
+ }
+
+ sprintf (cmd,
+ "/usr/sbin/adduser --quiet --system %s %s "
+ "--no-create-home %s",
+ haveGroup ? "--ingroup" : "",
+ haveGroup ? group_name : "", user_name);
+ system (cmd);
+ FREE (cmd);
+ return OK;
}
-
- sprintf(cmd,
- "/usr/sbin/adduser --quiet --system %s %s "
- "--no-create-home %s",
- haveGroup ? "--ingroup" : "",
- haveGroup ? group_name : "",
- user_name);
- system(cmd);
- FREE(cmd);
- return OK;
- }
/* TODO: useradd */
else
return SYSERR;
@@ -115,37 +119,38 @@
/**
* @brief Change user ID
*/
-int os_change_user(struct GE_Context * ectx,
- const char * user) {
+int
+os_change_user (struct GE_Context *ectx, const char *user)
+{
#ifndef MINGW
- struct passwd * pws;
+ struct passwd *pws;
errno = 0;
- pws = getpwnam(user);
- if (pws == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- _("Cannot obtain information about user `%s': %s\n"),
- user,
- errno == 0 ? _("No such user") : STRERROR(errno));
- return SYSERR;
- }
- if ( (0 != setgid(pws->pw_gid)) ||
- (0 != setegid(pws->pw_gid)) ||
+ pws = getpwnam (user);
+ if (pws == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ _("Cannot obtain information about user `%s': %s\n"),
+ user, errno == 0 ? _("No such user") : STRERROR (errno));
+ return SYSERR;
+ }
+ if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
#if HAVE_INITGROUPS
- (0 != initgroups(user, pws->pw_gid)) ||
+ (0 != initgroups (user, pws->pw_gid)) ||
#endif
- (0 != setuid(pws->pw_uid)) || (0 != seteuid(pws->pw_uid))) {
- if ( (0 != setregid(pws->pw_gid, pws->pw_gid)) ||
- (0 != setreuid(pws->pw_uid, pws->pw_uid)) ) {
- GE_LOG(ectx,
- GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- _("Cannot change user/group to `%s': %s\n"),
- user,
- STRERROR(errno));
- return SYSERR;
+ (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
+ {
+ if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
+ (0 != setreuid (pws->pw_uid, pws->pw_uid)))
+ {
+ GE_LOG (ectx,
+ GE_FATAL | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ _("Cannot change user/group to `%s': %s\n"),
+ user, STRERROR (errno));
+ return SYSERR;
+ }
}
- }
#endif
return OK;
@@ -156,30 +161,26 @@
/**
* @brief Change owner of a file
*/
-int os_change_owner(struct GE_Context * ectx,
- const char * filename,
- const char * user) {
+int
+os_change_owner (struct GE_Context *ectx,
+ const char *filename, const char *user)
+{
#ifndef MINGW
- struct passwd * pws;
+ struct passwd *pws;
- pws = getpwnam(user);
- if (pws == NULL) {
- GE_LOG(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- _("Cannot obtain information about user `%s': %s\n"),
- user,
- STRERROR(errno));
- return SYSERR;
- }
- if (0 != chown(filename,
- pws->pw_uid,
- pws->pw_gid))
- GE_LOG_STRERROR_FILE(ectx,
- GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
- "chown",
- filename);
+ pws = getpwnam (user);
+ if (pws == NULL)
+ {
+ GE_LOG (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ _("Cannot obtain information about user `%s': %s\n"),
+ user, STRERROR (errno));
+ return SYSERR;
+ }
+ if (0 != chown (filename, pws->pw_uid, pws->pw_gid))
+ GE_LOG_STRERROR_FILE (ectx,
+ GE_ERROR | GE_USER | GE_ADMIN | GE_IMMEDIATE,
+ "chown", filename);
#endif
return OK;
}
-
-
Modified: GNUnet/src/util/string/string.c
===================================================================
--- GNUnet/src/util/string/string.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/string/string.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -32,20 +32,16 @@
#endif
-int SNPRINTF(char * buf,
- size_t size,
- const char * format,
- ...) {
+int
+SNPRINTF (char *buf, size_t size, const char *format, ...)
+{
int ret;
va_list args;
- va_start(args, format);
- ret = VSNPRINTF(buf,
- size,
- format,
- args);
- va_end(args);
- GE_ASSERT(NULL, ret <= size);
+ va_start (args, format);
+ ret = VSNPRINTF (buf, size, format, args);
+ va_end (args);
+ GE_ASSERT (NULL, ret <= size);
return ret;
}
@@ -61,21 +57,22 @@
* of course, the buffer size is zero). It does not pad
* out the result like strncpy() does.
*/
-size_t strlcpy(char * dest,
- const char * src,
- size_t size) {
+size_t
+strlcpy (char *dest, const char *src, size_t size)
+{
size_t ret;
- GE_ASSERT(NULL, dest != NULL);
- GE_ASSERT(NULL, size > 0);
- GE_ASSERT(NULL, src != NULL);
- ret = strlen(src);
+ GE_ASSERT (NULL, dest != NULL);
+ GE_ASSERT (NULL, size > 0);
+ GE_ASSERT (NULL, src != NULL);
+ ret = strlen (src);
- if (size) {
- size_t len = (ret >= size) ? size-1 : ret;
- memcpy(dest, src, len);
- dest[len] = '\0';
- }
+ if (size)
+ {
+ size_t len = (ret >= size) ? size - 1 : ret;
+ memcpy (dest, src, len);
+ dest[len] = '\0';
+ }
return ret;
}
#endif
@@ -88,26 +85,26 @@
* @param src The string to append to it
* @param count The size of the destination buffer.
*/
-size_t strlcat(char * dest,
- const char * src,
- size_t count) {
+size_t
+strlcat (char *dest, const char *src, size_t count)
+{
size_t dsize;
size_t len;
size_t res;
- GE_ASSERT(NULL, dest != NULL);
- GE_ASSERT(NULL, src != NULL);
- GE_ASSERT(NULL, count > 0);
- dsize = strlen(dest);
- len = strlen(src);
+ GE_ASSERT (NULL, dest != NULL);
+ GE_ASSERT (NULL, src != NULL);
+ GE_ASSERT (NULL, count > 0);
+ dsize = strlen (dest);
+ len = strlen (src);
res = dsize + len;
- GE_ASSERT(NULL, dsize < count);
+ GE_ASSERT (NULL, dsize < count);
dest += dsize;
count -= dsize;
if (len >= count)
- len = count-1;
- memcpy(dest, src, len);
+ len = count - 1;
+ memcpy (dest, src, len);
dest[len] = 0;
return res;
}
@@ -117,64 +114,68 @@
* Give relative time in human-readable fancy format.
* @param delta time in milli seconds
*/
-char * string_get_fancy_time_interval(unsigned long long delta) {
- const char * unit = _(/* time unit */ "ms");
- char * ret;
+char *
+string_get_fancy_time_interval (unsigned long long delta)
+{
+ const char *unit = _( /* time unit */ "ms");
+ char *ret;
- if (delta > 5 * 1000) {
- delta = delta / 1000;
- unit = _(/* time unit */ "s");
- if (delta > 5 * 60) {
- delta = delta / 60;
- unit = _(/* time unit */ "m");
- if (delta > 5 * 60) {
- delta = delta / 60;
- unit = _(/* time unit */ "h");
- if (delta > 5 * 24) {
- delta = delta / 24;
- unit = _(/* time unit */ " days");
- }
- }
+ if (delta > 5 * 1000)
+ {
+ delta = delta / 1000;
+ unit = _( /* time unit */ "s");
+ if (delta > 5 * 60)
+ {
+ delta = delta / 60;
+ unit = _( /* time unit */ "m");
+ if (delta > 5 * 60)
+ {
+ delta = delta / 60;
+ unit = _( /* time unit */ "h");
+ if (delta > 5 * 24)
+ {
+ delta = delta / 24;
+ unit = _( /* time unit */ " days");
+ }
+ }
+ }
}
- }
- ret = MALLOC(32);
- SNPRINTF(ret,
- 32,
- "%llu%s",
- delta,
- unit);
+ ret = MALLOC (32);
+ SNPRINTF (ret, 32, "%llu%s", delta, unit);
return ret;
}
/**
* Convert a given filesize into a fancy human-readable format.
*/
-char * string_get_fancy_byte_size(unsigned long long size) {
-const char * unit = _(/* size unit */ "b");
- char * ret;
+char *
+string_get_fancy_byte_size (unsigned long long size)
+{
+ const char *unit = _( /* size unit */ "b");
+ char *ret;
- if (size > 5 * 1024) {
- size = size / 1024;
- unit = _(/* size unit */ "KiB");
- if (size > 5 * 1024) {
+ if (size > 5 * 1024)
+ {
size = size / 1024;
- unit = _(/* size unit */ "MiB");
- if (size > 5 * 1024) {
- size = size / 1024;
- unit = _(/* size unit */ "GiB");
- if (size > 5 * 1024) {
- size = size / 1024;
- unit = _(/* size unit */ "TiB");
- }
- }
+ unit = _( /* size unit */ "KiB");
+ if (size > 5 * 1024)
+ {
+ size = size / 1024;
+ unit = _( /* size unit */ "MiB");
+ if (size > 5 * 1024)
+ {
+ size = size / 1024;
+ unit = _( /* size unit */ "GiB");
+ if (size > 5 * 1024)
+ {
+ size = size / 1024;
+ unit = _( /* size unit */ "TiB");
+ }
+ }
+ }
}
- }
- ret = MALLOC(32);
- SNPRINTF(ret,
- 32,
- "%llu%s",
- size,
- unit);
+ ret = MALLOC (32);
+ SNPRINTF (ret, 32, "%llu%s", size, unit);
return ret;
}
@@ -189,61 +190,53 @@
* if conversion fails, a copy of the orignal
* string is returned.
*/
-char * string_convertToUtf8(struct GE_Context * ectx,
- const char * input,
- size_t len,
- const char * charset) {
- char * ret;
+char *
+string_convertToUtf8 (struct GE_Context *ectx,
+ const char *input, size_t len, const char *charset)
+{
+ char *ret;
#if ENABLE_NLS && HAVE_ICONV
size_t tmpSize;
size_t finSize;
- char * tmp;
- char * itmp;
+ char *tmp;
+ char *itmp;
iconv_t cd;
- cd = iconv_open("UTF-8", charset);
- if (cd == (iconv_t) -1) {
- GE_LOG_STRERROR(ectx,
- GE_USER | GE_ADMIN | GE_WARNING | GE_BULK,
- "iconv_open");
- ret = MALLOC(len+1);
- memcpy(ret, input, len);
- ret[len] = '\0';
- return ret;
- }
+ cd = iconv_open ("UTF-8", charset);
+ if (cd == (iconv_t) - 1)
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_USER | GE_ADMIN | GE_WARNING | GE_BULK,
+ "iconv_open");
+ ret = MALLOC (len + 1);
+ memcpy (ret, input, len);
+ ret[len] = '\0';
+ return ret;
+ }
tmpSize = 3 * len + 4;
- tmp = MALLOC(tmpSize);
+ tmp = MALLOC (tmpSize);
itmp = tmp;
finSize = tmpSize;
- if (iconv(cd,
- (char**) &input,
- &len,
- &itmp,
- &finSize) == (size_t)-1) {
- GE_LOG_STRERROR(ectx,
- GE_USER | GE_WARNING | GE_BULK,
- "iconv");
- iconv_close(cd);
- FREE(tmp);
- ret = MALLOC(len+1);
- memcpy(ret, input, len);
- ret[len] = '\0';
- return ret;
- }
- ret = MALLOC(tmpSize - finSize + 1);
- memcpy(ret,
- tmp,
- tmpSize - finSize);
+ if (iconv (cd, (char **) &input, &len, &itmp, &finSize) == (size_t) - 1)
+ {
+ GE_LOG_STRERROR (ectx, GE_USER | GE_WARNING | GE_BULK, "iconv");
+ iconv_close (cd);
+ FREE (tmp);
+ ret = MALLOC (len + 1);
+ memcpy (ret, input, len);
+ ret[len] = '\0';
+ return ret;
+ }
+ ret = MALLOC (tmpSize - finSize + 1);
+ memcpy (ret, tmp, tmpSize - finSize);
ret[tmpSize - finSize] = '\0';
- FREE(tmp);
- if (0 != iconv_close(cd))
- GE_LOG_STRERROR(ectx,
- GE_ADMIN | GE_WARNING | GE_REQUEST,
- "iconv_close");
+ FREE (tmp);
+ if (0 != iconv_close (cd))
+ GE_LOG_STRERROR (ectx, GE_ADMIN | GE_WARNING | GE_REQUEST, "iconv_close");
return ret;
#else
- ret = MALLOC(len+1);
- memcpy(ret, input, len);
+ ret = MALLOC (len + 1);
+ memcpy (ret, input, len);
ret[len] = '\0';
return ret;
#endif
@@ -259,16 +252,17 @@
* @returns the full file name,
* NULL is returned on error
*/
-char * string_expandFileName(struct GE_Context * ectx,
- const char * fil) {
- char * buffer;
+char *
+string_expandFileName (struct GE_Context *ectx, const char *fil)
+{
+ char *buffer;
#ifndef MINGW
size_t len;
size_t n;
- char * fm;
- const char * fil_ptr;
+ char *fm;
+ const char *fil_ptr;
#else
- char * fn;
+ char *fn;
long lRet;
#endif
@@ -278,88 +272,94 @@
#ifndef MINGW
if (fil[0] == DIR_SEPARATOR)
/* absolute path, just copy */
- return STRDUP(fil);
- if (fil[0] == '~') {
- fm = getenv("HOME");
- if (fm == NULL) {
- GE_LOG(ectx,
- GE_USER | GE_ADMIN | GE_WARNING | GE_IMMEDIATE,
- _("Failed to expand `$HOME': environment variable `HOME' not set"));
- return NULL;
- }
- fm = STRDUP(fm);
- /* do not copy '~' */
- fil_ptr = fil + 1;
+ return STRDUP (fil);
+ if (fil[0] == '~')
+ {
+ fm = getenv ("HOME");
+ if (fm == NULL)
+ {
+ GE_LOG (ectx,
+ GE_USER | GE_ADMIN | GE_WARNING | GE_IMMEDIATE,
+ _
+ ("Failed to expand `$HOME': environment variable `HOME' not
set"));
+ return NULL;
+ }
+ fm = STRDUP (fm);
+ /* do not copy '~' */
+ fil_ptr = fil + 1;
- /* skip over dir seperator to be consistent */
- if (fil_ptr[0] == DIR_SEPARATOR)
- fil_ptr++;
- } else {
- /* relative path */
- fil_ptr = fil;
- len = 512;
- fm = NULL;
- while (1) {
- buffer = MALLOC(len);
- if (getcwd(buffer, len) != NULL) {
- fm = buffer;
- break;
- }
- if ( (errno == ERANGE) &&
- (len < 1024 * 1024 * 4) ) {
- len *= 2;
- FREE(buffer);
- continue;
- }
- FREE(buffer);
- break;
+ /* skip over dir seperator to be consistent */
+ if (fil_ptr[0] == DIR_SEPARATOR)
+ fil_ptr++;
}
- if (fm == NULL) {
- GE_LOG_STRERROR(ectx,
- GE_USER | GE_WARNING | GE_IMMEDIATE,
- "getcwd");
- buffer = getenv("PWD"); /* alternative */
- if (buffer != NULL)
- fm = STRDUP(buffer);
+ else
+ {
+ /* relative path */
+ fil_ptr = fil;
+ len = 512;
+ fm = NULL;
+ while (1)
+ {
+ buffer = MALLOC (len);
+ if (getcwd (buffer, len) != NULL)
+ {
+ fm = buffer;
+ break;
+ }
+ if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
+ {
+ len *= 2;
+ FREE (buffer);
+ continue;
+ }
+ FREE (buffer);
+ break;
+ }
+ if (fm == NULL)
+ {
+ GE_LOG_STRERROR (ectx,
+ GE_USER | GE_WARNING | GE_IMMEDIATE, "getcwd");
+ buffer = getenv ("PWD"); /* alternative */
+ if (buffer != NULL)
+ fm = STRDUP (buffer);
+ }
+ if (fm == NULL)
+ fm = STRDUP ("./"); /* give up */
}
- if (fm == NULL)
- fm = STRDUP("./"); /* give up */
- }
- n = strlen(fm) + 1 + strlen(fil_ptr) + 1;
- buffer = MALLOC(n);
- SNPRINTF(buffer, n,
- "%s/%s", fm, fil_ptr);
- FREE(fm);
+ n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
+ buffer = MALLOC (n);
+ SNPRINTF (buffer, n, "%s/%s", fm, fil_ptr);
+ FREE (fm);
return buffer;
#else
- fn = MALLOC(MAX_PATH + 1);
+ fn = MALLOC (MAX_PATH + 1);
- if ((lRet = plibc_conv_to_win_path(fil, fn)) != ERROR_SUCCESS) {
- SetErrnoFromWinError(lRet);
- GE_LOG_STRERROR(ectx,
- GE_USER | GE_WARNING | GE_IMMEDIATE,
- "plibc_conv_to_win_path");
- return NULL;
- }
- /* is the path relative? */
- if ( (strncmp(fn + 1, ":\\", 2) != 0) &&
- (strncmp(fn, "\\\\", 2) != 0)) {
- char szCurDir[MAX_PATH + 1];
- lRet = GetCurrentDirectory(MAX_PATH + 1, szCurDir);
- if (lRet + strlen(fn) + 1 > (MAX_PATH + 1)) {
- SetErrnoFromWinError(ERROR_BUFFER_OVERFLOW);
- GE_LOG_STRERROR(ectx,
- GE_USER | GE_WARNING | GE_IMMEDIATE,
- "GetCurrentDirectory");
+ if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
+ {
+ SetErrnoFromWinError (lRet);
+ GE_LOG_STRERROR (ectx,
+ GE_USER | GE_WARNING | GE_IMMEDIATE,
+ "plibc_conv_to_win_path");
return NULL;
}
- buffer = MALLOC(MAX_PATH + 1);
- SNPRINTF(buffer,
- MAX_PATH+1,
- "%s\\%s", szCurDir, fn);
- FREE(fn);
- fn = buffer;
- }
+ /* is the path relative? */
+ if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
+ {
+ char szCurDir[MAX_PATH + 1];
+ lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
+ if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
+ {
+ SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
+ GE_LOG_STRERROR (ectx,
+ GE_USER | GE_WARNING | GE_IMMEDIATE,
+ "GetCurrentDirectory");
+ return NULL;
+ }
+ buffer = MALLOC (MAX_PATH + 1);
+ SNPRINTF (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
+ FREE (fn);
+ fn = buffer;
+ }
return fn;
#endif
Modified: GNUnet/src/util/string/xmalloc.c
===================================================================
--- GNUnet/src/util/string/xmalloc.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/string/xmalloc.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -44,45 +44,31 @@
* @param linenumber where in the code was the call to GROW
* @return pointer to size bytes of memory
*/
-void * xmalloc_(size_t size,
- const char * filename,
- int linenumber,
- const char * function) {
+void *
+xmalloc_ (size_t size,
+ const char *filename, int linenumber, const char *function)
+{
/* As a security precaution, we generally do not allow very large
allocations using the default 'MALLOC' macro */
- GE_ASSERT_FLF(NULL,
- size <= MAX_MALLOC_CHECKED,
- filename,
- linenumber,
- function);
- return xmalloc_unchecked_(size,
- filename,
- linenumber,
- function);
+ GE_ASSERT_FLF (NULL,
+ size <= MAX_MALLOC_CHECKED, filename, linenumber, function);
+ return xmalloc_unchecked_ (size, filename, linenumber, function);
}
-void * xmalloc_unchecked_(size_t size,
- const char * filename,
- int linenumber,
- const char * function) {
- void * result;
+void *
+xmalloc_unchecked_ (size_t size,
+ const char *filename,
+ int linenumber, const char *function)
+{
+ void *result;
- GE_ASSERT_FLF(NULL,
- size < INT_MAX,
- filename,
- linenumber,
- function);
- result = malloc(size);
+ GE_ASSERT_FLF (NULL, size < INT_MAX, filename, linenumber, function);
+ result = malloc (size);
if (result == NULL)
- GE_DIE_STRERROR_FLF(NULL,
- GE_IMMEDIATE | GE_USER | GE_DEVELOPER | GE_FATAL,
- "malloc",
- filename,
- linenumber,
- function);
- memset(result,
- 0,
- size); /* client code should not rely on this, though... */
+ GE_DIE_STRERROR_FLF (NULL,
+ GE_IMMEDIATE | GE_USER | GE_DEVELOPER | GE_FATAL,
+ "malloc", filename, linenumber, function);
+ memset (result, 0, size); /* client code should not rely on this,
though... */
return result;
}
@@ -98,20 +84,17 @@
* @param linenumber where in the code was the call to REALLOC
* @return pointer to size bytes of memory
*/
-void * xrealloc_(void * ptr,
- const size_t n,
- const char * filename,
- int linenumber,
- const char * function) {
- ptr = realloc(ptr, n);
+void *
+xrealloc_ (void *ptr,
+ const size_t n,
+ const char *filename, int linenumber, const char *function)
+{
+ ptr = realloc (ptr, n);
if (!ptr)
- GE_DIE_STRERROR_FLF(NULL,
- GE_IMMEDIATE | GE_USER | GE_DEVELOPER | GE_FATAL,
- "realloc",
- filename,
- linenumber,
- function);
+ GE_DIE_STRERROR_FLF (NULL,
+ GE_IMMEDIATE | GE_USER | GE_DEVELOPER | GE_FATAL,
+ "realloc", filename, linenumber, function);
return ptr;
}
@@ -123,16 +106,11 @@
* @param filename where in the code was the call to GROW
* @param linenumber where in the code was the call to GROW
*/
-void xfree_(void * ptr,
- const char * filename,
- int linenumber,
- const char * function) {
- GE_ASSERT_FLF(NULL,
- ptr != NULL,
- filename,
- linenumber,
- function);
- free(ptr);
+void
+xfree_ (void *ptr, const char *filename, int linenumber, const char *function)
+{
+ GE_ASSERT_FLF (NULL, ptr != NULL, filename, linenumber, function);
+ free (ptr);
}
/**
@@ -143,24 +121,15 @@
* @param linenumber where in the code was the call to GROW
* @return strdup(str)
*/
-char * xstrdup_(const char * str,
- const char * filename,
- int linenumber,
- const char * function) {
- char * res;
+char *
+xstrdup_ (const char *str,
+ const char *filename, int linenumber, const char *function)
+{
+ char *res;
- GE_ASSERT_FLF(NULL,
- str != NULL,
- filename,
- linenumber,
- function);
- res = (char*)xmalloc_(strlen(str)+1,
- filename,
- linenumber,
- function);
- memcpy(res,
- str,
- strlen(str)+1);
+ GE_ASSERT_FLF (NULL, str != NULL, filename, linenumber, function);
+ res = (char *) xmalloc_ (strlen (str) + 1, filename, linenumber, function);
+ memcpy (res, str, strlen (str) + 1);
return res;
}
@@ -173,27 +142,20 @@
* @param linenumber where in the code was the call to GROW
* @return strdup(str)
*/
-char * xstrndup_(const char * str,
- const size_t n,
- const char * filename,
- int linenumber,
- const char * function) {
- char * res;
+char *
+xstrndup_ (const char *str,
+ const size_t n,
+ const char *filename, int linenumber, const char *function)
+{
+ char *res;
size_t min;
- GE_ASSERT_FLF(NULL,
- str != NULL,
- filename,
- linenumber,
- function);
+ GE_ASSERT_FLF (NULL, str != NULL, filename, linenumber, function);
min = 0;
- while ( (min < n) && (str[min] != '\0'))
+ while ((min < n) && (str[min] != '\0'))
min++;
- res = (char*)xmalloc_(min+1,
- filename,
- linenumber,
- function);
- memcpy(res, str, min);
+ res = (char *) xmalloc_ (min + 1, filename, linenumber, function);
+ memcpy (res, str, min);
res[min] = '\0';
return res;
}
@@ -211,47 +173,40 @@
* @param filename where in the code was the call to GROW
* @param linenumber where in the code was the call to GROW
*/
-void xgrow_(void ** old,
- size_t elementSize,
- unsigned int * oldCount,
- unsigned int newCount,
- const char * filename,
- int linenumber,
- const char * function) {
- void * tmp;
+void
+xgrow_ (void **old,
+ size_t elementSize,
+ unsigned int *oldCount,
+ unsigned int newCount,
+ const char *filename, int linenumber, const char *function)
+{
+ void *tmp;
size_t size;
- GE_ASSERT_FLF(NULL,
- INT_MAX / elementSize > newCount,
- filename,
- linenumber,
- function);
+ GE_ASSERT_FLF (NULL,
+ INT_MAX / elementSize > newCount,
+ filename, linenumber, function);
size = newCount * elementSize;
- if (size == 0) {
- tmp = NULL;
- } else {
- tmp = xmalloc_(size,
- filename,
- linenumber,
- function);
- GE_ASSERT(NULL, tmp != NULL);
- memset(tmp, 0, size); /* client code should not rely on this, though... */
- if (*oldCount > newCount)
- *oldCount = newCount; /* shrink is also allowed! */
- memcpy(tmp,
- *old,
- elementSize * (*oldCount));
- }
+ if (size == 0)
+ {
+ tmp = NULL;
+ }
+ else
+ {
+ tmp = xmalloc_ (size, filename, linenumber, function);
+ GE_ASSERT (NULL, tmp != NULL);
+ memset (tmp, 0, size); /* client code should not rely on this,
though... */
+ if (*oldCount > newCount)
+ *oldCount = newCount; /* shrink is also allowed! */
+ memcpy (tmp, *old, elementSize * (*oldCount));
+ }
- if (*old != NULL) {
- xfree_(*old,
- filename,
- linenumber,
- function);
- }
+ if (*old != NULL)
+ {
+ xfree_ (*old, filename, linenumber, function);
+ }
*old = tmp;
*oldCount = newCount;
}
/* end of xmalloc.c */
-
Modified: GNUnet/src/util/string/xmalloctest.c
===================================================================
--- GNUnet/src/util/string/xmalloctest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/string/xmalloctest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -26,77 +26,73 @@
#include "gnunet_util.h"
#include "platform.h"
-static int check() {
+static int
+check ()
+{
#define MAX_TESTVAL 1024
- char * ptrs[MAX_TESTVAL];
+ char *ptrs[MAX_TESTVAL];
int i;
int j;
int k;
unsigned int ui;
/* MALLOC/FREE test */
- k = 352; /* random start value */
- for (i=1;i<MAX_TESTVAL;i++) {
- ptrs[i] = MALLOC(i);
- for (j=0;j<i;j++)
- ptrs[i][j] = k++;
- }
+ k = 352; /* random start value */
+ for (i = 1; i < MAX_TESTVAL; i++)
+ {
+ ptrs[i] = MALLOC (i);
+ for (j = 0; j < i; j++)
+ ptrs[i][j] = k++;
+ }
- for (i=MAX_TESTVAL-1;i>=1;i--) {
- for (j=i-1;j>=0;j--)
- if (ptrs[i][j] != (char) --k)
- return 1;
- FREE(ptrs[i]);
- }
+ for (i = MAX_TESTVAL - 1; i >= 1; i--)
+ {
+ for (j = i - 1; j >= 0; j--)
+ if (ptrs[i][j] != (char) --k)
+ return 1;
+ FREE (ptrs[i]);
+ }
/* STRNDUP tests */
- FREE(STRNDUP("foo", 0));
- ptrs[0] = STRNDUP("foo", 42);
- if (0 != strcmp(ptrs[0], "foo"))
+ FREE (STRNDUP ("foo", 0));
+ ptrs[0] = STRNDUP ("foo", 42);
+ if (0 != strcmp (ptrs[0], "foo"))
return 1;
- FREE(ptrs[0]);
- ptrs[0] = STRNDUP("foo", 2);
- if (0 != strcmp(ptrs[0], "fo"))
+ FREE (ptrs[0]);
+ ptrs[0] = STRNDUP ("foo", 2);
+ if (0 != strcmp (ptrs[0], "fo"))
return 2;
- FREE(ptrs[0]);
+ FREE (ptrs[0]);
/* FREENONNULL test */
- FREENONNULL(NULL);
- FREENONNULL(MALLOC(4));
+ FREENONNULL (NULL);
+ FREENONNULL (MALLOC (4));
/* STRDUP tests */
- ptrs[0] = STRDUP("bar");
- if (0 != strcmp(ptrs[0], "bar"))
+ ptrs[0] = STRDUP ("bar");
+ if (0 != strcmp (ptrs[0], "bar"))
return 3;
- FREE(ptrs[0]);
+ FREE (ptrs[0]);
/* GROW tests */
ptrs[0] = NULL;
- ui=0;
- GROW(ptrs[0],
- ui,
- 42);
+ ui = 0;
+ GROW (ptrs[0], ui, 42);
if (ui != 42)
return 4;
- GROW(ptrs[0],
- ui,
- 22);
+ GROW (ptrs[0], ui, 22);
if (ui != 22)
return 5;
- for (j=0;j<22;j++)
+ for (j = 0; j < 22; j++)
ptrs[0][j] = j;
- GROW(ptrs[0],
- ui,
- 32);
- for (j=0;j<22;j++)
+ GROW (ptrs[0], ui, 32);
+ for (j = 0; j < 22; j++)
if (ptrs[0][j] != j)
return 6;
- for (j=22;j<32;j++)
+ for (j = 22; j < 32; j++)
if (ptrs[0][j] != 0)
return 7;
- GROW(ptrs[0],
- ui,
- 0);
+ GROW (ptrs[0], ui, 0);
if (i != 0)
return 8;
if (ptrs[0] != NULL)
@@ -106,14 +102,13 @@
return 0;
}
-int main(int argc,
- char * argv[]){
+int
+main (int argc, char *argv[])
+{
int ret;
- ret = check();
+ ret = check ();
if (ret != 0)
- fprintf(stderr,
- "ERROR %d.\n",
- ret);
+ fprintf (stderr, "ERROR %d.\n", ret);
return ret;
}
Modified: GNUnet/src/util/threads/mutex.c
===================================================================
--- GNUnet/src/util/threads/mutex.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/threads/mutex.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -57,149 +57,147 @@
* on all pthread-systems so far. Odd.
*/
#ifndef _MSC_VER
-extern int pthread_mutexattr_setkind_np(pthread_mutexattr_t *attr,
- int kind);
+extern int pthread_mutexattr_setkind_np (pthread_mutexattr_t * attr,
+ int kind);
#endif
-typedef struct MUTEX {
+typedef struct MUTEX
+{
pthread_mutex_t pt;
- const char * locked_file;
- cron_t locked_time;
+ const char *locked_file;
+ cron_t locked_time;
unsigned int locked_line;
unsigned int locked_depth;
} Mutex;
-Mutex * MUTEX_CREATE(int isRecursive) {
+Mutex *
+MUTEX_CREATE (int isRecursive)
+{
pthread_mutexattr_t attr;
- Mutex * mut;
+ Mutex *mut;
#if WINDOWS
attr = NULL;
#endif
- pthread_mutexattr_init(&attr);
- if (isRecursive) {
+ pthread_mutexattr_init (&attr);
+ if (isRecursive)
+ {
#if LINUX
- GE_ASSERT(NULL,
- 0 == pthread_mutexattr_setkind_np
- (&attr,
- PTHREAD_MUTEX_RECURSIVE_NP));
+ GE_ASSERT (NULL,
+ 0 == pthread_mutexattr_setkind_np
+ (&attr, PTHREAD_MUTEX_RECURSIVE_NP));
#elif SOMEBSD || FREEBSD || FREEBSD5
- GE_ASSERT(NULL,
- 0 == pthread_mutexattr_setkind_np
- (&attr,
- PTHREAD_MUTEX_RECURSIVE));
+ GE_ASSERT (NULL,
+ 0 == pthread_mutexattr_setkind_np
+ (&attr, PTHREAD_MUTEX_RECURSIVE));
#elif SOLARIS || OSX || WINDOWS
- GE_ASSERT(NULL,
- 0 == pthread_mutexattr_settype
- (&attr,
- PTHREAD_MUTEX_RECURSIVE));
+ GE_ASSERT (NULL,
+ 0 == pthread_mutexattr_settype
+ (&attr, PTHREAD_MUTEX_RECURSIVE));
#endif
- } else {
+ }
+ else
+ {
#if LINUX
- GE_ASSERT(NULL,
- 0 == pthread_mutexattr_setkind_np
- (&attr,
- PTHREAD_MUTEX_ERRORCHECK_NP));
+ GE_ASSERT (NULL,
+ 0 == pthread_mutexattr_setkind_np
+ (&attr, PTHREAD_MUTEX_ERRORCHECK_NP));
#else
- GE_ASSERT(NULL,
- 0 == pthread_mutexattr_settype
- (&attr,
- PTHREAD_MUTEX_ERRORCHECK));
+ GE_ASSERT (NULL,
+ 0 == pthread_mutexattr_settype
+ (&attr, PTHREAD_MUTEX_ERRORCHECK));
#endif
- }
- mut = MALLOC(sizeof(Mutex));
- memset(mut,
- 0,
- sizeof(Mutex));
- GE_ASSERT(NULL,
- 0 == pthread_mutex_init(&mut->pt,
- &attr));
+ }
+ mut = MALLOC (sizeof (Mutex));
+ memset (mut, 0, sizeof (Mutex));
+ GE_ASSERT (NULL, 0 == pthread_mutex_init (&mut->pt, &attr));
return mut;
}
-void MUTEX_DESTROY(Mutex * mutex) {
+void
+MUTEX_DESTROY (Mutex * mutex)
+{
int ret;
- GE_ASSERT(NULL, mutex != NULL);
+ GE_ASSERT (NULL, mutex != NULL);
errno = 0;
- ret = pthread_mutex_destroy(&mutex->pt);
- GE_ASSERT(NULL, 0 == ret);
- FREE(mutex);
+ ret = pthread_mutex_destroy (&mutex->pt);
+ GE_ASSERT (NULL, 0 == ret);
+ FREE (mutex);
}
-void MUTEX_LOCK_FL(Mutex * mutex,
- const char * file,
- unsigned int line) {
+void
+MUTEX_LOCK_FL (Mutex * mutex, const char *file, unsigned int line)
+{
int ret;
cron_t start;
cron_t end;
- GE_ASSERT(NULL, mutex != NULL);
- start = get_time();
- ret = pthread_mutex_lock(&mutex->pt);
- end = get_time();
- if ( (end - start > REALTIME_LIMIT) &&
- (REALTIME_LIMIT != 0) ) {
- GE_LOG(NULL,
- GE_DEVELOPER | GE_WARNING | GE_IMMEDIATE,
- _("Real-time delay violation (%llu ms) at %s:%u\n"),
- end - start,
- file,
- line);
- }
- if (ret != 0) {
- if (ret == EINVAL)
- GE_LOG(NULL,
- GE_FATAL | GE_DEVELOPER | GE_USER | GE_IMMEDIATE,
- _("Invalid argument for `%s'.\n"),
- "pthread_mutex_lock");
- if (ret == EDEADLK)
- GE_LOG(NULL,
- GE_FATAL | GE_DEVELOPER | GE_USER | GE_IMMEDIATE,
- _("Deadlock due to `%s'.\n"),
- "pthread_mutex_lock");
- GE_ASSERT(NULL, 0);
- }
- if (mutex->locked_depth++ == 0) {
- mutex->locked_file = file;
- mutex->locked_line = line;
- mutex->locked_time = end;
- }
+ GE_ASSERT (NULL, mutex != NULL);
+ start = get_time ();
+ ret = pthread_mutex_lock (&mutex->pt);
+ end = get_time ();
+ if ((end - start > REALTIME_LIMIT) && (REALTIME_LIMIT != 0))
+ {
+ GE_LOG (NULL,
+ GE_DEVELOPER | GE_WARNING | GE_IMMEDIATE,
+ _("Real-time delay violation (%llu ms) at %s:%u\n"),
+ end - start, file, line);
+ }
+ if (ret != 0)
+ {
+ if (ret == EINVAL)
+ GE_LOG (NULL,
+ GE_FATAL | GE_DEVELOPER | GE_USER | GE_IMMEDIATE,
+ _("Invalid argument for `%s'.\n"), "pthread_mutex_lock");
+ if (ret == EDEADLK)
+ GE_LOG (NULL,
+ GE_FATAL | GE_DEVELOPER | GE_USER | GE_IMMEDIATE,
+ _("Deadlock due to `%s'.\n"), "pthread_mutex_lock");
+ GE_ASSERT (NULL, 0);
+ }
+ if (mutex->locked_depth++ == 0)
+ {
+ mutex->locked_file = file;
+ mutex->locked_line = line;
+ mutex->locked_time = end;
+ }
}
-void MUTEX_UNLOCK(Mutex * mutex) {
+void
+MUTEX_UNLOCK (Mutex * mutex)
+{
int ret;
cron_t now;
- GE_ASSERT(NULL, mutex != NULL);
- if (0 == --mutex->locked_depth) {
- now = get_time();
- if ( (now - mutex->locked_time > REALTIME_LIMIT) &&
- (REALTIME_LIMIT != 0) )
- GE_LOG(NULL,
- GE_DEVELOPER | GE_WARNING | GE_IMMEDIATE,
- _("Lock aquired for too long (%llu ms) at %s:%u\n"),
- now - mutex->locked_time,
- mutex->locked_file,
- mutex->locked_line);
- mutex->locked_file = NULL;
- mutex->locked_line = 0;
- mutex->locked_time = 0;
- }
- ret = pthread_mutex_unlock(&mutex->pt);
- if (ret != 0) {
- if (ret == EINVAL)
- GE_LOG(NULL,
- GE_FATAL | GE_DEVELOPER | GE_USER | GE_IMMEDIATE,
- _("Invalid argument for `%s'.\n"),
- "pthread_mutex_lock");
- if (ret == EPERM)
- GE_LOG(NULL,
- GE_FATAL | GE_DEVELOPER | GE_USER | GE_IMMEDIATE,
- _("Permission denied for `%s'.\n"),
- "pthread_mutex_unlock");
- GE_ASSERT(NULL, 0);
- }
+ GE_ASSERT (NULL, mutex != NULL);
+ if (0 == --mutex->locked_depth)
+ {
+ now = get_time ();
+ if ((now - mutex->locked_time > REALTIME_LIMIT) &&
+ (REALTIME_LIMIT != 0))
+ GE_LOG (NULL,
+ GE_DEVELOPER | GE_WARNING | GE_IMMEDIATE,
+ _("Lock aquired for too long (%llu ms) at %s:%u\n"),
+ now - mutex->locked_time,
+ mutex->locked_file, mutex->locked_line);
+ mutex->locked_file = NULL;
+ mutex->locked_line = 0;
+ mutex->locked_time = 0;
+ }
+ ret = pthread_mutex_unlock (&mutex->pt);
+ if (ret != 0)
+ {
+ if (ret == EINVAL)
+ GE_LOG (NULL,
+ GE_FATAL | GE_DEVELOPER | GE_USER | GE_IMMEDIATE,
+ _("Invalid argument for `%s'.\n"), "pthread_mutex_lock");
+ if (ret == EPERM)
+ GE_LOG (NULL,
+ GE_FATAL | GE_DEVELOPER | GE_USER | GE_IMMEDIATE,
+ _("Permission denied for `%s'.\n"), "pthread_mutex_unlock");
+ GE_ASSERT (NULL, 0);
+ }
}
/* end of mutex.c */
Modified: GNUnet/src/util/threads/pthread.c
===================================================================
--- GNUnet/src/util/threads/pthread.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/threads/pthread.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -42,23 +42,26 @@
#include <pthread.h>
#endif
-typedef struct PTHREAD {
+typedef struct PTHREAD
+{
pthread_t pt;
} PThread;
/**
* Returns YES if pt is the handle for THIS thread.
*/
-int PTHREAD_TEST_SELF(PThread * handle) {
+int
+PTHREAD_TEST_SELF (PThread * handle)
+{
if (handle == NULL)
return NO;
#if HAVE_PTHREAD_EQUAL
- if (pthread_equal(pthread_self(), handle->pt))
+ if (pthread_equal (pthread_self (), handle->pt))
#else
#if HAVE_NEW_PTHREAD_T
- if (handle->pt->p == pthread_self().p)
+ if (handle->pt->p == pthread_self ().p)
#else
- if (handle->pt == pthread_self())
+ if (handle->pt == pthread_self ())
#endif
#endif
return YES;
@@ -69,18 +72,22 @@
/**
* Get the handle for THIS thread.
*/
-PThread * PTHREAD_GET_SELF() {
- PThread * ret;
- ret = MALLOC(sizeof(PThread));
- ret->pt = pthread_self();
+PThread *
+PTHREAD_GET_SELF ()
+{
+ PThread *ret;
+ ret = MALLOC (sizeof (PThread));
+ ret->pt = pthread_self ();
return ret;
}
/**
* Release handle for a thread.
*/
-void PTHREAD_REL_SELF(PThread * handle) {
- FREE(handle);
+void
+PTHREAD_REL_SELF (PThread * handle)
+{
+ FREE (handle);
}
/**
@@ -95,108 +102,100 @@
* will just segfault and gdb will give a messed-up stacktrace.
* @return see pthread_create
*/
-PThread * PTHREAD_CREATE(PThreadMain main,
- void * arg,
- unsigned int stackSize) {
- PThread * handle;
+PThread *
+PTHREAD_CREATE (PThreadMain main, void *arg, unsigned int stackSize)
+{
+ PThread *handle;
#ifndef LINUX
pthread_attr_t stack_size_custom_attr;
#endif
int ret;
- handle = MALLOC(sizeof(PThread));
+ handle = MALLOC (sizeof (PThread));
#ifdef MINGW
- memset(handle, 0, sizeof(PThread));
+ memset (handle, 0, sizeof (PThread));
#endif
#ifndef LINUX
- pthread_attr_init(&stack_size_custom_attr);
- pthread_attr_setstacksize(&stack_size_custom_attr,
- stackSize);
+ pthread_attr_init (&stack_size_custom_attr);
+ pthread_attr_setstacksize (&stack_size_custom_attr, stackSize);
#endif
- ret = pthread_create(&handle->pt,
+ ret = pthread_create (&handle->pt,
#ifndef LINUX
- &stack_size_custom_attr,
+ &stack_size_custom_attr,
#else
- NULL,
+ NULL,
#endif
- main,
- arg);
- if (ret != 0) {
- FREE(handle);
- return NULL;
- }
+ main, arg);
+ if (ret != 0)
+ {
+ FREE (handle);
+ return NULL;
+ }
return handle;
}
-void PTHREAD_JOIN_FL(PThread * handle,
- void ** ret,
- const char * file,
- unsigned int line) {
+void
+PTHREAD_JOIN_FL (PThread * handle,
+ void **ret, const char *file, unsigned int line)
+{
cron_t start;
cron_t end;
int k;
- GE_ASSERT(NULL,
- handle != NULL);
- GE_ASSERT(NULL,
- NO == PTHREAD_TEST_SELF(handle));
- start = get_time();
- k = pthread_join(handle->pt, ret);
- end = get_time();
- if ( (end - start > REALTIME_LIMIT) &&
- (REALTIME_LIMIT != 0) ) {
- GE_LOG(NULL,
- GE_DEVELOPER | GE_WARNING | GE_IMMEDIATE,
- _("Real-time delay violation (%llu ms) at %s:%u\n"),
- end - start,
- file,
- line);
- }
- FREE(handle);
- switch (k) {
- case 0:
- return;
- case ESRCH:
- GE_LOG(NULL,
- GE_FATAL | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
- _("`%s' failed with error code %s: %s\n"),
- "pthread_join",
- "ESRCH",
- STRERROR(errno));
- break;
- case EINVAL:
- GE_LOG(NULL,
- GE_FATAL | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
- _("`%s' failed with error code %s: %s\n"),
- "pthread_join",
- "EINVAL",
- STRERROR(errno));
- case EDEADLK:
- GE_LOG(NULL,
- GE_FATAL | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
- _("`%s' failed with error code %s: %s\n"),
- "pthread_join",
- "EDEADLK",
- STRERROR(errno));
- default:
- GE_LOG(NULL,
- GE_FATAL | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
- _("`%s' failed with error code %d: %s\n"),
- "pthread_join",
- k,
- STRERROR(errno));
- }
- GE_ASSERT(NULL, 0);
+ GE_ASSERT (NULL, handle != NULL);
+ GE_ASSERT (NULL, NO == PTHREAD_TEST_SELF (handle));
+ start = get_time ();
+ k = pthread_join (handle->pt, ret);
+ end = get_time ();
+ if ((end - start > REALTIME_LIMIT) && (REALTIME_LIMIT != 0))
+ {
+ GE_LOG (NULL,
+ GE_DEVELOPER | GE_WARNING | GE_IMMEDIATE,
+ _("Real-time delay violation (%llu ms) at %s:%u\n"),
+ end - start, file, line);
+ }
+ FREE (handle);
+ switch (k)
+ {
+ case 0:
+ return;
+ case ESRCH:
+ GE_LOG (NULL,
+ GE_FATAL | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
+ _("`%s' failed with error code %s: %s\n"),
+ "pthread_join", "ESRCH", STRERROR (errno));
+ break;
+ case EINVAL:
+ GE_LOG (NULL,
+ GE_FATAL | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
+ _("`%s' failed with error code %s: %s\n"),
+ "pthread_join", "EINVAL", STRERROR (errno));
+ case EDEADLK:
+ GE_LOG (NULL,
+ GE_FATAL | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
+ _("`%s' failed with error code %s: %s\n"),
+ "pthread_join", "EDEADLK", STRERROR (errno));
+ default:
+ GE_LOG (NULL,
+ GE_FATAL | GE_USER | GE_DEVELOPER | GE_IMMEDIATE,
+ _("`%s' failed with error code %d: %s\n"),
+ "pthread_join", k, STRERROR (errno));
+ }
+ GE_ASSERT (NULL, 0);
}
#ifdef WINDOWS
/**
* @brief Called if a sleeping thread is interrupted
*/
-static void CALLBACK __PTHREAD_SIGNALED(DWORD sig) {
+static void CALLBACK
+__PTHREAD_SIGNALED (DWORD sig)
+{
}
#else
-static void sigalrmHandler(int sig) {
+static void
+sigalrmHandler (int sig)
+{
}
#endif
@@ -206,7 +205,9 @@
* wake the thread up early. Caller is responsible to check that the
* sleep was long enough.
*/
-void PTHREAD_SLEEP(unsigned long long delay) {
+void
+PTHREAD_SLEEP (unsigned long long delay)
+{
#if LINUX || SOLARIS || SOMEBSD || OSX
struct timespec req;
struct timespec rem;
@@ -218,72 +219,61 @@
/* actual sleep */
#if LINUX || SOLARIS || SOMEBSD || OSX
- req.tv_sec
- = delay / 1000; /* ms -> seconds */
- req.tv_nsec
- = (delay - req.tv_sec * 1000) * 1000 * 1000; /* ms -> ns */
+ req.tv_sec = delay / 1000; /* ms -> seconds */
+ req.tv_nsec = (delay - req.tv_sec * 1000) * 1000 * 1000; /* ms -> ns */
rem.tv_sec = 0;
rem.tv_nsec = 0;
- if ( (0 != nanosleep(&req, &rem)) &&
- (errno != EINTR) )
- GE_LOG_STRERROR(NULL,
- GE_WARNING | GE_USER | GE_BULK,
- "nanosleep");
+ if ((0 != nanosleep (&req, &rem)) && (errno != EINTR))
+ GE_LOG_STRERROR (NULL, GE_WARNING | GE_USER | GE_BULK, "nanosleep");
#elif WINDOWS
- SleepEx(delay, TRUE);
+ SleepEx (delay, TRUE);
#else
/* fall back to select */
- timeout.tv_sec
- = delay / CRON_UNIT_TO_SECONDS;
+ timeout.tv_sec = delay / CRON_UNIT_TO_SECONDS;
timeout.tv_usec
- = (delay - timeout.tv_sec * CRON_UNIT_TO_SECONDS)
- * MICROSEC_TO_CRON_UNIT;
- ret = SELECT(0, NULL, NULL, NULL, &timeout);
- if ( (ret == -1) &&
- (errno != EINTR) )
- GE_LOG_STRERROR(NULL,
- GE_WARNING | GE_USER | GE_BULK,
- "select");
+ = (delay - timeout.tv_sec * CRON_UNIT_TO_SECONDS) * MICROSEC_TO_CRON_UNIT;
+ ret = SELECT (0, NULL, NULL, NULL, &timeout);
+ if ((ret == -1) && (errno != EINTR))
+ GE_LOG_STRERROR (NULL, GE_WARNING | GE_USER | GE_BULK, "select");
#endif
}
-void PTHREAD_STOP_SLEEP(PThread * handle) {
+void
+PTHREAD_STOP_SLEEP (PThread * handle)
+{
int ret;
if (handle == NULL)
return;
#ifdef WINDOWS
- ret = QueueUserAPC((PAPCFUNC) __PTHREAD_SIGNALED,
- pthread_getw32threadhandle_np(handle->pt),
- 0) != 0 ? 0 : EINVAL;
+ ret = QueueUserAPC ((PAPCFUNC) __PTHREAD_SIGNALED,
+ pthread_getw32threadhandle_np (handle->pt),
+ 0) != 0 ? 0 : EINVAL;
#else
- ret = pthread_kill(handle->pt, SIGALRM);
+ ret = pthread_kill (handle->pt, SIGALRM);
#endif
- switch (ret) {
- case 0:
- break; /* ok */
- case EINVAL:
- GE_LOG(NULL,
- GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
- _("`%s' failed with error code %s: %s\n"),
- "pthread_kill",
- "EINVAL",
- STRERROR(ret));
- break;
- case ESRCH:
- /* ignore, thread might have already exited by chance */
- break;
- default:
- GE_LOG(NULL,
- GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
- _("`%s' failed with error code %d: %s\n"),
- "pthread_kill",
- ret,
- STRERROR(ret));
- break;
- }
+ switch (ret)
+ {
+ case 0:
+ break; /* ok */
+ case EINVAL:
+ GE_LOG (NULL,
+ GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
+ _("`%s' failed with error code %s: %s\n"),
+ "pthread_kill", "EINVAL", STRERROR (ret));
+ break;
+ case ESRCH:
+ /* ignore, thread might have already exited by chance */
+ break;
+ default:
+ GE_LOG (NULL,
+ GE_ERROR | GE_USER | GE_DEVELOPER | GE_BULK,
+ _("`%s' failed with error code %d: %s\n"),
+ "pthread_kill", ret, STRERROR (ret));
+ break;
+ }
}
#ifndef MINGW
@@ -295,30 +285,28 @@
/**
* Initialize the signal handlers, etc.
*/
-void __attribute__ ((constructor)) pthread_handlers_ltdl_init() {
+void __attribute__ ((constructor)) pthread_handlers_ltdl_init ()
+{
/* make sure SIGALRM does not kill us */
#ifndef MINGW
- memset(&sig, 0, sizeof(struct sigaction));
- memset(&old, 0, sizeof(struct sigaction));
+ memset (&sig, 0, sizeof (struct sigaction));
+ memset (&old, 0, sizeof (struct sigaction));
sig.sa_flags = SA_NODEFER;
- sig.sa_handler = &sigalrmHandler;
- if (0 != sigaction(SIGALRM, &sig, &old))
- GE_LOG_STRERROR(NULL,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "sigaction");
+ sig.sa_handler = &sigalrmHandler;
+ if (0 != sigaction (SIGALRM, &sig, &old))
+ GE_LOG_STRERROR (NULL, GE_WARNING | GE_ADMIN | GE_BULK, "sigaction");
#else
- InitWinEnv(NULL);
+ InitWinEnv (NULL);
#endif
}
-void __attribute__ ((destructor)) pthread_handlers_ltdl_fini() {
+void __attribute__ ((destructor)) pthread_handlers_ltdl_fini ()
+{
#ifndef MINGW
- if (0 != sigaction(SIGALRM, &old, &sig))
- GE_LOG_STRERROR(NULL,
- GE_WARNING | GE_ADMIN | GE_BULK,
- "sigaction");
+ if (0 != sigaction (SIGALRM, &old, &sig))
+ GE_LOG_STRERROR (NULL, GE_WARNING | GE_ADMIN | GE_BULK, "sigaction");
#else
- ShutdownWinEnv();
+ ShutdownWinEnv ();
#endif
}
Modified: GNUnet/src/util/threads/semaphore.c
===================================================================
--- GNUnet/src/util/threads/semaphore.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/threads/semaphore.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -49,7 +49,8 @@
/**
* @brief Internal state of a semaphore.
*/
-typedef struct SEMAPHORE {
+typedef struct SEMAPHORE
+{
/**
* Counter
*/
@@ -80,8 +81,8 @@
* on all pthread-systems so far. Odd.
*/
#ifndef _MSC_VER
-extern int pthread_mutexattr_setkind_np(pthread_mutexattr_t *attr,
- int kind);
+extern int pthread_mutexattr_setkind_np (pthread_mutexattr_t * attr,
+ int kind);
#endif
/**
@@ -89,93 +90,82 @@
* setup and initialization. semaphore destroy (below) should
* be called when the semaphore is no longer needed.
*/
-Semaphore * SEMAPHORE_CREATE(int value) {
- Semaphore * s;
+Semaphore *
+SEMAPHORE_CREATE (int value)
+{
+ Semaphore *s;
pthread_mutexattr_t attr;
#if WINDOWS
attr = NULL;
#endif
- pthread_mutexattr_init(&attr);
+ pthread_mutexattr_init (&attr);
#if LINUX
- GE_ASSERT(NULL,
- 0 == pthread_mutexattr_setkind_np
- (&attr,
- PTHREAD_MUTEX_ERRORCHECK_NP));
+ GE_ASSERT (NULL,
+ 0 == pthread_mutexattr_setkind_np
+ (&attr, PTHREAD_MUTEX_ERRORCHECK_NP));
#else
- GE_ASSERT(NULL,
- 0 == pthread_mutexattr_settype
- (&attr,
- PTHREAD_MUTEX_ERRORCHECK));
+ GE_ASSERT (NULL,
+ 0 == pthread_mutexattr_settype
+ (&attr, PTHREAD_MUTEX_ERRORCHECK));
#endif
- s = MALLOC(sizeof(Semaphore));
+ s = MALLOC (sizeof (Semaphore));
s->v = value;
- GE_ASSERT(NULL,
- 0 == pthread_mutex_init(&s->mutex,
- &attr));
- GE_ASSERT(NULL,
- 0 == pthread_cond_init(&s->cond,
- NULL));
+ GE_ASSERT (NULL, 0 == pthread_mutex_init (&s->mutex, &attr));
+ GE_ASSERT (NULL, 0 == pthread_cond_init (&s->cond, NULL));
return s;
}
-void SEMAPHORE_DESTROY(Semaphore * s) {
- GE_ASSERT(NULL, s != NULL);
- GE_ASSERT(NULL,
- 0 == pthread_cond_destroy(&s->cond));
- GE_ASSERT(NULL,
- 0 == pthread_mutex_destroy(&s->mutex));
- FREE(s);
+void
+SEMAPHORE_DESTROY (Semaphore * s)
+{
+ GE_ASSERT (NULL, s != NULL);
+ GE_ASSERT (NULL, 0 == pthread_cond_destroy (&s->cond));
+ GE_ASSERT (NULL, 0 == pthread_mutex_destroy (&s->mutex));
+ FREE (s);
}
-int SEMAPHORE_UP(Semaphore * s) {
+int
+SEMAPHORE_UP (Semaphore * s)
+{
int ret;
- GE_ASSERT(NULL, s != NULL);
- GE_ASSERT(NULL,
- 0 == pthread_mutex_lock(&s->mutex));
+ GE_ASSERT (NULL, s != NULL);
+ GE_ASSERT (NULL, 0 == pthread_mutex_lock (&s->mutex));
ret = ++(s->v);
- GE_ASSERT(NULL,
- 0 == pthread_cond_signal(&s->cond));
- GE_ASSERT(NULL,
- 0 == pthread_mutex_unlock(&s->mutex));
+ GE_ASSERT (NULL, 0 == pthread_cond_signal (&s->cond));
+ GE_ASSERT (NULL, 0 == pthread_mutex_unlock (&s->mutex));
return ret;
}
-int SEMAPHORE_DOWN_FL(Semaphore * s,
- int mayblock,
- int longwait,
- const char * file,
- unsigned int line) {
+int
+SEMAPHORE_DOWN_FL (Semaphore * s,
+ int mayblock,
+ int longwait, const char *file, unsigned int line)
+{
int ret;
cron_t start;
cron_t end;
- GE_ASSERT(NULL, s != NULL);
- start = get_time();
- GE_ASSERT(NULL,
- 0 == pthread_mutex_lock(&s->mutex));
- while ( (s->v <= 0) && mayblock)
- GE_ASSERT(NULL,
- 0 == pthread_cond_wait(&s->cond,
- &s->mutex));
+ GE_ASSERT (NULL, s != NULL);
+ start = get_time ();
+ GE_ASSERT (NULL, 0 == pthread_mutex_lock (&s->mutex));
+ while ((s->v <= 0) && mayblock)
+ GE_ASSERT (NULL, 0 == pthread_cond_wait (&s->cond, &s->mutex));
if (s->v > 0)
ret = --(s->v);
else
ret = SYSERR;
- GE_ASSERT(NULL,
- 0 == pthread_mutex_unlock(&s->mutex));
- end = get_time();
- if ( (longwait == NO) &&
- (end - start > REALTIME_LIMIT) &&
- (REALTIME_LIMIT != 0) ) {
- GE_LOG(NULL,
- GE_DEVELOPER | GE_WARNING | GE_IMMEDIATE,
- _("Real-time delay violation (%llu ms) at %s:%u\n"),
- end - start,
- file,
- line);
- }
+ GE_ASSERT (NULL, 0 == pthread_mutex_unlock (&s->mutex));
+ end = get_time ();
+ if ((longwait == NO) &&
+ (end - start > REALTIME_LIMIT) && (REALTIME_LIMIT != 0))
+ {
+ GE_LOG (NULL,
+ GE_DEVELOPER | GE_WARNING | GE_IMMEDIATE,
+ _("Real-time delay violation (%llu ms) at %s:%u\n"),
+ end - start, file, line);
+ }
return ret;
}
Modified: GNUnet/src/util/threads/semaphoretest.c
===================================================================
--- GNUnet/src/util/threads/semaphoretest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/threads/semaphoretest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -27,174 +27,189 @@
#include <sys/types.h>
-static struct MUTEX * lock;
+static struct MUTEX *lock;
-static struct SEMAPHORE * sem;
+static struct SEMAPHORE *sem;
static volatile int sv;
static volatile int tv;
-static void * lockIt(void * unused) {
+static void *
+lockIt (void *unused)
+{
sv = 0;
while (sv == 0)
- PTHREAD_SLEEP(50 * cronMILLIS); /* busy waiting may not always work */
- MUTEX_LOCK(lock);
+ PTHREAD_SLEEP (50 * cronMILLIS); /* busy waiting may not always work */
+ MUTEX_LOCK (lock);
sv = 1;
- MUTEX_UNLOCK(lock);
+ MUTEX_UNLOCK (lock);
sv = 2;
tv = 2;
return NULL;
}
-static void * bigStack(void * unused) {
+static void *
+bigStack (void *unused)
+{
int i;
char big[1024 * 100];
- for (i=0;i<1024*100;i++)
+ for (i = 0; i < 1024 * 100; i++)
big[i] = (char) i;
return NULL;
}
-static int testPTHREAD_CREATE() {
- struct PTHREAD * pt;
- void * unused;
+static int
+testPTHREAD_CREATE ()
+{
+ struct PTHREAD *pt;
+ void *unused;
- sv = -1; tv = 0;
- lock = MUTEX_CREATE(NO);
- pt = PTHREAD_CREATE(&lockIt,
- NULL,
- 1024);
- while (tv != 2) {
- sv = 1;
- PTHREAD_SLEEP(50 * cronMILLIS); /* busy waiting may not always work */
- }
- PTHREAD_JOIN(pt, &unused);
- MUTEX_DESTROY(lock);
- pt = PTHREAD_CREATE(&bigStack,
- NULL,
- 1024*100 + 25000); /* fails by segfault */
- PTHREAD_JOIN(pt, &unused);
+ sv = -1;
+ tv = 0;
+ lock = MUTEX_CREATE (NO);
+ pt = PTHREAD_CREATE (&lockIt, NULL, 1024);
+ while (tv != 2)
+ {
+ sv = 1;
+ PTHREAD_SLEEP (50 * cronMILLIS); /* busy waiting may not always work */
+ }
+ PTHREAD_JOIN (pt, &unused);
+ MUTEX_DESTROY (lock);
+ pt = PTHREAD_CREATE (&bigStack, NULL, 1024 * 100 + 25000); /* fails by
segfault */
+ PTHREAD_JOIN (pt, &unused);
return 0;
}
-static int testMutex() {
- struct PTHREAD * pt;
- void * unused;
+static int
+testMutex ()
+{
+ struct PTHREAD *pt;
+ void *unused;
- lock = MUTEX_CREATE(NO);
+ lock = MUTEX_CREATE (NO);
sv = 1;
tv = 0;
- pt = PTHREAD_CREATE(&lockIt,
- NULL,
- 1024);
+ pt = PTHREAD_CREATE (&lockIt, NULL, 1024);
while (sv == 1)
- PTHREAD_SLEEP(50 * cronMILLIS); /* busy waiting may not always work */
- MUTEX_LOCK(lock);
- sv = 5; /* release lockIt from while sv==0 loop,
- blocks it on lock */
+ PTHREAD_SLEEP (50 * cronMILLIS); /* busy waiting may not always work */
+ MUTEX_LOCK (lock);
+ sv = 5; /* release lockIt from while sv==0 loop,
+ blocks it on lock */
- if (sv != 5) {
- MUTEX_UNLOCK(lock);
- while (tv != 2)
- PTHREAD_SLEEP(50 * cronMILLIS); /* busy waiting may not always work */
- MUTEX_DESTROY(lock);
- printf("MUTEX test failed at %s:%u\n",
- __FILE__, __LINE__);
- return 1; /* error */
- } else {
- MUTEX_UNLOCK(lock);
- while (tv != 2)
- PTHREAD_SLEEP(50 * cronMILLIS); /* busy waiting may not always work */
- PTHREAD_JOIN(pt, &unused);
- MUTEX_DESTROY(lock);
- return 0; /* ok */
- }
+ if (sv != 5)
+ {
+ MUTEX_UNLOCK (lock);
+ while (tv != 2)
+ PTHREAD_SLEEP (50 * cronMILLIS); /* busy waiting may not always
work */
+ MUTEX_DESTROY (lock);
+ printf ("MUTEX test failed at %s:%u\n", __FILE__, __LINE__);
+ return 1; /* error */
+ }
+ else
+ {
+ MUTEX_UNLOCK (lock);
+ while (tv != 2)
+ PTHREAD_SLEEP (50 * cronMILLIS); /* busy waiting may not always
work */
+ PTHREAD_JOIN (pt, &unused);
+ MUTEX_DESTROY (lock);
+ return 0; /* ok */
+ }
}
-static int testRecursiveMutex() {
+static int
+testRecursiveMutex ()
+{
int i;
- lock = MUTEX_CREATE(YES);
- for (i=0;i<50;i++)
- MUTEX_LOCK(lock);
- for (i=0;i<50;i++)
- MUTEX_UNLOCK(lock);
- MUTEX_DESTROY(lock);
- return 0; /* ok -- fails by hanging!*/
+ lock = MUTEX_CREATE (YES);
+ for (i = 0; i < 50; i++)
+ MUTEX_LOCK (lock);
+ for (i = 0; i < 50; i++)
+ MUTEX_UNLOCK (lock);
+ MUTEX_DESTROY (lock);
+ return 0; /* ok -- fails by hanging! */
}
-static void * semUpDown(void * unused) {
+static void *
+semUpDown (void *unused)
+{
int i;
- for (i=0;i<42;i++)
- SEMAPHORE_DOWN(sem, YES); /* fails by blocking */
- if (SEMAPHORE_DOWN(sem, NO) != SYSERR) {
- SEMAPHORE_DESTROY(sem);
- printf("SEMAPHORE_DOWN_NONBLOCKING failed at %s:%u\n"
- "Testcase deadlocked.\n",
- __FILE__, __LINE__);
- return NULL; /* will halt testcase! */
- }
- for (i=0;i<42;i++)
- SEMAPHORE_UP(sem);
+ for (i = 0; i < 42; i++)
+ SEMAPHORE_DOWN (sem, YES); /* fails by blocking */
+ if (SEMAPHORE_DOWN (sem, NO) != SYSERR)
+ {
+ SEMAPHORE_DESTROY (sem);
+ printf ("SEMAPHORE_DOWN_NONBLOCKING failed at %s:%u\n"
+ "Testcase deadlocked.\n", __FILE__, __LINE__);
+ return NULL; /* will halt testcase! */
+ }
+ for (i = 0; i < 42; i++)
+ SEMAPHORE_UP (sem);
return NULL;
}
-static int testSemaphore() {
+static int
+testSemaphore ()
+{
int i;
- struct PTHREAD * pt;
- void * unused;
+ struct PTHREAD *pt;
+ void *unused;
- sem = SEMAPHORE_CREATE(42);
- for (i=0;i<42;i++)
- SEMAPHORE_DOWN(sem, YES); /* fails by blocking */
- if (SEMAPHORE_DOWN(sem, NO) != SYSERR) {
- SEMAPHORE_DESTROY(sem);
- printf("SEMAPHORE_DOWN_NONBLOCKING failed at %s:%u\n",
- __FILE__, __LINE__);
- return 1;
- }
- for (i=0;i<42;i++)
- SEMAPHORE_UP(sem);
- for (i=0;i<42;i++)
- if (SYSERR == SEMAPHORE_DOWN(sem, NO)) {
- SEMAPHORE_DESTROY(sem);
- printf("SEMAPHORE_DOWN_NONBLOCKING failed at %s:%u iteration %d\n",
- __FILE__, __LINE__, i);
+ sem = SEMAPHORE_CREATE (42);
+ for (i = 0; i < 42; i++)
+ SEMAPHORE_DOWN (sem, YES); /* fails by blocking */
+ if (SEMAPHORE_DOWN (sem, NO) != SYSERR)
+ {
+ SEMAPHORE_DESTROY (sem);
+ printf ("SEMAPHORE_DOWN_NONBLOCKING failed at %s:%u\n",
+ __FILE__, __LINE__);
return 1;
}
- if (SEMAPHORE_DOWN(sem, NO) != SYSERR) {
- SEMAPHORE_DESTROY(sem);
- printf("SEMAPHORE_DOWN_NONBLOCKING failed at %s:%u\n",
- __FILE__, __LINE__);
- return 1;
- }
- pt = PTHREAD_CREATE(&semUpDown,
- NULL,
- 1024);
- for (i=0;i<42;i++)
- SEMAPHORE_UP(sem);
- PTHREAD_JOIN(pt, &unused);
- for (i=0;i<42;i++)
- SEMAPHORE_DOWN(sem, YES);
- if (SEMAPHORE_DOWN(sem, NO) != SYSERR) {
- SEMAPHORE_DESTROY(sem);
- printf("SEMAPHORE_DOWN_NONBLOCKING failed at %s:%u\n",
- __FILE__, __LINE__);
- return 1;
- }
+ for (i = 0; i < 42; i++)
+ SEMAPHORE_UP (sem);
+ for (i = 0; i < 42; i++)
+ if (SYSERR == SEMAPHORE_DOWN (sem, NO))
+ {
+ SEMAPHORE_DESTROY (sem);
+ printf ("SEMAPHORE_DOWN_NONBLOCKING failed at %s:%u iteration %d\n",
+ __FILE__, __LINE__, i);
+ return 1;
+ }
+ if (SEMAPHORE_DOWN (sem, NO) != SYSERR)
+ {
+ SEMAPHORE_DESTROY (sem);
+ printf ("SEMAPHORE_DOWN_NONBLOCKING failed at %s:%u\n",
+ __FILE__, __LINE__);
+ return 1;
+ }
+ pt = PTHREAD_CREATE (&semUpDown, NULL, 1024);
+ for (i = 0; i < 42; i++)
+ SEMAPHORE_UP (sem);
+ PTHREAD_JOIN (pt, &unused);
+ for (i = 0; i < 42; i++)
+ SEMAPHORE_DOWN (sem, YES);
+ if (SEMAPHORE_DOWN (sem, NO) != SYSERR)
+ {
+ SEMAPHORE_DESTROY (sem);
+ printf ("SEMAPHORE_DOWN_NONBLOCKING failed at %s:%u\n",
+ __FILE__, __LINE__);
+ return 1;
+ }
return 0;
}
-int main(int argc,
- char * argv[]){
+int
+main (int argc, char *argv[])
+{
int ret = 0;
- ret += testPTHREAD_CREATE();
- ret += testMutex();
- ret += testRecursiveMutex();
- ret += testSemaphore();
+ ret += testPTHREAD_CREATE ();
+ ret += testMutex ();
+ ret += testRecursiveMutex ();
+ ret += testSemaphore ();
return ret;
}
Modified: GNUnet/src/util/threads/shutdown.c
===================================================================
--- GNUnet/src/util/threads/shutdown.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/threads/shutdown.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -35,32 +35,40 @@
/**
* Semaphore used to signal "shutdown"
*/
-static struct SEMAPHORE * shutdown_signal;
+static struct SEMAPHORE *shutdown_signal;
static int shutdown_active;
-static struct SignalHandlerContext * shc_int;
+static struct SignalHandlerContext *shc_int;
-static struct SignalHandlerContext * shc_term;
+static struct SignalHandlerContext *shc_term;
-static struct SignalHandlerContext * shc_quit;
+static struct SignalHandlerContext *shc_quit;
-void GNUNET_SHUTDOWN_INITIATE() {
- GE_ASSERT(NULL, shutdown_signal != NULL);
+void
+GNUNET_SHUTDOWN_INITIATE ()
+{
+ GE_ASSERT (NULL, shutdown_signal != NULL);
shutdown_active = YES;
- SEMAPHORE_UP(shutdown_signal);
+ SEMAPHORE_UP (shutdown_signal);
}
-int GNUNET_SHUTDOWN_TEST() {
+int
+GNUNET_SHUTDOWN_TEST ()
+{
return shutdown_active;
}
-void GNUNET_SHUTDOWN_WAITFOR() {
- SEMAPHORE_DOWN(shutdown_signal, YES);
+void
+GNUNET_SHUTDOWN_WAITFOR ()
+{
+ SEMAPHORE_DOWN (shutdown_signal, YES);
}
-static void run_shutdown() {
- GNUNET_SHUTDOWN_INITIATE();
+static void
+run_shutdown ()
+{
+ GNUNET_SHUTDOWN_INITIATE ();
}
/**
@@ -68,17 +76,18 @@
* @param dwCtrlType is ignored
*/
#ifdef MINGW
-BOOL WINAPI run_shutdown_win(DWORD dwCtrlType)
+BOOL WINAPI
+run_shutdown_win (DWORD dwCtrlType)
{
- switch(dwCtrlType)
- {
+ switch (dwCtrlType)
+ {
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_SHUTDOWN_EVENT:
case CTRL_LOGOFF_EVENT:
case SERVICE_CONTROL_STOP:
- GNUNET_SHUTDOWN_INITIATE();
- }
+ GNUNET_SHUTDOWN_INITIATE ();
+ }
return TRUE;
}
@@ -87,28 +96,30 @@
/**
* Initialize the signal handlers, etc.
*/
-void __attribute__ ((constructor)) shutdown_handlers_ltdl_init() {
- GE_ASSERT(NULL, shutdown_signal == NULL);
- GE_ASSERT(NULL, shutdown_active == NO);
- shutdown_signal = SEMAPHORE_CREATE(0);
+void __attribute__ ((constructor)) shutdown_handlers_ltdl_init ()
+{
+ GE_ASSERT (NULL, shutdown_signal == NULL);
+ GE_ASSERT (NULL, shutdown_active == NO);
+ shutdown_signal = SEMAPHORE_CREATE (0);
#ifndef MINGW
- shc_int = signal_handler_install(SIGINT, &run_shutdown);
- shc_term = signal_handler_install(SIGTERM, &run_shutdown);
- shc_quit = signal_handler_install(SIGQUIT, &run_shutdown);
+ shc_int = signal_handler_install (SIGINT, &run_shutdown);
+ shc_term = signal_handler_install (SIGTERM, &run_shutdown);
+ shc_quit = signal_handler_install (SIGQUIT, &run_shutdown);
#else
- SetConsoleCtrlHandler(&run_shutdown_win, TRUE);
+ SetConsoleCtrlHandler (&run_shutdown_win, TRUE);
#endif
}
-void __attribute__ ((destructor)) shutdown_handlers_ltdl_fini() {
+void __attribute__ ((destructor)) shutdown_handlers_ltdl_fini ()
+{
#ifndef MINGW
- signal_handler_uninstall(SIGINT, &run_shutdown, shc_int);
- signal_handler_uninstall(SIGTERM, &run_shutdown, shc_term);
- signal_handler_uninstall(SIGQUIT, &run_shutdown, shc_quit);
+ signal_handler_uninstall (SIGINT, &run_shutdown, shc_int);
+ signal_handler_uninstall (SIGTERM, &run_shutdown, shc_term);
+ signal_handler_uninstall (SIGQUIT, &run_shutdown, shc_quit);
#else
- SetConsoleCtrlHandler(&run_shutdown_win, FALSE);
+ SetConsoleCtrlHandler (&run_shutdown_win, FALSE);
#endif
- SEMAPHORE_DESTROY(shutdown_signal);
+ SEMAPHORE_DESTROY (shutdown_signal);
shutdown_signal = NULL;
shc_int = NULL;
shc_term = NULL;
Modified: GNUnet/src/util/threads/shutdowntest.c
===================================================================
--- GNUnet/src/util/threads/shutdowntest.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/threads/shutdowntest.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -26,21 +26,24 @@
#include "gnunet_util.h"
#include "platform.h"
-static int check() {
- if (GNUNET_SHUTDOWN_TEST() != NO)
+static int
+check ()
+{
+ if (GNUNET_SHUTDOWN_TEST () != NO)
return 1;
- GNUNET_SHUTDOWN_INITIATE();
- if (GNUNET_SHUTDOWN_TEST() != YES)
+ GNUNET_SHUTDOWN_INITIATE ();
+ if (GNUNET_SHUTDOWN_TEST () != YES)
return 2;
- GNUNET_SHUTDOWN_WAITFOR();
+ GNUNET_SHUTDOWN_WAITFOR ();
return 0;
}
-int main(int argc,
- char * argv[]){
+int
+main (int argc, char *argv[])
+{
int ret;
- ret = check();
+ ret = check ();
return ret;
}
Modified: GNUnet/src/util/threads/shutdowntest2.c
===================================================================
--- GNUnet/src/util/threads/shutdowntest2.c 2007-07-10 04:03:47 UTC (rev
5294)
+++ GNUnet/src/util/threads/shutdowntest2.c 2007-07-10 08:36:37 UTC (rev
5295)
@@ -26,25 +26,28 @@
#include "gnunet_util.h"
#include "platform.h"
-static int check() {
- if (GNUNET_SHUTDOWN_TEST() != NO)
+static int
+check ()
+{
+ if (GNUNET_SHUTDOWN_TEST () != NO)
return 1;
#ifndef MINGW
- kill(getpid(), SIGINT);
+ kill (getpid (), SIGINT);
#else
- GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
+ GenerateConsoleCtrlEvent (CTRL_C_EVENT, 0);
#endif
- if (GNUNET_SHUTDOWN_TEST() != YES)
+ if (GNUNET_SHUTDOWN_TEST () != YES)
return 2;
- GNUNET_SHUTDOWN_WAITFOR();
+ GNUNET_SHUTDOWN_WAITFOR ();
return 0;
}
-int main(int argc,
- char * argv[]){
+int
+main (int argc, char *argv[])
+{
int ret;
- ret = check();
+ ret = check ();
return ret;
}
Modified: GNUnet/src/util/threads/signal.c
===================================================================
--- GNUnet/src/util/threads/signal.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/threads/signal.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -29,7 +29,8 @@
#include "platform.h"
#ifndef MINGW
-typedef struct SignalHandlerContext {
+typedef struct SignalHandlerContext
+{
int sig;
SignalHandler method;
@@ -37,34 +38,37 @@
struct sigaction oldsig;
} SignalHandlerContext;
-struct SignalHandlerContext * signal_handler_install(int signal,
- SignalHandler handler) {
- struct SignalHandlerContext * ret;
+struct SignalHandlerContext *
+signal_handler_install (int signal, SignalHandler handler)
+{
+ struct SignalHandlerContext *ret;
struct sigaction sig;
- ret = MALLOC(sizeof(struct SignalHandlerContext));
+ ret = MALLOC (sizeof (struct SignalHandlerContext));
ret->sig = signal;
ret->method = handler;
- sig.sa_handler = (void*) handler;
- sigemptyset(&sig.sa_mask);
+ sig.sa_handler = (void *) handler;
+ sigemptyset (&sig.sa_mask);
#ifdef SA_INTERRUPT
- sig.sa_flags = SA_INTERRUPT; /* SunOS */
+ sig.sa_flags = SA_INTERRUPT; /* SunOS */
#else
sig.sa_flags = SA_RESTART;
#endif
- sigaction(signal, &sig, &ret->oldsig);
+ sigaction (signal, &sig, &ret->oldsig);
return ret;
}
-void signal_handler_uninstall(int signal,
- SignalHandler handler,
- struct SignalHandlerContext * ctx) {
+void
+signal_handler_uninstall (int signal,
+ SignalHandler handler,
+ struct SignalHandlerContext *ctx)
+{
struct sigaction sig;
- GE_ASSERT(NULL, (ctx->sig == signal) && (ctx->method == handler));
- sigemptyset(&sig.sa_mask);
- sigaction(signal, &ctx->oldsig, &sig);
- FREE(ctx);
+ GE_ASSERT (NULL, (ctx->sig == signal) && (ctx->method == handler));
+ sigemptyset (&sig.sa_mask);
+ sigaction (signal, &ctx->oldsig, &sig);
+ FREE (ctx);
}
#endif
Modified: GNUnet/src/util/threads/time.c
===================================================================
--- GNUnet/src/util/threads/time.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/threads/time.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -32,15 +32,17 @@
*
* @return the current time
*/
-cron_t get_time() {
+cron_t
+get_time ()
+{
struct timeval tv;
#ifndef WINDOWS
- struct timezone tz; /* man page says it's obsolete, but
- I'd rather not pass a NULL pointer */
+ struct timezone tz; /* man page says it's obsolete, but
+ I'd rather not pass a NULL pointer */
- gettimeofday(&tv, &tz);
+ gettimeofday (&tv, &tz);
#else
- gettimeofday(&tv, NULL);
+ gettimeofday (&tv, NULL);
#endif
- return (((cron_t)tv.tv_sec) * 1000) + (tv.tv_usec / 1000);
+ return (((cron_t) tv.tv_sec) * 1000) + (tv.tv_usec / 1000);
}
Modified: GNUnet/src/util/threads/timertest.c
===================================================================
--- GNUnet/src/util/threads/timertest.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/threads/timertest.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -29,7 +29,9 @@
#define VERBOSE NO
-static int check() {
+static int
+check ()
+{
cron_t now;
cron_t last;
TIME_T tnow;
@@ -41,57 +43,54 @@
increasing;
measure precision of sleep and report;
test that sleep is interrupted by signals; */
- last = now = get_time();
+ last = now = get_time ();
while (now == last)
- now = get_time();
+ now = get_time ();
if (now < last)
return 1;
- tnow = tlast = TIME(NULL);
+ tnow = tlast = TIME (NULL);
while (tnow == tlast)
- tnow = TIME(NULL);
+ tnow = TIME (NULL);
if (tnow < tlast)
return 2;
cumDelta = 0;
#define INCR 47
#define MAXV 1500
- for (i=0;i<MAXV;i+=INCR) {
- last = get_time();
- PTHREAD_SLEEP(cronMILLIS * i);
- now = get_time();
+ for (i = 0; i < MAXV; i += INCR)
+ {
+ last = get_time ();
+ PTHREAD_SLEEP (cronMILLIS * i);
+ now = get_time ();
#if VERBOSE
- fprintf(stderr,
- "%4llu ms requested, got: %4llu ms\n",
- i * cronMILLIS,
- (now - last));
+ fprintf (stderr,
+ "%4llu ms requested, got: %4llu ms\n",
+ i * cronMILLIS, (now - last));
#endif
- if (last + cronMILLIS * i < now)
- cumDelta += (now - (last+cronMILLIS*i));
- else
- cumDelta += ((last+cronMILLIS*i) - now);
- }
- FPRINTF(stdout,
- "Sleep precision: %llu ms. ",
- cumDelta / cronMILLIS / (MAXV/INCR));
+ if (last + cronMILLIS * i < now)
+ cumDelta += (now - (last + cronMILLIS * i));
+ else
+ cumDelta += ((last + cronMILLIS * i) - now);
+ }
+ FPRINTF (stdout,
+ "Sleep precision: %llu ms. ",
+ cumDelta / cronMILLIS / (MAXV / INCR));
if (cumDelta <= 10 * cronMILLIS * MAXV / INCR)
- fprintf(stdout,
- "Timer precision is excellent.\n");
- else if (cumDelta <= 50 * cronMILLIS * MAXV / INCR) /* 50 ms average
deviation */
- fprintf(stdout,
- "Timer precision is good.\n");
+ fprintf (stdout, "Timer precision is excellent.\n");
+ else if (cumDelta <= 50 * cronMILLIS * MAXV / INCR) /* 50 ms average
deviation */
+ fprintf (stdout, "Timer precision is good.\n");
else if (cumDelta > 250 * cronMILLIS * MAXV / INCR)
- fprintf(stdout,
- "Timer precision is awful.\n");
+ fprintf (stdout, "Timer precision is awful.\n");
else
- fprintf(stdout,
- "Timer precision is acceptable.\n");
+ fprintf (stdout, "Timer precision is acceptable.\n");
return 0;
}
-int main(int argc,
- char * argv[]){
+int
+main (int argc, char *argv[])
+{
int ret;
- ret = check();
+ ret = check ();
return ret;
}
Modified: GNUnet/src/util/win/winproc.c
===================================================================
--- GNUnet/src/util/win/winproc.c 2007-07-10 04:03:47 UTC (rev 5294)
+++ GNUnet/src/util/win/winproc.c 2007-07-10 08:36:37 UTC (rev 5295)
@@ -70,13 +70,16 @@
/**
* Log (panic) messages from PlibC
*/
-void plibc_panic(int err, char *msg)
+void
+plibc_panic (int err, char *msg)
{
if (!pEctx)
- fprintf(stderr, "%s", msg);
+ fprintf (stderr, "%s", msg);
else
- GE_LOG(pEctx, ((err == INT_MAX) ? GE_DEBUG : GE_FATAL) | GE_USER |
GE_ADMIN |
- GE_IMMEDIATE, "%s", msg);
+ GE_LOG (pEctx,
+ ((err ==
+ INT_MAX) ? GE_DEBUG : GE_FATAL) | GE_USER | GE_ADMIN |
+ GE_IMMEDIATE, "%s", msg);
}
/**
@@ -84,155 +87,150 @@
* @param logging context, NULL means stderr
* @return Error code from winerror.h, ERROR_SUCCESS on success
*/
-int InitWinEnv(struct GE_Context *ectx)
+int
+InitWinEnv (struct GE_Context *ectx)
{
int ret, init;
if (ectx)
pEctx = ectx;
- init = plibc_initialized();
- plibc_set_panic_proc(plibc_panic);
- ret = plibc_init("GNU", PACKAGE);
+ init = plibc_initialized ();
+ plibc_set_panic_proc (plibc_panic);
+ ret = plibc_init ("GNU", PACKAGE);
/* don't load other DLLs twice */
if (init)
return ret;
- hNTDLL = LoadLibrary("ntdll.dll");
+ hNTDLL = LoadLibrary ("ntdll.dll");
/* Function to get CPU usage under Win NT */
if (hNTDLL)
- {
- GNNtQuerySystemInformation = (TNtQuerySystemInformation)
- GetProcAddress(hNTDLL, "NtQuerySystemInformation");
- }
+ {
+ GNNtQuerySystemInformation = (TNtQuerySystemInformation)
+ GetProcAddress (hNTDLL, "NtQuerySystemInformation");
+ }
else
- {
- GNNtQuerySystemInformation = NULL;
- }
+ {
+ GNNtQuerySystemInformation = NULL;
+ }
/* Functions to get information about a network adapter */
- hIphlpapi = LoadLibrary("iphlpapi.dll");
+ hIphlpapi = LoadLibrary ("iphlpapi.dll");
if (hIphlpapi)
- {
- GNGetIfEntry = (TGetIfEntry) GetProcAddress(hIphlpapi, "GetIfEntry");
- GNGetIpAddrTable = (TGetIpAddrTable) GetProcAddress(hIphlpapi,
- "GetIpAddrTable");
- GNGetIfTable = (TGetIfTable) GetProcAddress(hIphlpapi, "GetIfTable");
- GNGetBestInterface = (TGetBestInterface) GetProcAddress(hIphlpapi,
- "GetBestInterface");
- GGetAdaptersInfo = (TGetAdaptersInfo) GetProcAddress(hIphlpapi,
- "GetAdaptersInfo");
- }
+ {
+ GNGetIfEntry = (TGetIfEntry) GetProcAddress (hIphlpapi, "GetIfEntry");
+ GNGetIpAddrTable = (TGetIpAddrTable) GetProcAddress (hIphlpapi,
+ "GetIpAddrTable");
+ GNGetIfTable = (TGetIfTable) GetProcAddress (hIphlpapi, "GetIfTable");
+ GNGetBestInterface = (TGetBestInterface) GetProcAddress (hIphlpapi,
+
"GetBestInterface");
+ GGetAdaptersInfo = (TGetAdaptersInfo) GetProcAddress (hIphlpapi,
+ "GetAdaptersInfo");
+ }
else
- {
- GNGetIfEntry = NULL;
- GNGetIpAddrTable = NULL;
- GNGetIfTable = NULL;
- GNGetBestInterface = NULL;
- GGetAdaptersInfo = NULL;
- }
+ {
+ GNGetIfEntry = NULL;
+ GNGetIpAddrTable = NULL;
+ GNGetIfTable = NULL;
+ GNGetBestInterface = NULL;
+ GGetAdaptersInfo = NULL;
+ }
/* Service & Account functions */
- hAdvapi = LoadLibrary("advapi32.dll");
+ hAdvapi = LoadLibrary ("advapi32.dll");
if (hAdvapi)
- {
- GNOpenSCManager = (TOpenSCManager)
- GetProcAddress(hAdvapi, "OpenSCManagerA");
- GNCreateService = (TCreateService)
- GetProcAddress(hAdvapi, "CreateServiceA");
- GNCloseServiceHandle = (TCloseServiceHandle)
- GetProcAddress(hAdvapi, "CloseServiceHandle");
- GNDeleteService = (TDeleteService)
- GetProcAddress(hAdvapi, "DeleteService");
- GNRegisterServiceCtrlHandler = (TRegisterServiceCtrlHandler)
- GetProcAddress(hAdvapi, "RegisterServiceCtrlHandlerA");
- GNSetServiceStatus = (TSetServiceStatus)
- GetProcAddress(hAdvapi, "SetServiceStatus");
- GNStartServiceCtrlDispatcher = (TStartServiceCtrlDispatcher)
- GetProcAddress(hAdvapi, "StartServiceCtrlDispatcherA");
- GNControlService = (TControlService)
- GetProcAddress(hAdvapi, "ControlService");
- GNOpenService = (TOpenService)
- GetProcAddress(hAdvapi, "OpenServiceA");
+ {
+ GNOpenSCManager = (TOpenSCManager)
+ GetProcAddress (hAdvapi, "OpenSCManagerA");
+ GNCreateService = (TCreateService)
+ GetProcAddress (hAdvapi, "CreateServiceA");
+ GNCloseServiceHandle = (TCloseServiceHandle)
+ GetProcAddress (hAdvapi, "CloseServiceHandle");
+ GNDeleteService = (TDeleteService)
+ GetProcAddress (hAdvapi, "DeleteService");
+ GNRegisterServiceCtrlHandler = (TRegisterServiceCtrlHandler)
+ GetProcAddress (hAdvapi, "RegisterServiceCtrlHandlerA");
+ GNSetServiceStatus = (TSetServiceStatus)
+ GetProcAddress (hAdvapi, "SetServiceStatus");
+ GNStartServiceCtrlDispatcher = (TStartServiceCtrlDispatcher)
+ GetProcAddress (hAdvapi, "StartServiceCtrlDispatcherA");
+ GNControlService = (TControlService)
+ GetProcAddress (hAdvapi, "ControlService");
+ GNOpenService = (TOpenService) GetProcAddress (hAdvapi, "OpenServiceA");
- GNLsaOpenPolicy = (TLsaOpenPolicy)
- GetProcAddress(hAdvapi, "LsaOpenPolicy");
- GNLsaAddAccountRights = (TLsaAddAccountRights)
- GetProcAddress(hAdvapi, "LsaAddAccountRights");
- GNLsaRemoveAccountRights = (TLsaRemoveAccountRights)
- GetProcAddress(hAdvapi, "LsaRemoveAccountRights");
- GNLsaClose = (TLsaClose)
- GetProcAddress(hAdvapi, "LsaClose");
- GNLookupAccountName = (TLookupAccountName)
- GetProcAddress(hAdvapi, "LookupAccountNameA");
+ GNLsaOpenPolicy = (TLsaOpenPolicy)
+ GetProcAddress (hAdvapi, "LsaOpenPolicy");
+ GNLsaAddAccountRights = (TLsaAddAccountRights)
+ GetProcAddress (hAdvapi, "LsaAddAccountRights");
+ GNLsaRemoveAccountRights = (TLsaRemoveAccountRights)
+ GetProcAddress (hAdvapi, "LsaRemoveAccountRights");
+ GNLsaClose = (TLsaClose) GetProcAddress (hAdvapi, "LsaClose");
+ GNLookupAccountName = (TLookupAccountName)
+ GetProcAddress (hAdvapi, "LookupAccountNameA");
- GNGetFileSecurity = (TGetFileSecurity)
- GetProcAddress(hAdvapi, "GetFileSecurityA");
- GNInitializeSecurityDescriptor = (TInitializeSecurityDescriptor)
- GetProcAddress(hAdvapi, "InitializeSecurityDescriptor");
- GNGetSecurityDescriptorDacl = (TGetSecurityDescriptorDacl)
- GetProcAddress(hAdvapi, "GetSecurityDescriptorDacl");
- GNGetAclInformation = (TGetAclInformation)
- GetProcAddress(hAdvapi, "GetAclInformation");
- GNInitializeAcl = (TInitializeAcl)
- GetProcAddress(hAdvapi, "InitializeAcl");
- GNGetAce = (TGetAce)
- GetProcAddress(hAdvapi, "GetAce");
- GNEqualSid = (TEqualSid)
- GetProcAddress(hAdvapi, "EqualSid");
- GNAddAce = (TAddAce)
- GetProcAddress(hAdvapi, "AddAce");
- GNAddAccessAllowedAce = (TAddAccessAllowedAce)
- GetProcAddress(hAdvapi, "AddAccessAllowedAce");
- GNSetNamedSecurityInfo = (TSetNamedSecurityInfo)
- GetProcAddress(hAdvapi, "SetNamedSecurityInfoA");
- }
+ GNGetFileSecurity = (TGetFileSecurity)
+ GetProcAddress (hAdvapi, "GetFileSecurityA");
+ GNInitializeSecurityDescriptor = (TInitializeSecurityDescriptor)
+ GetProcAddress (hAdvapi, "InitializeSecurityDescriptor");
+ GNGetSecurityDescriptorDacl = (TGetSecurityDescriptorDacl)
+ GetProcAddress (hAdvapi, "GetSecurityDescriptorDacl");
+ GNGetAclInformation = (TGetAclInformation)
+ GetProcAddress (hAdvapi, "GetAclInformation");
+ GNInitializeAcl = (TInitializeAcl)
+ GetProcAddress (hAdvapi, "InitializeAcl");
+ GNGetAce = (TGetAce) GetProcAddress (hAdvapi, "GetAce");
+ GNEqualSid = (TEqualSid) GetProcAddress (hAdvapi, "EqualSid");
+ GNAddAce = (TAddAce) GetProcAddress (hAdvapi, "AddAce");
+ GNAddAccessAllowedAce = (TAddAccessAllowedAce)
+ GetProcAddress (hAdvapi, "AddAccessAllowedAce");
+ GNSetNamedSecurityInfo = (TSetNamedSecurityInfo)
+ GetProcAddress (hAdvapi, "SetNamedSecurityInfoA");
+ }
else
- {
- GNOpenSCManager = NULL;
- GNCreateService = NULL;
- GNCloseServiceHandle = NULL;
- GNDeleteService = NULL;
- GNRegisterServiceCtrlHandler = NULL;
- GNSetServiceStatus = NULL;
- GNStartServiceCtrlDispatcher = NULL;
- GNControlService = NULL;
- GNOpenService = NULL;
+ {
+ GNOpenSCManager = NULL;
+ GNCreateService = NULL;
+ GNCloseServiceHandle = NULL;
+ GNDeleteService = NULL;
+ GNRegisterServiceCtrlHandler = NULL;
+ GNSetServiceStatus = NULL;
+ GNStartServiceCtrlDispatcher = NULL;
+ GNControlService = NULL;
+ GNOpenService = NULL;
- GNLsaOpenPolicy = NULL;
- GNLsaAddAccountRights = NULL;
- GNLsaRemoveAccountRights = NULL;
- GNLsaClose = NULL;
- GNLookupAccountName = NULL;
+ GNLsaOpenPolicy = NULL;
+ GNLsaAddAccountRights = NULL;
+ GNLsaRemoveAccountRights = NULL;
+ GNLsaClose = NULL;
+ GNLookupAccountName = NULL;
- GNGetFileSecurity = NULL;
- GNInitializeSecurityDescriptor = NULL;
- GNGetSecurityDescriptorDacl = NULL;
- GNGetAclInformation = NULL;
- GNInitializeAcl = NULL;
- GNGetAce = NULL;
- GNEqualSid = NULL;
- GNAddAce = NULL;
- GNAddAccessAllowedAce = NULL;
- GNSetNamedSecurityInfo = NULL;
- }
+ GNGetFileSecurity = NULL;
+ GNInitializeSecurityDescriptor = NULL;
+ GNGetSecurityDescriptorDacl = NULL;
+ GNGetAclInformation = NULL;
+ GNInitializeAcl = NULL;
+ GNGetAce = NULL;
+ GNEqualSid = NULL;
+ GNAddAce = NULL;
+ GNAddAccessAllowedAce = NULL;
+ GNSetNamedSecurityInfo = NULL;
+ }
/* Account function */
- hNetapi = LoadLibrary("netapi32.dll");
+ hNetapi = LoadLibrary ("netapi32.dll");
if (hNetapi)
- {
- GNNetUserAdd = (TNetUserAdd)
- GetProcAddress(hNetapi, "NetUserAdd");
- GNNetUserSetInfo = (TNetUserSetInfo)
- GetProcAddress(hNetapi, "NetUserSetInfo");
- }
+ {
+ GNNetUserAdd = (TNetUserAdd) GetProcAddress (hNetapi, "NetUserAdd");
+ GNNetUserSetInfo = (TNetUserSetInfo)
+ GetProcAddress (hNetapi, "NetUserSetInfo");
+ }
else
- {
- GNNetUserAdd = NULL;
- GNNetUserSetInfo = NULL;
- }
+ {
+ GNNetUserAdd = NULL;
+ GNNetUserSetInfo = NULL;
+ }
return ret;
}
@@ -240,16 +238,17 @@
/**
* Clean up Windows environment
*/
-void ShutdownWinEnv()
+void
+ShutdownWinEnv ()
{
- plibc_shutdown();
+ plibc_shutdown ();
- FreeLibrary(hNTDLL);
- FreeLibrary(hIphlpapi);
- FreeLibrary(hAdvapi);
- FreeLibrary(hNetapi);
+ FreeLibrary (hNTDLL);
+ FreeLibrary (hIphlpapi);
+ FreeLibrary (hAdvapi);
+ FreeLibrary (hNetapi);
- CoUninitialize();
+ CoUninitialize ();
pEctx = NULL;
}
@@ -257,8 +256,9 @@
#endif /* MINGW */
#if !HAVE_ATOLL
-long long atoll(const char *nptr)
+long long
+atoll (const char *nptr)
{
- return atol(nptr);
+ return atol (nptr);
}
#endif
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- [GNUnet-SVN] r5295 - in GNUnet: . libltdl src/applications/advertising src/applications/bootstrap_http src/applications/chat src/applications/datastore src/applications/dht/module src/applications/dht/tools src/applications/dstore src/applications/fragmentation src/applications/fs src/applications/fs/collection src/applications/fs/ecrs src/applications/fs/fsui src/applications/fs/lib src/applications/fs/module src/applications/fs/namespace src/applications/fs/tools src/applications/fs/uritrack src/applications/gap src/applications/getoption src/applications/identity src/applications/kvstore_sqlite src/applications/pingpong src/applications/rpc src/applications/session src/applications/sqstore_mysql src/applications/sqstore_mysql_embedded src/applications/sqstore_sqlite src/applications/state src/applications/stats src/applications/tbench src/applications/template src/applications/testbed src/applications/testing src/applications/topology_default src/applications/topology_f2f src/applications/tracekit src/applications/traffic src/applications/transport src/applications/vpn src/include src/server src/setup src/setup/gtk src/setup/lib src/setup/ncurses src/setup/text src/transports src/transports/upnp src/util/boot src/util/config src/util/config_impl src/util/containers src/util/cron src/util/crypto src/util/disk src/util/error src/util/getopt src/util/loggers src/util/network src/util/network_client src/util/os src/util/string src/util/threads src/util/win,
gnunet <=