forked from servalproject/serval-dna
-
Notifications
You must be signed in to change notification settings - Fork 0
/
commandline.c
2428 lines (2219 loc) · 79.6 KB
/
commandline.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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.
*/
#include <sys/time.h>
#include <sys/wait.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include <time.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#ifdef HAVE_JNI_H
#include <jni.h>
#endif
#include "serval.h"
#include "conf.h"
#include "rhizome.h"
#include "strbuf.h"
#include "strbuf_helpers.h"
#include "str.h"
#include "mdp_client.h"
#include "cli.h"
#include "overlay_address.h"
#include "overlay_buffer.h"
extern struct cli_schema command_line_options[];
int commandline_usage(const struct cli_parsed *parsed, void *context)
{
printf("Serval Mesh version <version>.\n");
return cli_usage(command_line_options);
}
/* 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 jniResults = NULL;
jclass IJniResults = NULL;
jmethodID startResultSet, setColumnName, putString, putBlob, putLong, putDouble, totalRowCount;
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 put_blob(jbyte *value, jsize length){
jbyteArray arr = NULL;
if (value && length>0){
arr = (*jni_env)->NewByteArray(jni_env, length);
if (arr == NULL || (*jni_env)->ExceptionOccurred(jni_env)) {
jni_exception = 1;
return WHY("Exception thrown from NewByteArray()");
}
(*jni_env)->SetByteArrayRegion(jni_env, arr, 0, length, value);
if ((*jni_env)->ExceptionOccurred(jni_env)) {
jni_exception = 1;
return WHYF("Exception thrown from SetByteArrayRegion()");
}
}
(*jni_env)->CallVoidMethod(jni_env, jniResults, putBlob, arr);
if ((*jni_env)->ExceptionOccurred(jni_env)) {
jni_exception = 1;
return WHY("Exception thrown from CallVoidMethod()");
}
if (arr)
(*jni_env)->DeleteLocalRef(jni_env, arr);
return 0;
}
static int outv_end_field()
{
jsize length = outv_current - outv_buffer;
outv_current = outv_buffer;
return put_blob((jbyte *)outv_buffer, length);
}
int Throw(JNIEnv *env, const char *class, const char *msg)
{
jclass exceptionClass = NULL;
if ((exceptionClass = (*env)->FindClass(env, class)) == NULL)
return -1; // exception
(*env)->ThrowNew(env, exceptionClass, msg);
return -1;
}
/* 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)
{
if (!IJniResults){
IJniResults = (*env)->FindClass(env, "org/servalproject/servald/IJniResults");
if (IJniResults==NULL)
return Throw(env, "java/lang/IllegalStateException", "Unable to locate class org.servalproject.servald.IJniResults");
startResultSet = (*env)->GetMethodID(env, IJniResults, "startResultSet", "(I)V");
if (startResultSet==NULL)
return Throw(env, "java/lang/IllegalStateException", "Unable to locate method startResultSet");
setColumnName = (*env)->GetMethodID(env, IJniResults, "setColumnName", "(ILjava/lang/String;)V");
if (setColumnName==NULL)
return Throw(env, "java/lang/IllegalStateException", "Unable to locate method setColumnName");
putString = (*env)->GetMethodID(env, IJniResults, "putString", "(Ljava/lang/String;)V");
if (putString==NULL)
return Throw(env, "java/lang/IllegalStateException", "Unable to locate method putString");
putBlob = (*env)->GetMethodID(env, IJniResults, "putBlob", "([B)V");
if (putBlob==NULL)
return Throw(env, "java/lang/IllegalStateException", "Unable to locate method putBlob");
putLong = (*env)->GetMethodID(env, IJniResults, "putLong", "(J)V");
if (putLong==NULL)
return Throw(env, "java/lang/IllegalStateException", "Unable to locate method putLong");
putDouble = (*env)->GetMethodID(env, IJniResults, "putDouble", "(D)V");
if (putDouble==NULL)
return Throw(env, "java/lang/IllegalStateException", "Unable to locate method putDouble");
totalRowCount = (*env)->GetMethodID(env, IJniResults, "totalRowCount", "(I)V");
if (totalRowCount==NULL)
return Throw(env, "java/lang/IllegalStateException", "Unable to locate method totalRowCount");
}
unsigned char status = 0; // to match what the shell gets: 0..255
if (jni_env)
return Throw(env, "java/lang/IllegalStateException", "re-entrancy not supported");
// Construct argv, argc from this method's arguments.
jsize len = (*env)->GetArrayLength(env, args);
const char **argv = alloca(sizeof(char*) * (len + 1));
if (argv == NULL)
return Throw(env, "java/lang/OutOfMemoryError", "alloca() returned NULL");
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 ((*env)->ExceptionOccurred(env))
jni_exception = 1;
else if (arg == NULL) {
Throw(env, "java/lang/NullPointerException", "null element in argv");
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.
jniResults = outv;
outv_current = outv_buffer;
// Execute the command.
jni_env = env;
status = parseCommandLine(NULL, 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]);
}
}
// 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 */
/* The argc and argv arguments must be passed verbatim from main(argc, argv), so argv[0] is path to
executable.
*/
int parseCommandLine(const char *argv0, int argc, const char *const *args)
{
fd_clearstats();
IN();
struct cli_parsed parsed;
int result = cli_parse(argc, args, command_line_options, &parsed);
if (result != -1) {
// Do not run the command if the configuration does not load ok
if (((parsed.command->flags & CLIFLAG_PERMISSIVE_CONFIG) ? cf_reload_permissive() : cf_reload()) != -1)
result = cli_invoke(&parsed, NULL);
else {
strbuf b = strbuf_alloca(160);
strbuf_append_argv(b, argc, args);
result = WHYF("configuration unavailable, not running command: %s", strbuf_str(b));
}
} else {
// Load configuration so that "unsupported command" log message can get out
cf_reload_permissive();
}
/* clean up after ourselves */
overlay_mdp_client_done();
rhizome_close_db();
OUT();
if (config.debug.timing)
fd_showstats();
return result;
}
/* 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;
}
#endif
return putchar(c);
}
/* Write a buffer of data to output. If in a JNI call, then this appends the data to the
current output field, including any embedded nul characters. Returns a non-negative integer on
success, EOF on error.
*/
int cli_write(const unsigned char *buf, size_t len)
{
#ifdef HAVE_JNI_H
if (jni_env) {
size_t avail = outv_limit - outv_current;
if (avail < len) {
memcpy(outv_current, buf, avail);
outv_current = outv_limit;
if (outv_growbuf(len) == -1)
return EOF;
len -= avail;
buf += avail;
}
memcpy(outv_current, buf, len);
outv_current += len;
return 0;
}
#endif
return fwrite(buf, len, 1, stdout);
}
/* 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)
return cli_write((const unsigned char *) str, strlen(str));
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;
#ifdef HAVE_JNI_H
if (jni_env) {
size_t avail = outv_limit - outv_current;
va_start(ap, fmt);
int count = vsnprintf(outv_current, avail, fmt, ap);
va_end(ap);
if (count >= avail) {
if (outv_growbuf(count) == -1)
return -1;
va_start(ap, fmt);
vsprintf(outv_current, fmt, ap);
va_end(ap);
}
outv_current += count;
ret = count;
} else
#endif
{
va_start(ap, fmt);
ret = vfprintf(stdout, fmt, ap);
va_end(ap);
}
return ret;
}
void cli_columns(int columns, const char *names[]){
#ifdef HAVE_JNI_H
if (jni_env) {
(*jni_env)->CallVoidMethod(jni_env, jniResults, startResultSet, columns);
if ((*jni_env)->ExceptionOccurred(jni_env)) {
jni_exception = 1;
WHY("Exception thrown from CallVoidMethod()");
return;
}
int i;
for (i=0;i<columns;i++){
jstring str = (jstring)(*jni_env)->NewStringUTF(jni_env, names[i]);
if (str == NULL) {
jni_exception = 1;
WHY("Exception thrown from NewStringUTF()");
return;
}
(*jni_env)->CallVoidMethod(jni_env, jniResults, setColumnName, i, str);
(*jni_env)->DeleteLocalRef(jni_env, str);
}
return;
}
#endif
cli_printf("%d",columns);
cli_delim("\n");
int i;
for (i=0;i<columns;i++){
cli_puts(names[i]);
if (i+1==columns)
cli_delim("\n");
else
cli_delim(":");
}
}
void cli_field_name(const char *name, const char *delim){
#ifdef HAVE_JNI_H
if (jni_env) {
jstring str = (jstring)(*jni_env)->NewStringUTF(jni_env, name);
if (str == NULL) {
jni_exception = 1;
WHY("Exception thrown from NewStringUTF()");
return;
}
(*jni_env)->CallVoidMethod(jni_env, jniResults, setColumnName, -1, str);
(*jni_env)->DeleteLocalRef(jni_env, str);
return;
}
#endif
cli_puts(name);
cli_delim(delim);
}
void cli_put_long(int64_t value, const char *delim){
#ifdef HAVE_JNI_H
if (jni_env) {
(*jni_env)->CallVoidMethod(jni_env, jniResults, putLong, value);
return;
}
#endif
cli_printf("%lld",value);
cli_delim(delim);
}
void cli_put_string(const char *value, const char *delim){
#ifdef HAVE_JNI_H
if (jni_env) {
jstring str = NULL;
if (value){
str = (jstring)(*jni_env)->NewStringUTF(jni_env, value);
if (str == NULL) {
jni_exception = 1;
WHY("Exception thrown from NewStringUTF()");
return;
}
}
(*jni_env)->CallVoidMethod(jni_env, jniResults, putString, str);
(*jni_env)->DeleteLocalRef(jni_env, str);
return;
}
#endif
if (value)
cli_puts(value);
cli_delim(delim);
}
void cli_put_hexvalue(const unsigned char *value, int length, const char *delim){
#ifdef HAVE_JNI_H
if (jni_env) {
put_blob((jbyte*)value, length);
return;
}
#endif
if (value)
cli_puts(alloca_tohex(value, length));
cli_delim(delim);
}
void cli_row_count(int rows){
#ifdef HAVE_JNI_H
if (jni_env) {
(*jni_env)->CallVoidMethod(jni_env, jniResults, totalRowCount, rows);
if ((*jni_env)->ExceptionOccurred(jni_env)) {
jni_exception = 1;
WHY("Exception thrown from CallVoidMethod()");
return;
}
}
#endif
}
/* 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();
#endif
const char *delim = getenv("SERVALD_OUTPUT_DELIMITER");
if (delim == NULL)
delim = opt ? opt : "\n";
fputs(delim, stdout);
return 0;
}
/* Flush the output fields if they are being written to standard output.
*/
void cli_flush()
{
#ifdef HAVE_JNI_H
if (jni_env)
return;
#endif
fflush(stdout);
}
int app_echo(const struct cli_parsed *parsed, void *context)
{
if (config.debug.verbose)
DEBUG_cli_parsed(parsed);
int escapes = !cli_arg(parsed, "-e", NULL, NULL, NULL);
int i;
for (i = parsed->varargi; i < parsed->argc; ++i) {
const char *arg = parsed->args[i];
if (config.debug.verbose)
DEBUGF("echo:argv[%d]=\"%s\"", i, arg);
if (escapes) {
unsigned char buf[strlen(arg)];
size_t len = str_fromprint(buf, arg);
cli_write(buf, len);
} else
cli_puts(arg);
cli_delim(NULL);
}
return 0;
}
void lookup_send_request(const sid_t *srcsid, int srcport, const sid_t *dstsid, const char *did)
{
int i;
overlay_mdp_frame mdp;
bzero(&mdp,sizeof(mdp));
/* set source address to a local address, and pick a random port */
mdp.out.src.port=srcport;
bcopy(srcsid->binary, mdp.out.src.sid, SID_SIZE);
/* Send to destination address and DNA lookup port */
if (dstsid) {
/* Send an encrypted unicast packet */
mdp.packetTypeAndFlags=MDP_TX;
bcopy(dstsid->binary, mdp.out.dst.sid, SID_SIZE);
}else{
/* Send a broadcast packet, flooding across the local mesh network */
mdp.packetTypeAndFlags=MDP_TX|MDP_NOCRYPT;
for(i=0;i<SID_SIZE;i++)
mdp.out.dst.sid[i]=0xff;
}
mdp.out.dst.port=MDP_PORT_DNALOOKUP;
/* put DID into packet */
bcopy(did,&mdp.out.payload[0],strlen(did)+1);
mdp.out.payload_length=strlen(did)+1;
overlay_mdp_send(&mdp,0,0);
/* Also send an encrypted unicast request to a configured directory service */
if (!dstsid){
if (!is_sid_any(config.directory.service.binary)) {
memcpy(mdp.out.dst.sid, config.directory.service.binary, SID_SIZE);
mdp.packetTypeAndFlags=MDP_TX;
overlay_mdp_send(&mdp,0,0);
}
}
}
int app_dna_lookup(const struct cli_parsed *parsed, void *context)
{
if (config.debug.verbose)
DEBUG_cli_parsed(parsed);
/* Create the instance directory if it does not yet exist */
if (create_serval_instance_dir() == -1)
return -1;
int uri_count=0;
#define MAXREPLIES 256
#define MAXURILEN 256
char uris[MAXREPLIES][MAXURILEN];
const char *did, *delay;
if (cli_arg(parsed, "did", &did, cli_lookup_did, "*") == -1)
return -1;
if (cli_arg(parsed, "timeout", &delay, NULL, "3000") == -1)
return -1;
int idelay=atoi(delay);
int one_reply=0;
// Ugly hack, if timeout is negative, stop after first reply
if (idelay<0){
one_reply=1;
idelay=-idelay;
}
/* Bind to MDP socket and await confirmation */
sid_t srcsid;
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. */
/* Now repeatedly send resolution request and collect results until we reach
timeout. */
time_ms_t timeout = gettime_ms() + idelay;
time_ms_t last_tx = 0;
time_ms_t now;
int interval=125;
while (timeout > (now = gettime_ms()))
{
if ((last_tx+interval)<now)
{
lookup_send_request(&srcsid, port, NULL, did);
last_tx=now;
interval+=interval>>1;
}
time_ms_t short_timeout=125;
while(short_timeout>0) {
if (overlay_mdp_client_poll(short_timeout))
{
overlay_mdp_frame rx;
int ttl;
if (overlay_mdp_recv(&rx, port, &ttl)==0)
{
if (rx.packetTypeAndFlags==MDP_ERROR)
{
WHYF(" Error message: %s", rx.error.message);
}
else if ((rx.packetTypeAndFlags&MDP_TYPE_MASK)==MDP_TX) {
/* Extract DID, Name, URI from response. */
if (strlen((char *)rx.in.payload)<512) {
char sidhex[SID_STRLEN + 1];
char did[DID_MAXSIZE + 1];
char name[64];
char uri[512];
if ( !parseDnaReply((char *)rx.in.payload, rx.in.payload_length, sidhex, did, name, uri, NULL)
|| !str_is_subscriber_id(sidhex)
|| !str_is_did(did)
|| !str_is_uri(uri)
) {
WHYF("Received malformed DNA reply: %s", alloca_toprint(160, (const char *)rx.in.payload, rx.in.payload_length));
} else {
/* Have we seen this response before? */
int i;
for(i=0;i<uri_count;i++)
if (!strcmp(uri,uris[i])) break;
if (i==uri_count) {
/* Not previously seen, so report it */
cli_puts(uri); cli_delim(":");
cli_puts(did); cli_delim(":");
cli_puts(name); cli_delim("\n");
if (one_reply){
timeout=now;
short_timeout=0;
}
/* Remember that we have seen it */
if (uri_count<MAXREPLIES&&strlen(uri)<MAXURILEN) {
strcpy(uris[uri_count++],uri);
}
}
}
}
}
else WHYF("packettype=0x%x",rx.packetTypeAndFlags);
if (servalShutdown) break;
}
}
if (servalShutdown) break;
short_timeout=125-(gettime_ms()-now);
}
if (servalShutdown) break;
}
overlay_mdp_client_done();
return 0;
}
int app_server_start(const struct cli_parsed *parsed, void *context)
{
IN();
if (config.debug.verbose)
DEBUG_cli_parsed(parsed);
/* Process optional arguments */
int pid=-1;
int cpid=-1;
#if 0
// It would have been nice if whoever disabled this code had left a comment as to why they didn't
// simply delete it altogether. In any event, this logic is largely redundant because the Android
// Batphone app automatically calls "servald stop" then "servald start" (via JNI) whenever its
// monitor interface socket is broken.
// -- Andrew Bettison <andrew@servalproject.com>
int status=server_probe(&pid);
switch(status) {
case SERVER_NOTRESPONDING:
/* server is not responding, and we have been asked to start,
so try to kill it?
*/
WHYF("Serval process already running (pid=%d), but no responding.", pid);
if (pid>-1) {
kill(pid,SIGHUP); sleep(1);
status=server_probe(&pid);
if (status!=SERVER_NOTRUNNING) {
WHY("Tried to stop stuck servald process, but attempt failed.");
RETURN(-1);
}
WHY("Killed stuck servald process, so will try to start");
pid=-1;
}
break;
case SERVER_NOTRUNNING:
/* all is well */
break;
case SERVER_RUNNING:
/* instance running */
break;
default:
/* no idea what is going on, so try to start anyway */
break;
}
#endif
const char *execpath, *instancepath;
char *tmp;
int foregroundP = parsed->argc >= 2 && !strcasecmp(parsed->args[1], "foreground");
if (cli_arg(parsed, "instance path", &instancepath, cli_absolute_path, NULL) == -1
|| cli_arg(parsed, "exec path", &execpath, cli_absolute_path, NULL) == -1)
RETURN(-1);
if (instancepath != NULL)
serval_setinstancepath(instancepath);
if (execpath == NULL) {
#ifdef HAVE_JNI_H
if (jni_env)
RETURN(WHY("Must supply <exec path> argument when invoked via JNI"));
#endif
if ((tmp = malloc(PATH_MAX)) == NULL)
RETURN(WHY("Out of memory"));
if (get_self_executable_path(tmp, PATH_MAX) == -1)
RETURN(WHY("unable to determine own executable name"));
execpath = tmp;
}
/* Create the instance directory if it does not yet exist */
if (create_serval_instance_dir() == -1)
RETURN(-1);
/* Now that we know our instance path, we can ask for the default set of
network interfaces that we will take interest in. */
if (config.interfaces.ac == 0)
WARN("No network interfaces configured (empty 'interfaces' config option)");
if (pid == -1)
pid = server_pid();
if (pid < 0)
RETURN(-1);
int ret = -1;
// If the pidfile identifies this process, it probably means we are re-spawning after a SEGV, so
// go ahead and do the fork/exec.
if (pid > 0 && pid != getpid()) {
INFOF("Server already running (pid=%d)", pid);
ret = 10;
} else {
if (foregroundP)
INFOF("Foreground server process %s", execpath ? execpath : "without exec");
else
INFOF("Starting background server %s", execpath ? execpath : "without exec");
/* Start the Serval process. All server settings will be read by the server process from the
instance directory when it starts up. */
if (server_remove_stopfile() == -1)
RETURN(-1);
overlayMode = 1;
if (foregroundP)
RETURN(server(NULL));
const char *dir = getenv("SERVALD_SERVER_CHDIR");
if (!dir)
dir = config.server.chdir;
switch (cpid = fork()) {
case -1:
/* Main process. Fork failed. There is no child process. */
RETURN(WHY_perror("fork"));
case 0: {
/* Child process. Fork then exit, to disconnect daemon from parent process, so that
when daemon exits it does not live on as a zombie. N.B. Do not return from within this
process; that will unroll the JNI call stack and cause havoc. Use _exit(). */
switch (fork()) {
case -1:
exit(WHY_perror("fork"));
case 0: {
/* Grandchild process. Close logfile (so that it gets re-opened again on demand, with
our own file pointer), disconnect from current directory, disconnect standard I/O
streams, and start a new process session so that if we are being started by an adb
shell session, then we don't receive a SIGHUP when the adb shell process ends. */
close_logging();
int fd;
if ((fd = open("/dev/null", O_RDWR, 0)) == -1)
_exit(WHY_perror("open"));
if (setsid() == -1)
_exit(WHY_perror("setsid"));
(void)chdir(dir);
(void)dup2(fd, 0);
(void)dup2(fd, 1);
(void)dup2(fd, 2);
if (fd > 2)
(void)close(fd);
/* The execpath option is provided so that a JNI call to "start" can be made which
creates a new server daemon process with the correct argv[0]. Otherwise, the servald
process appears as a process with argv[0] = "org.servalproject". */
if (execpath) {
/* Need the cast on Solaris because it defines NULL as 0L and gcc doesn't see it as a
sentinal. */
execl(execpath, execpath, "start", "foreground", (void *)NULL);
_exit(-1);
}
_exit(server(NULL));
// NOT REACHED
}
}
_exit(0); // Main process is waitpid()-ing for this.
}
}
/* Main process. Wait for the child process to fork the grandchild and exit. */
waitpid(cpid, NULL, 0);
/* Allow a few seconds for the grandchild process to report for duty. */
time_ms_t timeout = gettime_ms() + 5000;
do {
sleep_ms(200); // 5 Hz
} while ((pid = server_pid()) == 0 && gettime_ms() < timeout);
if (pid == -1)
RETURN(-1);
if (pid == 0)
RETURN(WHY("Server process did not start"));
ret = 0;
}
cli_puts("instancepath");
cli_delim(":");
cli_puts(serval_instancepath());
cli_delim("\n");
cli_puts("pid");
cli_delim(":");
cli_printf("%d", pid);
cli_delim("\n");
cli_flush();
/* Sleep before returning if env var is set. This is used in testing, to simulate the situation
on Android phones where the "start" command is invoked via the JNI interface and the calling
process does not die.
*/
const char *post_sleep = getenv("SERVALD_START_POST_SLEEP");
if (post_sleep) {
time_ms_t milliseconds = atof(post_sleep) * 1000;
if (milliseconds > 0) {
INFOF("Sleeping for %lld milliseconds", (long long) milliseconds);
sleep_ms(milliseconds);
}
}
RETURN(ret);
OUT();
}
int app_server_stop(const struct cli_parsed *parsed, void *context)
{
if (config.debug.verbose)
DEBUG_cli_parsed(parsed);
int pid, tries, running;
const char *instancepath;
time_ms_t timeout;
if (cli_arg(parsed, "instance path", &instancepath, cli_absolute_path, NULL) == -1)
{
WHY("Unable to determine instance path");
return 254;
}
if (instancepath != NULL)
serval_setinstancepath(instancepath);
instancepath = serval_instancepath();
cli_puts("instancepath");
cli_delim(":");
cli_puts(instancepath);
cli_delim("\n");
pid = server_pid();
/* Not running, nothing to stop */
if (pid <= 0)
return 1;
INFOF("Stopping server (pid=%d)", pid);
/* Set the stop file and signal the process */
cli_puts("pid");
cli_delim(":");
cli_printf("%d", pid);
cli_delim("\n");
tries = 0;
running = pid;
while (running == pid) {
if (tries >= 5) {
WHYF(
"Servald pid=%d for instance '%s' did not stop after %d SIGHUP signals",
pid, instancepath, tries
);
return 253;
}
++tries;
/* Create the stopfile, which causes the server process's signal handler to exit
instead of restarting. */
server_create_stopfile();
if (kill(pid, SIGHUP) == -1) {
// ESRCH means process is gone, possibly we are racing with another stop, or servald just
// died voluntarily.
if (errno == ESRCH) {
serverCleanUp();
break;
}
WHY_perror("kill");
WHYF("Error sending SIGHUP to Servald pid=%d for instance '%s'", pid, instancepath);
return 252;
}
/* Allow a few seconds for the process to die. */
timeout = gettime_ms() + 2000;
do
sleep_ms(200); // 5 Hz
while ((running = server_pid()) == pid && gettime_ms() < timeout);
}
server_remove_stopfile();
cli_puts("tries");
cli_delim(":");
cli_printf("%d", tries);
cli_delim("\n");
return 0;
}
int app_server_status(const struct cli_parsed *parsed, void *context)
{
if (config.debug.verbose)
DEBUG_cli_parsed(parsed);
int pid;
const char *instancepath;
if (cli_arg(parsed, "instance path", &instancepath, cli_absolute_path, NULL) == -1)
return WHY("Unable to determine instance path");
if (instancepath != NULL)
serval_setinstancepath(instancepath);
pid = server_pid();
cli_puts("instancepath");
cli_delim(":");
cli_puts(serval_instancepath());
cli_delim("\n");
cli_puts("status");
cli_delim(":");
cli_printf("%s", pid > 0 ? "running" : "stopped");
cli_delim("\n");
if (pid > 0) {
cli_puts("pid");
cli_delim(":");
cli_printf("%d", pid);
cli_delim("\n");
}
return pid > 0 ? 0 : 1;
}
int app_mdp_ping(const struct cli_parsed *parsed, void *context)
{
if (config.debug.verbose)
DEBUG_cli_parsed(parsed);
const char *sidhex, *count;
if (cli_arg(parsed, "SID|broadcast", &sidhex, str_is_subscriber_id, "broadcast") == -1)
return -1;
if (cli_arg(parsed, "count", &count, NULL, "0") == -1)
return -1;
// assume we wont hear any responses
int ret=-1;
int icount=atoi(count);
overlay_mdp_frame mdp;
bzero(&mdp, sizeof(overlay_mdp_frame));
/* Bind to MDP socket and await confirmation */
sid_t srcsid;
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.
TODO - allow lookup of SID prefixes and telephone numbers
(that would require MDP lookup of phone numbers, which doesn't yet occur) */
sid_t ping_sid;
if (str_to_sid_t(&ping_sid, sidhex) == -1)
return WHY("str_to_sid_t() failed");
int broadcast = is_sid_broadcast(ping_sid.binary);
/* TODO Eventually we should try to resolve SID to phone number and vice versa */
printf("MDP PING %s (%s): 12 data bytes\n", alloca_tohex_sid_t(ping_sid), alloca_tohex_sid_t(ping_sid));
time_ms_t rx_mintime=-1;
time_ms_t rx_maxtime=-1;
time_ms_t rx_ms=0;
time_ms_t rx_times[1024];
long long rx_count=0,tx_count=0;
if (broadcast)
WHY("WARNING: broadcast ping packets will not be encryped.");
while(icount==0 || tx_count<icount) {
/* Now send the ping packets */
mdp.packetTypeAndFlags=MDP_TX;
if (broadcast) mdp.packetTypeAndFlags|=MDP_NOCRYPT;
mdp.out.src.port=port;
bcopy(srcsid.binary, mdp.out.src.sid, SID_SIZE);
bcopy(ping_sid.binary, mdp.out.dst.sid, SID_SIZE);
mdp.out.queue=OQ_MESH_MANAGEMENT;
/* Set port to well known echo port */
mdp.out.dst.port=MDP_PORT_ECHO;
mdp.out.payload_length=4+8;
int *seq=(int *)&mdp.out.payload;
*seq=sequence_number;
long long *txtime=(long long *)&mdp.out.payload[4];
*txtime=gettime_ms();
int res=overlay_mdp_send(&mdp,0,0);
if (res) {
WHYF("ERROR: Could not dispatch PING frame #%d (error %d)", sequence_number - firstSeq, res);
if (mdp.packetTypeAndFlags==MDP_ERROR)
WHYF(" Error message: %s", mdp.error.message);
} else tx_count++;
/* Now look for replies until one second has passed, and print any replies
with appropriate information as required */