-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathzoosh.cpp
More file actions
1471 lines (1319 loc) · 40.1 KB
/
zoosh.cpp
File metadata and controls
1471 lines (1319 loc) · 40.1 KB
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
// Copyright 2015 Yahoo! Inc.
// Author: Tim Crowder
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <zookeeper.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/errno.h>
#include <regex.h>
#include <time.h>
#include <string>
#include <vector>
#include <map>
#include <readline/readline.h>
#include <readline/history.h>
using namespace std;
class FileCommand;
typedef map<string, FileCommand*>::iterator CommandIterator;
const char* WHITESPACE = " \t\f";
string pwdStr("/");
int done;
string servers;
zhandle_t *zh;
clientid_t myid;
volatile bool connected;
#define ifstr(var, val) if (var==val) { return #val; }
const char* ZooStatusToStr(int zstatus) {
ifstr(zstatus, ZOK)
ifstr(zstatus, ZSYSTEMERROR)
ifstr(zstatus, ZRUNTIMEINCONSISTENCY)
ifstr(zstatus, ZDATAINCONSISTENCY)
ifstr(zstatus, ZCONNECTIONLOSS)
ifstr(zstatus, ZMARSHALLINGERROR)
ifstr(zstatus, ZUNIMPLEMENTED)
ifstr(zstatus, ZOPERATIONTIMEOUT)
ifstr(zstatus, ZBADARGUMENTS)
ifstr(zstatus, ZINVALIDSTATE)
ifstr(zstatus, ZAPIERROR)
ifstr(zstatus, ZNONODE)
ifstr(zstatus, ZNOAUTH)
ifstr(zstatus, ZBADVERSION)
ifstr(zstatus, ZNOCHILDRENFOREPHEMERALS)
ifstr(zstatus, ZNODEEXISTS)
ifstr(zstatus, ZNOTEMPTY)
ifstr(zstatus, ZSESSIONEXPIRED)
ifstr(zstatus, ZINVALIDCALLBACK)
ifstr(zstatus, ZINVALIDACL)
ifstr(zstatus, ZAUTHFAILED)
ifstr(zstatus, ZCLOSING)
ifstr(zstatus, ZNOTHING)
ifstr(zstatus, ZSESSIONMOVED)
return "<Zoo Status Unknown>";
}
const char* GetZooErrorReason(int rc) {
if (rc) {
switch (rc) {
// system/server-side errors
case ZBADARGUMENTS : return "invalid input parameters";
case ZINVALIDSTATE : return "bad zookeeper state";
case ZMARSHALLINGERROR : return "marshall error (out of mem?)";
// API errors
case ZNONODE : return "node does not exist";
case ZNOAUTH : return "permission error";
case ZBADVERSION : return "node version check failed";
case ZNOCHILDRENFOREPHEMERALS : return "ephemeral nodes can't have children";
case ZNODEEXISTS : return "node already exists";
case ZNOTEMPTY : return "directory not empty";
case ZINVALIDACL : return "invalid ACL";
case ZAUTHFAILED : return "client auth failed";
}
return "<unknown>";
}
return NULL;
}
#ifndef CERT_UTIL
#define CERT_UTIL "zoosh-cert-util"
#define CERT_ARGS "--show"
#define CERT_TYPE "auth-type"
#endif
int GetCert(const std::string& role, std::string& cert) {
FILE *fpipe;
int status;
char buf[1024];
std::string cmd = CERT_UTIL " " CERT_ARGS;
cmd += role;
fpipe = (FILE*)popen(cmd.c_str(), "r");
if (!fpipe) {
fprintf(stderr, "Error on popen for " CERT_UTIL "\n");
return -1;
}
char* read = fgets(buf, sizeof(buf), fpipe);
if (!read) {
fprintf(stderr, "Error reading response from " CERT_UTIL "\n");
return -1;
}
status = pclose(fpipe);
if (status) {
fprintf(stderr, "Error %d on pclose for " CERT_UTIL "\n", status);
return -1;
}
int len = strlen(buf);
// remove trailing newline
if (buf[len-1] == '\n') { buf[len-1]=0; }
char *sep = strstr(buf, ": ");
if (!sep) {
fprintf(stderr, "Error parsing " CERT_UTIL " response [%s]\n", buf);
return -1;
}
cert = (sep+2); // skip ": "
if (cert == "NOT FOUND") {
return -1;
}
return 0;
}
// Strip whitespace from the start and end of 'text'.
void StripWhite(string &text) {
string::size_type s = text.find_first_not_of(WHITESPACE);
string::size_type e = text.find_last_not_of(WHITESPACE);
if (s==string::npos || e==string::npos) {
text.empty();
} else {
text = text.substr(s, e+1-s);
}
}
// split a string on any character in delimiters
int SplitString(string &str, vector<string> &tokens, const string& delims) {
string::size_type s = 0;
string::size_type e = str.find_first_of(delims, s);
tokens.clear();
while ((e!=string::npos)) {
string tmp = str.substr(s, e-s);
tokens.push_back(tmp);
s = str.find_first_not_of(delims, e);
if (s==string::npos) { break; }
e = str.find_first_of(delims, s);
}
if (s!=string::npos) {
string tmp = str.substr(s, str.size()+1-s);
tokens.push_back(tmp);
}
return tokens.size();
}
// split a string on whitespaces
int SplitTokens(string &cmd, vector<string> &tokens) {
return SplitString(cmd, tokens, WHITESPACE);
//string::size_type s = 0;
//string::size_type e = cmd.find_first_of(WHITESPACE, s);
//tokens.clear();
//while ((e!=string::npos)) {
// string tmp = cmd.substr(s, e-s);
// tokens.push_back(tmp);
// s = cmd.find_first_not_of(WHITESPACE, e);
// if (s==string::npos) { break; }
// e = cmd.find_first_of(WHITESPACE, s);
//}
//if (s!=string::npos) {
// string tmp = cmd.substr(s, cmd.size()+1-s);
// tokens.push_back(tmp);
//}
//return tokens.size();
}
int MergePath(string &dst, const string &sub) {
string::size_type found;
string newDir = dst;
if (sub.size() && '/'==sub[0]) {
newDir = sub;
} else {
// ensure a slash between directories
if ('/' != newDir[newDir.size()-1]) {
newDir += '/';
}
newDir += sub;
}
// ensure trailing slash
if ('/' != newDir[newDir.size()-1]) {
newDir += '/';
}
// simplify any parent-relative paths
while (string::npos != (found = newDir.find("/../")) ) {
string::size_type start = newDir.rfind('/', found-1);
if (start==string::npos) {
printf("Can't cd to non existent directory [%s] from [%s]\n", sub.c_str(), dst.c_str());
return (1);
}
newDir.erase(start, (found+3-start));
}
// remove any no-op paths
while (string::npos != (found=newDir.find("/./")) ) {
newDir.erase(found, 2);
}
while (string::npos != (found=newDir.find("//")) ) {
newDir.erase(found, 1);
}
dst = newDir;
return 0;
}
int FinalizePath(string& path) {
if (path.size()==0 || path[0]!='/') {
string tmp = pwdStr;
MergePath(tmp, path);
path = tmp;
}
if (path.size()<2) {
return 0;
}
if ('/' == path[path.size()-1]) {
path.resize(path.size()-1);
return 0;
}
return 0;
}
bool GetParentDirectory(const string &path, string &parent) {
string::size_type sep = path.find_last_of("/");
if (sep==string::npos || sep==0) {
return false;
}
parent = path.substr(0, sep);
return true;
}
bool IsWildcard(const string& arg) {
return
(arg.find_first_of("*?[]") != string::npos);
}
bool IsOption(const string& arg) {
return (arg[0]=='-' || arg[0] == '+');
}
int GetDirectoryListing(const string& path, vector<string> &entries) {
//printf("listing directory %s\n", path.c_str());
struct String_vector list;
int rc = zoo_get_children(zh, path.c_str(), 0, &list);
if (rc) { return rc; }
for (int i=0; i<list.count; ++i) {
entries.push_back(list.data[i]);
}
return 0;
}
// assumes the wildcard is at the end of the string
// doesn't do recursive matching
// TODO just split by directory separator '/' and expand into a tree...
// this doesn't allow for wildcard parts that span dir/subdir, but is much better
int GlobWildcardTail(const string& pattern, vector<string> &matched) {
string parent;
regex_t regex;
regmatch_t match;
vector<string> entries;
// force full line match?
//fullpat = "^"; fullpat += pattern; fullpat += "$";
if (regcomp(®ex, pattern.c_str(), REG_EXTENDED|REG_NOSUB)) {
printf("REGEX compiling %s FAILED \n", pattern.c_str());
return -1;
}
GetParentDirectory(pattern, parent);
GetDirectoryListing(parent, entries);
for (int i=entries.size()-1; i>=0; --i) {
string current = parent; current += '/'; current += entries[i];
if (0==regexec(®ex, current.c_str(), 1, &match, 0)) {
matched.push_back(current);
}
}
regfree(®ex);
return 0;
}
// tries to read the contents of a file into 'data'
// returns node-size on success (may be > 'maxlen')
// returns <0 on failure
int ReadFile(const string& path, string& data, int maxlen=-1) {
int rc, len, buflen;
struct stat st;
string src = path;
//FinalizePath(src);
rc = stat(src.c_str(), &st);
if (rc) {
printf("Error stat (local-fs) on [%s] %d: %s\n", src.c_str(), errno, strerror(errno));
return -1;
}
int fd = open(src.c_str(), O_RDONLY);
if (fd<0) {
printf("Error open (local-fs) on [%s] %d: %s\n", src.c_str(), errno, strerror(errno));
return -1;
}
buflen = st.st_size;
len = buflen;
if ((maxlen > 0) && (maxlen < len)) {
len = maxlen;
}
char buff[len];
ssize_t bytes = read(fd, buff, len);
close(fd);
if (bytes<0) {
printf("Read failed (local-fs) on [%s], %s\n", src.c_str(), strerror(errno));
return -1;
}
data.assign(buff, bytes);
return buflen;
}
// tries to read the contents of a ZK node into 'data'
// returns node-size on success (may be > 'maxlen')
// returns <0 on failure
int ReadNode(const string& path, string& data, int maxlen=-1) {
int rc, len, buflen;
struct Stat st;
string src = path;
FinalizePath(src);
rc=zoo_exists(zh, src.c_str(), 0, &st);
if (rc) {
printf("Error stat on [%s] %d: %s\n", src.c_str(), rc, zerror(rc));
return -1;
}
// NOTE: current jute settings limit node size to < 1MB.
buflen = st.dataLength;
len = buflen;
if ((maxlen > 0) && (maxlen < len)) {
len = maxlen;
}
char buff[len];
rc = zoo_get(zh, src.c_str(), 0, buff, &len, NULL);
if (rc) {
const char* reason = GetZooErrorReason(rc);
printf("Read (get) failed on [%s], %s\n", src.c_str(), reason);
return -1;
}
data.assign(buff, len);
return buflen;
}
int WriteFile(const string& path, string& data) {
string dest = path;
//FinalizePath(dest);
int fd = open(dest.c_str(), O_WRONLY|O_CREAT, 0644);
if (fd<0) {
printf("Error open (local-fs, write) on [%s] %d: %s\n", dest.c_str(), errno, strerror(errno));
return -1;
}
ssize_t bytes = write(fd, data.data(), data.size());
close(fd);
if (bytes<0) {
printf("Read failed (local-fs) on [%s], %s\n", dest.c_str(), strerror(errno));
return -1;
}
return bytes;
}
int WriteNode(const string& path, string& data) {
string dest = path;
FinalizePath(dest);
int flags = 0;
int rc = zoo_create(zh, dest.c_str(), data.data(), data.size(), &ZOO_OPEN_ACL_UNSAFE, flags, NULL, 0);
if (rc == ZNODEEXISTS) {
rc = zoo_set(zh, dest.c_str(), data.data(), data.size(), -1);
}
if (rc) {
fprintf(stderr, "ERROR creating node [%s] for %d -- %s\n", dest.c_str(), rc, zerror(rc));
return rc;
}
return data.size();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class FileCommand {
public:
static map<string, FileCommand*> commands;
public:
string name;
string desc;
public:
FileCommand() : name("<unknown>"), desc("<unknown>") {}
FileCommand(const char* name_, const char* desc_) : name(name_), desc(desc_) {}
virtual ~FileCommand() {}
static int RegisterCommand(FileCommand* cmd) {
commands[cmd->name] = cmd;
return commands.size();
}
// return a FileCommand or NULL if not found
static FileCommand* FindCommand(const char* name) {
CommandIterator found = commands.find(name);
if (found != commands.end()) {
return found->second;
}
return ((FileCommand *)NULL);
}
virtual bool DoFullPaths() { return true; }
virtual bool DoGlobPaths() { return true; }
virtual bool WarnNoGlobMatch() { return false; }
virtual bool ErrorNoGlobMatch() { return false; }
virtual int ExpandArgs(const vector<string> &argsIn, vector<string> &argsOut) {
if (!DoFullPaths() && !DoGlobPaths()) {
argsOut = argsIn;
return 0;
}
// push the command name
argsOut.push_back(argsIn[0]);
for (unsigned i=1; i<argsIn.size(); ++i) {
const string &word=argsIn[i];
if (IsOption(word)) {
argsOut.push_back(word);
} else if ((word.size()>0) && (word.data()[0]==':')) {
// don't mess with local paths yet
// TODO add `pwd`
argsOut.push_back(word);
} else if (DoGlobPaths() && IsWildcard(word)) {
vector<string> entries;
GlobWildcardTail(word, entries);
if (entries.size() == 0) {
if (ErrorNoGlobMatch()) {
fprintf(stderr, "ERROR: %s No Match %s\n", argsIn[0].c_str(), word.c_str());
return -1;
} else if (WarnNoGlobMatch()) {
printf("Warn: %s No Match %s\n", argsIn[0].c_str(), word.c_str());
}
}
for (unsigned c=0; c<entries.size(); ++c) {
if (DoFullPaths()) {
string path(pwdStr);
MergePath(path, entries[i]);
// strip trailing dir-slash
if (path.size()>1) {
path=path.substr(0, path.size()-1);
}
argsOut.push_back(path);
} else {
argsOut.push_back(entries[i]);
}
}
} else {
string path(pwdStr);
MergePath(path, word);
// strip trailing dir-slash
if (path.size()>1) {
path=path.substr(0, path.size()-1);
}
argsOut.push_back(path);
}
}
return 0;
}
// args[0] is the command itself
virtual int Run(const vector<string> &args) {
if (args.size()==1) {
// call the function with no args
return (Run());
} else {
unsigned i;
// loop over args, so commands don't have to deal with args
// TODO do absolute path conversion here...
for (i=1; i<args.size(); ++i) {
const string &word=args[i];
if (IsWildcard(word)) {
vector<string> entries;
// put the command itself in...
entries.push_back(args[0]);
GlobWildcardTail(word, entries);
if (entries.size()>1) {
int rc = Run(entries);
if (rc) { return rc; }
} else {
printf("%s No Matches: %s\n", args[0].c_str(), word.c_str());
}
} else {
// Call the function.
int rc = (Run(word));
if (rc) { return rc; }
}
}
}
return (0);
}
virtual int Run() {
printf("command %s can't run without a filename\n", name.c_str());
return -1;
}
virtual int Run(const string& arg) {
printf("command %s can't run with a filename\n", desc.c_str());
return -1;
}
};
map<string, FileCommand*> FileCommand::commands;
class ListState {
public:
bool recurse; // recursive listing
bool full; // show full path
bool zstat; // show ctime/mtime/version/dataLength/ephem
bool sec; // show perms/ACLs
public:
ListState() { Reset(); }
void Reset() {
recurse=false;
full=false;
zstat=false;
sec=false;
}
int ParseArg(const string& arg) {
for (unsigned j=1; j<arg.size(); ++j) {
switch (arg[j]) {
case 'r' : recurse = true; break;
case 'f' : full = true; break;
case 'l' : zstat = true; break;
case 'z' : sec = true; break;
default:
fprintf(stderr, "invalid option [%s]\n", arg.c_str());
return -1;
}
}
return 0;
}
};
//struct Stat {
// int64_t czxid; int64_t mzxid; int64_t pzxid;
// int64_t ctime; int64_t mtime;
// int32_t version; int32_t cversion; int32_t aversion;
// int64_t ephemeralOwner;
// int32_t dataLength;
// int32_t numChildren;
//};
//struct Id {
// char * scheme;
// char * id;
//};
//struct ACL {
// int32_t perms;
// struct Id id;
//};
//struct ACL_vector {
// int32_t count;
// struct ACL *data;
//};
int GetStatAclString(const string& path, string* stats, string* acls) {
struct Stat zks;
struct ACL_vector aclVec;
char tbuf[128];
char buf[1024];
int i;
int rc = zoo_get_acl(zh, path.c_str(), &aclVec, &zks);
if (rc) {
return rc;
}
if (acls) {
//*acls += "ACLs: \n";
for (i=0; i<aclVec.count; ++i) {
*acls += " ";
ACL *acl = &(aclVec.data[i]);
// loop over acls in aclVec
*acls += (acl->perms & ZOO_PERM_CREATE) ? "c":"-";
*acls += (acl->perms & ZOO_PERM_DELETE) ? "d":"-";
*acls += (acl->perms & ZOO_PERM_READ) ? "r":"-";
*acls += (acl->perms & ZOO_PERM_WRITE) ? "w":"-";
*acls += (acl->perms & ZOO_PERM_ADMIN) ? "a":"-";
*acls += " ";
*acls += acl->id.scheme; *acls += "::"; *acls += acl->id.id; *acls += " \n";
}
//printf("%s", acls->c_str());
}
if (stats) {
time_t t = (time_t)(zks.mtime/1000);
struct tm *tmp;
tmp = localtime(&t);
strftime(tbuf, sizeof(tbuf), "%Y/%m/%d-%H:%M:%S ", tmp);
// version and aversion seem to be uniformly 0
snprintf(buf, 1023, "%4.4ld %s v:%3.3ld cv:%3.3ld eph:%ld",
(long)zks.dataLength, tbuf,
(long)zks.version,
(long)zks.cversion,
(long)(zks.ephemeralOwner ? 1 : 0)
);
buf[1023]='0';
*stats = buf;
}
return 0;
}
int ListFile(const string& pref, const string& path0, const ListState& state) {
string path = path0;
FinalizePath(path);
struct String_vector list;
//printf("[%s]\n", path.c_str());
int rc = zoo_get_children(zh, path.c_str(), 0, &list);
if (rc==0) {
for (int i=0; i<list.count; ++i) {
string sub = path;
MergePath(sub, list.data[i]);
FinalizePath(sub);
string subPref = pref;
string stats;
string acls;
if (state.zstat || state.sec) {
GetStatAclString(sub, state.zstat?&stats:NULL, state.sec?&acls:NULL);
}
if (state.zstat) {
printf("%s ", stats.c_str());
}
if (state.full) {
// sub has a trailing '/' ...
//printf("%s%s%s%s\n", stats.c_str(), pref.c_str(), path.c_str(), list.data[i]);
printf("%s%s\n", pref.c_str(), sub.c_str());
} else {
printf("%s%s\n", pref.c_str(), list.data[i]);
subPref += " ";
}
if (state.sec) {
printf("%s", acls.c_str());
}
if (state.recurse) {
ListFile(subPref, sub, state);
}
}
deallocate_String_vector(&list);
}
return rc;
}
class ListCommand : public FileCommand {
public:
ListCommand() : FileCommand("ls", "List nodes under the current node.\n"
" -r recursive\n -f full path\n -l long listing\n -z print ACLs") {}
virtual int Run() {
string dummy;
return Run(dummy);
}
virtual int Run(const vector<string> &args) {
state.Reset();
vector<string> fileArgs;
for (unsigned i=0; i<args.size(); ++i) {
const string& cur = args[i];
if (cur.size() && cur[0]=='-') {
if (state.ParseArg(cur)) {
return -1;
}
} else {
fileArgs.push_back(cur);
}
}
return FileCommand::Run(fileArgs);
}
virtual int Run(const string& arg0) {
return ListFile(" ", arg0, state);
}
public:
ListState state;
};
int ListDummy = FileCommand::RegisterCommand(new ListCommand);
class CatCommand : public FileCommand {
public:
CatCommand() : FileCommand("cat", "Show node contents.") {}
virtual int Run(const string &arg0) {
string data;
int maxlen = 65536;
int len = ReadNode(arg0, data, maxlen);
printf("[%s] %d bytes: \n", arg0.c_str(), len);
if (len<0) {
printf("<error>\n");
} else if (len==0) {
printf("<empty>\n");
} else {
bool truncated = false;
if (len>maxlen) {
len = maxlen;
truncated = true;
}
printf("%s\n", data.c_str());
if (truncated) {
printf("<truncated>\n");
}
}
// TODO cat arbitrary sized files
// NOTE: current jute settings limit node size to < 1MB.
return (0);
}
};
int CatDummy = FileCommand::RegisterCommand(new CatCommand);
int ParseACL(const std::string& aclStr, struct ACL* acl) {
unsigned i;
bool done = false;
int32_t perms = 0;
std::string scheme;
std::string id;
//fprintf(stderr, "NOTE parsing acl [%s]\n", aclStr.c_str());
for (i=0; (!done) && i<aclStr.size(); ++i) {
// loop over acls in aclVec
switch (aclStr[i]) {
case 'c' : perms |= ZOO_PERM_CREATE; break;
case 'd' : perms |= ZOO_PERM_DELETE; break;
case 'r' : perms |= ZOO_PERM_READ; break;
case 'w' : perms |= ZOO_PERM_WRITE; break;
case 'a' : perms |= ZOO_PERM_ADMIN; break;
default :
done=true; break;
}
}
if (i==aclStr.size()) {
acl->perms = perms;
acl->id = ZOO_AUTH_IDS;
return 0;
}
if (i>=aclStr.size() || !i || aclStr[i-1]!=':') {
// error
fprintf(stderr, "Error parsing acl [%s]\n", aclStr.c_str());
return -1;
}
// parse out scheme and id
size_t idSep = aclStr.find("::", i+1);
if (idSep == string::npos) {
fprintf(stderr, "Error parsing acl [%s]\n", aclStr.c_str());
return -1;
}
scheme = aclStr.substr(i, idSep-i);
id = aclStr.substr(idSep+2);
acl->perms = perms;
acl->id.id = strdup(id.c_str());
acl->id.scheme = strdup(scheme.c_str());
return 0;
}
class ChmodCommand : public FileCommand {
public:
ACL_vector aclVec;
public:
ChmodCommand() : FileCommand("chmod", "change node permissions.") {}
virtual int Run(const vector<string> &args) {
int rc = 0;
if (args.size()<2) {
fprintf(stderr, "Error chmod missing acl or filename\n");
return -1;
}
// create aclVec
allocate_ACL_vector(&aclVec, 1);
// parse first arg as "[cdrwa]:scheme::id"
if (ParseACL(args[1], &aclVec.data[0])) {
// error already printed
// fall thru to cleanup
} else {
vector<string> fileArgs;
fileArgs.push_back(args[0]);
for (unsigned i=2; i<args.size(); ++i) {
const string& cur = args[i];
if (cur.size() && cur[0]=='-') {
// TODO parse additional args or complain
//if (state.ParseArg(cur)) {
// return -1;
//}
} else {
fileArgs.push_back(cur);
}
}
rc = FileCommand::Run(fileArgs);
}
// free acl
if (ZOO_AUTH_IDS.id == aclVec.data[0].id.id &&
ZOO_AUTH_IDS.scheme == aclVec.data[0].id.scheme) {
aclVec.data[0].id.id=NULL;
aclVec.data[0].id.scheme=NULL;
}
deallocate_ACL_vector(&aclVec);
return rc;
}
virtual int Run(const string& arg0) {
int rc;
string arg = arg0;
FinalizePath(arg);
//struct ACL acl = aclVec.data[0];
//fprintf(stdout, "node:[%s] perm:0x%x scheme:[%s] id:[%s]\n", arg.c_str(), acl.perms, acl.id.scheme, acl.id.id);
rc = zoo_set_acl(zh, arg.c_str(), -1, &aclVec);
if (rc) {
printf("Error chmod on [%s] %d: %s\n", arg.c_str(), rc, zerror(rc));
return rc;
}
return (0);
}
};
int ChmodDummy = FileCommand::RegisterCommand(new ChmodCommand);
class CopyCommand : public FileCommand {
public:
CopyCommand() : FileCommand("cp", "Copy a file/node.\nNOTES:\n zk source and dest should include the filename.\n Prefix local (non-ZK) files with ':' .") {}
virtual int Run(const string &arg0, const string &arg1) {
string src = arg0;
string dest = arg1;
int rc = 0;
string data;
if (src.c_str()[0] == ':') {
rc = ReadFile(src.substr(1), data);
} else {
rc = ReadNode(src, data);
}
if (rc<0) {
printf("Copy failed (read) [%s to %s]\n", src.c_str(), dest.c_str());
return -1;
}
if (dest.c_str()[0] == ':') {
rc = WriteFile(dest.substr(1), data);
} else {
rc = WriteNode(dest, data);
}
if (rc<0) {
printf("Copy failed (write) [%s to %s]\n", src.c_str(), dest.c_str());
return -1;
}
return 0;
}
virtual int Run(const vector<string> &argsIn) {
vector<string> args;
int rc = ExpandArgs(argsIn, args);
if (rc) { return rc; }
vector<string> options;
vector<string> fileArgs;
// skip command name...
for (unsigned i=1; i<args.size(); ++i) {
const string& cur = args[i];
if (IsOption(cur)) {
//if (state.ParseArg(cur)) {
options.push_back(cur);
printf("Command %s: unexpected option [%s]!\n", args[0].c_str(), cur.c_str());
return -1;
//}
} else {
fileArgs.push_back(cur);
}
}
if (fileArgs.size() != 2) {
printf("Command %s: expects exactly 2 full filenames, got %d!\n", args[0].c_str(), (int)fileArgs.size());
}
return Run(fileArgs[0], fileArgs[1]);
}
};
int CopyDummy = FileCommand::RegisterCommand(new CopyCommand);
class StatCommand : public FileCommand {
public:
StatCommand() : FileCommand("stat", "Show node statistics.") {}
virtual int Run(const string& arg0) {
string arg = arg0;
FinalizePath(arg);
int rc;
struct Stat st;
char tctimes[40], tmtimes[40];
time_t tctime, tmtime;
if ( (rc=zoo_exists(zh, arg.c_str(), 0, &st)) ) {
printf("Error stat on [%s] %d: %s\n", arg.c_str(), rc, zerror(rc));
return (1);
}
printf("[%s]:\n", arg.c_str());
tctime = st.ctime/1000;
tmtime = st.mtime/1000;
fprintf(stderr, "\tctime = %s\tczxid=%llx\n" "\tmtime=%s\tmzxid=%llx\n"
"\tversion=%x\taversion=%x\n" "\tephemeralOwner = %llx\n",
ctime_r(&tctime, tctimes), (long long unsigned)st.czxid,
ctime_r(&tmtime, tmtimes), (long long unsigned)st.mzxid,
(unsigned int)st.version, (unsigned int)st.aversion,
(long long unsigned)st.ephemeralOwner);
return (0);
}
};
int StatDummy = FileCommand::RegisterCommand(new StatCommand);
class TouchCommand : public FileCommand {
public:
int flags;
public:
TouchCommand() : FileCommand("touch", "Touch (create) node(s).\n -e for ephemeral\n -s for sequential."), flags(0) {}
virtual int Run() {
string dummy;
return Run(dummy);
}
virtual int Run(const vector<string> &argsIn) {
flags = 0;
return FileCommand::Run(argsIn);
}
virtual int Run(const string& arg0) {
if (IsOption(arg0)) {
if (arg0 == "-e") {
flags |= ZOO_EPHEMERAL;
} else if (arg0 == "-s") {
flags |= ZOO_SEQUENCE;
} else {
printf("Unknown option [%s]!\n", arg0.c_str());
return -1;
}
return 0;
}
string arg = arg0;
FinalizePath(arg);
// TODO deal with ephemeral and sequence flags
char createdPath[1024];
string data;
//bool ephemeral = false;
//bool sequence = false;
//int flags = (ephemeral ? ZOO_EPHEMERAL : 0) | (sequence ? ZOO_SEQUENCE : 0 );
int rc = zoo_create(zh, arg.c_str(), data.data(), data.size(), &ZOO_OPEN_ACL_UNSAFE, flags, createdPath, 1023);
if (rc) {
fprintf(stderr, "ERROR creating node [%s] for %d -- %s\n", arg.c_str(), rc, zerror(rc));
return rc;
}
if (arg!=createdPath) {
printf("Created %s\n", createdPath);