예제 #1
0
 public SecurityDescriptor(Sid owner, Sid group, Acl dacl, Acl sacl)
     : this()
 {
     this.Owner = owner;
     this.Group = group;
     this.Dacl = dacl;
     this.Sacl = sacl;
 }
 /// <summary>
 /// Constructs a new ReadObjectStreamResponse
 /// </summary>
 /// <param name="s">The object content stream</param>
 /// <param name="contentType">The MIME type of the stream</param>
 /// <param name="length">The length.  Set to -1 if unknown.</param>
 /// <param name="meta">The object metadata</param>
 /// <param name="acl">The object's ACL</param>
 /// <param name="extent">The extent that was read, or null</param>
 /// <param name="response">the HTTP response object to close the connection</param>
 /// <param name="checksum">The content checksum if the Atmos server had one stored</param>
 public ReadObjectStreamResponse(Stream s, string contentType, long length, MetadataList meta, Acl acl, Extent extent, HttpWebResponse response, string checksum)
 {
     this.Content = s;
     this.ContentType = contentType;
     this.Length = length;
     this.Metadata = meta;
     this.Acl = acl;
     this.response = response;
     this.ContentChecksum = checksum;
 }
예제 #3
0
 public override void ExecuteCmdlet()
 {
     ConfirmAction(
         Force.IsPresent,
         string.Format(Resources.SettingDataLakeStoreItemAcl, Path.OriginalPath),
         string.Format(Resources.SetDataLakeStoreItemAcl, Path.OriginalPath),
         Path.OriginalPath,
         () =>
         DataLakeStoreFileSystemClient.SetAcl(Path.TransformedPath, Account,
                                              Acl.GetAclSpec()));
 }
예제 #4
0
        public override int GetHashCode()
        {
            int result = 17;
            int ret    = GetType().GetHashCode();

            result = 37 * result + ret;
            ret    = Acl.GetHashCode();
            result = 37 * result + ret;
            ret    = Stat.GetHashCode();
            result = 37 * result + ret;
            return(result);
        }
예제 #5
0
 /// <summary>
 /// New API: obsoletes Public and Private Command, Commandlet has changed too
 /// </summary>
 /// <param name="cmd"></param>
 /// <returns></returns>
 public bool AddCommand(Commandlet cmd)
 {
     if (cmd.AccessString != null && Acl != null)
     {
         Acl.AddAccessString(cmd.AccessString);
     }
     if (!commands.ContainsKey(cmd.Command))
     {
         commands.Add(cmd.Command, cmd);
         return(true);
     }
     return(false);
 }
