Exemple #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ZpAccessException"/> class.
 /// </summary>
 /// <param name="aMessage">The AccessException message.</param>
 /// <param name="aUserID">The UserID of the access controlled user.</param>
 /// <param name="aAccessMode">The AccessMode.</param>
 /// <param name="aObject">The access controlled object.</param>
 public ZpAccessException(string aMessage, string aUserID, AccessMode aAccessMode, string aObject)
     : base(aMessage)
 {
     _userID = aUserID;
     _accessMode = aAccessMode;
     _object = aObject;
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 public GXDLT645Property(ulong dataID, string name, DataType type, AccessMode access) : 
     base(name)
 {
     this.DataID = dataID;
     Type = type;
     this.AccessMode = access;
 }
Exemple #3
0
		public ImageMapSegment(string name, uint size, AccessMode access) : base(size) 
		{
			if (name == null)
				throw new ArgumentNullException("name", "Segments must have names.");
			this.Name = name;
			this.Access = access;
		}
Exemple #4
0
 public ImageSegment(string name, Address addr, long size, AccessMode access)
 {
     if (name == null)
         throw new ArgumentNullException("name", "Segments must have names.");
     this.Name = name;
     this.Size = (uint) size;
     this.Address = addr;
     this.Access = access;
 }
Exemple #5
0
        /// <summary>
        /// Use this constructor when the segment shares the MemoryArea with
        /// other segments.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="addr"></param>
        /// <param name="mem"></param>
        /// <param name="access"></param>
		public ImageSegment(string name, Address addr, MemoryArea mem, AccessMode access) : base() 
		{
			if (name == null)
				throw new ArgumentNullException("name", "Segments must have names.");
			this.Name = name;
            this.Address = addr;
            this.MemoryArea = mem;
			this.Access = access;
		}
Exemple #6
0
 public ImageSegment AddSegment(MemoryArea mem, string segmentName, AccessMode mode)
 {
     var segment = new ImageSegment(
             segmentName,
             mem,
             mode);
     AddSegment(segment);
     return segment;
 }
Exemple #7
0
		/// <summary>
		/// Checks if the caller has access to the inode 
		/// </summary>
		/// <param name="path">The resource to check permissions for.</param>
		/// <returns>True if the requested access mode combination is available to the immediate caller. If any one requested access mode is not available, the result is false.</returns>
		public static bool Access(string path, AccessMode mode)
		{
			DirectoryEntry entry = PathResolver.Resolve(rootNode, ref path, PathResolutionFlags.DoNotThrowNotFoundException);
			if (null != entry) {
				return AccessCheck.Perform(entry, mode, AccessCheckFlags.NoThrow);
			}

			return false;
		}
        public LockingObject Lock(AccessMode accessMode, bool enableSynchronize)
        {
            if (!enableSynchronize)
            {
                return null;
            }

            return this.Lock(accessMode);
        }
		public Task<Stream> OpenStreamAsync(string boardName, AccessMode accessMode)
		{
			// Note that we do not need any preconditions here. They are inherited from
			// the base interface.

			return Task.FromResult(new FileStream(
				Path.Combine(this.boardsDirectory.Value, boardName),
				accessMode == AccessMode.Read ? FileMode.Open : FileMode.OpenOrCreate) as Stream);
		}
Exemple #10
0
 /// <summary>
 /// Use this constructor when the segment's memory area is completely 
 /// disjoint fromother segments. This is usually the case in PE or ELF
 /// binaries.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="mem"></param>
 /// <param name="access"></param>
 public ImageSegment(string name, MemoryArea mem, AccessMode access)
 {
     if (name == null)
         throw new ArgumentNullException("name", "Segments must have names.");
     this.Name = name;
     this.Size = (uint)mem.Length;
     this.Address = mem.BaseAddress;
     this.MemoryArea = mem;
     this.Access = access;
 }
		public async Task<Stream> OpenStreamAsync(string boardName, AccessMode accessMode)
		{
			// Note that we do not need any preconditions here. They are inherited from
			// the base interface.

			// Get reference to requested blob and open stream
			var blob = this.container.GetBlockBlobReference(boardName);
			return accessMode == AccessMode.Read
				? await blob.OpenReadAsync().ConfigureAwait(false)
				: await blob.OpenWriteAsync().ConfigureAwait(false);
		}
	    public static String getAccessString(AccessMode access_mode) {
		    switch (access_mode) {
		    case AccessMode.ACCESS_READWRITE:
			    return "Read/Write";
            //case AccessMode.ACCESS_WRITEONLY:
			//    return "Write only";
            case AccessMode.ACCESS_READONLY:
			    return "Read only";
		    default:
			    return "unknowm Access Mode";
		    }
	    }
        async Task ChangeAccessMode(AccessMode changeAccessMode, byte portNo) {
            var S3F23 = new SecsMessage(3, 23, "ChangeAccessMode",
                Item.L(
                    Item.A(),
                    Item.U1((byte)changeAccessMode),
                    Item.L(
                        Item.U1(portNo))));

            var S3F24 = await EAP.SendAsync(S3F23);
            byte returnCode = (byte)S3F24.SecsItem.Items[0];
            if (returnCode != 0 && returnCode != 4)
                throw new ScenarioException("Change Loadport[" + portNo + "] access mode fial. " + S3F24.SecsItem.Items[1].Items[1].GetValue<string>());
        }
 async Task ChangeAccessMode(AccessMode changeAccessMode, int portNo) {
     var s3f24 = await EAP.SendAsync(new SecsMessage(3, 23, "ChangeAccessMode",
         Item.L(
             Item.A("ChangeAccess"),
             Item.A(portNo.ToString()),
             Item.L(
                 Item.L(
                     Item.A("AccessMode"),
                     Item.B((byte)changeAccessMode))))));
     byte returnCode = (byte)s3f24.SecsItem.Items[0];
     if (returnCode != 0 && returnCode != 4)
         throw new ScenarioException("Change Loadport[" + portNo + "] access mode fial: " + s3f24.SecsItem.Items[1].Items[0].Items[1].GetValue<string>());
 }
        public LockingObject Lock(AccessMode accessMode)
        {
            if (accessMode == AccessMode.Read)
            {
                this.lastRequireReadTime = DateTime.Now;
            }
            else
            {
                this.lastRequireWriteTime = DateTime.Now;
            }

            return new LockingObject(this.readerWriterLock, accessMode);
        } 
        internal DocumentStoreWrapper(
            string name, 
            AccessMode accessMode,
            Action<DocumentStoreWrapper> updateInnerStore)
        {
            name.Ensure("name").IsNotNullOrWhiteSpace();
            updateInnerStore.Ensure("updateInnerStore").IsNotNull();

            this.Name = name;
            this.AccessMode = accessMode;
            this.IsInitialized = false;
            this.UpdateInnerStore = updateInnerStore;
        }
		public Task<Stream> OpenStreamAsync(string boardName, AccessMode accessMode)
		{
			// Note that we cannot make this precondition a legacy-requires in our sample.
			Contract.Requires(boardName != null);

			// The following postcondition checks the resulting task.
			Contract.Ensures(Contract.Result<Task<Stream>>() != null);

			// The following postcondition checks the result once the Task has been completed.
			Contract.Ensures(Contract.Result<Task<Stream>>().Result != null);

			return default(Task<Stream>);
		}
Exemple #18
0
        public LockingObject(ReaderWriterLock _lock, AccessMode _lockMode)
        {
            readerWriterLock = _lock;
            accessMode = _lockMode;

            if (accessMode == AccessMode.Read)
            {
                readerWriterLock.AcquireReaderLock(-1);
            }
            else
            {
                readerWriterLock.AcquireWriterLock(-1);
            }
        }
		/// <summary>
		/// Constructor.
		/// </summary>
		public VistaDBConnection()
		{
			VistaDBErrorMsgs.SetErrorFunc();
			this.connectionState = ConnectionState.Closed;
			this.accessMode      = AccessMode.Local;
			this.vistaDBSQL      = null;

			this.dataSource      = null;
			this.database        = null;
			this.cypher          = CypherType.None;
			this.password        = null;
			this.exclusive       = false;
			this.readOnly        = false;
			this.loginUser       = "";
			this.loginPassword   = "";
		}
        public LockingObject(ReaderWriterLock _lock, AccessMode _lockMode)
        {
            this.readerWriterLock = _lock;
            this.accessMode = _lockMode;

            if (this.accessMode == AccessMode.Read)
            {
                this.readerWriterLock.AcquireReaderLock(-1);
            }
            else if (this.accessMode == AccessMode.Write)
            {
                this.readerWriterLock.AcquireWriterLock(-1);
            }
            else //UpAndDowngrade
            {
                this.lockCookie = this.readerWriterLock.UpgradeToWriterLock(-1);
            }
        }
Exemple #21
0
        private void TestBandwidth(Context context, Device[] devices, int start, int end, int increment, TestMode testMode, MemoryCopyKind memoryCopyKind, PrintMode printMode, AccessMode accessMode, MemoryMode memoryMode, int startDevice, int endDevice)
        {
            switch (testMode)
            {
            case TestMode.Quick:
                TestBandwidthQuick(context, devices, DefaultSize, memoryCopyKind, printMode, accessMode, memoryMode, startDevice, endDevice);
                break;

            case TestMode.Range:
                TestBandwidthRange(context, devices, start, end, increment, memoryCopyKind, printMode, accessMode, memoryMode, startDevice, endDevice);
                break;

            case TestMode.Shmoo:
                TestBandwidthShmoo(context, devices, memoryCopyKind, printMode, accessMode, memoryMode, startDevice, endDevice);
                break;

            default:
                break;
            }
        }
 /// <summary>
 /// Gets a specific access of a Specific mode for a user.
 /// </summary>
 /// <param name="aUserKey">A user key composite.</param>
 /// <param name="aFunction">A function.</param>
 /// <param name="aAccessMode">A access mode.</param>
 /// <returns></returns>
 public static bool HasModeAccess(UserKey aUserKey, string aFunction, AccessMode aAccessMode)
 {
     UserFunctionAccess vUserFunctionAccess = new UserFunctionAccess() { UsrKey = aUserKey.UsrKey };
     vUserFunctionAccess.FunctionAccess.Function = aFunction;
     Load(vUserFunctionAccess);
     bool vAccess = false;
     switch (aAccessMode)
     {
         case AccessMode.List:
             {
                 vAccess = vUserFunctionAccess.FunctionAccess.Access.List;
                 break;
             }
         case AccessMode.Read:
             {
                 vAccess = vUserFunctionAccess.FunctionAccess.Access.Read;
                 break;
             }
         case AccessMode.Create:
             {
                 vAccess = vUserFunctionAccess.FunctionAccess.Access.Create;
                 break;
             }
         case AccessMode.Update:
             {
                 vAccess = vUserFunctionAccess.FunctionAccess.Access.Update;
                 break;
             }
         case AccessMode.Delete:
             {
                 vAccess = vUserFunctionAccess.FunctionAccess.Access.Delete;
                 break;
             }
         default:
             {
                 vAccess = false;
                 break;
             }
     }
     return vAccess;
 }
        /// <summary>
        /// Retrieve a Stream for the given path (Read or Write access can be specified)
        /// Stream.Close() should be called when you are finished using the Stream.
        /// </summary>
        /// <param name="file">Heirarchical path designating stream location (uses "/" as
        /// path designator)</param>
        /// <param name="mode">Read or Write. Write will overwrite any exising path of
        /// the same name.</param>
        /// <returns>Stream that can be used to access the path (Stream.Close() must be
        /// called when you are finished using the Stream).</returns>
        public override Stream Open(string file, AccessMode mode)
        {
            // validate the path (throws an exception if it is invalid)
            ValidatePath(file);

            // convert the path to lower-case
            string pathLower = file.ToLower(CultureInfo.InvariantCulture);

            // return the approrpiate stream
            switch (mode)
            {
                case AccessMode.Read:
                    return OpenMemoryStreamForRead(pathLower);

                case AccessMode.Write:
                    return OpenMemoryStreamForWrite(pathLower);

                default:
                    Debug.Assert(false, "Invalid AccessMode");
                    return null;
            }
        }
Exemple #24
0
        public IDocumentStore GetOrCreate(
            string name,
            AccessMode accessMode = AccessMode.ReadOnly,
            Action<DocumentStore> initializer = null)
        {
            name.Ensure("name").IsNotNullOrWhiteSpace();

            var existingWrapper = allStoreWrappers.SingleOrDefault(
                store =>
                    store.Name.Equals(name, StringComparison.OrdinalIgnoreCase) &&
                    store.AccessMode == accessMode);
            if (existingWrapper != null)
            {
                return existingWrapper;
            }

            initializer = initializer ?? (store => store.Initialize());
            Action<DocumentStoreWrapper> updateInnerStore =
                wrapper => this.UpdateInnerStore(wrapper, initializer);
            var newStore = new DocumentStoreWrapper(name, accessMode, updateInnerStore);

            allStoreWrappers.Add(newStore);
            return newStore;
        }
Exemple #25
0
        ///<summary>
        ///Handle set request.
        ///</summary>
        ///<returns>
        ///Reply to the client.
        ///</returns>
        private byte[][] HandleSetRequest()
        {
            ErrorCode    error = ErrorCode.Ok;
            GXByteBuffer data  = Reply.Data;
            GXDataInfo   info  = new GXDataInfo();
            GXByteBuffer bb    = new GXByteBuffer();
            // Get type.
            short type = data.GetUInt8();

            // Get invoke ID and priority.
            data.GetUInt8();
            // SetRequest normal
            if (type == 1)
            {
                Settings.ResetBlockIndex();
                ServerReply.Index = 0;
                // CI
                ObjectType ci = (ObjectType)data.GetUInt16();
                byte[]     ln = new byte[6];
                data.Get(ln);
                // Attribute index.
                int index = data.GetUInt8();
                // Get Access Selection.
                data.GetUInt8();
                object       value = GXCommon.GetData(data, info);
                GXDLMSObject obj   = Settings.Objects.FindByLN(ci, GXDLMSObject.ToLogicalName(ln));
                if (obj == null)
                {
                    obj = FindObject(ci, 0, GXDLMSObject.ToLogicalName(ln));
                }
                // If target is unknown.
                if (obj == null)
                {
                    Debug.WriteLine("Undefined object.");
                    // Device reports a undefined object.
                    error = ErrorCode.UndefinedObject;
                }
                else
                {
                    AccessMode am = obj.GetAccess(index);
                    // If write is denied.
                    if (am != AccessMode.Write && am != AccessMode.ReadWrite)
                    {
                        Debug.WriteLine("Read Write denied.");
                        error = ErrorCode.ReadWriteDenied;
                    }
                    else
                    {
                        try
                        {
                            if (value is byte[])
                            {
                                DataType dt = (obj as IGXDLMSBase).GetDataType(index);
                                if (dt != DataType.None)
                                {
                                    value = GXDLMSClient.ChangeType((byte[])value, dt);
                                }
                            }
                            ValueEventArgs e = new ValueEventArgs(obj, index, 0, null);
                            Write(e);
                            if (!e.Handled)
                            {
                                (obj as IGXDLMSBase).SetValue(Settings, index, value);
                            }
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(e.Message);
                            error = ErrorCode.HardwareFault;
                        }
                    }
                }
            }
            else
            {
                Debug.WriteLine("handleSetRequest failed. Unknown command.");
                Settings.ResetBlockIndex();
                error = ErrorCode.HardwareFault;
            }
            return(GXDLMS.SplitPdu(Settings, Command.SetResponse, 1, bb, error, DateTime.MinValue)[0]);
        }
Exemple #26
0
            public MockedConnection(AccessMode mode, List <Tuple <IRequestMessage, IResponseMessage> > messages,
                                    ServerInfo serverInfo = null, IDictionary <string, string> routingContext = null)
            {
                foreach (var pair in messages)
                {
                    if (pair.Item1 != null)
                    {
                        _requestMessages.Add(pair.Item1);
                    }

                    if (pair.Item2 != null)
                    {
                        _responseMessages.Add(pair.Item2);
                    }
                }

                _mockConn.Setup(x => x.EnqueueAsync(It.IsAny <IRequestMessage>(), It.IsAny <IResponseHandler>(),
                                                    It.IsAny <IRequestMessage>(), It.IsAny <IResponseHandler>()))
                .Returns(Task.CompletedTask)
                .Callback <IRequestMessage, IResponseHandler, IRequestMessage, IResponseHandler>(
                    (msg1, handler1, msg2, handler2) =>
                {
                    msg1.ToString().Should().Be(_requestMessages[_requestCount].ToString());
                    _requestCount++;
                    _pipeline.Enqueue(msg1, handler1);

                    if (msg2 != null)
                    {
                        msg2.ToString().Should().Be(_requestMessages[_requestCount].ToString());
                        _requestCount++;
                        _pipeline.Enqueue(msg2, handler2);
                    }
                });

                _mockConn.Setup(x => x.ReceiveOneAsync())
                .Returns(() =>
                {
                    if (_responseCount < _responseMessages.Count)
                    {
                        _responseMessages[_responseCount].Dispatch(_pipeline);
                        _responseCount++;
                        _pipeline.AssertNoFailure();
                        return(Task.CompletedTask);
                    }
                    else
                    {
                        throw new InvalidOperationException("Not enough response message to provide");
                    }
                });

                _mockConn.Setup(x => x.SyncAsync())
                .Returns(() =>
                {
                    if (_responseCount < _responseMessages.Count)
                    {
                        _responseMessages[_responseCount].Dispatch(_pipeline);
                        _responseCount++;
                        _pipeline.AssertNoFailure();
                        return(Task.CompletedTask);
                    }
                    else
                    {
                        throw new InvalidOperationException("Not enough response message to provide");
                    }
                });


                _mockConn.Setup(x => x.IsOpen).Returns(() => _responseCount < _responseMessages.Count);

                _mockConn.Setup(x => x.Mode).Returns(mode);

                var protocol = new BoltProtocolV3();

                if (serverInfo != null)
                {
                    if (serverInfo.Protocol >= BoltProtocolVersion.V4_3)
                    {
                        protocol = new BoltProtocolV4_3(routingContext);
                    }
                    else if (serverInfo.Protocol >= BoltProtocolVersion.V4_0)
                    {
                        protocol = new BoltProtocolV4_0();
                    }

                    _mockConn.Setup(x => x.Server).Returns(serverInfo);
                }
                else
                {
                    _mockConn.Setup(x => x.Server)
                    .Returns(new ServerInfo(new Uri("bolt://123:456"))
                    {
                        Agent = "Neo4j/3.5.0"
                    });
                }

                _mockConn.Setup(x => x.BoltProtocol).Returns(protocol);
            }
Exemple #27
0
        ///<summary>
        /// Handle write request.
        ///</summary>
        ///<param name="Reply">
        /// Received data from the client.
        /// </param>
        ///<returns>
        /// Reply.
        ///</returns>
        private byte[][] HandleWriteRequest()
        {
            GXByteBuffer data = Reply.Data;
            short        type;
            object       value;
            // Get object count.
            IList <GXSNInfo> targets = new List <GXSNInfo>();
            int          cnt         = GXCommon.GetObjectCount(data);
            GXByteBuffer results     = new GXByteBuffer((ushort)cnt);

            for (int pos = 0; pos != cnt; ++pos)
            {
                type = data.GetUInt8();
                if (type == 2)
                {
                    int      sn   = data.GetUInt16();
                    GXSNInfo info = FindSNObject(sn);
                    targets.Add(info);
                    // If target is unknown.
                    if (info == null)
                    {
                        // Device reports a undefined object.
                        results.SetUInt8(ErrorCode.UndefinedObject);
                    }
                    else
                    {
                        results.SetUInt8(ErrorCode.Ok);
                    }
                }
                else
                {
                    // Device reports a HW error.
                    results.SetUInt8(ErrorCode.HardwareFault);
                }
            }
            // Get data count.
            cnt = GXCommon.GetObjectCount(data);
            GXDataInfo di = new GXDataInfo();

            for (int pos = 0; pos != cnt; ++pos)
            {
                if (results.GetUInt8(pos) == 0)
                {
                    // If object has found.
                    GXSNInfo target = targets[pos];
                    value = GXCommon.GetData(data, di);
                    if (value is byte[])
                    {
                        DataType dt = target.Item.GetDataType(target.Index);
                        if (dt != DataType.None && dt != DataType.OctetString)
                        {
                            value = GXDLMSClient.ChangeType((byte[])value, dt);
                        }
                    }
                    di.Clear();
                    AccessMode am = target.Item.GetAccess(target.Index);
                    // If write is denied.
                    if (am != AccessMode.Write && am != AccessMode.ReadWrite)
                    {
                        results.SetUInt8((byte)pos, (byte)ErrorCode.ReadWriteDenied);
                    }
                    else
                    {
                        ValueEventArgs e = new ValueEventArgs(target.Item, target.Index, 0, null);
                        e.Value = value;
                        Write(e);
                        if (!e.Handled)
                        {
                            (target.Item as IGXDLMSBase).SetValue(Settings, target.Index, value);
                        }
                    }
                }
            }
            GXByteBuffer bb = new GXByteBuffer((UInt16)(2 * cnt + 2));

            GXCommon.SetObjectCount(cnt, bb);
            byte ret;

            for (int pos = 0; pos != cnt; ++pos)
            {
                ret = results.GetUInt8(pos);
                // If meter returns error.
                if (ret != 0)
                {
                    bb.SetUInt8(1);
                }
                bb.SetUInt8(ret);
            }
            return(GXDLMS.SplitPdu(Settings, Command.WriteResponse, 1, bb, ErrorCode.Ok, DateTime.MinValue)[0]);
        }
Exemple #28
0
        public override SegmentMap LoadImageBytes(IPlatform platform, byte[] rawImage, Address addrPreferred)
        {
            var segMap = AllocateMemoryAreas(
                Segments
                .Where(p => IsLoadable(p.p_pmemsz, p.p_type))
                .OrderBy(p => p.p_vaddr)
                .Select(p => Tuple.Create(
                            Address.Ptr32((uint)p.p_vaddr),
                            (uint)p.p_pmemsz)));

            foreach (var ph in Segments)
            {
                ElfImageLoader.trace.Inform("ph: addr {0:X8} filesize {0:X8} memsize {0:X8}", ph.p_vaddr, ph.p_filesz, ph.p_pmemsz);
                if (!IsLoadable(ph.p_pmemsz, ph.p_type))
                {
                    continue;
                }
                var vaddr = Address.Ptr32((uint)ph.p_vaddr);
                segMap.TryGetLowerBound(vaddr, out var mem);
                if (ph.p_filesz > 0)
                {
                    Array.Copy(
                        rawImage,
                        (long)ph.p_offset, mem.Bytes,
                        vaddr - mem.BaseAddress, (long)ph.p_filesz);
                }
            }
            var segmentMap = new SegmentMap(addrPreferred);

            if (Sections.Count > 0)
            {
                foreach (var section in Sections)
                {
                    if (string.IsNullOrEmpty(section.Name) || section.Address == null)
                    {
                        continue;
                    }

                    if (segMap.TryGetLowerBound(section.Address, out var mem) &&
                        section.Address - mem.BaseAddress < mem.Length)
                    {
                        AccessMode mode = AccessModeOf(section.Flags);
                        var        seg  = segmentMap.AddSegment(new ImageSegment(
                                                                    section.Name,
                                                                    section.Address,
                                                                    mem, mode)
                        {
                            Size = (uint)section.Size
                        });
                        seg.Designer = CreateRenderer(section, machine);
                    }
                    else
                    {
                        //$TODO: warn
                    }
                }
            }
            else
            {
                // There are stripped ELF binaries with 0 sections. If we have one
                // create a pseudo-section from the segMap.
                foreach (var segment in segMap)
                {
                    var elfSegment = this.GetSegmentByAddress(segment.Value.BaseAddress.ToLinear());
                    var imgSegment = new ImageSegment(
                        segment.Value.BaseAddress.GenerateName("seg", ""),
                        segment.Value,
                        elfSegment != null
                            ? elfSegment.GetAccessMode()
                            : AccessMode.ReadExecute)

                    {
                        Size = (uint)segment.Value.Length,
                    };
                    segmentMap.AddSegment(imgSegment);
                }
            }
            segmentMap.DumpSections();
            return(segmentMap);
        }
Exemple #29
0
        internal static Session NewSession(IBoltProtocol protocol, IDriverLogger logger = null, IRetryLogic retryLogic = null, AccessMode mode = AccessMode.Write, string bookmark = null)
        {
            var mockConn = new Mock <IConnection>();

            mockConn.Setup(x => x.IsOpen).Returns(true);
            mockConn.Setup(x => x.BoltProtocol).Returns(protocol);
            return(new Session(new TestConnectionProvider(mockConn.Object), logger, retryLogic, mode, Bookmark.From(bookmark)));
        }
 public ISession Session(AccessMode defaultMode, IEnumerable <string> bookmarks)
 {
     return(driver.Session(defaultMode, bookmarks));
 }
 public IAsyncSession NewSession(AccessMode mode, TContext context)
 {
     return(_driver.AsyncSession(o =>
                                 o.WithDefaultAccessMode(mode)
                                 .WithBookmarks(_useBookmark ? new[] { context.Bookmark } : Array.Empty <Bookmark>())));
 }
 protected override IRequestMessage GetRunWithMetaDataMessage(Query query, Bookmark bookmark = null, TransactionConfig config = null, AccessMode mode = AccessMode.Write, string database = null, string impersonatedUser = null)
 {
     ValidateImpersonatedUserForVersion(impersonatedUser);
     return(new RunWithMetadataMessage(query, database, bookmark, config, mode, impersonatedUser));
 }
Exemple #33
0
            void parseSection64(uint protection)
            {
                var   abSectname = rdr.ReadBytes(16);
                var   abSegname  = rdr.ReadBytes(16);
                ulong addr;
                ulong size;
                uint  offset;
                uint  align;
                uint  reloff;
                uint  nreloc;
                uint  flags;
                uint  reserved1;
                uint  reserved2;
                uint  reserved3;

                if (!rdr.TryReadUInt64(out addr) ||
                    !rdr.TryReadUInt64(out size) ||
                    !rdr.TryReadUInt32(out offset) ||
                    !rdr.TryReadUInt32(out align) ||
                    !rdr.TryReadUInt32(out reloff) ||
                    !rdr.TryReadUInt32(out nreloc) ||
                    !rdr.TryReadUInt32(out flags) ||
                    !rdr.TryReadUInt32(out reserved1) ||
                    !rdr.TryReadUInt32(out reserved2) ||
                    !rdr.TryReadUInt32(out reserved3))
                {
                    throw new BadImageFormatException("Could not read Mach-O section.");
                }

                var sectionName = GetAsciizString(abSectname);
                var segmentName = GetAsciizString(abSegname);

                Debug.Print("Found section '{0}' in segment '{1}, addr = 0x{2:X}, size = 0x{3:X}.",
                            sectionName,
                            segmentName,
                            addr,
                            size);

                AccessMode am = 0;

                if ((protection & VM_PROT_READ) != 0)
                {
                    am |= AccessMode.Read;
                }
                if ((protection & VM_PROT_WRITE) != 0)
                {
                    am |= AccessMode.Write;
                }
                if ((protection & VM_PROT_EXECUTE) != 0)
                {
                    am |= AccessMode.Execute;
                }

                var imageSection = new ImageMapSegment(
                    string.Format("{0},{1}", segmentName, sectionName),
                    (uint)size,
                    am);        //imageSection.setData(!imageSection->isCode());
                //imageSection.setBss((section.flags & SECTION_TYPE) == S_ZEROFILL);

                //if (!imageSection.isBss()) {
                //    auto pos = source_->pos();
                //    if (!source_->seek(section.offset)) {
                //        throw ParseError("Could not seek to the beginning of the section's content.");
                //    }
                //    auto bytes = source_->read(section.size);
                //    if (checked_cast<uint>(bytes.size()) != section.size) {
                //        log_.warning("Could not read all the section's content.");
                //    } else {
                //        imageSection->setContent(std::move(bytes));
                //    }
                //    source_->seek(pos);
                //}

                //sections_.push_back(imageSection.get());
                //image_->addSection(std::move(imageSection));
            }
Exemple #34
0
		/// <summary>
		///    Searches forwards through a file for a specified
		///    pattern, starting at a specified offset.
		/// </summary>
		/// <param name="pattern">
		///    A <see cref="ByteVector" /> object containing a pattern
		///    to search for in the current instance.
		/// </param>
		/// <param name="startPosition">
		///    A <see cref="int" /> value specifying at what
		///    seek position to start searching.
		/// </param>
		/// <param name="before">
		///    A <see cref="ByteVector" /> object specifying a pattern
		///    that the searched for pattern must appear before. If this
		///    pattern is found first, -1 is returned.
		/// </param>
		/// <returns>
		///    A <see cref="long" /> value containing the index at which
		///    the value was found. If not found, -1 is returned.
		/// </returns>
		/// <exception cref="ArgumentNullException">
		///    <paramref name="pattern" /> is <see langword="null" />.
		/// </exception>
		public long Find (ByteVector pattern, long startPosition,
		                  ByteVector before)
		{
			if (pattern == null)
				throw new ArgumentNullException ("pattern");
			
			Mode = AccessMode.Read;
			
			if (pattern.Count > buffer_size)
				return -1;
			
			// The position in the file that the current buffer
			// starts at.
			
			long buffer_offset = startPosition;
			ByteVector buffer;
			
			// These variables are used to keep track of a partial
			// match that happens at the end of a buffer.
			
			int previous_partial_match = -1;
			int before_previous_partial_match = -1;
			
			// Save the location of the current read pointer.  We
			// will restore the position using Seek() before all
			// returns.
			
			long original_position = file_stream.Position;
			
			// Start the search at the offset.
			
			file_stream.Position = startPosition;
			
			// This loop is the crux of the find method.  There are
			// three cases that we want to account for:
			//
			// (1) The previously searched buffer contained a
			//     partial match of the search pattern and we want
			//     to see if the next one starts with the remainder
			//     of that pattern.
			//
			// (2) The search pattern is wholly contained within the
			//     current buffer.
			//
			// (3) The current buffer ends with a partial match of
			//     the pattern.  We will note this for use in the 
			//     next iteration, where we will check for the rest 
			//     of the pattern.
			//
			// All three of these are done in two steps.  First we
			// check for the pattern and do things appropriately if
			// a match (or partial match) is found.  We then check 
			// for "before".  The order is important because it 
			// gives priority to "real" matches.
			
			for (buffer = ReadBlock (buffer_size); 
				buffer.Count > 0;
				buffer = ReadBlock(buffer_size)) {
				
				// (1) previous partial match
				
				if (previous_partial_match >= 0 &&
					buffer_size > previous_partial_match) {
					int pattern_offset = buffer_size -
						previous_partial_match;
					
					if (buffer.ContainsAt (pattern, 0,
						pattern_offset)) {
						
						file_stream.Position =
							original_position;
						
						return buffer_offset -
							buffer_size +
							previous_partial_match;
					}
				}
				
				if (before != null &&
					before_previous_partial_match >= 0 &&
					buffer_size >
					before_previous_partial_match) {
					
					int before_offset = buffer_size -
						before_previous_partial_match;
					
					if (buffer.ContainsAt (before, 0,
						before_offset)) {
						
						file_stream.Position =
							original_position;
						
						return -1;
					}
				}
				
				// (2) pattern contained in current buffer
				
				long location = buffer.Find (pattern);
				
				if (location >= 0) {
					file_stream.Position = original_position;
					return buffer_offset + location;
				}
				
				if (before != null && buffer.Find (before) >= 0) {
					file_stream.Position = original_position;
					return -1;
				}
				
				// (3) partial match
				
				previous_partial_match =
					buffer.EndsWithPartialMatch (pattern);
				
				if (before != null)
					before_previous_partial_match =
						buffer.EndsWithPartialMatch (
							before);
				
				buffer_offset += buffer_size;
			}
			
			// Since we hit the end of the file, reset the status
			// before continuing.
			
			file_stream.Position = original_position;
			return -1;
		}
Exemple #35
0
 /// <summary>
 /// This method performs an access check on the given dentry.
 /// </summary>
 /// <param name="dentry">The directory entry to perform the access check on.</param>
 /// <param name="mode">The access mode to check.</param>
 /// <param name="flags">Flags, which control the operation.</param>
 /// <returns>True if the caller has the requested permissions on the given directory entry.</returns>
 /// <exception cref="System.Security.SecurityException">This exception is thrown for failed access checks unless the caller has specified AccessCheckFlags.NoThrow.</exception>
 /// <remarks>
 /// This function only checks the permissions on the dentry itself. It does not traverse the directory tree towards the root
 /// to check the entire tree. Tree checking is automatically performed by Lookup and related functions.
 /// </remarks>
 public static bool Perform(DirectoryEntry dentry, AccessMode mode, AccessCheckFlags flags)
 {
     // FIXME: Implement the access checking
     return(true);
 }
Exemple #36
0
		/// <summary>
		///    Reads a specified number of bytes at the current seek
		///    position from the current instance.
		/// </summary>
		/// <param name="length">
		///    A <see cref="int" /> value specifying the number of bytes
		///    to read.
		/// </param>
		/// <returns>
		///    A <see cref="ByteVector" /> object containing the data
		///    read from the current instance.
		/// </returns>
		/// <remarks>
		///    <para>This method reads the block of data at the current
		///    seek position. To change the seek position, use <see
		///    cref="Seek(long,System.IO.SeekOrigin)" />.</para>
		/// </remarks>
		/// <exception cref="ArgumentException">
		///    <paramref name="length" /> is less than zero.
		/// </exception>
		public ByteVector ReadBlock (int length)
		{
			if (length < 0)
				throw new ArgumentException (
					"Length must be non-negative",
					"length");
			
			if (length == 0)
				return new ByteVector ();
			
			Mode = AccessMode.Read;
			
			byte [] buffer = new byte [length];
			int count = file_stream.Read (buffer, 0, length);
			return new ByteVector (buffer, count);
		}
Exemple #37
0
		/// <summary>
		///    Removes a specified block of data from the file
		///    represented by the current instance.
		/// </summary>
		/// <param name="start">
		///    A <see cref="long" /> value specifying at which point to
		///    remove data.
		/// </param>
		/// <param name="length">
		///    A <see cref="long" /> value specifying the number of
		///    bytes to remove.
		/// </param>
		public void RemoveBlock (long start, long length)
		{
			if (length <= 0)
				return;
			
			Mode = AccessMode.Write;
			
			int buffer_length = buffer_size;
			
			long read_position = start + length;
			long write_position = start;
			
			ByteVector buffer = (byte) 1;
			
			while(buffer.Count != 0) {
				file_stream.Position = read_position;
				buffer = ReadBlock (buffer_length);
				read_position += buffer.Count;
				
				file_stream.Position = write_position;
				WriteBlock (buffer);
				write_position += buffer.Count;
			}
			
			Truncate (write_position);
		}
Exemple #38
0
 public IConnection Acquire(AccessMode mode)
 {
     Mode = mode;
     return(Connection);
 }
Exemple #39
0
        /// <summary>
        /// 执行连接ID过程
        /// 如果传过来的连接ID为空,则会创建新的连接ID,结束后会自动注释连接ID,否则不会
        /// </summary>
        /// <param name="action">动作</param>
        /// <param name="connectionId">连接ID</param>
        /// <param name="accessMode">访问模式</param>
        protected void ExecProcConnectionId(Action <string> action, string connectionId = null, AccessMode accessMode = AccessMode.MASTER)
        {
            if (string.IsNullOrWhiteSpace(connectionId))
            {
                connectionId = WorkflowPersistence.NewConnectionId(accessMode);

                try
                {
                    action(connectionId);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex);
                }
                finally
                {
                    WorkflowPersistence.Release(connectionId);
                }
            }
            else
            {
                action(connectionId);
                return;
            }
        }
