/* Serval Distributed Numbering Architecture (DNA) Copyright (C) 2010-2012 Paul Gardner-Stephen This program 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 of the License, or (at your option) any later version. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define _GNU_SOURCE // For asprintf() #include #include #include #include #include #include #include #include #include #ifdef HAVE_JNI_H #include #endif #include "serval.h" #include "rhizome.h" /** Return the PID of the currently running server process, return 0 if there is none. */ static int servalNodeRunning() { const char *instancepath = serval_instancepath(); struct stat st; if (stat(instancepath, &st) == -1) return setReason( "Instance path '%s' non existant or not accessable: %s [errno=%d]" " (Set SERVALINSTANCE_PATH to specify an alternate location)", instancepath, strerror(errno), errno ); if ((st.st_mode & S_IFMT) != S_IFDIR) return setReason("Instance path '%s' is not a directory", instancepath); char filename[1024]; if (!FORM_SERVAL_INSTANCE_PATH(filename, "serval.pid")) return -1; FILE *f = NULL; if ((f = fopen(filename, "r"))) { char buf[20]; fgets(buf, sizeof buf, f); fclose(f); int pid = atoi(buf); if (pid > 0 && kill(pid, 0) != -1) return pid; unlink(filename); } return 0; } int cli_usage() { fprintf(stderr,"\nServal Mesh version .\n"); fprintf(stderr,"Usage:\n"); int i,j; for(i=0;command_line_options[i].function;i++) { for(j=0;command_line_options[i].words[j];j++) fprintf(stderr," %s",command_line_options[i].words[j]); fprintf(stderr,"\n %s\n",command_line_options[i].description); } return -1; } /* Data structures for accumulating output of a single JNI call. */ #ifdef HAVE_JNI_H #define OUTV_BUFFER_ALLOCSIZE (8192) JNIEnv *jni_env = NULL; int jni_exception = 0; jobject outv_list = NULL; jmethodID listAddMethodId = NULL; char *outv_buffer = NULL; char *outv_current = NULL; char *outv_limit = NULL; static int outv_growbuf(size_t needed) { size_t newsize = (outv_limit - outv_current < needed) ? (outv_limit - outv_buffer) + needed : 0; if (newsize) { // Round up to nearest multiple of OUTV_BUFFER_ALLOCSIZE. newsize = newsize + OUTV_BUFFER_ALLOCSIZE - ((newsize - 1) % OUTV_BUFFER_ALLOCSIZE + 1); size_t length = outv_current - outv_buffer; outv_buffer = realloc(outv_buffer, newsize); if (outv_buffer == NULL) return WHYF("Out of memory allocating %lu bytes", (unsigned long) newsize); outv_current = outv_buffer + length; outv_limit = outv_buffer + newsize; } return 0; } static int outv_end_field() { outv_growbuf(1); *outv_current++ = '\0'; jstring str = (jstring)(*jni_env)->NewStringUTF(jni_env, outv_buffer); outv_current = outv_buffer; if (str == NULL) { jni_exception = 1; return WHY("Exception thrown from NewStringUTF()"); } (*jni_env)->CallBooleanMethod(jni_env, outv_list, listAddMethodId, str); if ((*jni_env)->ExceptionOccurred(jni_env)) { jni_exception = 1; return WHY("Exception thrown from CallBooleanMethod()"); } return 0; } /* JNI entry point to command line. See org.servalproject.servald.ServalD class for the Java side. JNI method descriptor: "(Ljava/util/List;[Ljava/lang/String;)I" */ JNIEXPORT jint JNICALL Java_org_servalproject_servald_ServalD_rawCommand(JNIEnv *env, jobject this, jobject outv, jobjectArray args) { jclass stringClass = NULL; jclass listClass = NULL; unsigned char status = 0; // to match what the shell gets: 0..255 // Enforce non re-entrancy. if (jni_env) { jclass exceptionClass = NULL; if ((exceptionClass = (*env)->FindClass(env, "java/lang/IllegalStateException")) == NULL) return -1; // exception (*env)->ThrowNew(env, exceptionClass, "re-entrancy not supported"); return -1; } // Get some handles to some classes and methods that we use later on. if ((stringClass = (*env)->FindClass(env, "java/lang/String")) == NULL) return -1; // exception if ((listClass = (*env)->FindClass(env, "java/util/List")) == NULL) return -1; // exception if ((listAddMethodId = (*env)->GetMethodID(env, listClass, "add", "(Ljava/lang/Object;)Z")) == NULL) return -1; // exception // Construct argv, argc from this method's arguments. jsize len = (*env)->GetArrayLength(env, args); const char **argv = malloc(sizeof(char*) * (len + 1)); if (argv == NULL) { jclass exceptionClass = NULL; if ((exceptionClass = (*env)->FindClass(env, "java/lang/OutOfMemoryError")) == NULL) return -1; // exception (*env)->ThrowNew(env, exceptionClass, "malloc returned NULL"); return -1; } jsize i; for (i = 0; i <= len; ++i) argv[i] = NULL; int argc = len; // From now on, in case of an exception we have to free some resources before // returning. jni_exception = 0; for (i = 0; !jni_exception && i != len; ++i) { const jstring arg = (jstring)(*env)->GetObjectArrayElement(env, args, i); if (arg == NULL) jni_exception = 1; else { const char *str = (*env)->GetStringUTFChars(env, arg, NULL); if (str == NULL) jni_exception = 1; else argv[i] = str; } } if (!jni_exception) { // Set up the output buffer. outv_list = outv; outv_current = outv_buffer; // Execute the command. jni_env = env; status = parseCommandLine(argc, argv); jni_env = NULL; } // Release argv Java string buffers. for (i = 0; i != len; ++i) { if (argv[i]) { const jstring arg = (jstring)(*env)->GetObjectArrayElement(env, args, i); (*env)->ReleaseStringUTFChars(env, arg, argv[i]); } } free(argv); // Deal with Java exceptions: NewStringUTF out of memory in outv_end_field(). if (jni_exception || (outv_current != outv_buffer && outv_end_field() == -1)) return -1; return (jint) status; } #endif /* HAVE_JNI_H */ static void complainCommandLine(const char *prefix, int argc, const char *const *argv) { char buf[1024]; char *b = buf; int i; char *e = buf + sizeof(buf) - 4; for (i = 0; b < e && i != argc; ++i) { if (i) *b++ = ' '; if (b < e) b += snprintf(b, e - b, "%s", argv[i]); } if (b < e) *b = '\0'; else strcpy(e, "..."); setReason("%s%s", prefix, buf); } /* args[] excludes command name (unless hardlinks are used to use first words of command sequences as alternate names of the command. */ int parseCommandLine(int argc, const char *const *args) { int i; int ambiguous=0; int cli_call=-1; for(i=0;command_line_options[i].function;i++) { int j; const char *word = NULL; int optional = 0; int mandatory = 0; for (j = 0; (word = command_line_options[i].words[j]); ++j) { int wordlen = strlen(word); if (optional < 0) { WHYF("Internal error: command_line_options[%d].word[%d]=\"%s\" not allowed after \"...\"", i, j, word); break; } else if (!( (wordlen > 2 && word[0] == '<' && word[wordlen-1] == '>') || (wordlen > 4 && word[0] == '[' && word[1] == '<' && word[wordlen-2] == '>' && word[wordlen-1] == ']') || (wordlen > 0) )) { WHYF("Internal error: command_line_options[%d].word[%d]=\"%s\" is malformed", i, j, word); break; } else if (word[0] == '<') { ++mandatory; if (optional) { WHYF("Internal error: command_line_options[%d].word[%d]=\"%s\" should be optional", i, j, word); break; } } else if (word[0] == '[') { ++optional; } else if (wordlen == 3 && word[0] == '.' && word[1] == '.' && word[2] == '.') { optional = -1; } else { ++mandatory; if (j < argc && strcasecmp(word, args[j])) // literal words don't match break; } } if (!word && argc >= mandatory && (optional < 0 || argc <= mandatory + optional)) { /* A match! We got through the command definition with no internal errors and all literal args matched and we have a proper number of args. If we have multiple matches, then note that the call is ambiguous. */ if (cli_call>=0) ambiguous++; if (ambiguous==1) { setReason("Ambiguous command line call:"); complainCommandLine(" ", argc, args); setReason("Matches the following known command line calls:"); } if (ambiguous) { complainCommandLine(" ", argc, command_line_options[i].words); } cli_call=i; } } /* Don't process ambiguous calls */ if (ambiguous) return -1; /* Complain if we found no matching calls */ if (cli_call<0) { setReason("Unknown command line call:"); complainCommandLine(" ", argc, args); return cli_usage(); } /* Otherwise, make call */ setVerbosity(confValueGet("debug","")); int result=command_line_options[cli_call].function(argc, args, &command_line_options[cli_call]); /* clean up after ourselves */ overlay_mdp_client_done(); return result; } int cli_arg(int argc, const char *const *argv, command_line_option *o, char *argname, const char **dst, int (*validator)(const char *arg), char *defaultvalue) { int arglen = strlen(argname); int i; const char *word; for(i = 0; (word = o->words[i]); ++i) { int wordlen = strlen(word); /* No need to check that the "<...>" and "[<...>]" are all intact in the command_line_option, because that was already checked in parseCommandLine(). */ if (i < argc &&( (wordlen == arglen + 2 && word[0] == '<' && !strncasecmp(&word[1], argname, arglen)) || (wordlen == arglen + 4 && word[0] == '[' && !strncasecmp(&word[2], argname, arglen))) ) { const char *value = argv[i]; if (validator && !(*validator)(value)) return setReason("Invalid argument %d '%s': \"%s\"", i, argname, value); *dst = value; return 0; } } /* No matching valid argument was found, so return default value. It might seem that this should never happen, but it can because more than one version of a command line option may exist, one with a given argument and another without, and allowing a default value means we can have a single function handle both in a fairly simple manner. */ *dst = defaultvalue; return 1; } /* Write a single character to output. If in a JNI call, then this appends the character to the current output field. Returns the character written cast to an unsigned char then to int, or EOF on error. */ int cli_putchar(char c) { #ifdef HAVE_JNI_H if (jni_env) { if (outv_current == outv_limit && outv_growbuf(1) == -1) return EOF; *outv_current++ = c; return (unsigned char) c; } else #endif return putchar(c); } /* Write a null-terminated string to output. If in a JNI call, then this appends the string to the current output field. The terminating null is not included. Returns a non-negative integer on success, EOF on error. */ int cli_puts(const char *str) { #ifdef HAVE_JNI_H if (jni_env) { size_t len = strlen(str); size_t avail = outv_limit - outv_current; if (avail < len) { strncpy(outv_current, str, avail); outv_current = outv_limit; if (outv_growbuf(len) == -1) return EOF; len -= avail; str += avail; } strncpy(outv_current, str, len); outv_current += len; return 0; } else #endif return fputs(str, stdout); } /* Write a formatted string to output. If in a JNI call, then this appends the string to the current output field, excluding the terminating null. Returns the number of bytes written/appended, or -1 on error. */ int cli_printf(const char *fmt, ...) { int ret = 0; va_list ap,ap2; va_start(ap,fmt); va_copy(ap2,ap); #ifdef HAVE_JNI_H if (jni_env) { size_t avail = outv_limit - outv_current; int count = vsnprintf(outv_current, avail, fmt, ap2); if (count >= avail) { if (outv_growbuf(count) == -1) return -1; vsprintf(outv_current, fmt, ap2); } outv_current += count; ret = count; } else #endif ret = vfprintf(stdout, fmt, ap2); va_end(ap); return ret; } /* Delimit the current output field. This closes the current field, so that the next cli_ output function will start appending to a new field. Returns 0 on success, -1 on error. If not in a JNI call, then this simply writes a newline to standard output (or the value of the SERVALD_OUTPUT_DELIMITER env var if set). */ int cli_delim(const char *opt) { #ifdef HAVE_JNI_H if (jni_env) { return outv_end_field(); } else #endif { const char *delim = getenv("SERVALD_OUTPUT_DELIMITER"); if (delim == NULL) delim = opt ? opt : "\n"; fputs(delim, stdout); } return 0; } int app_echo(int argc, const char *const *argv, struct command_line_option *o) { int i; for (i = 1; i < argc; ++i) { cli_puts(argv[i]); cli_delim(NULL); } return 0; } int app_dna_lookup(int argc, const char *const *argv, struct command_line_option *o) { int i; /* Create the instance directory if it does not yet exist */ if (create_serval_instance_dir() == -1) return -1; int sid_count=0; unsigned char sids[128][SID_SIZE]; const char *did; if (cli_arg(argc, argv, o, "did", &did, NULL, "*") == -1) return -1; /* Bind to MDP socket and await confirmation */ unsigned char srcsid[SID_SIZE]; int port=32768+(random()&32767); if (overlay_mdp_getmyaddr(0,srcsid)) return WHY("Could not get local address"); if (overlay_mdp_bind(srcsid,port)) return WHY("Could not bind to MDP socket"); /* use MDP to send the lookup request to MDP_PORT_DNALOOKUP, and wait for replies. */ overlay_mdp_frame mdp; bzero(&mdp,sizeof(mdp)); WHY("polling network"); /* Now repeatedly send resolution request and collect results until we reach timeout. */ unsigned long long timeout=overlay_gettime_ms()+3000; unsigned long long last_tx=0; while(timeout>overlay_gettime_ms()) { unsigned long long now=overlay_gettime_ms(); if ((last_tx+125)0) { if (overlay_mdp_client_poll(short_timeout)) { overlay_mdp_frame rx; int ttl; while (overlay_mdp_recv(&rx,&ttl)==0) { if (rx.packetTypeAndFlags==MDP_ERROR) { WHYF(" Error message: %s", mdp.error.message); } else if ((rx.packetTypeAndFlags&MDP_TYPE_MASK)==MDP_TX) { /* Display match unless it is a duplicate. XXX - For wildcard searches, each sid will only show up once. */ int i; for(i=0;i127) return defaultValue; /* The rotor is used to pick which of four buffers to return in. This allows the use of up to four calls to confValueGet() in a single string formatting exercise, without unexpected side effect. */ confValueRotor++; confValueRotor&=3; strcpy(&confValue[confValueRotor][0],&line[varLen+1]); return &confValue[confValueRotor][0]; } } line[0]=0; fgets(line,1024,f); } fclose(f); return defaultValue; } int cli_absolute_path(const char *arg) { return arg[0] == '/' && arg[1] != '\0'; } int app_server_start(int argc, const char *const *argv, struct command_line_option *o) { /* Process optional arguments */ int foregroundP= (argc >= 2 && !strcasecmp(argv[1], "foreground")); if (cli_arg(argc, argv, o, "instance path", &thisinstancepath, cli_absolute_path, NULL) == -1) return -1; /* Create the instance directory if it does not yet exist */ if (create_serval_instance_dir() == -1) return -1; cli_puts("instancepath"); cli_delim(":"); cli_puts(serval_instancepath()); cli_delim("\n"); /* Now that we know our instance path, we can ask for the default set of network interfaces that we will take interest in. */ const char *interfaces = confValueGet("interfaces", ""); if (!interfaces[0]) WHY("No network interfaces configured (empty 'interfaces' config setting)"); overlay_interface_args(interfaces); int pid = servalNodeRunning(); if (pid < 0) return -1; int ret = 1; if (pid > 0) { WHYF("Serval process already running (pid=%d)", pid); } else { /* Start the Serval process. All server settings will be read by the server process from the instance directory when it starts up. We can just become the server process ourselves --- no need to fork. */ rhizome_datastore_path = serval_instancepath(); rhizome_opendb(); overlayMode = 1; if ((pid = server(NULL, foregroundP)) <= 0) return -1; ret = 0; } cli_puts("pid"); cli_delim(":"); cli_printf("%d", pid); cli_delim("\n"); return ret; } int app_server_stop(int argc, const char *const *argv, struct command_line_option *o) { if (cli_arg(argc, argv, o, "instance path", &thisinstancepath, cli_absolute_path, NULL) == -1) return -1; const char *instancepath = serval_instancepath(); int pid = servalNodeRunning(); if (pid < 0) return -1; cli_puts("instancepath"); cli_delim(":"); cli_puts(instancepath); cli_delim("\n"); if (pid) { cli_puts("pid"); cli_delim(":"); cli_printf("%d", pid); cli_delim("\n"); int tries = 0; while (1) { if (tries >= 3) return WHYF( "Serval process for instance '%s' did not stop after %d SIGHUP signals", instancepath, tries ); ++tries; /* Create the stopfile, which causes the server process's signal handler to exit instead of restarting. */ char stopfile[1024]; if (!FORM_SERVAL_INSTANCE_PATH(stopfile, "doshutdown")) return -1; FILE *f; if ((f = fopen(stopfile, "w")) == NULL) return WHYF("Could not create shutdown file '%s'", stopfile); fclose(f); if (kill(pid,SIGHUP) == -1) { // ESRCH means process is gone, possibly we are racing with another stop, or servald just // died unexpectedly. if (errno == ESRCH) { serverCleanUp(); break; } return WHYF("Error sending SIGHUP to Serval instance '%s' process pid=%d: %s [errno=%d]", instancepath, pid, strerror(errno), errno ); } /* Allow a few seconds for the process to die, and keep an eye on things while this is happening. */ time_t timeout = time(NULL) + 2; while (time(NULL) < timeout && servalNodeRunning() == pid) usleep(200000); // 5 Hz } cli_puts("tries"); cli_delim(":"); cli_printf("%d", tries); cli_delim("\n"); } return pid ? 0 : 1; } int app_server_status(int argc, const char *const *argv, struct command_line_option *o) { if (cli_arg(argc, argv, o, "instance path", &thisinstancepath, cli_absolute_path, NULL) == -1) return -1; int pid = servalNodeRunning(); if (pid < 0) return -1; cli_puts("instancepath"); cli_delim(":"); cli_puts(serval_instancepath()); cli_delim("\n"); if (pid) { cli_puts("pid"); cli_delim(":"); cli_printf("%d", pid); cli_delim("\n"); } return pid > 0 ? 0 : 1; } int app_mdp_ping(int argc, const char *const *argv, struct command_line_option *o) { const char *sid; if (cli_arg(argc, argv, o, "SID|broadcast", &sid, validateSid, "broadcast") == -1) return -1; overlay_mdp_frame mdp; /* Bind to MDP socket and await confirmation */ unsigned char srcsid[SID_SIZE]; int port=32768+(random()&32767); if (overlay_mdp_getmyaddr(0,srcsid)) return WHY("Could not get local address"); if (overlay_mdp_bind(srcsid,port)) return WHY("Could not bind to MDP socket"); /* First sequence number in the echo frames */ unsigned int firstSeq=random(); unsigned int sequence_number=firstSeq; /* Get SID that we want to ping. XXX - allow lookup of SID prefixes and telephone numbers (that would require MDP lookup of phone numbers, which doesn't yet occur) */ int i; int broadcast=0; unsigned char ping_sid[SID_SIZE]; if (strcasecmp(sid,"broadcast")) { stowSid(ping_sid,0,sid); } else { for(i=0;i0) { int ttl=-1; while (overlay_mdp_recv(&mdp,&ttl)==0) { switch(mdp.packetTypeAndFlags&MDP_TYPE_MASK) { case MDP_ERROR: WHYF("mdpping: overlay_mdp_recv: %s (code %d)", mdp.error.message, mdp.error.error); break; case MDP_TX: { int *rxseq=(int *)&mdp.in.payload; long long *txtime=(long long *)&mdp.in.payload[4]; long long delay=overlay_gettime_ms()-*txtime; printf("%s: seq=%d time=%lld ms%s%s\n", overlay_render_sid(mdp.in.src.sid),(*rxseq)-firstSeq+1,delay, mdp.packetTypeAndFlags&MDP_NOCRYPT?"":" ENCRYPTED", mdp.packetTypeAndFlags&MDP_NOSIGN?"":" SIGNED"); #warning put duplicate pong detection here so that stats work properly rx_count++; rx_ms+=delay; if (rx_mintime>delay||rx_mintime==-1) rx_mintime=delay; if (delay>rx_maxtime) rx_maxtime=delay; rx_times[rx_count%1024]=delay; } break; default: WHYF("mdpping: overlay_mdp_recv: Unexpected MDP frame type 0x%x", mdp.packetTypeAndFlags); break; } } } now=overlay_gettime_ms(); if (servalShutdown) { float rx_stddev=0; float rx_mean=rx_ms*1.0/rx_count; int samples=rx_count; if (samples>1024) samples=1024; int i; for(i=0;icryptoSignPublic, crypto_sign_edwards25519sha512batch_PUBLICKEYBYTES)); cli_delim("\n"); cli_puts("filehash"); cli_delim(":"); cli_puts(mout->fileHexHash); cli_delim("\n"); cli_puts("filesize"); cli_delim(":"); cli_printf("%lld", mout->fileLength); cli_delim("\n"); const char *name = rhizome_manifest_get(mout, "name", NULL, 0); if (name) { cli_puts("name"); cli_delim(":"); cli_puts(name); cli_delim("\n"); } rhizome_manifest_free(m); if (mout != m) rhizome_manifest_free(mout); return ret; } int cli_manifestid(const char *arg) { return rhizome_str_is_manifest_id(arg); } int app_rhizome_extract_manifest(int argc, const char *const *argv, struct command_line_option *o) { const char *manifestid, *manifestpath; if (cli_arg(argc, argv, o, "manifestid", &manifestid, cli_manifestid, NULL) || cli_arg(argc, argv, o, "manifestpath", &manifestpath, NULL, "") == -1) return -1; /* Ensure the Rhizome database exists and is open */ if (create_serval_instance_dir() == -1) return -1; rhizome_datastore_path = serval_instancepath(); rhizome_opendb(); /* Extract the manifest from the database */ rhizome_manifest *m = NULL; int ret = rhizome_retrieve_manifest(manifestid, &m); switch (ret) { case 0: ret = 1; break; case 1: ret = 0; if (manifestpath[0]) { if (rhizome_manifest_finalise(m, 1) == -1) ret = WHY("Could not overwrite manifest file."); else if (rhizome_write_manifest_file(m, manifestpath) == -1) ret = WHY("Could not overwrite manifest file."); } break; case -1: break; default: ret = WHYF("Unsupported return value %d", ret); break; } if (m) rhizome_manifest_free(m); return ret; } int cli_fileid(const char *arg) { return rhizome_str_is_file_hash(arg); } int app_rhizome_extract_file(int argc, const char *const *argv, struct command_line_option *o) { const char *fileid, *filepath; if (cli_arg(argc, argv, o, "fileid", &fileid, cli_fileid, NULL) || cli_arg(argc, argv, o, "filepath", &filepath, NULL, "") == -1) return -1; /* Ensure the Rhizome database exists and is open */ if (create_serval_instance_dir() == -1) return -1; rhizome_datastore_path = serval_instancepath(); rhizome_opendb(); /* Extract the file from the database */ int ret = rhizome_retrieve_file(fileid, filepath); switch (ret) { case 0: ret = 1; break; case 1: ret = 0; break; case -1: break; default: ret = WHYF("Unsupported return value %d", ret); break; } return ret; } int cli_uint(const char *arg) { register const char *s = arg; while (isdigit(*s++)) ; return s != arg && *s == '\0'; } int app_rhizome_list(int argc, const char *const *argv, struct command_line_option *o) { const char *offset, *limit; cli_arg(argc, argv, o, "offset", &offset, cli_uint, "0"); cli_arg(argc, argv, o, "limit", &limit, cli_uint, "0"); /* Create the instance directory if it does not yet exist */ if (create_serval_instance_dir() == -1) return -1; rhizome_datastore_path = serval_instancepath(); rhizome_opendb(); return rhizome_list_manifests(atoi(offset), atoi(limit)); } int app_keyring_create(int argc, const char *const *argv, struct command_line_option *o) { const char *pin; cli_arg(argc, argv, o, "pin,pin ...", &pin, NULL, ""); keyring_file *k=keyring_open_with_pins(pin); if (!k) WHY("keyring create: Failed to create/open keyring file"); return 0; } int app_keyring_list(int argc, const char *const *argv, struct command_line_option *o) { const char *pin; cli_arg(argc, argv, o, "pin,pin ...", &pin, NULL, ""); keyring_file *k=keyring_open_with_pins(pin); int cn=0; int in=0; for(cn=0;cncontext_count;cn++) for(in=0;incontexts[cn]->identity_count;in++) { int kpn; keypair *kp; unsigned char *sid=NULL,*did=NULL; for(kpn=0;kpncontexts[cn]->identities[in]->keypair_count;kpn++) { kp=k->contexts[cn]->identities[in]->keypairs[kpn]; if (kp->type==KEYTYPE_CRYPTOBOX) sid=kp->public_key; if (kp->type==KEYTYPE_DID) did=kp->private_key; } if (sid||did) { int i; if (sid) for(i=0;icontexts[0],(char *)pin)==NULL) return setReason("Could not create new identity (keyring_create_identity() failed)"); if (keyring_commit(k)) return setReason("Could not write new identity (keyring_commit() failed)"); keyring_free(k); return 0; } int app_keyring_set_did(int argc, const char *const *argv, struct command_line_option *o) { const char *sid, *did, *pin, *name; cli_arg(argc, argv, o, "sid", &sid, NULL, ""); cli_arg(argc, argv, o, "did", &did, NULL, ""); cli_arg(argc, argv, o, "name", &name, NULL, ""); cli_arg(argc, argv, o, "pin", &pin, NULL, ""); if (strlen(did)>31) return WHY("DID too long (31 digits max)"); if (strlen(name)>63) return WHY("Name too long (31 char max)"); keyring=keyring_open_with_pins((char *)pin); if (!keyring) return WHY("Could not open keyring file"); unsigned char packedSid[SID_SIZE]; stowSid(packedSid,0,(char *)sid); int cn=0,in=0,kp=0; int r=keyring_find_sid(keyring,&cn,&in,&kp,packedSid); if (!r) return WHY("No matching SID"); if (keyring_set_did(keyring->contexts[cn]->identities[in], (char *)did,(char *)name)) return WHY("Could not set DID"); if (keyring_commit(keyring)) return WHY("Could not write updated keyring record"); return 0; } int app_id_self(int argc, const char *const *argv, struct command_line_option *o) { /* List my own identities */ overlay_mdp_frame a; int result; int count=0; a.packetTypeAndFlags=MDP_GETADDRS; if (!strcasecmp(argv[1],"self")) a.addrlist.selfP=1; /* get own identities, not those of peers */ else a.addrlist.selfP=0; /* get peer list */ a.addrlist.first_sid=-1; a.addrlist.last_sid=0x7fffffff; a.addrlist.frame_sid_count=MDP_MAX_SID_REQUEST; while(a.addrlist.frame_sid_count==MDP_MAX_SID_REQUEST) { result=overlay_mdp_send(&a,MDP_AWAITREPLY,5000); if (result) { if (a.packetTypeAndFlags==MDP_ERROR) { WHYF(" MDP Server error #%d: '%s'", a.error.error,a.error.message); } else WHYF("Could not get list of local MDP addresses"); return WHY("Failed to get local address list"); } if ((a.packetTypeAndFlags&MDP_TYPE_MASK)!=MDP_ADDRLIST) return WHY("MDP Server returned something other than an address list"); int i; for(i=0;i3) mdp.nodeinfo.resolve_did=1; resolveDid=mdp.nodeinfo.resolve_did; /* get SID or SID prefix XXX - Doesn't correctly handle odd-lengthed SID prefixes (ignores last digit). The matching code in overlay_route.c also has a similar problem with the last digit of an odd-length prefix being ignored. */ int i; mdp.nodeinfo.sid_prefix_length=0; for(i = 0; (i != SID_SIZE)&&sid[i<<1]&&sid[(i<<1)+1]; i++) { mdp.nodeinfo.sid[mdp.nodeinfo.sid_prefix_length] = hexvalue(sid[i<<1]) << 4; mdp.nodeinfo.sid[mdp.nodeinfo.sid_prefix_length++] |= hexvalue(sid[(i<<1)+1]); } mdp.nodeinfo.sid_prefix_length*=2; int result=overlay_mdp_send(&mdp,MDP_AWAITREPLY,5000); if (result) { if (mdp.packetTypeAndFlags==MDP_ERROR) { overlay_mdp_client_done(); return WHYF(" MDP Server error #%d: '%s'",mdp.error.error,mdp.error.message); } else { overlay_mdp_client_done(); return WHYF("Could not get information about node."); } } if (resolveDid&&(!mdp.nodeinfo.resolve_did)) { /* Asked for DID resolution, but did not get it, so do a DNA lookup here. We do this on the client side, so that we don't block the single-threaded server. */ overlay_mdp_frame m2; bzero(&m2,sizeof(m2)); int port=32768+(random()&0xffff); unsigned char srcsid[SID_SIZE]; if (overlay_mdp_getmyaddr(0,srcsid)) port=0; if (overlay_mdp_bind(srcsid,port)) port=0; if (port) { int i; for(i=0;i<(3000/125);i++) { m2.packetTypeAndFlags=MDP_TX; m2.out.src.port=port; bcopy(&srcsid[0],&m2.out.src.sid[0],SID_SIZE); bcopy(&mdp.nodeinfo.sid[0],&m2.out.dst.sid[0],SID_SIZE); m2.out.dst.port=MDP_PORT_DNALOOKUP; /* search for any DID */ m2.out.payload[0]=0; m2.out.payload_length=1; if (!overlay_mdp_send(&m2,MDP_AWAITREPLY,125)) { int bytes=m2.in.payload_length; if ((bytes+1)" marks an arg that can take any value. "[]" marks an optional arg that can take any value. All args following the first optional arg are optional, whether marked or not. Only exactly matching prototypes will be used. Together with the description, this makes it easy for us to auto-generate the list of valid command line formats for display to the user if they try an invalid one. It also means we can do away with getopt() etc. The CLIFLAG_STANDALONE means that they cannot be used with a running servald instance, but act as an instance. In other words, don't call these from the serval frontend, e.g, Java application on Android. There are various reasons, such as some will try to fork() and exec() (bad for a Java thread to do), while others manipulate files that the running instance may be using. Keep this list alphabetically sorted for user convenience. */ command_line_option command_line_options[]={ {app_dna_lookup,{"dna","lookup","",NULL},0, "Lookup the SIP/MDP address of the supplied telephone number (DID)."}, {cli_usage,{"help",NULL},0, "Display command usage."}, {app_echo,{"echo","...",NULL},CLIFLAG_STANDALONE, "Output the supplied string."}, {app_server_start,{"start",NULL},CLIFLAG_STANDALONE, "Start Serval Mesh node process with instance path taken from SERVALINSTANCE_PATH environment variable."}, {app_server_start,{"start","in","",NULL},CLIFLAG_STANDALONE, "Start Serval Mesh node process with given instance path."}, {app_server_start,{"start","foreground",NULL},CLIFLAG_STANDALONE, "Start Serval Mesh node process without detatching from foreground."}, {app_server_start,{"start","foreground","in","",NULL},CLIFLAG_STANDALONE, "Start Serval Mesh node process with given instance path, without detatching from foreground."}, {app_server_stop,{"stop",NULL},0, "Stop a running Serval Mesh node process with instance path taken from SERVALINSTANCE_PATH environment variable."}, {app_server_stop,{"stop","in","",NULL},0, "Stop a running Serval Mesh node process with given instance path."}, {app_server_status,{"status",NULL},0, "Display information about any running Serval Mesh node."}, {app_mdp_ping,{"mdp","ping","",NULL},CLIFLAG_STANDALONE, "Attempts to ping specified node via Mesh Datagram Protocol (MDP)."}, {app_config_set,{"config","set","","",NULL},CLIFLAG_STANDALONE, "Set specified configuration variable."}, {app_config_del,{"config","del","",NULL},CLIFLAG_STANDALONE, "Set specified configuration variable."}, {app_config_get,{"config","get","[]",NULL},CLIFLAG_STANDALONE, "Get specified configuration variable."}, {app_rhizome_add_file,{"rhizome","add","file","","[]",NULL},CLIFLAG_STANDALONE, "Add a file to Rhizome and optionally write its manifest to the given path"}, {app_rhizome_list,{"rhizome","list","[]","[]",NULL},CLIFLAG_STANDALONE, "List all manifests and files in Rhizome"}, {app_rhizome_extract_manifest,{"rhizome","extract","manifest","","[]",NULL},CLIFLAG_STANDALONE, "Extract a manifest from Rhizome and write it to the given path"}, {app_rhizome_extract_file,{"rhizome","extract","file","","[]",NULL},CLIFLAG_STANDALONE, "Extract a file from Rhizome and write it to the given path"}, {app_keyring_create,{"keyring","create",NULL},0, "Create a new keyring file."}, {app_keyring_list,{"keyring","list","[]",NULL},CLIFLAG_STANDALONE, "List identites in specified key ring that can be accessed using the specified PINs"}, {app_keyring_add,{"keyring","add","[]",NULL},CLIFLAG_STANDALONE, "Create a new identity in the keyring protected by the provided PIN"}, {app_keyring_set_did,{"set","did","","","","[]",NULL},CLIFLAG_STANDALONE, "Set the DID for the specified SID. Optionally supply PIN to unlock the SID record in the keyring."}, {app_vomp_status,{"vomp","status",NULL},0, "Display status of any VoMP calls"}, {app_vomp_monitor,{"vomp","monitor",NULL},0, "Monitor state and audio-flow of VoMP calls"}, {app_vomp_pickup,{"vomp","pickup","",NULL},0, "Accept specified call (use vomp status to get list of calls)"}, {app_vomp_hangup,{"vomp","hangup","",NULL},0, "End specified call (use vomp status to get list of calls)"}, {app_vomp_dtmf,{"vomp","dtmf","","",NULL},0, "Send DTMF digits over specified call"}, {app_vomp_dial,{"vomp","dial","","","[]",NULL},0, "Attempt to dial the specified sid and did."}, {app_id_self,{"id","self",NULL},0, "Return my own identity(s) as SIDs"}, {app_id_self,{"id","peers",NULL},0, "Return identity of known peers as SIDs"}, {app_node_info,{"node","info","","[getdid]",NULL},0, "Return information about SID, and optionally ask for DID resolution via network"}, #ifdef HAVE_VOIPTEST {app_pa_phone,{"phone",NULL},0, "Run phone test application"}, #endif {NULL,{NULL}} };