예제 #6
0
 public void CreateBucket(string bucketName, Acl acl)
 {
     try
     {
         var client = new OssClient(_endPoint, _accessKeyId, _accessKeySecret);
         client.CreateBucket(bucketName);
         client.SetBucketAcl(bucketName, (CannedAccessControlList)acl);
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
예제 #7
0
        public void TestDomainJoinRolePositive()
        {
            // This should test positively because while the userSID is only granted one of the permissions (create computer),
            // the group SID ending with "-1440" has all of them, and the assertor will search groups.
            Acl          dacl     = this.sdd.GetDacl();
            DaclAssertor assertor = new DaclAssertor(dacl, true);

            List <SID> groupSiDs = this.groupSIDList.Select(s => SID.Parse(GetSidAsByteBuffer(s))).ToList();
            DomainJoinRoleAssertion djAssertion = new DomainJoinRoleAssertion(this.userSID, false, groupSiDs);
            bool result = assertor.DoAssert(djAssertion);

            Assert.True(result);
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 public NewNtTokenCmdlet()
 {
     AuthenticationId = NtToken.LocalSystemAuthId;
     TokenType        = TokenType.Primary;
     ExpirationTime   = DateTime.Now.AddYears(10);
     Groups           = new Sid[0];
     Privileges       = new TokenPrivilegeValue[0];
     DefaultAcl       = new Acl();
     DefaultAcl.AddAccessAllowedAce(GenericAccessRights.GenericAll, AceFlags.None, "SY");
     DefaultAcl.AddAccessAllowedAce(GenericAccessRights.GenericAll, AceFlags.None, "BA");
     IntegrityLevel           = TokenIntegrityLevel.System;
     SecurityQualityOfService = new SecurityQualityOfService(SecurityImpersonationLevel.Anonymous, SecurityContextTrackingMode.Static, false);
 }
        public static Entity CreateTileTemplate(Vector3 position)
        {
            var tileTemplate = EntityBuilder.Begin()
                               .AddPositionComponent(position, CommonRequirementSets.PhysicsOnly)
                               .AddMetadataComponent(entityType: SimulationSettings.TilePrefabName)
                               .SetPersistence(true)
                               .SetReadAcl(Acl.MakeRequirementSet(CommonAttributeSets.Physics, CommonAttributeSets.Visual, Acl.MakeAttributeSet("turret_rotation")))
                               .AddComponent(new Improbable.Demo.PositionColor.Data(0), CommonRequirementSets.PhysicsOnly)
                               .AddComponent(new Improbable.Demo.CheckOutColor.Data(new List <uint>()), CommonRequirementSets.PhysicsOnly)
                               .Build();

            return(tileTemplate);
        }
        private bool _addResultCanExecute()
        {
            if (!Acl.IsGranted(AnalysisRights.AnalysisAddResult))
            {
                return(false);
            }
            if (Workflow.CurrentStage != SampleTestWorkflow.Running)
            {
                return(false);
            }

            return(true);
        }
예제 #11
0
        /// <summary>
        /// Serialize <see cref="Acl"/>.
        /// </summary>
        /// <param name="acl"><see cref="Acl"/> to serialize</param>
        private void SerializeAcl(Acl acl)
        {
            bool isNull = acl == null;

            this.binaryWriter.Write((bool)isNull);
            if (!isNull)
            {
                Id id = acl.Id;
                this.binaryWriter.Write(id.Scheme);
                this.binaryWriter.Write(id.Identifier);
                this.binaryWriter.Write((int)acl.Perms);
            }
        }
예제 #12
0
        public static TokenHandle Create(
            TokenAccess access,
            string name,
            ObjectFlags objectFlags,
            DirectoryHandle rootDirectory,
            TokenType tokenType,
            Luid authenticationId,
            long expirationTime,
            Sid user,
            Sid[] groups,
            PrivilegeSet privileges,
            Sid owner,
            Sid primaryGroup,
            Acl defaultDacl,
            TokenSource source
            )
        {
            TokenUser         tokenUser         = new TokenUser(user);
            TokenGroups       tokenGroups       = new TokenGroups(groups);
            TokenPrivileges   tokenPrivileges   = new TokenPrivileges(privileges);
            TokenOwner        tokenOwner        = new TokenOwner(owner);
            TokenPrimaryGroup tokenPrimaryGroup = new TokenPrimaryGroup(primaryGroup);
            TokenDefaultDacl  tokenDefaultDacl  = new TokenDefaultDacl(defaultDacl);
            ObjectAttributes  oa = new ObjectAttributes(name, objectFlags, rootDirectory);
            IntPtr            handle;

            try
            {
                Win32.NtCreateToken(
                    out handle,
                    access,
                    ref oa,
                    tokenType,
                    ref authenticationId,
                    ref expirationTime,
                    ref tokenUser,
                    ref tokenGroups,
                    ref tokenPrivileges,
                    ref tokenOwner,
                    ref tokenPrimaryGroup,
                    ref tokenDefaultDacl,
                    ref source
                    ).ThrowIf();
            }
            finally
            {
                oa.Dispose();
            }

            return(new TokenHandle(handle, true));
        }
예제 #13
0
        private void InsertRecord(AzRecord r)
        {
            var record = new Acl
            {
                AceType = r.Reaction,
                Action  = r.ActionId,
                Object  = r.ObjectId ?? string.Empty,
                Subject = r.SubjectId,
                Tenant  = r.Tenant
            };

            CoreDbContext.AddOrUpdate(r => r.Acl, record);
            CoreDbContext.SaveChanges();
        }
        public override void ExecuteCmdlet()
        {
            var aclSpec = ParameterSetName.Equals(BaseParameterSetName)
                ? Acl.GetAclSpec()
                : string.Format("{0}{1}:{2}:{3}", Default ? "default:" : string.Empty, AceType, Id,
                                DataLakeStoreItemPermissionInstance.GetPermissionString(Permissions)).ToLowerInvariant();

            ConfirmAction(
                string.Format(Resources.SetDataLakeStoreItemAcl, Path.OriginalPath),
                Path.OriginalPath,
                () =>
                DataLakeStoreFileSystemClient.ModifyAcl(Path.TransformedPath, Account,
                                                        aclSpec));
        }
예제 #15
0
        public override int GetHashCode()
        {
            int result = 17;
            int ret    = GetType().GetHashCode();

            result = 37 * result + ret;
            ret    = Path.GetHashCode();
            result = 37 * result + ret;
            ret    = Acl.GetHashCode();
            result = 37 * result + ret;
            ret    = (int)Version;
            result = 37 * result + ret;
            return(result);
        }
예제 #16
0
        public void Parse_Defaults()
        {
            const string        acl    = @"[{ ""subjects"": [ ], ""permissions"": { } }]";
            IReadOnlyList <Acl> result = Acl.Parse(acl, LedgerPath.Parse("/root/path/"), new KeyEncoder(111));

            Assert.Equal(1, result.Count);
            Assert.Equal("", result[0].RecordName.Pattern);
            Assert.Equal(PatternMatchingStrategy.Prefix, result[0].RecordName.MatchingStrategy);
            Assert.Equal(true, result[0].Recursive);
            Assert.Equal(0, result[0].Subjects.Count);
            Assert.Equal(Access.Unset, result[0].Permissions.AccountModify);
            Assert.Equal(Access.Unset, result[0].Permissions.AccountSpend);
            Assert.Equal(Access.Unset, result[0].Permissions.AccountModify);
            Assert.Equal(Access.Unset, result[0].Permissions.DataModify);
        }
예제 #17
0
        public void Parse_Success()
        {
            IReadOnlyList <Acl> result = Acl.Parse(GetValidAcl(), LedgerPath.Parse("/root/path/"), new KeyEncoder(111));

            Assert.Equal(1, result.Count);
            Assert.Equal("/root/path/", result[0].Path.FullPath);
            Assert.Equal("name", result[0].RecordName.Pattern);
            Assert.Equal(PatternMatchingStrategy.Exact, result[0].RecordName.MatchingStrategy);
            Assert.Equal(true, result[0].Recursive);
            Assert.Equal(1, result[0].Subjects.Count);
            Assert.Equal(Access.Permit, result[0].Permissions.AccountModify);
            Assert.Equal(Access.Permit, result[0].Permissions.AccountSpend);
            Assert.Equal(Access.Permit, result[0].Permissions.AccountModify);
            Assert.Equal(Access.Permit, result[0].Permissions.DataModify);
        }
예제 #18
0
        public static SnapshotEntity CreatePlayerCreatorTemplate()
        {
            var entityTemplate = new SnapshotEntity {
                Prefab = SimulationSettings.PlayerCreatorPrefabName
            };

            entityTemplate.Add(new WorldTransform.Data(Coordinates.ZERO, new Quaternion(0, 0, 0, 0)));
            entityTemplate.Add(new PlayerCreation.Data());

            var acl = Acl.GenerateServerAuthoritativeAcl(entityTemplate);

            entityTemplate.SetAcl(acl);

            return(entityTemplate);
        }
예제 #19
0
        public static SnapshotEntity CreateCubeEntityTemplate(Coordinates spawnPosition)
        {
            var entityTemplate = new SnapshotEntity {
                Prefab = SimulationSettings.CubePrefabName
            };

            entityTemplate.Add(new WorldTransform.Data(spawnPosition, new Quaternion(0, 0, 0, 0)));
            entityTemplate.Add(new Grabbable.Data(new Option <CurrentGrabberInfo>()));

            var acl = Acl.GenerateServerAuthoritativeAcl(entityTemplate);

            entityTemplate.SetAcl(acl);

            return(entityTemplate);
        }
예제 #20
0
        public static SnapshotEntity CreateArmchairEntityTemplate(Coordinates spawnPosition, float rotation)
        {
            var entityTemplate = new SnapshotEntity {
                Prefab = SimulationSettings.ArmchairPrefabName
            };

            entityTemplate.Add(new WorldTransform.Data(spawnPosition, MathUtils.ToNativeQuaternion(UnityEngine.Quaternion.Euler(0, rotation, 0))));
            entityTemplate.Add(new Grabbable.Data(new Option <CurrentGrabberInfo>()));

            var acl = Acl.GenerateServerAuthoritativeAcl(entityTemplate);

            entityTemplate.SetAcl(acl);

            return(entityTemplate);
        }
       	public AclPackage CreateAcl(String repoName, String userName, String aclName)
	{
		AclIdentity aclIdentity = new AclIdentity();
		aclIdentity.RepositoryName = repoName;
		aclIdentity.Domain = userName;
		aclIdentity.Name = aclName;

		Permission basicReadPermission = new Permission();
		basicReadPermission.Name = Permission.READ;
		basicReadPermission.Type = PermissionType.BASIC;

		Permission basicDeletePermission = new Permission();
		basicDeletePermission.Name = Permission.DELETE;
		basicDeletePermission.Type = PermissionType.BASIC;

		List<AclEntry> entryList = new List<AclEntry>();

		AclEntry aclEntry = new AclEntry();
		aclEntry.AccessType = AccessType.PERMIT;
		aclEntry.Accessor = "dm_world";
		List<Permission> permissionList = new List<Permission>();
		permissionList.Add(basicReadPermission);
		aclEntry.Permissions = permissionList;

		AclEntry aclEntry1 = new AclEntry();
		aclEntry1.AccessType = AccessType.PERMIT;
		aclEntry1.Accessor = "dm_owner";
		List<Permission> permissionList1 = new List<Permission>();
		permissionList1.Add(basicDeletePermission);
		aclEntry1.Permissions = permissionList1;

		entryList.Add(aclEntry);
		entryList.Add(aclEntry1);

		Acl acl = new Acl();
		acl.Identity = aclIdentity;
		acl.Description = "a test acl" + System.DateTime.Now.Ticks;
		// acl.setType(AclType.REGULAR); // defaults to REGULAR
		// acl.setVisibility(AclVisibility.PRIVATE); // defaults to PRIVATE
		acl.Entries = entryList;

		AclPackage aclPackage = new AclPackage();
		List<Acl> aclList = new List<Acl>();
		aclList.Add(acl);
		aclPackage.Acls = aclList;

		return accessControlService.Create(aclPackage);
	}
예제 #22
0
        private void ParseAcl(string acl)
        {
            //and example of a real acl string:
            //user::rw-,user:6b157067-78b0-4478-ba7b-ade5c66f1a9a:rwx,group::r--,mask::rwx,other::---

            Acl.Clear();

            if (acl == null)
            {
                return;
            }

            foreach (string textForm in acl.Split(','))
            {
                bool isDefault = textForm.StartsWith("default:");

                string processForm = isDefault ? textForm.Substring(8) : textForm;

                var entry = new AclEntry(processForm);

                if (entry.ObjectId == null)
                {
                    //special entry
                    if (entry.Type == "user")
                    {
                        OwningUserPermissions = entry;
                    }
                    else if (entry.Type == "group")
                    {
                        OwningGroupPermissions = entry;
                    }

                    //ignore other special objects as they're not important
                }
                else
                {
                    //push ID'd objects to the rest of the ACL
                    if (isDefault)
                    {
                        DefaultAcl.Add(entry);
                    }
                    else
                    {
                        Acl.Add(entry);
                    }
                }
            }
        }
예제 #23
0
        public override int GetHashCode()
        {
            var result = 17;
            int ret    = GetType().GetHashCode();

            result = 37 * result + ret;
            ret    = Path.GetHashCode();
            result = 37 * result + ret;
            ret    = Data.GetHashCode();
            result = 37 * result + ret;
            ret    = Acl.GetHashCode();
            result = 37 * result + ret;
            ret    = Flags;
            result = 37 * result + ret;
            return(result);
        }
예제 #24
0
        public static SnapshotEntity CreateIndividualTemplate(Coordinates initialPosition)
        {
            var template = new SnapshotEntity {
                Prefab = SimulationSettings.PlayerPrefabName
            };

            template.Add(new TransformComponent.Data(initialPosition, (uint)0));

            var permissions = Acl.Build()
                              .SetReadAccess(CommonPredicates.PhysicsOrVisual)
                              .SetWriteAccess <TransformComponent>(CommonPredicates.PhysicsOnly);

            template.SetAcl(permissions);

            return(template);
        }
예제 #25
0
        public static string ToString(Acl acl)
        {
            var sb = new StringBuilder();

            sb.AppendFormat(CultureInfo.InvariantCulture, "Acl[AceCount={0}, AceEntries=", acl.AceItems.Count);
            sb.AppendLine();

            for (int i = 0; i < acl.AceItems.Count; i++)
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "#{0} {1}", i, ToString(acl.AceItems[i]));
                sb.AppendLine();
            }

            sb.AppendLine("]");
            return(sb.ToString());
        }
예제 #26
0
        /// <summary>
        /// Converts the specified string to ACL
        /// </summary>
        /// <param name="aclStr">ACL in string</param>
        /// <param name="acl">Converted ACL</param>
        public static void FromString(string aclStr, out Acl acl)
        {
            if (aclStr == null)
            {
                throw new ArgumentNullException("aclStr");
            }

            string[] aclpieces = aclStr.Split(',');

            if (aclpieces.Length < 3)
            {
                throw new ArgumentException("Acl string is not in expected format", "aclStr");
            }

            acl = new Acl(int.Parse(aclpieces[0]), new Id(aclpieces[1], aclpieces[2]));
        }
예제 #27
0
        private List <Acl> ConvertToAcl(List <org.apache.zookeeper.data.ACL> innerAcl)
        {
            var result = new List <Acl>();

            // ReSharper disable once ForeachCanBeConvertedToQueryUsingAnotherGetEnumerator
            foreach (var resultAcl in innerAcl)
            {
                var resultId = resultAcl.getId();
                var acl      = new Acl((AclPerm)resultAcl.getPerms(),
                                       (AclScheme)Enum.Parse(typeof(AclScheme), resultId.getScheme().ToUpper(), true),
                                       new AclId(resultId.getId())
                                       );
                result.Add(acl);
            }
            return(result);
        }
예제 #28
0
        public void testDomainJoinRoleNegative_Denials()
        {
            // This should test negatively because the userSID is denied one of the permissions (create computer),
            // within the OU the Sddl was pulled from (not inherited).
            Acl          dacl     = this.sddlDenials.GetDacl();
            DaclAssertor assertor = new DaclAssertor(dacl, true);

            List <SID> groupSiDs = this.groupSIDList.Select(s => SID.Parse(GetSidAsByteBuffer(s))).ToList();
            DomainJoinRoleAssertion djAssertion = new DomainJoinRoleAssertion(this.userSID, false, groupSiDs);
            bool result = assertor.DoAssert(djAssertion);

            Assert.False(result);

            // should be 1 of them
            Assert.Single(assertor.GetUnsatisfiedAssertions());
        }
예제 #29
0
        public override int GetHashCode()
        {
            int result = 17;
            int ret    = GetType().GetHashCode();

            result = 37 * result + ret;
            ret    = Path.GetHashCode();
            result = 37 * result + ret;
            ret    = Data.GetHashCode();
            result = 37 * result + ret;
            ret    = Acl.GetHashCode();
            result = 37 * result + ret;
            ret    = (Ephemeral)?0:1;
            result = 37 * result + ret;
            return(result);
        }
        /// <summary>
        /// Get the source of inherited ACEs.
        /// </summary>
        /// <param name="name">The name of the resource.</param>
        /// <param name="type">The type of the resource.</param>
        /// <param name="container">Whether the resource is a container.</param>
        /// <param name="object_types">Optional list of object types.</param>
        /// <param name="security_descriptor">The security descriptor for the resource.</param>
        /// <param name="sacl">True to check the SACL otherwise checks the DACL.</param>
        /// <param name="generic_mapping">Generic mapping for the resource.</param>
        /// <param name="query_security">Query security descriptors for sources.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The list of inheritance sources.</returns>
        public static NtResult <IEnumerable <SecurityDescriptorInheritanceSource> > GetInheritanceSource(
            string name,
            SeObjectType type,
            bool container,
            Guid[] object_types,
            SecurityDescriptor security_descriptor,
            bool sacl,
            GenericMapping generic_mapping,
            bool query_security,
            bool throw_on_error)
        {
            Acl acl = sacl ? security_descriptor.Sacl : security_descriptor.Dacl;

            if (acl == null || acl.NullAcl)
            {
                return(NtStatus.STATUS_INVALID_ACL.CreateResultFromError <IEnumerable <SecurityDescriptorInheritanceSource> >(throw_on_error));
            }

            using (var list = new DisposableList())
            {
                SafeGuidArrayBuffer guids = SafeGuidArrayBuffer.Null;
                if (object_types?.Length > 0)
                {
                    guids = list.AddResource(new SafeGuidArrayBuffer(object_types));
                }

                NtType native_type = GetNativeType(type);

                INHERITED_FROM[] inherited_from = new INHERITED_FROM[acl.Count];
                NtStatus         status         = NtStatus.STATUS_INVALID_PARAMETER;
                try
                {
                    status = Win32NativeMethods.GetInheritanceSource(name, type, sacl ? SecurityInformation.Sacl : SecurityInformation.Dacl,
                                                                     container, guids, guids.Count, acl.ToByteArray(), IntPtr.Zero, ref generic_mapping, inherited_from).MapDosErrorToStatus();
                    return(status.CreateResult(throw_on_error, () => (IEnumerable <SecurityDescriptorInheritanceSource>)inherited_from
                                               .Select((s, i) => new SecurityDescriptorInheritanceSource(acl[i], s, type,
                                                                                                         native_type, container, query_security, sacl)).Where(s => s.Depth != -1).ToArray()));
                }
                finally
                {
                    if (status.IsSuccess())
                    {
                        Win32NativeMethods.FreeInheritedFromArray(inherited_from, (ushort)inherited_from.Length, IntPtr.Zero);
                    }
                }
            }
        }
예제 #31
0
        private IReadOnlyList <Acl> TranslateZkprAclListToRMAclList(IReadOnlyList <Acl> zkprAcls)
        {
            if (zkprAcls == null || zkprAcls.Any <Acl>() == false)
            {
                return(null);
            }

            List <Acl> rmAcls = new List <Acl>();

            foreach (Acl a in zkprAcls)
            {
                Acl rmAcl = this.TranslateZkprAclToRmAcl(a);
                rmAcls.Add(rmAcl);
            }

            return(rmAcls as IReadOnlyList <Acl>);
        }
예제 #32
0
        public EditableAcl(AccessControl acl)
        {
            OwnerUser           = new EditableAclEntry(acl.OwningUserPermissions);
            OwnerGroup          = new EditableAclEntry(acl.OwningGroupPermissions);
            OwnerUser.Identity  = acl.OwnerUserId;
            OwnerGroup.Identity = acl.OwnerGroupId;

            foreach (AclEntry acle in acl.Acl)
            {
                Acl.Add(new EditableAclEntry(acle));
            }

            foreach (AclEntry acle in acl.DefaultAcl)
            {
                DefaultAcl.Add(new EditableAclEntry(acle));
            }
        }
예제 #33
0
        public void TestDomainJoinRoleNegative()
        {
            // This should test negatively because the userSID is only granted one of the permissions (create computer)
            // and this test tells the assertor to NOT search groups.
            Acl          dacl     = this.sdd.GetDacl();
            DaclAssertor assertor = new DaclAssertor(dacl, false);

            DomainJoinRoleAssertion djAssertion = new DomainJoinRoleAssertion(this.userSID, false, null);
            bool result = assertor.DoAssert(djAssertion);

            Assert.False(result);

            // should be 6 of them
            List <AceAssertion> unsatisfiedAssertions = assertor.GetUnsatisfiedAssertions();

            Assert.Equal(6, unsatisfiedAssertions.Count);
        }
예제 #34
0
        public void IsMatch_Success()
        {
            // Recursive ACL
            Acl acl = new Acl(new[] { subject }, path, true, new StringPattern("name", PatternMatchingStrategy.Exact), permissions);
            // Match (recursiveOnly = true)
            Assert.True(acl.IsMatch(evidence, path, true, "name"));
            // Match (recursiveOnly = false)
            Assert.True(acl.IsMatch(evidence, path, false, "name"));

            // Non-recursive ACL
            acl = new Acl(new[] { subject }, path, false, new StringPattern("name", PatternMatchingStrategy.Exact), permissions);
            // Match (recursiveOnly = false)
            Assert.True(acl.IsMatch(evidence, path, false, "name"));
            // Error: record non recursive (recursiveOnly = true)
            Assert.False(acl.IsMatch(evidence, path, true, "name"));
            // Error: path mismatch
            Assert.False(acl.IsMatch(evidence, LedgerPath.Parse("/"), false, "name"));
            // Error: name mismatch
            Assert.False(acl.IsMatch(evidence, path, false, "n"));
            // Error: identity mismatch
            Assert.False(acl.IsMatch(new[] { new SignatureEvidence(ByteString.Parse("ab"), ByteString.Empty) }, path, false, "name"));
        }
예제 #35
0
        /// <summary>
        /// Creates a new object in the cloud with the given key (and key-pool).
        /// </summary>
        /// <param name="key">the key-pool and key to use for the new object.</param>
        /// <param name="acl">Access control list for the new object.  May be null to use a default ACL</param>
        /// <param name="metadata">Metadata for the new object.  May be null for no metadata.</param>
        /// <param name="data">The initial contents of the object.  May be appended to later.  May be null to create an object with no content or a directory.</param>
        /// <param name="mimeType">the MIME type of the content.  Optional, may be null.  If data is non-null and mimeType is null, the MIME type will default to application/octet-stream.</param>
        /// <param name="checksum">the checksum object to use to compute checksums.  If you're doing incremental updates after the create, include the same object in subsequent calls.  Can be null to omit checksums.</param>
        /// <returns>the ObjectId of the newly-created object for references by ID.</returns>
        public ObjectId CreateObjectFromSegmentWithKey(ObjectKey key, Acl acl, MetadataList metadata, ArraySegment<byte> data,
            String mimeType, Checksum checksum)
        {
            HttpWebResponse resp = null;
            try
            {
                string resource = getResourcePath(context, key);
                Uri u = buildUrl(resource);
                HttpWebRequest con = createWebRequest(u);

                // Build headers
                Dictionary<string, string> headers = new Dictionary<string, string>();

                // Figure out the mimetype
                if (mimeType == null)
                {
                    mimeType = "application/octet-stream";
                }

                headers.Add("Content-Type", mimeType);
                headers.Add("x-emc-uid", uid);
                headers.Add("x-emc-pool", key.pool);

                // Process metadata
                if (metadata != null)
                {
                    processMetadata(metadata, headers);
                }

                // Add acl
                if (acl != null)
                {
                    processAcl(acl, headers);
                }

                // Add date
                addDateHeader(headers);

                // Checksum if required
                if (checksum != null)
                {
                    checksum.Update(data);
                    headers.Add("x-emc-wschecksum", checksum.ToString());
                }

                // Sign request
                signRequest(con, "POST", resource, headers);

                // post data
                Stream s = null;
                try
                {
                    con.ContentLength = data.Count;
                    con.SendChunked = false;
                    s = con.GetRequestStream();
                    s.Write(data.Array, data.Offset, data.Count);
                    s.Close();
                }
                catch (IOException e)
                {
                    s.Close();
                    throw new EsuException("Error posting data", e);
                }

                // Check response
                resp = (HttpWebResponse)con.GetResponse();
                int statInt = (int)resp.StatusCode;
                if (statInt > 299)
                {
                    handleError(resp);
                }

                // The new object ID is returned in the location response header
                string location = resp.Headers["location"];

                // Parse the value out of the URL

                MatchCollection m = OBJECTID_EXTRACTOR.Matches(location);
                if (m.Count > 0)
                {
                    string id = m[0].Groups[1].Value;
                    log.TraceEvent(TraceEventType.Verbose, 0, "Id: " + id);
                    return new ObjectId(id);
                }
                else
                {
                    throw new EsuException("Could not find ObjectId in " + location);
                }
            }
            catch (UriFormatException e)
            {
                throw new EsuException("Invalid URL", e);
            }
            catch (IOException e)
            {
                throw new EsuException("Error connecting to server", e);
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    handleError((HttpWebResponse)e.Response);
                }
                else
                {
                    throw new EsuException("Error executing request: " + e.Message, e);
                }
            }
            finally
            {
                if (resp != null)
                {
                    resp.Close();
                }
            }
            return null;
        }
