-
Notifications
You must be signed in to change notification settings - Fork 51
/
vosamp.c
2298 lines (1899 loc) · 65.9 KB
/
vosamp.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
/**
* VOSAMP - Example task to send a single SAMP message for the cmdline.
*
* Usage:
*
* vosamp [<opts>] <cmd> [args ...]
*
* Where
* <cmd> command to process
* -%,--test run unit tests
* -h,--help print help summary
* -d,--debug debug output
* -v,--verbose verbose output
* -q,--quiet suppress all output
*
* -i,--interactive interactive mode
* -m,--many handle multiple messages
* -s,--sender <sender> handle only messages from <sender>
*
* -t,--to <to> send to specified application (or all)
* -p,--pattern <pattern> message pattern: sync|async|notify
* -f,--file <file> send all commands in the file
* -n,--nokeepalive disable keep_alive feature
*
* -P,--proxy <pattern> proxy process connection
* -T,--timeout <N> keepalive timeout
* -S,--session <name> session name
*
* -r,--return return result to API
*
*
* Subcommands:
*
* snoop print all received messages
*
* session list list all nodes in current session
* session leave|exit|logout leave the current session
* session <name> join the named session
*
* status print Hub availability
* list list all registered clients
* access <appName> print <appName> availability
* handle <mtype> wait for <mtype> message
*
* send <mtype> [<args> ...] generalized <mtype> message send
* exec <cmd> execute a client command
* pointAt <ra> <dec> point at given coords
* setenv <name> <value> set an environment value
* getenv <name> get an environment value
* setparam <name> <value> set a parameter value
* getparam <name> get a parameter value
*
* load <url> load the named image/table file
* loadImage <url> load the named image
* loadVOTable <url> load the named VOTable
* loadFITS <url> load the named FITS bintable
* showRow [<tblId>] [<url>] <row> highlight specified row
* selectRows [<tblId>] [<url>] <rows> select specified rows
* bibcode <bibcode> load the named bibcode
*
*
* @file vosamp.c
* @author Mike Fitzpatrick
* @date 6/03/12
*
* @brief Desktop SAMP messaging utility.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <time.h>
#include <netdb.h>
#include <sys/errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "samp.h" /* LIBSAMP interface */
#include "voApps.h" /* voApps interface */
#define SZ_MTYPE 64
#define SZ_BUF 128
#define SZ_HOSTIP 16
#define SZ_APPNAME 16
#define SZ_BLOCK 4096
#define HUB_TIMEOUT /* allow timeout */
#define ENV_PROXY "VOSAMP_PROXY"
#define MAX_ARGS 8
#define VOS_TIMEOUT 600 /* 10-min proxy timeout */
#define VOS_DEFPORT 3999
#define VOS_HUBWAIT 3
#define MATCH(s) (strcasecmp(cmd,s)==0)
char senderIP[SZ_HOSTIP];
char fname[SZ_FNAME];
char *to = NULL;
static int sampH = 0; /* samp struct handle */
/* task options */
static int verbose = 0; /* verbose output */
static int quiet = 0; /* suppress all output */
static int debug = 0; /* verbose output */
static int interact = 0; /* interactive shell */
static int multiple = 0; /* accept multiple msgs */
static int xml_trace = 0; /* trace XML_RPC */
static int keep_alive = 1; /* lingering connection */
static int proxy_pid = 0; /* proxy vosamp pid */
static int proxy_port = VOS_DEFPORT; /* proxy vosamp port */
static int svr_sock = 0; /* child server socket */
static int ipc_sock = 0; /* IPC sock (parent/child) */
static int session_sock = 0; /* session mgr socket */
static int input_sock = 0; /* cmd input socket */
static int use_ipc = 1; /* use IPC */
static int have_dotfile = 0; /* have a valid .vosamp? */
static int in_parent = 1; /* are we parent process? */
static int do_return = 1; /* return result to API */
static int return_stat = OK; /* return status */
static int numargs = 0; /* number of cmdline args */
static int timeout = VOS_TIMEOUT; /* child timeout */
static int hub_connected = 0; /* connected to SAMP hub */
static int sess_connected = 0; /* connected to session mgr */
char *session_host = SESS_DEFHOST; /* session manager host IP */
int session_port = SESS_DEFPORT; /* session manager port */
static char *proxy = NULL; /* proxy connection string */
static char *session = NULL; /* session name */
static char *pattern = NULL; /* SAMP msg pattern */
static char *cmdfile = NULL; /* input command file */
static char *filt_mtype = NULL; /* snoop filter mtype */
static char *filt_sender = NULL; /* snoop sender name */
static char cmd[SZ_CMD]; /* command name */
static char cmdline[SZ_CMD]; /* full command line */
static char proxy_host[SZ_FNAME]; /* proxy vosamp host name */
static char dotfile[SZ_FNAME]; /* path to local dotfile */
static char psession[SZ_FNAME]; /* proxy file session name */
static char *args[MAX_ARGS]; /* command args buffer */
static FILE *fd = (FILE *) NULL;
static fd_set allset, fds;
static struct timeval tm;
static int vos_sendToProxy (char *cmdline);
static int vos_startProxy (void);
static int vos_sampInit (void);
static int vos_sendCmd (int sock, char *cmdline);
static int vos_invalidArg (int argc, char *argv[], int nargs, int exist);
static void vos_sampShutdown (void);
static void vos_cmdHelp (char *cmd);
static void vos_procCmd(int sampH, char *to, char *cmd, char **argv, int argc);
static void vos_handleCmdInput (void);
static void vos_msgHandler (char *sender, char *mtype, char *msg_id, Map map);
static void vos_sessionHandler (char *sender, char *mtype, char *id, Map map);
static void vos_forwardCmd (char *sess_cmd);
static void vos_printMessage (char *mtype, char *sender, Map map);
static void vos_rewriteCmd (char *line, char *fname);
static void vosDebug (char *format, ...);
static char *vos_rewriteURL (char *in);
static char *vos_dotFile ();
int vos_uploadFiles (int fd, char *cmdline);
int vos_recvFile (int sock, int size, char *fname);
int vos_sendFile (int sock, char *path, char *fname);
int vos_openSession (char *host, int port, char *session_name);
int vos_closeSession (int sock);
extern char *vos_toURL (char *arg);
extern char *vos_optArg (char *arg);
extern char *vos_getLocalIP (void);
extern char *vos_getFName (char *url);
extern char *vos_typeName (int type);
extern int *vos_toIntArray (char *arg, int *nrows);
extern int vot_atoi (char *v);
/* Utility socket routines.
*/
extern int vos_fileRead (int fd, void *vptr, int nbytes);
extern int vos_fileWrite (int fd, void *vptr, int nbytes);
extern int vos_openServerSocket (int port);
extern int vos_openClientSocket (char *host, int port, int retry);
extern int vos_testClientSocket (char *host, int port);
extern int vos_sockRead (int fd, void *vptr, int nbytes);
extern int vos_sockWrite (int fd, void *vptr, int nbytes);
extern int vos_sockWriteHdr (int fd, int len, char *name, int type,
int mode, char *to);
extern int vos_sockReadHdr (int fd, int *len, char *name, int *type,
int *mode);
extern int vos_urlType (char *url);
extern int vos_getURL (char *url, char *fname);
extern double vot_atof (char *v);
extern void vos_setNonBlock (int sock);
extern struct hostent *vos_getHostByName (char *lhost);
extern struct hostent *vos_dupHostent (struct hostent *hentry);
/* Task specific option declarations.
*/
int vosamp (int argc, char **argv, size_t *len, void **result);
static Task self = { "vosamp", vosamp, 0, 0, 0 };
static char *opts = "%:hnrdif:mps:t:vP:T:S:";
static struct option long_opts[] = {
{ "return", 0, 0, 'r'}, /* task option */
{ "help", 2, 0, 'h'}, /* required */
{ "test", 1, 0, '%'}, /* required */
{ "debug", 2, 0, 'd'}, /* debug */
{ "verbose", 2, 0, 'v'}, /* verbose output */
{ "quiet", 2, 0, 'q'}, /* suppress output */
{ "many", 2, 0, 'm'}, /* multiple msgs */
{ "sender", 1, 0, 's'}, /* sender filter */
{ "interactive", 2, 0, 'i'}, /* interactive mode */
{ "file", 1, 0, 'f'}, /* cmd file */
{ "pattern", 1, 0, 'p'}, /* msg pattern */
{ "proxy", 1, 0, 'P'}, /* proxy connection */
{ "session", 1, 0, 'S'}, /* session name */
{ "to", 1, 0, 't'}, /* recipient name */
{ "nokeepalive", 2, 0, 'n'}, /* keep connection */
{ "timeout", 1, 0, 'T'}, /* connection timeout */
{ NULL, 0, 0, 0 }
};
static void Usage (void);
static void Tests (char *input);
/****************************************************************************
* Program entry point.
*/
int
vosamp (int argc, char **argv, size_t *reslen, void **result)
{
char **pargv, optval[SZ_FNAME], *env_proxy = NULL;
int i, pos = 0, len = 0, ch;
time_t expiry;
/* Initialize.
*/
memset (cmd, 0, SZ_CMD);
memset (cmdline, 0, SZ_CMD);
memset (dotfile, 0, SZ_FNAME);
memset (psession, 0, SZ_FNAME);
memset (proxy_host, 0, SZ_FNAME);
strcpy (proxy_host, vos_getLocalIP ());
strcpy (dotfile, vos_dotFile ());
for (i=0; i < MAX_ARGS; i++)
args[i] = calloc (1, SZ_LINE);
*reslen = 0;
*result = NULL;
return_stat = OK;
/* Parse the argument list.
*/
pargv = vo_paramInit (argc, argv, opts, long_opts);
i = 0;
while ((ch = vo_paramNext (opts,long_opts,argc,pargv,optval,&pos)) != 0) {
i++;
if (ch > 0) {
switch (ch) {
case '%': Tests (optval); return (self.nfail);
case 'h': Usage (); return (OK);
case 'd': debug++; break;
case 'v': verbose++; break;
case 'q': quiet++; break;
case 'n': keep_alive = 0; break;
case 'm': multiple++; break;
case 'i': interact++; break;
case 's': filt_sender = strdup (optval); i++; break;
case 'f': cmdfile = strdup (optval); i++; break;
case 't': to = strdup (optval); i++; break;
case 'p': pattern = strdup (optval); i++; break;
case 'P': proxy = strdup (optval); i++; break;
case 'S': session = strdup (optval); i++; break;
case 'T': timeout = vot_atoi (optval); i++; break;
case 'r': do_return=1; break;
default:
fprintf (stderr, "Invalid option '%s'\n", optval);
return (1);
}
} else if (ch == PARG_ERR) {
return (ERR);
} else {
/* Remainder of argv is the subcommand and its arguments.
*/
if (pargv[i] == NULL)
break;
if (!cmd[0]) {
strcpy (cmd, optval);
} else {
if (strcasecmp (cmd, "exec") == 0 ||
strcasecmp (cmd, "echo") == 0) {
strcat (args[0], optval);
strcat (args[0], " ");
} else {
char *ip;
while (pargv[i]) {
if (strstr (pargv[i], "://") == NULL) {
/* replace ':' w/ '=' */
for (ip=pargv[i]; *ip; ip++)
*ip = ((*ip == ':') ? '=' : *ip);
}
strcpy (args[numargs++], pargv[i++]);
}
break;
}
}
}
}
/* Print command help if that's all we're asked.
*/
if (strncmp (cmd, "?", 1) == 0 || strncasecmp (cmd, "help", 4) == 0) {
Usage ();
return (OK);
}
if (strncmp(args[0], "?", 1) == 0 || strncasecmp(args[0], "help", 4) == 0) {
vos_cmdHelp (cmd);
return (OK);
}
if (strncmp(cmd, "access", 6) == 0 && strncasecmp(args[0], "hub", 3) == 0) {
int hub_connected = vos_sampInit ();
printf ("%s\n", (hub_connected ? "yes" : "no"));
if (hub_connected)
vos_sampShutdown ();
return ( (hub_connected ? OK : ERR) );
}
if (strcmp (cmd, "handle") == 0 || strcmp (cmd, "snoop") == 0)
keep_alive = 0;
/* Sanity checks.
*/
if (interact || argc <= 1)
cmdfile = strdup ("-");
if (to == NULL)
to = strdup ("all");
if (pattern == NULL)
pattern = strdup ("async");
/* Initialize the SAMP interface.
tm.tv_sec = VOS_HUBWAIT;
*/
tm.tv_sec = timeout;
tm.tv_usec = 0;
session_sock = 0;
/* Check for environment definitions.
*/
if ((env_proxy = getenv (ENV_PROXY)))
proxy = strdup (env_proxy);
if (proxy) {
/* We've been asked to send the command to a particular proxy, just
* send the command line and any required data.
*/
char *cp = strchr (proxy, (int)':');
vosDebug ("Using proxy '%s'\n", proxy);
if (cp) {
proxy_port = vot_atoi (cp+1);
*cp = '\0';
strcpy (proxy_host, proxy);
} else {
proxy_port = VOS_DEFPORT;
strcpy (proxy_host, proxy);
}
use_ipc++;
have_dotfile++;
ipc_sock = vos_openClientSocket (proxy_host, proxy_port, 1);
} else {
/* See if we have a local proxy running we can use instead of starting
* a new connection. Data references remain local unless being
* passed on to the session manager service.
*/
FILE *fd = (FILE *) NULL;
if (keep_alive && access (dotfile , R_OK) == 0) {
if ((fd = fopen (dotfile, "r+")) != (FILE *) NULL) {
time_t now = time ((time_t) 0);
int test = 0;
/* Read the dotfile contents.
*/
fscanf (fd, "%s %d %d %ld %s",
proxy_host, &proxy_port, &proxy_pid, &expiry, psession);
fclose (fd);
/* Make sure we can reach the running proxy, otherwise
* assume it is a stale dotfile.
*/
if ((test = vos_testClientSocket(proxy_host, proxy_port)) < 0) {
if (verbose)
fprintf (stderr, "Removing stale .vosamp file ...\n");
unlink (dotfile);
goto samp_init;
} else {
vos_sockWriteHdr (test, 0, NULL, SAMP_TEST, 0, "proxy");
close (test);
}
/* Check for a stale dotfile. */
if (now <= (expiry - 2)) {
use_ipc++;
have_dotfile++;
} else {
if (verbose)
fprintf (stderr, "Removing stale .vosamp file ...\n");
unlink (dotfile);
goto samp_init;
}
}
} else {
/* First do some sanity checks on the command. If we're asked
* to quit, then simply don't connect.
*/
if (strncasecmp ("quit", cmd, 4) == 0) {
return (OK);
}
/* No remote command specified, no local connection, so connect to
* the Hub as a new application.
*
* Start the keep-alive proxy server.
*/
samp_init:
if (keep_alive) {
vos_startProxy ();
use_ipc = 1;
} else {
if (! (hub_connected = vos_sampInit ())) {
fprintf (stderr, "Error: cannot connect to Hub.\n");
return (ERR);
}
use_ipc = 0;
}
}
}
/* Process a single command if we're not in keep_alive mode.
*/
if (!keep_alive) {
vos_procCmd (sampH, to, cmd, args, numargs);
goto cleanup_;
}
/* Open an IPC socket to the proxy.
*/
while (in_parent && ipc_sock <= 0) {
vosDebug ("opening ipc socket to %s:%d\n", proxy_host, proxy_port);
ipc_sock = vos_openClientSocket (proxy_host, proxy_port, 1);
if (ipc_sock < 0) {
if (verbose)
fprintf (stderr, "Cannot open client ipc_sock\n");
sleep (1);
}
}
vosDebug ("ipc socket %d\n", ipc_sock);
/* Process the messages in the named file, or from the cmdline. Since
* there is some overhead in connecting to the hub, this is an efficient
* way to send multiple messages from a single connection.
*/
if (cmdfile) {
fd = (cmdfile[0] == '-' ? stdin : fopen (cmdfile, "r"));
/* Send the command string from the stdin or the cmd file.
*/
fprintf (stderr, "vosamp> ");
#ifdef FGETS
while (fgets (cmdline, SZ_CMD, fd) && !feof (fd) && !ferror (fd)) {
#else
FD_ZERO (&allset);
FD_SET (fileno (stdin), &allset);
while (1) {
memcpy (&fds, &allset, sizeof(allset));
if (select (8, &fds, NULL, NULL, NULL) == 0)
continue;
if (fgets (cmdline, SZ_CMD, stdin) == NULL)
continue;
#endif
len = strlen (cmdline);
if (cmdline[len-1] == '\n')
cmdline[len-1] = '\0';
if (strncasecmp (cmdline, "quit", 4) == 0 ||
strncasecmp (cmdline, "logo", 4) == 0)
break;
else if (cmdline[0]) {
vos_sendToProxy (cmdline);
fprintf (stderr, "vosamp> ");
}
}
if (fd != stdin)
fclose (fd);
} else if (cmd[0]) {
/* Send the command string from the commandline.
*/
int i, len = 0;
memset (cmdline, 0, SZ_CMD);
sprintf (cmdline, "%s %s ", cmd, args[0]);
for (i=1; i < numargs; i++) {
strcat (cmdline, args[i]);
strcat (cmdline, " ");
}
len = strlen (cmdline); cmdline[len-1] = '\0';
vos_sendToProxy (cmdline);
}
close (ipc_sock);
/* Close down and clean up.
*/
cleanup_:
if (!keep_alive)
vos_sampShutdown ();
if (to) free ((void *) to);
if (proxy) free ((void *) proxy);
if (cmdfile) free ((void *) cmdfile);
if (pattern) free ((void *) pattern);
if (session) free ((void *) session);
if (filt_sender) free ((void *) filt_sender);
return (return_stat);
}
/**
* VOS_SENDTOPROXY -- Send a cmdline to the proxy.
*/
static int
vos_sendToProxy (char *cmdline)
{
/* See if we need to join a session before processing the cmd.
*/
if (session && psession[0] != '\0') {
/* Have session param and running a proxy.
*/
memset (cmdline, 0, SZ_CMD);
sprintf (cmdline, "session %s", session);
} else if (strcasecmp (cmd, "session") == 0 &&
(psession[0] && strcasecmp (psession, "none") == 0)) {
/* Have session command and not running a proxy.
*/
memset (cmdline, 0, SZ_CMD);
sprintf (cmdline, "session %s", args[0]);
}
if (strcasecmp (proxy_host, vos_getLocalIP())) {
int nfiles = vos_uploadFiles (ipc_sock, cmdline);
vosDebug ("....sent %d data files....\n", nfiles);
}
if (strncmp (cmd, "?", 1) == 0 || strncmp (cmd, "help", 4) == 0) {
vos_cmdHelp (cmd);
return (0);
}
/* Send the command string.
*/
vosDebug ("sending to proxy: '%s'\n", cmdline);
if (vos_sendCmd (ipc_sock, cmdline) == 0) {
vosDebug ("sending to proxy fails: '%s'\n", cmdline);
if (verbose)
fprintf (stderr, "Error writing command '%s'\n", cmdline);
return (0);
} else {
short nread, len;
vosDebug ("reading ipc response ....\n");
nread = vos_sockRead (ipc_sock, &len, sizeof (short));
vosDebug ("ipc response len = %d....\n", len);
if (len > 0) {
char *res = calloc (1, (len+1));
nread = vos_sockRead (ipc_sock, res, len);
vosDebug ("ipc response nread = %d....res = '%s'\n", nread, res);
if ((nread > 0 && strcmp (res, "OK") != 0) || verbose)
printf ("%s\n", res);
if (res) free ((void *) res);
}
return (1);
}
return (0);
}
/**
* VOS_STARTPROXY -- Start the VOSAMP proxy process.
*/
static int
vos_startProxy (void)
{
/* Start the keep-alive proxy server.
*/
if (keep_alive && in_parent && !have_dotfile) {
switch ( fork() ) {
case 0: /* start child proxy */
vosDebug ("child pid\n");
/* Open server socket, read future input from socket.
*/
vosDebug ("child opening server port %d...\n", proxy_port);
if ((svr_sock = vos_openServerSocket (proxy_port)) < 0) {
fprintf (stderr, "Cannot open VOSAMP port %d\n", proxy_port);
if (have_dotfile) unlink (dotfile);
}
FD_ZERO (&allset);
FD_SET (svr_sock, &allset); vos_setNonBlock (svr_sock);
vosDebug ("child svr_sock %d...\n", svr_sock);
if (session) {
/* Open a client connection to the VOSAMP Session Manager.
*/
vosDebug ("initializing session '%s' on %s:%d\n", session,
session_host, session_port);
if ((session_sock = vos_openSession (session_host,
session_port, session)) < 2) {
vosDebug ("session open fails...\n");
session_sock = 0;
session = NULL;
} else {
vosDebug ("child session sock %d...\n", session_sock);
FD_SET (session_sock, &allset);
vos_setNonBlock (session_sock);
sess_connected = 1;
}
}
/* Now initialize the SAMP interface.
*/
vosDebug ("initializing SAMP connection\n");
#ifdef HUB_BLOCKS
while (vos_sampInit () == 0) {
/* Wait for a Hub connection.
*/
if (debug || verbose) {
fprintf (stderr, "Waiting for Hub ....");
sleep (VOS_HUBWAIT);
}
}
#else
hub_connected = vos_sampInit ();
#endif
in_parent = 0;
vos_handleCmdInput ();
/* Child never returns from this point .....
*/
exit (0);
break;
case -1: /* fork fails */
if (verbose && in_parent)
fprintf (stderr, "%d proxy fork failure.\n", (int)getpid());
break;
default: /* parent exits */
vosDebug ("parent pid\n");
sleep (2); /* give child a chance to start */
}
}
return (0);
}
/**
* VOS_SENDCMD -- Send a SAMP_CMD to the specified socket.
*/
static int
vos_sendCmd (int sock, char *cmdline)
{
char res[SZ_LINE];
int nread = 0, nwrite = 0, len = (cmdline ? strlen (cmdline) : 0);
vosDebug ("sendCmd: '%s'\n", cmdline);
memset (res, 0, SZ_LINE);
if (vos_sockWriteHdr (sock, len, NULL, SAMP_CMD, SAMP_NOTIFY, to)) {
vosDebug ("writing cmdline '%s' fd=%d\n", cmdline, sock);
nwrite = vos_sockWrite (sock, cmdline, len);
/* See if we have a result returned to us. If so, it will be
* a character string we should just print out.
*/
if (session && sock != session_sock) {
vosDebug ("reading response fd=%d\n", sock);
nread = vos_sockRead (sock, &len, sizeof (int));
if (len > 0) {
char *res = calloc (1, (len+1));
nread = vos_sockRead (sock, res, len);
if ((nread > 0 && strcmp (res, "OK") != 0) || verbose)
printf ("%s\n", res);
if (res) free ((void *) res);
}
} else
return (1);
}
return (nread);
}
/**
* VOS_UPLOADFILES -- Upload any files on the commandline to the remote
* host. The remote client is responsible for rewriting the commandline
* as appropriate, our job here is to suss out which are the file arguments.
*/
int
vos_uploadFiles (int sock, char *cmdline)
{
char *ip, *op, buf[SZ_BUF], fname[SZ_FNAME];
int nfiles = 0;
for (ip=cmdline; *ip; ) {
memset (buf, 0, SZ_BUF);
memset (fname, 0, SZ_FNAME);
for (op=buf; *ip && !isspace(*ip); ) /* get token */
*op++ = *ip++;
/* Upload the file. If we have a file:// URL strip out the
* local pathname. Note that in this implementation we're
* limited to a single data file per-message.
*/
if (strncmp ("file://", buf, 7) == 0) {
strcpy (fname, &buf[7]);
if (access (fname, F_OK) < 0) /* file doesn't exist */
return (-1);
}
if (access (buf, F_OK) == 0)
strcpy (fname, buf);
if (fname[0]) { /* upload the file */
vosDebug ("uploading file '%s'....\n", fname);
if (vos_sendFile (sock, fname, vos_getFName (fname)) != OK)
fprintf (stderr, "Error sending file '%s'\n", fname);
nfiles++;
}
while (*ip && isspace (*ip)) /* skip whitespace */
ip++;
}
return (nfiles);
}
/**
* VOS_SENDFILE -- Send a file to a remote host.
*/
int
vos_sendFile (int sock, char *path, char *fname)
{
char block[SZ_BLOCK];
int fd, nread = 0, nleft = 0, size = 0, nb = 0;
struct stat fs;
if (access (path, R_OK) != 0 || stat (path, &fs) != 0)
return (ERR);
size = fs.st_size;
nleft = size;
if ((fd = open (path, O_RDONLY))) {
/* Send the header to pass the filename and size, then
* send the data itself.
*/
vos_sockWriteHdr (sock, size, fname, SAMP_DATA, 0, to);
while (nleft > 0) {
memset (block, 0, SZ_BLOCK);
nb = min (SZ_BLOCK, nleft);
/* Read from the file, write it to the socket.
*/
vos_fileRead (fd, block, nb);
vos_sockWrite (sock, block, nb);
nleft -= nb;
nread += nb;
}
close (fd);
}
return (OK);
}
/**
* VOS_RECVFILE -- Receive a file of the specified size from a remote host.
*/
int
vos_recvFile (int sock, int size, char *fname)
{
char block[SZ_BLOCK];
int fd, nread = 0, nleft = size, nb = 0;
/* Read the file from the socket, write to the filename.
*/
vosDebug ("receiving file '%s'....%d\n", fname, size);
if ((fd = open (fname, O_WRONLY|O_CREAT, 0664))) {
while (nleft > 0) {
memset (block, 0, SZ_BLOCK);
nb = min (SZ_BLOCK, nleft);
/* Read from the socket, write it to the file.
*/
vos_sockRead (sock, block, nb);
vos_fileWrite (fd, block, nb);
nleft -= nb;
nread += nb;
}
close (fd);
}
return (OK);
}
/**
* VOS_HANDLECMDINPUT -- Handle input from an input source.
*/
static void
vos_handleCmdInput ()
{
register int i, read_timeout = 0, rc;
char line[SZ_CMD];
static char data_file[SZ_FNAME];
memset (line, 0, SZ_CMD);
memset (data_file, 0, SZ_FNAME);
while (1) { /* loop until timeout */
/* Initialize the input file descriptor set and cmd buffer.
*/
memset (line, 0, SZ_CMD);
memset (cmd, 0, SZ_CMD);
for (i=0; i < MAX_ARGS; i++)
memset (args[i], 0, SZ_LINE);
memcpy (&fds, &allset, sizeof(allset));
if ((rc = select (8, &fds, NULL, NULL, (timeout ? &tm : NULL))) == 0) {
read_timeout++; /* input timeout */
if (hub_connected && !samp_hubRunning()) {
hub_connected = 0;
}
if (!hub_connected && samp_hubRunning()) {
hub_connected = vos_sampInit();
#ifdef HUB_TIMEOUT
} else {
unlink (dotfile); /* clean up the dotfile */
vos_sampShutdown (); /* shutdown Hub connection */
return;
#endif
}
continue;
} else if (rc < 0) { /* Select error .... */
vosDebug ("select error '%s'\n", strerror (errno));
continue;
}
if (FD_ISSET(svr_sock, &fds)) {
int nbytes = 0, nread = 0, type = 0, mode = 0;
char fname[SZ_FNAME];
/* Accept a connection on the proxy port from a cmdline client.
*/
vosDebug ("got input on server socket....\n");
memset (fname, 0, SZ_FNAME);
if ((ipc_sock = accept (svr_sock, NULL, NULL)) < 0) {
fprintf (stderr, "accept() errno %d: %s",
errno, strerror(errno));
continue;
}
if (vos_sockReadHdr (ipc_sock, &nbytes, fname, &type, &mode)) {
vosDebug ("server input: msgType = %s....\n",
vos_typeName (type));
if (strcasecmp (proxy_host, senderIP) && type == SAMP_DATA) {
if (vos_recvFile (ipc_sock, nbytes, fname) != OK) {
if (verbose || debug)
fprintf (stderr, "Error in recvFile '%s'\n", fname);
}
strcpy (data_file, fname);
if (vos_sockReadHdr(ipc_sock, &nbytes, fname,&type,&mode)) {
nread = vos_sockRead (ipc_sock, line, nbytes);
vos_rewriteCmd (line, data_file);
}
memset (data_file, 0, SZ_FNAME);
} else if (type == SAMP_CMD) {
nread = vos_sockRead (ipc_sock, line, nbytes);
vosDebug ("server cmd = '%s'....nr=%d nb=%d\n",
line, nread, nbytes);
if (data_file[0]) {
vos_rewriteCmd (line, data_file);
memset (data_file, 0, SZ_FNAME);
}
} else if (type == SAMP_RESULT) {
; /* Not yet implemented */
} else if (type == SAMP_TEST) {
close (ipc_sock); /* Test connection, just ignore. */
}
}
input_sock = ipc_sock;
} else if (FD_ISSET(session_sock, &fds)) {
int nbytes = 0, nread = 0, type = 0, mode = 0;
/* Accept a command from the session manager for forwarding.
*/
if (vos_sockReadHdr (session_sock, &nbytes, fname, &type, &mode)) {
vosDebug ("got input on session socket....\n");
nread = vos_sockRead (session_sock, line, nbytes);
input_sock = session_sock;
} else {
/* Session manager closed the socket, shut it down and
* disconnect.
*/
vosDebug ("Closing session socket....\n");
FD_CLR (session_sock, &allset);
close (session_sock);
if (session) free ((void *) session);
session = NULL;
session_sock = 0;
continue;
}
} else
vosDebug ("Ignoring input on other descriptor ...\n");