Exemple #40
0
 public ISession Session(AccessMode defaultMode, string bookmark)
 {
     return(Session(defaultMode, Bookmark.From(bookmark, _logger)));
 }
 protected override IRequestMessage GetBeginMessage(string database, Bookmark bookmark, TransactionConfig config, AccessMode mode, string impersonatedUser)
 {
     ValidateImpersonatedUserForVersion(impersonatedUser);
     return(new BeginMessage(database, bookmark, config?.Timeout, config?.Metadata, mode, impersonatedUser));
 }
 public void OnAccessRightsChange(int attributeID, AccessMode access, bool connected)
 {
 }
 public ISession Session(AccessMode defaultMode, string bookmark)
 {
     return(driver.Session(defaultMode, bookmark));
 }
Exemple #44
0
        /// <summary>
        /// 执行返回函数且带有连接ID
        /// </summary>
        /// <typeparam name="OutT">输出类型</typeparam>
        /// <param name="func">函数</param>
        /// <param name="returnInfo">返回信息</param>
        /// <param name="connectionId">连接ID</param>
        /// <param name="accessMode">访问模式</param>
        /// <returns>返回信息</returns>
        protected ReturnInfo <OutT> ExecReturnFuncAndConnectionId <OutT>(Func <ReturnInfo <OutT>, string, OutT> func, ReturnInfo <OutT> returnInfo = null, string connectionId = null, AccessMode accessMode = AccessMode.MASTER)
        {
            return(ExecReturnFunc <OutT>((reInfo) =>
            {
                OutT result = default(OutT);
                ExecProcConnectionId((connId) =>
                {
                    result = func(reInfo, connId);
                }, connectionId, accessMode);

                return result;
            }, returnInfo));
        }
 public void OnAccessRightsChange(int index, AccessMode access)
 {
 }