예제 #36
0
        /// <summary>
        /// Creates an anonymous access token using the specified policy and ACL
        /// </summary>
        /// <param name="id">identifier of the target object for the access token.</param>
        /// <param name="policy">the token policy for the new access token.</param>
        /// <param name="acl">the ACL that will be assigned to objects created using this access token.</param>
        /// <returns>The URL of the access token.</returns>
        public Uri CreateAccessToken(Identifier id, PolicyType policy, Acl acl)
        {
            HttpWebResponse resp = null;
            try
            {
                string resource = context + "/accesstokens";
                Uri u = buildUrl(resource);
                HttpWebRequest con = createWebRequest(u);

                // Build headers
                Dictionary<string, string> headers = new Dictionary<string, string>();

                headers.Add("Content-Type", "application/xml");
                headers.Add("x-emc-uid", uid);

                // Add id
                if (id != null)
                {
                    if (id is ObjectId) headers.Add("x-emc-objectid", id.ToString());
                    else if (id is ObjectPath) headers.Add("x-emc-path", id.ToString());
                    else throw new EsuException("Only object ID and path are supported with access tokens");
                }

                // Add acl
                if (acl != null)
                {
                    processAcl(acl, headers);
                }

                // Add date
                addDateHeader(headers);

                // Sign request
                signRequest(con, "POST", resource, headers);

                // serialize XML
                Stream memStream = new MemoryStream();
                XmlSerializer serializer = new XmlSerializer(typeof(PolicyType));
                serializer.Serialize(memStream, policy);
                memStream.Position = 0;

                // post data
                writeRequestBodyFromStream(con, memStream, memStream.Length);

                // Check response
                resp = (HttpWebResponse)con.GetResponse();
                int statInt = (int)resp.StatusCode;
                if (statInt > 299)
                {
                    handleError(resp);
                }

                // The token URL is returned in the location response header
                string location = resp.Headers["location"];

                return buildUrl(location);
            }
            catch (UriFormatException e)
            {
                throw new EsuException("Invalid URL", e);
            }
            catch (IOException e)
            {
                throw new EsuException("Error connecting to server", e);
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    handleError((HttpWebResponse)e.Response);
                }
                else
                {
                    throw new EsuException("Error executing request: " + e.Message, e);
                }
            }
            finally
            {
                if (resp != null)
                {
                    resp.Close();
                }
            }
            return null;
        }
