-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnfs4lib.py
More file actions
executable file
·1358 lines (1084 loc) · 42.3 KB
/
nfs4lib.py
File metadata and controls
executable file
·1358 lines (1084 loc) · 42.3 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
#!/usr/bin/env python2
# nfs4lib.py - NFS4 library for Python.
#
# Written by Peter Åstrand <peter@cendio.se>
# Copyright (C) 2001 Cendio Systems AB (http://www.cendio.se)
#
# 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; version 2 of the License.
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
# TODO:
# Implement buffering in NFS4OpenFile.
__pychecker__ = 'no-callinit no-reimport'
NFS_PORT = 2049
BUFSIZE = 4096
import rpc
from nfs4constants import *
from nfs4types import *
import nfs4packer
import random
import array
import socket
import os
import re
# Stubs for Win32 systems
if not hasattr(os, "getuid"):
os.getuid = lambda: 1
if not hasattr(os, "getgid"):
os.getgid = lambda: 1
if not hasattr(os, "getgroups"):
os.getgroups = lambda: []
# All NFS errors are subclasses of NFSException
class NFSException(rpc.RPCException):
pass
class BadCompoundRes(NFSException):
"""The COMPOUND procedure returned some kind of error"""
def __init__(self, operation, errcode):
self.operation = operation
self.errcode = errcode
def __str__(self):
return "operation %s returned result %s" % (nfs_opnum4_id[self.operation],
nfsstat4_id[self.errcode])
class EmptyBadCompoundRes(NFSException):
"""The COMPOUND procedure returned some kind of error. No result array"""
def __init__(self, errcode):
self.errcode = errcode
def __str__(self):
return "compound call returned %s" % nfsstat4_id[self.errcode]
class InvalidCompoundRes(NFSException):
"""The COMPOUND procedure returned is invalid"""
def __init__(self, msg=""):
self.msg = msg
def __str__(self):
if self.msg:
return "invalid COMPOUND result: %s" % self.msg
else:
return "invalid COMPOUND result"
class EmptyCompoundRes(NFSException):
def __str__(self):
return "empty COMPOUND result"
class ChDirError(NFSException):
def __init__(self, dir):
self.dir = dir
def __str__(self):
return "Cannot change directory to %s" % self.dir
class DummyNcl:
def __init__(self, data = ""):
self.unpacker = nfs4packer.NFS4Unpacker(self, data)
self.packer = nfs4packer.NFS4Packer(self)
class PartialNFS4Client:
def __init__(self):
# Client state variables
self.clientid = None
self.verifier = None
# Current directory. A list of components, like ["doc", "porting"]
self.cwd = []
# Set in sub-classes
self.gid = None
self.uid = None
# Send call stack in COMPOUND tag?
self.debugtags = 0
# Owners
self.default_owner = os.getenv("USER", "pynfs-user")
self._active_owners = {}
def mkcred(self):
if self.cred == None:
hostname = socket.gethostname()
groups = os.getgroups()
self.cred = (rpc.AUTH_UNIX, rpc.make_auth_unix(1, hostname, self.uid, self.gid, groups))
return self.cred
def mkverf(self):
if self.verf == None:
self.verf = (rpc.AUTH_NULL, rpc.make_auth_null())
return self.verf
def addpackers(self):
# Pass a reference to ourself to NFS4Packer and NFS4Unpacker.
self.packer = nfs4packer.NFS4Packer(self)
self.unpacker = nfs4packer.NFS4Unpacker(self, '')
#
# RPC procedures
#
def null(self):
return self.make_call(NFSPROC4_NULL, None, None, None)
def compound(self, argarray, tag="", minorversion=0):
"""A Compound call"""
if not tag and self.debugtags:
tag = str(get_callstack())
compoundargs = COMPOUND4args(self, argarray=argarray, tag=tag, minorversion=minorversion)
res = COMPOUND4res(self)
# Save sent operations for later checks
sent_operations = [op.argop for op in argarray]
self.make_call(NFSPROC4_COMPOUND, None, compoundargs.pack, res.unpack)
recv_operations = [op.resop for op in res.resarray]
# The same numbers & the same operations should be returned,
# In case of an error, the reply is possible shorter than
# the request.
# FIXME: Should verify that an error indeed has occured if the response
# is shorter
if sent_operations[:len(recv_operations)] != recv_operations:
raise InvalidCompoundRes("sent=%s, got=%s" \
% (str(sent_operations),
str(recv_operations)))
# Check response sanity
verify_compound_result(res)
return res
#
# Utility methods
#
def gen_random_64(self):
a = array.array('I')
for unused in range(4):
a.append(random.randrange(2**16))
return a.tostring()
def gen_uniq_id(self):
# Use FQDN and pid as ID.
return socket.gethostname() + str(os.getpid())
def get_open_owner(self, ownername):
"""Return ActiveStateOwner object with open_owner"""
return self._get_owner(ownername, open_owner4)
def get_lock_owner(self, ownername):
"""Return ActiveStateOwner object with lock_owner"""
return self._get_owner(ownername, lock_owner4)
def _get_owner(self, ownername, createfunc):
if not self._active_owners.has_key(ownername):
# New owner
stateowner = createfunc(self, self.clientid, ownername)
active_owner = ActiveStateOwner(stateowner)
self._active_owners[ownername] = active_owner
else:
active_owner = self._active_owners[ownername]
assert(active_owner.stateowner.owner == ownername)
return active_owner
def get_pathcomps_rel(self, filename):
"""Transform a unix-like pathname, relative to self.ncl,
to a list of components. If filename is not, assume "."
"""
# FIXME: get_pathcomps_rel(../../../fff) returns ['fff']
if not filename:
return self.cwd
if filename[0] == "/":
# Absolute path
pathcomps = []
else:
pathcomps = self.cwd
return unixpath2comps(filename, pathcomps)
def cd_dotdot(self):
self.cwd = self.cwd[:-1]
def try_cd(self, dir):
# FIXME: Better error messages.
candidate_cwd = unixpath2comps(dir, self.cwd)
lookupops = self.lookup_path(candidate_cwd)
operations = [self.putrootfh_op()] + lookupops
getattrop = self.getattr([FATTR4_TYPE])
operations.append(getattrop)
try:
res = self.compound(operations)
check_result(res)
obj_type = opaque2long(res.resarray[-1].arm.arm.obj_attributes.attr_vals)
if not obj_type == NF4DIR:
raise ChDirError(dir)
except rpc.RPCException:
raise ChDirError(dir)
self.cwd = candidate_cwd
#
# Operations. These come in two flawors: <operation>_op and <operation>.
#
# <operation>_op: This is just a wrapper which creates a
# nfs_argop4. The arguments for the method <operation>_op should
# be the same as the arguments for <operation>4args. No default
# arguments or any other kind of intelligent handling should be
# done in the _op methods.
#
# <operation>: This is a convenience method. It can have default arguments
# and operation-specific arguments. Not all operations have <operation>
# methods. It's pretty useless for operations without arguments, for example.
# Eg., if the <operation> method doesn't do anything, it should not exist.
#
# The _op method should be defined first. Look at read_op and read for an
# example.
#
#
def access_op(self, access):
args = ACCESS4args(self, access)
return nfs_argop4(self, argop=OP_ACCESS, opaccess=args)
def close_op(self, seqid, stateid):
args = CLOSE4args(self, seqid, stateid)
return nfs_argop4(self, argop=OP_CLOSE, opclose=args)
def commit_op(self, offset, count):
args = COMMIT4args(self, offset, count)
return nfs_argop4(self, argop=OP_COMMIT, opcommit=args)
def create_op(self, objtype, objname, createattrs):
args = CREATE4args(self, objtype, objname, createattrs)
return nfs_argop4(self, argop=OP_CREATE, opcreate=args)
def create(self, objtype, objname):
"""CREATE with no attributes"""
createattrs = fattr4(self, [], "")
return self.create_op(objtype, objname, createattrs)
def delegpurge_op(self, clientid):
args = DELEGPURGE4args(self, clientid)
return nfs_argop4(self, argop=OP_DELEGPURGE, opdelegpurge=args)
def delegreturn_op(self, deleg_stateid):
args = DELEGRETURN4args(self, deleg_stateid)
return nfs_argop4(self, argop=OP_DELEGRETURN, opdelegreturn=args)
def getattr_op(self, attr_request):
args = GETATTR4args(self, attr_request)
return nfs_argop4(self, argop=OP_GETATTR, opgetattr=args)
def getattr(self, attrlist=[]):
# The argument to GETATTR4args is a list of integers.
return self.getattr_op(list2attrmask(attrlist))
def getfh_op(self):
return nfs_argop4(self, argop=OP_GETFH)
def link_op(self, newname):
args = LINK4args(self, newname)
return nfs_argop4(self, argop=OP_LINK, oplink=args)
def lock_op(self, locktype, reclaim, offset, length, locker):
args = LOCK4args(self, locktype, reclaim, offset, length, locker)
return nfs_argop4(self, argop=OP_LOCK, oplock=args)
def lockt_op(self, locktype, offset, length, owner):
args = LOCKT4args(self, locktype, offset, length, owner)
return nfs_argop4(self, argop=OP_LOCKT, oplockt=args)
def locku_op(self, locktype, seqid, lock_stateid, offset, length):
args = LOCKU4args(self, locktype, seqid, lock_stateid, offset, length)
return nfs_argop4(self, argop=OP_LOCKU, oplocku=args)
def lookup_op(self, objname):
args = LOOKUP4args(self, objname)
return nfs_argop4(self, argop=OP_LOOKUP, oplookup=args)
def lookup_path(self, pathcomps):
"""Generate a list of lookup operations from path components"""
lookupops = []
for component in pathcomps:
lookupops.append(self.lookup_op(component))
return lookupops
def lookupp_op(self):
return nfs_argop4(self, argop=OP_LOOKUPP)
def nverify_op(self, obj_attributes):
args = NVERIFY4args(self, obj_attributes)
return nfs_argop4(self, argop=OP_NVERIFY, opnverify=args)
def open_op(self, seqid, share_access, share_deny, owner, openhow, claim):
args = OPEN4args(self, seqid, share_access, share_deny, owner, openhow, claim)
return nfs_argop4(self, argop=OP_OPEN, opopen=args)
# Convenience method for open. Only handles claim type CLAIM_NULL. If you want
# to use other claims, use open_op directly.
def open(self, file, seqid, owner, opentype=OPEN4_NOCREATE,
# For OPEN4_CREATE
mode=UNCHECKED4, createattrs=None, createverf=None,
# Shares
share_access=OPEN4_SHARE_ACCESS_READ, share_deny=OPEN4_SHARE_DENY_NONE):
# claim
claim = open_claim4(self, CLAIM_NULL, file)
# openhow
if mode in [UNCHECKED4, GUARDED4] and not createattrs:
# FIXME: Consider using local umask as default mode.
#mask = os.umask(0)
#os.umask(mask)
attr_request = list2attrmask([])
createattrs = fattr4(self, attr_request, "")
how = createhow4(self, mode, createattrs, createverf)
openhow = openflag4(self, opentype, how)
return self.open_op(seqid, share_access, share_deny, owner, openhow, claim)
def openattr_op(self, createdir):
args = OPENATTR4args(self, createdir)
return nfs_argop4(self, argop=OP_OPENATTR, opopenattr=args)
def open_confirm_op(self, open_stateid, seqid):
args = OPEN_CONFIRM4args(self, open_stateid, seqid)
return nfs_argop4(self, argop=OP_OPEN_CONFIRM, opopen_confirm=args)
def open_downgrade_op(self, open_stateid, seqid, share_access, share_deny):
args = OPEN_DOWNGRADE4args(self, open_stateid, seqid, share_access, share_deny)
return nfs_argop4(self, argop=OP_OPEN_DOWNGRADE, opopen_downgrade=args)
def putfh_op(self, object):
args = PUTFH4args(self, object)
return nfs_argop4(self, argop=OP_PUTFH, opputfh=args)
def putpubfh_op(self):
return nfs_argop4(self, argop=OP_PUTPUBFH)
def putrootfh_op(self):
return nfs_argop4(self, argop=OP_PUTROOTFH)
def read_op(self, stateid, offset, count):
args = READ4args(self, stateid, offset, count)
return nfs_argop4(self, argop=OP_READ, opread=args)
def read(self, stateid, offset=0, count=0):
return self.read_op(stateid, offset, count)
def readdir_op(self, cookie, cookieverf, dircount, maxcount, attr_request):
args = READDIR4args(self, cookie, cookieverf, dircount, maxcount, attr_request)
return nfs_argop4(self, argop=OP_READDIR, opreaddir=args)
def readdir(self, cookie=0, cookieverf="", dircount=4096, maxcount=4096, attr_request=[]):
return self.readdir_op(cookie, cookieverf, dircount, maxcount, attr_request)
def readlink_op(self):
return nfs_argop4(self, argop=OP_READLINK)
def remove_op(self, target):
args = REMOVE4args(self, target)
return nfs_argop4(self, argop=OP_REMOVE, opremove=args)
def rename_op(self, oldname, newname):
args = RENAME4args(self, oldname, newname)
return nfs_argop4(self, argop=OP_RENAME, oprename=args)
def renew_op(self, clientid):
args = RENEW4args(self, clientid)
return nfs_argop4(self, argop=OP_RENEW, oprenew=args)
def restorefh_op(self):
return nfs_argop4(self, argop=OP_RESTOREFH)
def savefh_op(self):
return nfs_argop4(self, argop=OP_SAVEFH)
def secinfo_op(self, name):
args = SECINFO4args(self, name)
return nfs_argop4(self, argop=OP_SECINFO, opsecinfo=args)
def setattr_op(self, stateid, obj_attributes):
args = SETATTR4args(self, stateid, obj_attributes)
return nfs_argop4(self, argop=OP_SETATTR, opsetattr=args)
def setclientid_op(self, client, callback, callback_ident):
args = SETCLIENTID4args(self, client, callback, callback_ident)
return nfs_argop4(self, argop=OP_SETCLIENTID, opsetclientid=args)
def setclientid(self, verifier=None, id=None, cb_program=None, r_netid=None, r_addr=None,
callback_ident=None):
if not verifier:
self.verifier = self.gen_random_64()
else:
self.verifier = verifier
if not id:
id = self.gen_uniq_id()
if not cb_program:
# FIXME
cb_program = 0
if not r_netid:
# FIXME
r_netid = "udp"
if not r_addr:
# FIXME
r_addr = socket.gethostname()
if not callback_ident:
callback_ident = 0
client_id = nfs_client_id4(self, verifier=self.verifier, id=id)
cb_location = clientaddr4(self, r_netid=r_netid, r_addr=r_addr)
callback = cb_client4(self, cb_program=cb_program, cb_location=cb_location)
return self.setclientid_op(client_id, callback, callback_ident)
def setclientid_confirm_op(self, clientid, setclientid_confirm):
args = SETCLIENTID_CONFIRM4args(self, clientid, setclientid_confirm)
return nfs_argop4(self, argop=OP_SETCLIENTID_CONFIRM, opsetclientid_confirm=args)
def verify_op(self, obj_attributes):
args = VERIFY4args(self, obj_attributes)
return nfs_argop4(self, argop=OP_VERIFY, opverify=args)
def write_op(self, stateid, offset, stable, data):
args = WRITE4args(self, stateid, offset, stable, data)
return nfs_argop4(self, argop=OP_WRITE, opwrite=args)
def write(self, data, stateid, offset=0, stable=FILE_SYNC4):
return self.write_op(stateid, offset, stable, data)
def cb_getattr(self):
# FIXME
raise NotImplementedError()
def cb_recall(self):
# FIXME
raise NotImplementedError()
#
# NFS convenience methods. Calls server.
#
def init_connection(self):
# SETCLIENTID
setclientidop = self.setclientid()
res = self.compound([setclientidop])
check_result(res)
self.clientid = res.resarray[0].arm.arm.clientid
# SETCLIENTID_CONFIRM
self.setclientid_confirm = res.resarray[0].arm.arm.setclientid_confirm
setclientid_confirmop = self.setclientid_confirm_op(self.clientid, self.setclientid_confirm)
res = self.compound([setclientid_confirmop])
check_result(res)
# def do_access
def do_close(self, fh, seqid, stateid):
putfhop = self.putfh_op(fh)
closeop = self.close_op(seqid, stateid)
res = self.compound([putfhop, closeop])
check_result(res)
return res.resarray[1].arm.open_stateid
# def do_commit
# def do_create
# def do_delegpurge
# def do_delegreturn
# def do_getattr
def do_getfh(self, pathcomps):
"""Get filehandle"""
lookupops = self.lookup_path(pathcomps)
operations = [self.putrootfh_op()] + lookupops
operations.append(self.getfh_op())
res = self.compound(operations)
check_result(res)
return res.resarray[-1].arm.arm.object
# def do_link
# def do_lock
# def do_lockt
# def do_locku
def do_lookup(self, cfh, component):
"""Lookup"""
operations = [self.putfh_op(cfh)]
operations.append(self.lookup_op(component))
operations.append(self.getfh_op())
res = self.compound(operations)
check_result(res)
return res.resarray[-1].arm.arm.object
# def do_lookupp
# def do_nverify
# def do_open
# def do_openattr
# def do_open_confirm
# def do_open_downgrade
# def do_putfh
# def do_putpubfh
# def do_putrootfh
def do_read(self, stateid, fh, offset=0, size=None):
putfhop = self.putfh_op(fh)
data = ""
while 1:
readop = self.read(stateid, count=BUFSIZE, offset=offset)
res = self.compound([putfhop, readop])
check_result(res)
data += res.resarray[1].arm.arm.data
if res.resarray[1].arm.arm.eof:
break
# Have we got as much as we were asking for?
if size and (len(data) >= size):
break
offset += BUFSIZE
if size:
return data[:size]
else:
return data
def do_read_fast(self, fh, offset=0, size=None):
"""Fast implementation of do_read"""
# FIXME: broken.
def fast_pack(args):
(ncl, fh, offset) = args
# No compound tag; zerolength opaque.
ncl.packer.pack_uint(0)
# Minor version
ncl.packer.pack_uint32_t(0)
# Number of operations
ncl.packer.pack_uint(2)
# PUTFH
ncl.packer.pack_nfs_opnum4(OP_PUTFH)
ncl.packer.pack_opaque(fh)
# READ
ncl.packer.pack_nfs_opnum4(OP_READ)
ncl.packer.pack_stateid4(0)
ncl.packer.pack_offset4(offset)
ncl.packer.pack_count4(BUFSIZE)
def fast_unpack(ncl):
status = ncl.unpacker.unpack_nfsstat4()
if status:
raise BadCompoundRes(OP_READ, status)
# Tag
ncl.unpacker.unpack_opaque()
# resarray
unused = ncl.unpacker.unpack_uint()
# PUTFH result
unused_argop = ncl.unpacker.unpack_nfs_opnum4()
status = ncl.unpacker.unpack_nfsstat4()
# READ result
unused_argop = ncl.unpacker.unpack_nfs_opnum4()
status = ncl.unpacker.unpack_nfsstat4()
eof = ncl.unpacker.unpack_bool()
data = ncl.unpacker.unpack_opaque()
return (eof, data)
def custom_make_call(ncl, proc, pack_func, unpack_func,
pack_args=None, unpack_args=None):
"""customized rpc.make_call with possible argument to unpack_func"""
if pack_func is None and pack_args is not None:
raise TypeError("non-null pack_args with null pack_func")
ncl.start_call(proc)
if pack_func:
pack_func(pack_args)
ncl.do_call()
if unpack_func:
result = unpack_func(unpack_args)
else:
result = None
ncl.unpacker.done()
return result
data = ""
while 1:
(eof, got_data) = custom_make_call(self, 1, fast_pack, fast_unpack,
(self, fh, offset), self)
data += got_data
if eof:
break
# Have we got as much as we were asking for?
if size and (len(data) >= size):
break
offset += BUFSIZE
if size:
return data[:size]
else:
return data
def do_readdir(self, fh, attr_request=[]):
# Since we may not get whole directory listing in one readdir request,
# loop until we do. For each request result, create a flat list
# with <entry4> objects.
cookie = 0
cookieverf = ""
entries = []
while 1:
putfhop = self.putfh_op(fh)
readdirop = self.readdir(cookie, cookieverf, attr_request=attr_request)
res = self.compound([putfhop, readdirop])
check_result(res)
reply = res.resarray[1].arm.arm.reply
if not reply.entries:
break
entry = reply.entries[0]
# Loop over all entries in result.
while 1:
entries.append(entry)
if not entry.nextentry:
break
entry = entry.nextentry[0]
if res.resarray[1].arm.arm.reply.eof:
break
cookie = entry.cookie
cookieverf = res.resarray[1].arm.arm.cookieverf
return entries
# def do_readlink
def do_remove(self, pathcomps):
# Lookup all but last component
lookupops = self.lookup_path(pathcomps[:-1])
operations = [self.putrootfh_op()] + lookupops
operations.append(self.remove_op(pathcomps[-1]))
res = self.compound(operations)
check_result(res)
# def do_rename
# def do_renew
# def do_restorefh
# def do_savefh
# def do_secinfo
# def do_setattr
# def do_setclientid
# def do_setclientid_confirm
# def do_verify
def do_write(self, fh, data, stateid, offset=0, stable=FILE_SYNC4):
putfhop = self.putfh_op(fh)
writeop = self.write(data, stateid, offset=offset, stable=stable)
res = self.compound([putfhop, writeop])
check_result(res)
#
# Misc. convenience methods.
#
def get_ftype(self, pathcomps):
"""Get file type attribute"""
lookupops = self.lookup_path(pathcomps)
operations = [self.putrootfh_op()] + lookupops
getattrop = self.getattr([FATTR4_TYPE])
operations.append(getattrop)
res = self.compound(operations)
check_result(res)
obj_type = opaque2long(res.resarray[-1].arm.arm.obj_attributes.attr_vals)
return obj_type
#
# Misc classes
#
class ActiveStateOwner:
"""Contains either an open_owner och lock_owner, and
the seqid associated with this owner"""
def __init__(self, stateowner):
# stateowner is either an open_owner or lock_owner
self.stateowner = stateowner
# Last seqid sent
self._seqid = -1
def get_seqid(self):
self._seqid += 1
self._seqid = self._seqid % 2**32L
return self._seqid
#
# Misc. helper functions.
#
def check_result(compoundres):
"""Verify that a COMPOUND call was successful,
raise BadCompoundRes otherwise
"""
if not compoundres.status:
return
# If there was an error, it should be the last operation.
resop = compoundres.resarray[-1]
raise BadCompoundRes(resop.resop, resop.arm.status)
def verify_compound_result(res):
"""Check that COMPOUND result is sane, in every way
Raises InvalidCompoundRes on error
There is usually no need to use this function explicitly, since compound()
method always does that automatically.
"""
if res.status == NFS4_OK:
# All operations status should also be NFS4_OK
# Note: A zero-length res.resarray is possible
for resop in res.resarray:
if resop.arm.status != NFS4_OK:
raise InvalidCompoundRes("res.status was OK, but some operations"
"returned errors")
else:
# Note: A zero-length res.resarray is possible
if res.resarray:
# All operations up to the last operation returned should be NFS4_OK
for resop in res.resarray[:-1]:
if resop.arm.status != NFS4_OK:
raise InvalidCompoundRes("non-last operations returned error")
# The last operation result must be equal to res.status
lastop = res.resarray[-1]
if lastop.arm.status != res.status:
raise InvalidCompoundRes("last op not equal to res.status")
def unixpath2comps(str, pathcomps=None):
if pathcomps == None:
pathcomps = []
if str[0] == "/":
pathcomps = []
else:
pathcomps = pathcomps[:]
for component in str.split("/"):
if (component == "") or (component == "."):
pass
elif component == "..":
pathcomps = pathcomps[:-1]
else:
pathcomps.append(component)
return pathcomps
def comps2unixpath(comps):
result = ""
for component in comps:
result += "/" + component
return result
def opaque2long(data):
import struct
result = 0L
# Decode 4 bytes at a time.
for intpos in range(len(data)/4):
integer = data[intpos*4:intpos*4+4]
val = struct.unpack(">L", integer)[0]
shiftbits = (len(data)/4 - intpos - 1)*64
result = result | (val << shiftbits)
return result
def long2opaque(integer, pad_to=None):
import struct
# Make sure we are dealing with longs.
l = long(integer)
result = ""
# Encode 4 bytes at a time.
while l:
lowest_bits = l & 0xffffffffL
l = l >> 32
result = struct.pack(">L", lowest_bits) + result
if pad_to:
if len(result) < pad_to:
pad_bytes = "\x00" * (pad_to - len(result))
result = pad_bytes + result
return result
def intlist2long(intlist):
# Make sure we are dealing with longs.
# (unpack_uint in xdrlib returns an integer if possible, a long otherwise.)
intlist = map(lambda x: long(x), intlist)
result = 0L
for intpos in range(len(intlist)):
integer = intlist[intpos]
shiftbits = intpos * 32
result = result | (integer << shiftbits)
return result
def int2binstring(val):
numbits = 32
if type(val) == type(1L):
numbits = 64
result = ""
for bitpos in range(numbits-1, -1, -1):
bitval = 1L << bitpos
if bitval & val:
result += "1"
else:
result += "0"
return result
def get_attrbitnum_dict():
"""Get dictionary with attribute bit positions.
Note: This function uses introspection. It will fail if nfs4constants.py has
an attribute named FATTR4_<something>.
Returns {"fattr4_type": 1, "fattr4_change": 3 ...}
"""
import nfs4constants
attrbitnum_dict = {}
for name in dir(nfs4constants):
if name.startswith("FATTR4_"):
value = getattr(nfs4constants, name)
# Sanity checking. Must be integer.
assert(type(value) == type(0))
attrname = name[7:].lower()
attrbitnum_dict[attrname] = value
return attrbitnum_dict
def get_bitnumattr_dict():
"""Get dictionary with attribute bit positions.
Note: This function uses introspection. It will fail if nfs4constants.py has
an attribute named FATTR4_<something>.
Returns { 1: "fattr4_type", 3: "fattr4_change", ...}
"""
import nfs4constants
bitnumattr_dict = {}
for name in dir(nfs4constants):
if name.startswith("FATTR4_"):
value = getattr(nfs4constants, name)
# Sanity checking. Must be integer.
assert(type(value) == type(0))
attrname = name[7:].lower()
bitnumattr_dict[value] = attrname
return bitnumattr_dict
def get_attrunpackers(unpacker):
"""Get dictionary with attribute unpackers
Note: This function uses introspection. It depends on that nfs4packer.py
has methods for every unpacker.unpack_fattr4_<attribute>.
"""
import nfs4packer
attrunpackers = {}
for name in dir(nfs4packer.NFS4Unpacker):
if name.startswith("unpack_fattr4_"):
# unpack_fattr4_ is 14 chars.
attrname = name[14:]
attrunpackers[attrname] = getattr(unpacker, name)
return attrunpackers
def get_attrpackers(packer):
"""Get dictionary with attribute packers
Note: This function uses introspection. It depends on that nfs4packer.py
has methods for every packer.pack_fattr4_<attribute>.
"""
import nfs4packer
attrpackers = {}
dict = get_attrbitnum_dict()
for name in dir(nfs4packer.NFS4Packer):
if name.startswith("pack_fattr4_"):
# pack_fattr4 is 12 chars.
attrname = name[12:]
attrpackers[dict[attrname]] = getattr(packer, name)
return attrpackers
def dict2fattr(dict, ncl):
"""Convert a dictionary to a fattr4 object.
Returns a fattr4 object.
"""
attrs = dict.keys()
attrs.sort()
attr_vals = ""
rstncl = DummyNcl()
import nfs4packer;
packer = nfs4packer.NFS4Packer(rstncl)
attrpackers = get_attrpackers(packer)
for attr in attrs:
value = dict[attr];
packerfun = attrpackers[attr];
packer.reset()
packerfun(value)
attr_vals+=packer.get_buffer()
attrmask = list2attrmask(attrs)
return fattr4(ncl, attrmask, attr_vals);
def fattr2dict(obj):
"""Convert a fattr4 object to a dictionary with attribute name and values.
Returns a dictionary like {"size": 4711}
"""
attrbitnum_dict = get_attrbitnum_dict()
# Construct a dictionary with the attributes to unpack.
# Example: {53: 'time_modify', 4: 'size', 8: 'fsid'}
unpack_these = {}
# Construct one long integer from the integer list.
attrmask = 0L
for intpos in range(len(obj.attrmask)):
integer = long(obj.attrmask[intpos])