Exemple #46
0
 internal static extern int Access(string path, AccessMode mode);
Exemple #47
0
 public ISession Session(AccessMode defaultMode, IEnumerable <string> bookmarks)
 {
     return(Session(defaultMode, Bookmark.From(bookmarks, _logger)));
 }
Exemple #48
0
 internal static Session NewSession(IConnection connection, IDriverLogger logger = null, IRetryLogic retryLogic = null, AccessMode mode = AccessMode.Write, string bookmark = null)
 {
     return(new Session(new TestConnectionProvider(connection), logger, retryLogic, mode, Bookmark.From(bookmark)));
 }
 public bool IsReadingInAbsenceOfWriter(AccessMode mode)
 {
     return(mode == AccessMode.Read && !IsStale(AccessMode.Read) && IsStale(AccessMode.Write));
 }
 public void OnAccessRightsChange(int attributeID, AccessMode access)
 {
     throw new IndexOutOfRangeException("attributeID");
 }
Exemple #51
0
 public void OnAccessRightsChange(int index, AccessMode access)
 {
     throw new IndexOutOfRangeException("index");
 }
Exemple #52
0
 public ISession Session(AccessMode defaultMode)
 {
     return(Session(defaultMode, NullBookmark));
 }
Exemple #53
0
 public Task <IConnection> AcquireAsync(AccessMode mode)
 {
     return(Task.FromResult(Connection));
 }