예제 #37
0
 /// <summary>
 /// Creates a new object on the server with the contents of the given file,
 /// acl and metadata.
 /// </summary>
 /// <param name="path">The ObjectPath to create the new object on.</param>
 /// <param name="file">the path to the file to upload</param>
 /// <param name="acl">the ACL to assign to the new object.  Optional.  If null,
 /// the server will generate a default ACL for the file.</param>
 /// <param name="meta">The metadata to assign to the new object.
 /// Optional.  If null, no user metadata will be assigned to the new object.</param>
 /// <returns>the identifier of the newly-created object.</returns>
 public ObjectId CreateObjectOnPath(ObjectPath path, string file, Acl acl, MetadataList meta)
 {
     Stream s;
     // Open the file and call the streaming version
     try
     {
         totalBytes = new FileInfo(file).Length;
         s = File.OpenRead(file);
     }
     catch (FileNotFoundException e)
     {
         throw new EsuException("Could not open input file", e);
     }
     return CreateObjectOnPath(path, s, acl, meta, true);
 }
예제 #38
0
 /// <summary>
 /// Updates an existing object with the contents of the given file, ACL, and
 /// metadata.
 /// </summary>
 /// <param name="id">the identifier of the object to update.</param>
 /// <param name="file">the path to the file to replace the object's current
 /// contents with</param>
 /// <param name="acl">the ACL to update the object with.  Optional.  If null,
 /// the ACL will not be modified.</param>
 /// <param name="metadata">The metadata to assign to the object.
 /// Optional.  If null, no user metadata will be modified.</param>
 public void UpdateObject( Identifier id, string file, Acl acl, MetadataList metadata ) {
     // Open the file and call the streaming version
     Stream s;
     try {
         s = File.OpenRead( file );
     } catch ( FileNotFoundException e ) {
         throw new EsuException( "Could not open input file", e );
     }
     totalBytes = new FileInfo( file ).Length;
     UpdateObject( id, s, acl, metadata, true );
 }
예제 #39
0
 /// <summary>
 /// Creates a new object in the cloud with the given key (and key-pool).
 /// </summary>
 /// <param name="key">the key-pool and key to use for the new object.</param>
 /// <param name="acl">Access control list for the new object.  May be null to use a default ACL</param>
 /// <param name="metadata">Metadata for the new object.  May be null for no metadata.</param>
 /// <param name="data">The initial contents of the object.  May be appended to later.  May be null to create an object with no content or a directory.</param>
 /// <param name="mimeType">the MIME type of the content.  Optional, may be null.  If data is non-null and mimeType is null, the MIME type will default to application/octet-stream.</param>
 /// <param name="checksum">the checksum object to use to compute checksums.  If you're doing incremental updates after the create, include the same object in subsequent calls.  Can be null to omit checksums.</param>
 /// <returns>the ObjectId of the newly-created object for references by ID.</returns>
 public ObjectId CreateObjectWithKey(ObjectKey key, Acl acl, MetadataList metadata, byte[] data,
     String mimeType, Checksum checksum)
 {
     return CreateObjectFromSegmentWithKey(key, acl, metadata, new ArraySegment<byte>(data, 0, data.Length), mimeType, checksum);
 }
