#define _POSIX_C_SOURCE 200809L #include "cst_discover.h" #include "cst_realm.h" #include "cst_test_util.h" #include "os_compat.h" #include #include #include #include #include static int wait_peer(cst_discover_t *d, const char *want_iid, int ms) { cst_peer_info_t peers[8]; for (int t = 0; t < ms; t += 50) { int n = cst_discover_peers(d, peers, 8); for (int i = 0; i < n; i++) { if (!strcmp(peers[i].instance_id, want_iid) && peers[i].port > 0) return 1; } struct timespec ts = {0, 50 * 1000 * 1000}; nanosleep(&ts, NULL); } return 0; } int main(void) { char dir[2048]; assert(!test_tmpdir(dir, sizeof(dir), "discover")); /* Point config at tmp so local-instances.json is isolated. */ char cfg[512]; assert(snprintf(cfg, sizeof(cfg), "%s/cfg", dir) < (int)sizeof(cfg)); assert(!os_mkdir_p(cfg, 0700)); setenv("XDG_CONFIG_HOME", cfg, 1); cst_realm_keys_t realm; assert(cst_realm_generate(&realm) == 0); char rid[33]; assert(cst_realm_fingerprint(realm.pk, rid) == 0); assert(cst_discover_local_put(rid, "a", "alpha", 9101) == 0); assert(cst_discover_local_put(rid, "b", "beta", 9102) == 0); cst_peer_info_t list[8]; int n = cst_discover_local_list(rid, list, 8); assert(n == 2); cst_discover_t *da = cst_discover_start(rid, "a", "alpha", 9101); cst_discover_t *db = cst_discover_start(rid, "b", "beta", 9102); assert(da && db); assert(wait_peer(da, "b", 3000)); assert(wait_peer(db, "a", 3000)); cst_realm_keys_t other; assert(cst_realm_generate(&other) == 0); char other_rid[33]; assert(cst_realm_fingerprint(other.pk, other_rid) == 0); cst_discover_t *dc = cst_discover_start(other_rid, "c", "gamma", 9103); assert(dc); /* Foreign realm must not appear in same-realm peer lists. */ assert(!wait_peer(da, "c", 800)); assert(wait_peer(dc, "c", 200) == 0); /* self excluded */ cst_discover_stop(dc); cst_discover_stop(db); cst_discover_stop(da); test_rmrf(dir); puts("test_discover: OK"); return 0; }