Exemple #54
0
 public Task <IConnection> AcquireAsync(AccessMode mode, string database, Bookmark bookmark)
 {
     return(Task.FromResult(Connection));
 }
Exemple #55
0
		/// <summary>
		///    Resized the current instance to a specified number of
		///    bytes.
		/// </summary>
		/// <param name="length">
		///    A <see cref="long" /> value specifying the number of
		///    bytes to resize the file to.
		/// </param>
		protected void Truncate (long length)
		{
			AccessMode old_mode = Mode;
			Mode = AccessMode.Write;
			file_stream.SetLength (length);
			Mode = old_mode;
		}
 public void OnAccessRightsChange(int attributeID, AccessMode access)
 {
 }
Exemple #57
0
		/// <summary>
		///    Writes a block of data to the file represented by the
		///    current instance at the current seek position.
		/// </summary>
		/// <param name="data">
		///    A <see cref="ByteVector" /> object containing data to be
		///    written to the current instance.
		/// </param>
		/// <remarks>
		///    This will overwrite any existing data at the seek
		///    position and append new data to the file if writing past
		///    the current end.
		/// </remarks>
		/// <exception cref="ArgumentNullException">
		///    <paramref name="data" /> is <see langword="null" />.
		/// </exception>
		public void WriteBlock (ByteVector data)
		{
			if (data == null)
				throw new ArgumentNullException ("data");
			
			Mode = AccessMode.Write;
			
			file_stream.Write (data.Data, 0, data.Count);
		}