예제 #40
0
        /// <summary>
        /// Updates an object in the cloud.
        /// </summary>
        /// <param name="id">The ID of the object to update</param>
        /// <param name="acl">Access control list for the new object. Optional, set to NULL to leave the ACL unchanged.</param>
        /// <param name="metadata">Metadata list for the new object.  Optional, set to NULL for no changes to the metadata.</param>
        /// <param name="extent">portion of the object to update.  May be null to indicate the whole object is to be replaced.  If not null, the extent size must match the data size.</param>
        /// <param name="data">The initial contents of the object.  Note that we only read 'streamLength' bytes from the stream and do not close the stream.</param>
        /// <param name="streamLength">The number of bytes to read from the stream.  Must be &lt;= the actual stream length.</param>
        /// <param name="mimeType">the MIME type of the content.  Optional, may be null.  If data is non-null and mimeType is null, the MIME type will default to application/octet-stream.</param>
        /// <param name="checksum">the checksum object to use to compute checksums.  If you're doing incremental updates after the create, include the same object in subsequent calls.  Can be null to omit checksums.</param>
        public void UpdateObjectFromStream(Identifier id, Acl acl, MetadataList metadata, Extent extent, Stream data, long streamLength, string mimeType, Checksum checksum)
        {
            HttpWebResponse resp = null;
            try
            {
                string resource = getResourcePath(context, id);
                Uri u = buildUrl(resource);
                HttpWebRequest con = createWebRequest(u);

                // Build headers
                Dictionary<string, string> headers = new Dictionary<string, string>();

                // Figure out the mimetype
                if (mimeType == null)
                {
                    mimeType = "application/octet-stream";
                }

                headers.Add("Content-Type", mimeType);
                headers.Add("x-emc-uid", uid);
                if (id is ObjectKey) {
                    headers.Add("x-emc-pool", (id as ObjectKey).pool);
                }

                //Add extent if needed
                if (extent != null && !extent.Equals(Extent.ALL_CONTENT))
                {
                    long end = extent.Offset + (extent.Size - 1);
                    headers.Add("Range", "Bytes=" + extent.Offset + "-" + end);
                }

                // Process metadata
                if (metadata != null)
                {
                    processMetadata(metadata, headers);
                }

                // Add acl
                if (acl != null)
                {
                    processAcl(acl, headers);
                }

                // Add date
                addDateHeader(headers);

                // Checksum if required
                if (checksum != null)
                {
                    if (!data.CanSeek)
                    {
                        throw new EsuException("Cannot checksum a stream that does not support seeking");
                    }
                    long current = data.Position;
                    byte[] buffer = new byte[64 * 1024];
                    for (long i = 0; i < streamLength; i += buffer.Length)
                    {
                        if (i + buffer.Length > streamLength)
                        {
                            int bytesToRead = (int)(streamLength - i);
                            int count = data.Read(buffer, 0, bytesToRead);
                            checksum.Update(new ArraySegment<byte>(buffer, 0, count));
                        }
                        else
                        {
                            int count = data.Read(buffer, 0, buffer.Length);
                            checksum.Update(new ArraySegment<byte>(buffer, 0, count));
                        }
                    }
                    data.Seek(current, SeekOrigin.Begin);

                    //Checksum ckcopy = checksum.Clone();
                    headers.Add("x-emc-wschecksum", checksum.ToString());
                }

                // Sign request
                signRequest(con, "PUT", resource, headers);

                // post data
                writeRequestBodyFromStream(con, data, streamLength);

                // Check response
                resp = (HttpWebResponse)con.GetResponse();
                int statInt = (int)resp.StatusCode;
                if (statInt > 299)
                {
                    handleError(resp);
                }

            }
            catch (UriFormatException e)
            {
                throw new EsuException("Invalid URL", e);
            }
            catch (IOException e)
            {
                throw new EsuException("Error connecting to server", e);
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    handleError((HttpWebResponse)e.Response);
                }
                else
                {
                    throw new EsuException("Error executing request: " + e.Message, e);
                }
            }
            finally
            {
                if (resp != null)
                {
                    resp.Close();
                }
            }
        }
 private void SwapSacl(Acl sacl)
 {
     BaseObject.SwapRef(ref _sacl, sacl);
 }
예제 #42
0
 /// <summary>
 /// Updates an object in the cloud.
 /// </summary>
 /// <param name="id">The ID of the object to update</param>
 /// <param name="acl">Access control list for the new object. Optional, set to NULL to leave the ACL unchanged.</param>
 /// <param name="metadata">Metadata list for the new object.  Optional, set to NULL for no changes to the metadata.</param>
 /// <param name="extent">portion of the object to update.  May be null to indicate the whole object is to be replaced.  If not null, the extent size must match the data size.</param>
 /// <param name="data">The new contents of the object.  May be appended to later. Optional, set to null for no content changes.</param>
 /// <param name="mimeType">the MIME type of the content.  Optional, may be null.  If data is non-null and mimeType is null, the MIME type will default to application/octet-stream.</param>
 public void UpdateObjectFromSegment(Identifier id, Acl acl, MetadataList metadata, Extent extent, ArraySegment<byte> data, string mimeType)
 {
     UpdateObjectFromSegment(id, acl, metadata, extent, data, mimeType, null);
 }
예제 #43
0
        /// <summary>
        /// Updates an object in the cloud.
        /// </summary>
        /// <param name="id">The ID of the object to update</param>
        /// <param name="acl">Access control list for the new object. Optional, set to NULL to leave the ACL unchanged.</param>
        /// <param name="metadata">Metadata list for the new object.  Optional, set to NULL for no changes to the metadata.</param>
        /// <param name="extent">portion of the object to update.  May be null to indicate the whole object is to be replaced.  If not null, the extent size must match the data size.</param>
        /// <param name="data">The new contents of the object.  May be appended to later. Optional, set to null for no content changes.</param>
        /// <param name="mimeType">the MIME type of the content.  Optional, may be null.  If data is non-null and mimeType is null, the MIME type will default to application/octet-stream.</param>
        /// <param name="checksum">the checksum object to use to compute checksums.  If you're doing incremental updates after the create, include the same object in subsequent calls.  Can be null to omit checksums.</param>
        public void UpdateObjectFromSegment(Identifier id, Acl acl, MetadataList metadata, Extent extent, ArraySegment<byte> data, string mimeType, Checksum checksum)
        {
            HttpWebResponse resp = null;
            try {
                string resource = getResourcePath(context, id);
                Uri u = buildUrl( resource );
                HttpWebRequest con = createWebRequest(u);

                // Build headers
                Dictionary<string, string> headers = new Dictionary<string, string>();

                // Figure out the mimetype
                if( mimeType == null ) {
                    mimeType = "application/octet-stream";
                }

                headers.Add( "Content-Type", mimeType );
                headers.Add( "x-emc-uid", uid );
                if (id is ObjectKey) {
                    headers.Add( "x-emc-pool", (id as ObjectKey).pool );
                }

                //Add extent if needed
                if( extent != null && !extent.Equals( Extent.ALL_CONTENT ) ) {
                    long end = extent.Offset + (extent.Size - 1);
                    headers.Add( "Range", "Bytes=" + extent.Offset + "-" + end );
                }

                // Process metadata
                if( metadata != null ) {
                    processMetadata( metadata, headers );
                }

                // Add acl
                if( acl != null ) {
                    processAcl( acl, headers );
                }

                // Add date
                addDateHeader(headers);

                // Checksum if required
                if (checksum != null)
                {
                    checksum.Update(data);
                    headers.Add("x-emc-wschecksum", checksum.ToString());
                }

                // Sign request
                signRequest( con, "PUT", resource, headers );

                // post data
                Stream s = null;
                try {
                    s = con.GetRequestStream();
                    s.Write( data.Array, data.Offset, data.Count );
                    s.Close();
                } catch( IOException e ) {
                    s.Close();
                    throw new EsuException( "Error posting data", e );
                }

                // Check response
                resp = (HttpWebResponse)con.GetResponse();
                int statInt = (int)resp.StatusCode;
                if( statInt > 299 ) {
                    handleError( resp );
                }

            } catch( UriFormatException e ) {
                throw new EsuException( "Invalid URL", e );
            } catch( IOException e ) {
                throw new EsuException( "Error connecting to server", e );
            } catch( WebException e ) {
                if (e.Response != null)
                {
                    handleError((HttpWebResponse)e.Response);
                }
                else
                {
                    throw new EsuException("Error executing request: " + e.Message, e);
                }
            }
            finally
            {
                if( resp != null ) {
                    resp.Close();
                }
            }
        }
예제 #44
0
 /// <summary>
 /// Updates an object in the cloud.
 /// </summary>
 /// <param name="id">The ID of the object to update</param>
 /// <param name="acl">Access control list for the new object. Optional, set to NULL to leave the ACL unchanged.</param>
 /// <param name="metadata">Metadata list for the new object.  Optional, set to NULL for no changes to the metadata.</param>
 /// <param name="extent">portion of the object to update.  May be null to indicate the whole object is to be replaced.  If not null, the extent size must match the data size.</param>
 /// <param name="data">The new contents of the object.  May be appended to later. Optional, set to null for no content changes.</param>
 /// <param name="mimeType">the MIME type of the content.  Optional, may be null.  If data is non-null and mimeType is null, the MIME type will default to application/octet-stream.</param>
 /// <param name="checksum">the checksum object to use to compute checksums.  If you're doing incremental updates after the create, include the same object in subsequent calls.  Can be null to omit checksums.</param>
 public void UpdateObject(Identifier id, Acl acl, MetadataList metadata, Extent extent, byte[] data, string mimeType, Checksum checksum)
 {
     ArraySegment<byte> seg = new ArraySegment<byte>(data == null ? new byte[0] : data);
     UpdateObjectFromSegment(id, acl, metadata, extent, seg, mimeType, checksum);
 }
예제 #45
0
        /// <summary>
        /// Sets the access control list on the object.
        /// </summary>
        /// <param name="id">The identifier of the object whose ACL to change</param>
        /// <param name="acl">The new ACL for the object.</param>
        public void SetAcl( Identifier id, Acl acl )
        {
            HttpWebResponse resp = null;
            try {
                string resource = getResourcePath(context, id) + "?acl";
                Uri u = buildUrl( resource );
                HttpWebRequest con = createWebRequest(u);

                // Build headers
                Dictionary<string, string> headers = new Dictionary<string, string>();

                headers.Add( "x-emc-uid", uid );
                if (id is ObjectKey) {
                    headers.Add("x-emc-pool", (id as ObjectKey).pool);
                }

                // Add acl
                if( acl != null ) {
                    processAcl( acl, headers );
                }

                // Add date
                addDateHeader(headers);

                // Sign request
                signRequest( con, "POST", resource, headers );

                // Check response
                resp = (HttpWebResponse)con.GetResponse();
                int statInt = (int)resp.StatusCode;
                if( statInt > 299 ) {
                    handleError( resp );
                }

            } catch( UriFormatException e ) {
                throw new EsuException( "Invalid URL", e );
            } catch( IOException e ) {
                throw new EsuException( "Error connecting to server", e );
            } catch( WebException e ) {
                if (e.Response != null)
                {
                    handleError((HttpWebResponse)e.Response);
                }
                else
                {
                    throw new EsuException("Error executing request: " + e.Message, e);
                }
            }
            finally
            {
                if( resp != null ) {
                    resp.Close();
                }
            }
        }
예제 #46
0
        /// <summary>
        /// Fetches object content as a stream
        /// </summary>
        /// <param name="id">the identifier of the object whose content to read.</param>
        /// <param name="extent">the portion of the object data to read.  Optional.  If null, the entire object will be read.</param>
        /// <returns></returns>
        public ReadObjectStreamResponse ReadObjectStream(Identifier id, Extent extent)
        {
            HttpWebResponse resp = null;
            try
            {
                string resource = getResourcePath(context, id);
                Uri u = buildUrl(resource);
                HttpWebRequest con = createWebRequest(u);

                // Build headers
                Dictionary<string, string> headers = new Dictionary<string, string>();

                headers.Add("x-emc-uid", uid);
                if (id is ObjectKey) {
                    headers.Add("x-emc-pool", (id as ObjectKey).pool);
                }

                //Add extent if needed
                if (extent != null && !extent.Equals(Extent.ALL_CONTENT))
                {
                    long end = extent.Offset + (extent.Size - 1);
                    headers.Add("Range", "Bytes=" + extent.Offset + "-" + end);
                }

                // Add date
                addDateHeader(headers);

                // Sign request
                signRequest(con, "GET", resource, headers);

                // Check response
                resp = (HttpWebResponse)con.GetResponse();
                int statInt = (int)resp.StatusCode;
                if (statInt > 299)
                {
                    handleError(resp);
                }

                string contentChecksum = resp.Headers["x-emc-wschecksum"];

                // Parse return headers.  Regular metadata is in x-emc-meta and
                // listable metadata is in x-emc-listable-meta
                MetadataList meta = new MetadataList();
                readMetadata(meta, resp.Headers["x-emc-meta"], false);
                readMetadata(meta, resp.Headers["x-emc-listable-meta"], true);

                // Parse return headers.  User grants are in x-emc-useracl and
                // group grants are in x-emc-groupacl
                Acl acl = new Acl();
                readAcl(acl, resp.Headers["x-emc-useracl"], Grantee.GRANTEE_TYPE.USER);
                readAcl(acl, resp.Headers["x-emc-groupacl"], Grantee.GRANTEE_TYPE.GROUP);

                long streamLength = resp.ContentLength;

                return new ReadObjectStreamResponse(resp.GetResponseStream(), resp.ContentType,
                    streamLength, meta, acl, extent, resp, contentChecksum);
            }
            catch (UriFormatException e)
            {
                throw new EsuException("Invalid URL", e);
            }
            catch (IOException e)
            {
                if (resp != null)
                {
                    resp.Close();
                }
                throw new EsuException("Error connecting to server", e);
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    handleError((HttpWebResponse)e.Response);
                    if (resp != null)
                    {
                        resp.Close();
                    }
                }
                else
                {
                    throw new EsuException("Error executing request: " + e.Message, e);
                }
            }

            return null;
        }
예제 #47
0
        /// <summary>
        /// Creates a new object in the cloud reading the content a Stream.
        /// </summary>
        /// <param name="path">The path to create the new object on</param>
        /// <param name="acl">Access control list for the new object.  May be null to use a default ACL</param>
        /// <param name="metadata">Metadata for the new object.  May be null for no metadata.</param>
        /// <param name="data">The initial contents of the object.  Note that we only read 'streamLength' bytes from the stream and do not close the stream.</param>
        /// <param name="streamLength">The number of bytes to read from the stream.  Must be &lt;= the actual stream length.</param>
        /// <param name="mimeType">the MIME type of the content.  Optional, may be null.  If data is non-null and mimeType is null, the MIME type will default to application/octet-stream.</param>
        /// <param name="checksum">the checksum object to use to compute checksums.  If you're doing incremental updates after the create, include the same object in subsequent calls.  Can be null to omit checksums.</param>
        /// <returns>Identifier of the newly created object.</returns>
        public ObjectId CreateObjectFromStreamOnPath(ObjectPath path, Acl acl, MetadataList metadata, Stream data, long streamLength, string mimeType, Checksum checksum)
        {
            HttpWebResponse resp = null;
            try
            {
                string resource = getResourcePath(context, path);
                Uri u = buildUrl(resource);
                HttpWebRequest con = createWebRequest(u);

                // Build headers
                Dictionary<string, string> headers = new Dictionary<string, string>();

                // Figure out the mimetype
                if (mimeType == null)
                {
                    mimeType = "application/octet-stream";
                }

                headers.Add("Content-Type", mimeType);
                headers.Add("x-emc-uid", uid);

                // Process metadata
                if (metadata != null)
                {
                    processMetadata(metadata, headers);
                }

                // Add acl
                if (acl != null)
                {
                    processAcl(acl, headers);
                }

                // Add date
                addDateHeader(headers);

                // Checksum if required
                if (checksum != null)
                {
                    if (!data.CanSeek)
                    {
                        throw new EsuException("Cannot checksum a stream that does not support seeking");
                    }
                    long current = data.Position;
                    byte[] buffer = new byte[64 * 1024];
                    for (long i = 0; i < streamLength; i += buffer.Length)
                    {
                        if (i + buffer.Length > streamLength)
                        {
                            int bytesToRead = (int)(streamLength - i);
                            int count = data.Read(buffer, 0, bytesToRead);
                            checksum.Update(new ArraySegment<byte>(buffer, 0, count));
                        }
                        else
                        {
                            int count = data.Read(buffer, 0, buffer.Length);
                            checksum.Update(new ArraySegment<byte>(buffer, 0, count));
                        }
                    }
                    data.Seek(current, SeekOrigin.Begin);

                    //Checksum ckcopy = checksum.Clone();
                    headers.Add("x-emc-wschecksum", checksum.ToString());
                }

                // Sign request
                signRequest(con, "POST", resource, headers);

                writeRequestBodyFromStream(con, data, streamLength);

                // Check response
                resp = (HttpWebResponse)con.GetResponse();
                int statInt = (int)resp.StatusCode;
                if (statInt > 299)
                {
                    handleError(resp);
                }

                // The new object ID is returned in the location response header
                string location = resp.Headers["location"];

                // Parse the value out of the URL

                MatchCollection m = OBJECTID_EXTRACTOR.Matches(location);
                if (m.Count > 0)
                {
                    string id = m[0].Groups[1].Value;
                    log.TraceEvent(TraceEventType.Verbose, 0, "Id: " + id);
                    return new ObjectId(id);
                }
                else
                {
                    throw new EsuException("Could not find ObjectId in " + location);
                }
            }
            catch (UriFormatException e)
            {
                throw new EsuException("Invalid URL", e);
            }
            catch (IOException e)
            {
                throw new EsuException("Error connecting to server", e);
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    handleError((HttpWebResponse)e.Response);
                }
                else
                {
                    throw new EsuException("Error executing request: " + e.Message, e);
                }
            }
            finally
            {
                if (resp != null)
                {
                    resp.Close();
                }
            }
            return null;
        }