Exemple #58
0
 /// <summary>
 /// 新建一个连接ID
 /// </summary>
 /// <param name="accessMode">访问模式</param>
 /// <returns>连接ID</returns>
 public string NewConnectionId(AccessMode accessMode = AccessMode.MASTER)
 {
     return(null);
 }
Exemple #59
0
		/// <summary>
		///    Searches backwards through a file for a specified
		///    pattern, starting at a specified offset.
		/// </summary>
		/// <param name="pattern">
		///    A <see cref="ByteVector" /> object containing a pattern
		///    to search for in the current instance.
		/// </param>
		/// <param name="startPosition">
		///    A <see cref="int" /> value specifying at what
		///    seek position to start searching.
		/// </param>
		/// <param name="after">
		///    A <see cref="ByteVector" /> object specifying a pattern
		///    that the searched for pattern must appear after. If this
		///    pattern is found first, -1 is returned.
		/// </param>
		/// <returns>
		///    A <see cref="long" /> value containing the index at which
		///    the value was found. If not found, -1 is returned.
		/// </returns>
		/// <remarks>
		///    Searching for <paramref name="after" /> is not yet
		///    implemented.
		/// </remarks>
		/// <exception cref="ArgumentNullException">
		///    <paramref name="pattern" /> is <see langword="null" />.
		/// </exception>
		long RFind (ByteVector pattern, long startPosition,
		            ByteVector after)
		{
			if (pattern == null)
				throw new ArgumentNullException ("pattern");
			
			Mode = AccessMode.Read;
			
			if (pattern.Count > buffer_size)
				return -1;
			
			// The position in the file that the current buffer
			// starts at.
			
			ByteVector buffer;
			
			// These variables are used to keep track of a partial
			// match that happens at the end of a buffer.

			/*
			int previous_partial_match = -1;
			int after_previous_partial_match = -1;
			*/
			
			// Save the location of the current read pointer.  We
			// will restore the position using Seek() before all 
			// returns.
			
			long original_position = file_stream.Position;
			
			// Start the search at the offset.
			
			long buffer_offset = Length - startPosition;
			int read_size = buffer_size;
			
			read_size = (int) Math.Min (buffer_offset, buffer_size);
			buffer_offset -= read_size;
			file_stream.Position = buffer_offset;
			
			// See the notes in find() for an explanation of this
			// algorithm.
			
			for (buffer = ReadBlock (read_size); buffer.Count > 0;
				buffer = ReadBlock (read_size)) {
				
				// TODO: (1) previous partial match
				
				// (2) pattern contained in current buffer
				
				long location = buffer.RFind (pattern);
				if (location >= 0) {
					file_stream.Position = original_position;
					return buffer_offset + location;
				}
				
				if(after != null && buffer.RFind (after) >= 0) {
					file_stream.Position = original_position;
					return -1;
				}
				
				// TODO: (3) partial match

				
				read_size = (int) Math.Min (buffer_offset, buffer_size);
				buffer_offset -= read_size;
			
				file_stream.Position = buffer_offset;
			}
			
			// Since we hit the end of the file, reset the status
			// before continuing.
			
			file_stream.Position = original_position;
			return -1;
		}
Exemple #60
0
        private ImageSegment MakeSeg(string segname, uint uAddr, byte[] bytes, AccessMode mode)
        {
            var mem = new ByteMemoryArea(Address.Ptr32(uAddr), bytes);

            return(new ImageSegment(segname, mem, mode));
        }