예제 #48
0
 /// <summary>
 /// Creates a new object in the cloud.
 /// </summary>
 /// <param name="acl">Access control list for the new object.  May be null to use a default ACL</param>
 /// <param name="metadata">Metadata for the new object.  May be null for no metadata.</param>
 /// <param name="data">The initial contents of the object.  May be appended to later.  May be null to create an object with no content.</param>
 /// <param name="mimeType">the MIME type of the content.  Optional, may be null.  If data is non-null and mimeType is null, the MIME type will default to application/octet-stream.</param>
 /// <param name="checksum">the checksum object to use to compute checksums.  If you're doing incremental updates after the create, include the same object in subsequent calls.  Can be null to omit checksums.</param>
 /// <returns>Identifier of the newly created object.</returns>
 public ObjectId CreateObject(Acl acl, MetadataList metadata, byte[] data, string mimeType, Checksum checksum)
 {
     return CreateObjectFromSegment(acl, metadata,
         data == null ? new ArraySegment<byte>(new byte[0]) : new ArraySegment<byte>(data),
         mimeType, checksum);
 }
 private void SwapDacl(Acl dacl)
 {
     BaseObject.SwapRef(ref _dacl, dacl);
 }
예제 #50
0
 /// <summary>
 /// Creates a new object in the cloud using an ArraySegment.
 /// </summary>
 /// <param name="acl">Access control list for the new object.  May be null to use a default ACL</param>
 /// <param name="metadata">Metadata for the new object.  May be null for no metadata.</param>
 /// <param name="data">The initial contents of the object.  May be appended to later.  May be null to create an object with no content.</param>
 /// <param name="mimeType">the MIME type of the content.  Optional, may be null.  If data is non-null and mimeType is null, the MIME type will default to application/octet-stream.</param>
 /// <returns>Identifier of the newly created object.</returns>
 public ObjectId CreateObjectFromSegment(Acl acl, MetadataList metadata, ArraySegment<byte> data, string mimeType)
 {
     return CreateObjectFromSegment(acl, metadata, data, mimeType, null);
 }
예제 #51
0
        /// <summary>
        /// Returns an object's ACL
        /// </summary>
        /// <param name="id">The identifier of the object whose ACL to read</param>
        /// <returns>The object's ACL</returns>
        public Acl GetAcl( Identifier id )
        {
            HttpWebResponse resp = null;
            try {
                string resource = getResourcePath(context, id) + "?acl";
                Uri u = buildUrl( resource );
                HttpWebRequest con = createWebRequest(u);

                // Build headers
                Dictionary<string, string> headers = new Dictionary<string, string>();

                headers.Add( "x-emc-uid", uid );
                if (id is ObjectKey) {
                    headers.Add("x-emc-pool", (id as ObjectKey).pool);
                }

                // Add date
                addDateHeader(headers);

                // Sign request
                signRequest( con, "GET", resource, headers );

                // Check response
                resp = (HttpWebResponse)con.GetResponse();
                int statInt = (int)resp.StatusCode;
                if( statInt > 299 ) {
                    handleError( resp );
                }

                // Parse return headers.  User grants are in x-emc-useracl and
                // group grants are in x-emc-groupacl
                Acl acl = new Acl();
                readAcl( acl, resp.Headers["x-emc-useracl"], Grantee.GRANTEE_TYPE.USER );
                readAcl( acl, resp.Headers["x-emc-groupacl"], Grantee.GRANTEE_TYPE.GROUP );

                return acl;

            } catch( UriFormatException e ) {
                throw new EsuException( "Invalid URL", e );
            } catch( IOException e ) {
                throw new EsuException( "Error connecting to server", e );
            } catch( WebException e ) {
                if (e.Response != null)
                {
                    handleError((HttpWebResponse)e.Response);
                }
                else
                {
                    throw new EsuException("Error executing request: " + e.Message, e);
                }
            }
            finally
            {
                if( resp != null ) {
                    resp.Close();
                }
            }
            return null;
        }
예제 #52
0
        private void processAcl( Acl acl, Dictionary<string, string> headers )
        {
            StringBuilder userGrants = new StringBuilder();
            StringBuilder groupGrants = new StringBuilder();

            foreach( Grant grant in acl ) {
                if( grant.Grantee.GranteeType == Grantee.GRANTEE_TYPE.USER ) {
                    if( userGrants.Length > 0 ) {
                        userGrants.Append( "," );
                    }
                    userGrants.Append( grant.ToString() );
                } else {
                    if( groupGrants.Length > 0 ) {
                        groupGrants.Append( "," );
                    }
                    groupGrants.Append( grant.ToString() );
                }
            }

            headers.Add( "x-emc-useracl", userGrants.ToString() );
            headers.Add( "x-emc-groupacl", groupGrants.ToString() );
        }
 private static void ParseClaims(Acl acl, JObject item)
 {
     var sid = item.Property("sid").Value.ToString();
     var type = item.Property("type").Value.ToString();
     List<Access> allowed = new List<Access>();
     List<Access> denied = new List<Access>();
     var allowProperty = item.Property("allow");
     if (allowProperty != null)
     {
         allowProperty
             .Values()
             .Select(x => (Access)Enum.Parse(typeof(Access), x.ToString(), true))
             .For(x => allowed.Add(x));
     }
     var denyProperty = item.Property("deny");
     if (denyProperty != null)
     {
         denyProperty
             .Values()
             .Select(x => (Access)Enum.Parse(typeof(Access), x.ToString(), true))
             .For(x => denied.Add(x));
     }
     ClaimType claimType = (ClaimType)Enum.Parse(typeof(ClaimType), type, true);
     List<Claim> claims = new List<Claim>();
     allowed.For(x => claims.Add(new Claim(Permission.Allow, x, claimType, sid)));
     denied.For(x => claims.Add(new Claim(Permission.Deny, x, claimType, sid)));
     acl.SetInternal(claims);
 }
예제 #54
0
        private void readAcl( Acl acl, string header, EsuApiLib.Grantee.GRANTEE_TYPE type )
        {
            log.TraceEvent(TraceEventType.Verbose, 0,  "readAcl: " + header );
            string[] grants = header.Split( new string[] { "," }, StringSplitOptions.RemoveEmptyEntries );
            for( int i = 0; i < grants.Length; i++ ) {
                string[] nvpair = grants[i].Split( new string[] { "=" }, 2, StringSplitOptions.RemoveEmptyEntries );
                string grantee = nvpair[0];
                string permission = nvpair[1];

                grantee = grantee.Trim();

                // Currently, the server returns "FULL" instead of "FULL_CONTROL".
                // For consistency, change this to value use in the request
                if( "FULL".Equals( permission ) ) {
                    permission = Permission.FULL_CONTROL;
                }

                log.TraceEvent(TraceEventType.Verbose, 0,  "grant: " + grantee + "." + permission + " (" + type
                        + ")" );

                Grantee ge = new Grantee( grantee, type );
                Grant gr = new Grant( ge, permission );
                log.TraceEvent(TraceEventType.Verbose, 0,  "Grant: " + gr );
                acl.AddGrant( gr );
            }
        }
예제 #55
0
        /// <summary>
        /// Updates an existing object with the contents of the given stream, ACL, and
        /// metadata.
        /// </summary>
        /// <param name="id">the identifier of the object to update.</param>
        /// <param name="stream">the stream to replace the object's current
        /// contents with.  The stream will be read until an EOF is encountered.</param>
        /// <param name="acl">the ACL to update the object with.  Optional.  If not
        /// specified, the ACL will not be modified.</param>
        /// <param name="metadata">The metadata to assign to the object.
        /// Optional.  If null, no user metadata will be modified.</param>
        /// <param name="closeStream">If true, the stream will be closed after
        /// the object is updated.</param>
        public void UpdateObject( Identifier id, Stream stream, Acl acl,
                MetadataList metadata, bool closeStream ) {

            this.currentBytes = 0;
            this.complete = false;
            this.failed = false;
            this.error = null;
            this.closeStream = closeStream;
            this.stream = stream;

            if (computeChecksums)
            {
                checksum = new Checksum(Checksum.Algorithm.SHA0);
            }
            else
            {
                checksum = null;
            }

            // First call uses a null extent to truncate the file.
            try {
                bool eof = ReadChunk();
                this.esu.UpdateObjectFromSegment( id, acl, metadata, null, buffer,
                        contentType, checksum );

                if ( !eof ) {
                    this.OnProgress( buffer.Count );
                } else {
                    // No data in file? Complete
                    this.OnComplete();
                    return;
                }

                // Continue appending
                this.AppendChunks( id );

            } catch ( EsuException e ) {
                this.OnFail( e );
                throw e;
            } catch ( IOException e ) {
                this.OnFail( e );
                throw new EsuException( "Error updating object", e );
            }

        }
예제 #56
0
 /// <summary>
 /// Creates a new object in the cloud using a BufferSegment on the
 /// given path.
 /// </summary>
 /// <param name="path">the path to create the object on.</param>
 /// <param name="acl">Access control list for the new object.  May be null to use a default ACL</param>
 /// <param name="metadata">Metadata for the new object.  May be null for no metadata.</param>
 /// <param name="data">The initial contents of the object.  May be appended to later.  May be null to create an object with no content or a directory.</param>
 /// <param name="mimeType">the MIME type of the content.  Optional, may be null.  If data is non-null and mimeType is null, the MIME type will default to application/octet-stream.</param>
 /// <returns>the ObjectId of the newly-created object for references by ID.</returns>
 public ObjectId CreateObjectFromSegmentOnPath(ObjectPath path,
     Acl acl, MetadataList metadata,
     ArraySegment<byte> data, String mimeType)
 {
     return CreateObjectFromSegmentOnPath(path, acl, metadata, data, mimeType, null);
 }
예제 #57
0
        /// <summary>
        /// Creates a new object on the server with the contents of the given stream,
        /// acl and metadata.
        /// </summary>
        /// <param name="path">The ObjectPath to create the object on.</param>
        /// <param name="stream">the stream to upload.  The stream will be read until
        /// an EOF is encountered.</param>
        /// <param name="acl">the ACL to assign to the new object.  Optional.  If null,
        /// the server will generate a default ACL for the file.</param>
        /// <param name="metadata">The metadata to assign to the new object.
        /// Optional.  If null, no user metadata will be assigned to the new object.</param>
        /// <param name="closeStream">if true, the stream will be closed after
        /// the transfer completes.  If false, the stream will not be closed.</param>
        /// <returns>the identifier of the newly-created object.</returns>
        public ObjectId CreateObjectOnPath(ObjectPath path, Stream stream, Acl acl,
                MetadataList metadata, bool closeStream)
        {

            this.currentBytes = 0;
            this.complete = false;
            this.failed = false;
            this.error = null;
            this.closeStream = closeStream;
            this.stream = stream;

            if (computeChecksums)
            {
                checksum = new Checksum(Checksum.Algorithm.SHA0);
            }
            else
            {
                checksum = null;
            }

            ObjectId id = null;

            // First call should be to create object
            try
            {
                bool eof = ReadChunk();
                id = this.esu.CreateObjectFromSegmentOnPath(path, acl, metadata, buffer, contentType, checksum);
                if (!eof)
                {
                    this.OnProgress(buffer.Count);
                }
                else
                {
                    // No data in file? Complete
                    this.OnComplete();
                    return id;
                }

                // Continue appending
                this.AppendChunks(path);

            }
            catch (EsuException e)
            {
                this.OnFail(e);
                throw e;
            }
            catch (IOException e)
            {
                this.OnFail(e);
                throw new EsuException("Error uploading object", e);
            }

            return id;
        }
예제 #58
0
 /// <summary>
 /// Creates a new object in the cloud with the given key (and key-pool).
 /// </summary>
 /// <param name="key">the key-pool and key to use for the new object.</param>
 /// <param name="acl">Access control list for the new object.  May be null to use a default ACL</param>
 /// <param name="metadata">Metadata for the new object.  May be null for no metadata.</param>
 /// <param name="data">The initial contents of the object.  May be appended to later.  May be null to create an object with no content or a directory.</param>
 /// <param name="mimeType">the MIME type of the content.  Optional, may be null.  If data is non-null and mimeType is null, the MIME type will default to application/octet-stream.</param>
 /// <returns>the ObjectId of the newly-created object for references by ID.</returns>
 public ObjectId CreateObjectFromSegmentWithKey(ObjectKey key, Acl acl, MetadataList metadata,
     ArraySegment<byte> data, String mimeType)
 {
     return CreateObjectFromSegmentWithKey(key, acl, metadata, data, mimeType, null);
 }
예제 #59
0
 /// <summary>
 /// Creates a new object in the cloud on the
 /// given path.
 /// </summary>
 /// <param name="path">the path to create the object on.</param>
 /// <param name="acl">Access control list for the new object.  May be null to use a default ACL</param>
 /// <param name="metadata">Metadata for the new object.  May be null for no metadata.</param>
 /// <param name="data">The initial contents of the object.  May be appended to later.  May be null to create an object with no content or a directory.</param>
 /// <param name="mimeType">the MIME type of the content.  Optional, may be null.  If data is non-null and mimeType is null, the MIME type will default to application/octet-stream.</param>
 /// <returns>the ObjectId of the newly-created object for references by ID.</returns>
 public ObjectId CreateObjectOnPath(ObjectPath path, Acl acl,
     MetadataList metadata,
     byte[] data, String mimeType)
 {
     return CreateObjectFromSegmentOnPath(path, acl, metadata,
         data == null ? new ArraySegment<byte>(new byte[0]) : new ArraySegment<byte>(data),
         mimeType, null);
 }
예제 #60
0
        /// <summary>
        /// Returns all of an object's metadata and its ACL in
        /// one call.
        /// </summary>
        /// <param name="id">the object's identifier.</param>
        /// <returns>the object's metadata</returns>
        public ObjectMetadata GetAllMetadata( Identifier id )
        {
            HttpWebResponse resp = null;
            try {
                string resource = getResourcePath(context, id);
                Uri u = buildUrl(resource);
                HttpWebRequest con = createWebRequest(u);

                // Build headers
                Dictionary<string, string> headers = new Dictionary<string, string>();

                headers.Add("x-emc-uid", uid);
                if (utf8Enabled) headers.Add("x-emc-utf8", "true");
                if (id is ObjectKey) {
                    headers.Add("x-emc-pool", (id as ObjectKey).pool);
                }

                // Add date
                addDateHeader(headers);

                // Sign request
                signRequest(con, "HEAD", resource, headers);

                // Check response
                resp = (HttpWebResponse)con.GetResponse();
                int statInt = (int)resp.StatusCode;
                if (statInt > 299) {
                    handleError(resp);
                }

                // Parse return headers.  Regular metadata is in x-emc-meta and
                // listable metadata is in x-emc-listable-meta
                MetadataList meta = new MetadataList();
                readMetadata(meta, resp.Headers["x-emc-meta"], false);
                readMetadata(meta, resp.Headers["x-emc-listable-meta"], true);

                // Parse return headers.  User grants are in x-emc-useracl and
                // group grants are in x-emc-groupacl
                Acl acl = new Acl();
                readAcl(acl, resp.Headers["x-emc-useracl"], Grantee.GRANTEE_TYPE.USER);
                readAcl(acl, resp.Headers["x-emc-groupacl"], Grantee.GRANTEE_TYPE.GROUP);

                ObjectMetadata om = new ObjectMetadata();
                om.ACL = acl;
                om.Metadata = meta;

                return om;

            } catch (UriFormatException e) {
                throw new EsuException("Invalid URL", e);
            } catch (IOException e) {
                throw new EsuException("Error connecting to server", e);
            } catch (WebException e) {
                if (e.Response != null)
                {
                    handleError((HttpWebResponse)e.Response);
                }
                else
                {
                    throw new EsuException("Error executing request: " + e.Message, e);
                }
            }
            finally
            {
                if (resp != null) {
                    resp.Close();
                }
            }
            return null;
        }