/// <summary> /// Converts a <c>DateTime</c> value to a COM <c>FILETIME</c> structure. /// </summary> /// <param name="value">The <c>DateTime</c> value to convert.</param> /// <returns>Returns a <c>System.Runtime.InteropServices.ComTypes.FILETIME</c> structure.</returns> public static System.Runtime.InteropServices.ComTypes.FILETIME ToFileTimeCom(this DateTime value) { var filetime = value.ToFileTime(); var ft = new System.Runtime.InteropServices.ComTypes.FILETIME { dwLowDateTime = (int) (filetime & 0xFFFFFFFF), dwHighDateTime = (int) (filetime >> 32) }; return ft; }
public void OnDataChange(int dwTransid, int hGroup, HRESULT hrMasterquality, HRESULT hrMastererror, int dwCount, int[] phClientItems, object[] pvValues, short[] pwQualities, FILETIME[] pftTimeStamps, HRESULT[] pErrors) { var f = DataChange; if (f != null) { f(dwTransid, hGroup, hrMasterquality, hrMastererror, dwCount, phClientItems, pvValues, pwQualities, pftTimeStamps, pErrors); } }
/// <summary> /// Deletes the raw data for an item. /// </summary> private int[] DeleteAtTime(HdaItem item, DateTimeCollection timestamps) { string methodName = "IOPCHDA_SyncUpdate.DeleteAtTime"; int count = timestamps.Count; int[] serverHandles = new int[count]; System.Runtime.InteropServices.ComTypes.FILETIME[] pTimestamps = new System.Runtime.InteropServices.ComTypes.FILETIME[count]; for (int ii = 0; ii < count; ii++) { serverHandles[ii] = item.ServerHandle; pTimestamps[ii] = ComUtils.GetFILETIME(timestamps[ii]); } IntPtr ppErrors; try { IOPCHDA_SyncUpdate server = BeginComCall<IOPCHDA_SyncUpdate>(methodName, true); server.DeleteAtTime( count, serverHandles, pTimestamps, out ppErrors); } catch (Exception e) { ComCallError(methodName, e); int[] errors = new int[count]; for (int ii = 0; ii < count; ii++) { errors[ii] = ResultIds.E_FAIL; } return errors; } finally { EndComCall(methodName); } return ComUtils.GetInt32s(ref ppErrors, count, true); }
private static extern bool GetSystemTimes( out FILETIME lpIdleTime, out FILETIME lpKernelTime, out FILETIME lpUserTime);
/// <summary> /// Unmarshals an array of FILETIMEs /// </summary> public static System.Runtime.InteropServices.ComTypes.FILETIME[] GetFILETIMEs(ref IntPtr pArray, int size) { if (pArray == IntPtr.Zero || size <= 0) { return null; } System.Runtime.InteropServices.ComTypes.FILETIME[] values = new System.Runtime.InteropServices.ComTypes.FILETIME[size]; IntPtr pos = pArray; for (int ii = 0; ii < size; ii++) { try { values[ii] = (System.Runtime.InteropServices.ComTypes.FILETIME)Marshal.PtrToStructure(pos, typeof(System.Runtime.InteropServices.ComTypes.FILETIME)); } catch (Exception) { } pos = (IntPtr)(pos.ToInt64() + 8); } Marshal.FreeCoTaskMem(pArray); pArray = IntPtr.Zero; return values; }
private UInt64 SubtractTimes(System.Runtime.InteropServices.ComTypes.FILETIME a, System.Runtime.InteropServices.ComTypes.FILETIME b) { UInt64 aInt = ((UInt64)(a.dwHighDateTime << 32)) | (UInt64)a.dwLowDateTime; UInt64 bInt = ((UInt64)(b.dwHighDateTime << 32)) | (UInt64)b.dwLowDateTime; return(aInt - bInt); }
/// <summary> /// Builds and validates a certificate chain, similar to <see cref="X509Chain.Build" />. /// </summary> /// <param name="certificate">The certificate to validate.</param> /// <param name="chainPolicy">The chain policy to apply.</param> /// <param name="chain">The resulting chain, whose <see cref="X509Chain.ChainStatus"/> and <see cref="X509Chain.ChainElements"/> properties are populated.</param> /// <returns>Whether the certificate is valid accoring to the given <paramref name="chainPolicy"/></returns> /// <exception cref="System.Security.Cryptography.CryptographicException"> /// When any of the underlying Windows CryptoAPI calls fail. /// </exception> public unsafe bool BuildChain(X509Certificate2 certificate, X509ChainPolicy chainPolicy, out X509Chain chain) { SafeX509ChainHandle ppChainContext = SafeX509ChainHandle.InvalidHandle; SafeCertStoreHandle hCertStore = SafeCertStoreHandle.InvalidHandle; if (chainPolicy.ExtraStore != null && chainPolicy.ExtraStore.Count > 0) { hCertStore = ExportToMemoryStore(chainPolicy.ExtraStore); } NativeMethods.CERT_CHAIN_PARA chainPara = new NativeMethods.CERT_CHAIN_PARA(); // Initialize the structure size. chainPara.cbSize = (uint)Marshal.SizeOf(chainPara); SafeLocalAllocHandle applicationPolicyHandle = SafeLocalAllocHandle.InvalidHandle; SafeLocalAllocHandle certificatePolicyHandle = SafeLocalAllocHandle.InvalidHandle; try { // Application policy if (chainPolicy.ApplicationPolicy != null && chainPolicy.ApplicationPolicy.Count > 0) { chainPara.RequestedUsage.dwType = NativeMethods.USAGE_MATCH_TYPE_AND; chainPara.RequestedUsage.Usage.cUsageIdentifier = (uint)chainPolicy.ApplicationPolicy.Count; applicationPolicyHandle = CopyOidsToUnmanagedMemory(chainPolicy.ApplicationPolicy); chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = applicationPolicyHandle.DangerousGetHandle(); } // Certificate policy if (chainPolicy.CertificatePolicy != null && chainPolicy.CertificatePolicy.Count > 0) { chainPara.RequestedIssuancePolicy.dwType = NativeMethods.USAGE_MATCH_TYPE_AND; chainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint)chainPolicy.CertificatePolicy.Count; certificatePolicyHandle = CopyOidsToUnmanagedMemory(chainPolicy.CertificatePolicy); chainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = certificatePolicyHandle.DangerousGetHandle(); } chainPara.dwUrlRetrievalTimeout = (uint)Math.Floor(chainPolicy.UrlRetrievalTimeout.TotalMilliseconds); FILETIME ft = new FILETIME(); *(long *)&ft = chainPolicy.VerificationTime.ToFileTime(); uint flags = MapRevocationFlags(chainPolicy.RevocationMode, chainPolicy.RevocationFlag); using (SafeCertContextHandle certContextHandle = NativeMethods.CertDuplicateCertificateContext(certificate.Handle)) { // Build the chain. if (!NativeMethods.CertGetCertificateChain(hChainEngine: this.safeChainEngineHandle, pCertContext: certContextHandle, pTime: ref ft, hAdditionalStore: hCertStore, pChainPara: ref chainPara, dwFlags: flags, pvReserved: IntPtr.Zero, ppChainContext: ref ppChainContext)) { throw new CryptographicException(Marshal.GetHRForLastWin32Error()); } chain = new X509Chain(ppChainContext.DangerousGetHandle()) { ChainPolicy = chainPolicy }; // Verify the chain using the specified policy. NativeMethods.CERT_CHAIN_POLICY_PARA policyPara = new NativeMethods.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(NativeMethods.CERT_CHAIN_POLICY_PARA))); NativeMethods.CERT_CHAIN_POLICY_STATUS policyStatus = new NativeMethods.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(NativeMethods.CERT_CHAIN_POLICY_STATUS))); policyPara.dwFlags = (uint)chainPolicy.VerificationFlags; if (!NativeMethods.CertVerifyCertificateChainPolicy( pszPolicyOID: new IntPtr(NativeMethods.CERT_CHAIN_POLICY_BASE), pChainContext: ppChainContext, pPolicyPara: ref policyPara, pPolicyStatus: ref policyStatus)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } NativeMethods.SetLastError(policyStatus.dwError); return(policyStatus.dwError == 0); } } finally { applicationPolicyHandle.Dispose(); certificatePolicyHandle.Dispose(); } }
public bool CheckInputFileTimes(System.Runtime.InteropServices.ComTypes.FILETIME output) { throw new NotImplementedException(); }
public static extern HRESULT InitPropVariantFromFileTime([In] ref FILETIME pftIn, [In, Out] Ole32.PROPVARIANT ppropvar);
public static extern HRESULT PropVariantToFileTime([In] Ole32.PROPVARIANT propVar, PSTIME_FLAGS pstfOut, out FILETIME pftOut);
///////////////////////////////////////////////////// // // // EnumerateUSBDevices() // // // ///////////////////////////////////////////////////// //Description: Uses .NET registry objects to dig in // the infamous USBSTOR key for past and // present USB devices. //Returns: true if successful // NOTE: // techniques used in this function are from // "Windows Forensic Analysis" by Harlan Carvey // ///////////////////////////////////////////////////// public static bool EnumerateUSBDevices(ref StringBuilder usbdata) { RegistryKey USBSTOR; string current = ""; //loop through 10 currentcontrolsets //sample structure: // HKLM\System\CurrentControlSet003\Enum\USBSTOR\ // \Disk&Ven_ChipsBnk&Prod_Flash_Disk&Rev_2.00 --> USB DRIVE // \3852u395823 --> Instance ID // \ag3490t24t940 // \Disk&Ven_SanDisk&Prod_Cruzer_Slide&Rev_4.05 --> USB DRIVE // .... // for (int i = 0; i < 10; i++) { current = "00" + i.ToString(); //001,002,003,etc USBSTOR = Registry.LocalMachine.OpenSubKey("System\\ControlSet" + current + "\\Enum\\USBSTOR"); //if the key doesnt exist, we must continue b/c control set numbering isn't contiguous if (USBSTOR == null) { continue; } string[] DeviceClassIds = USBSTOR.GetSubKeyNames(); //loop through all usb device class IDs beneath USBSTOR... //get a list of subkeys which are named by instance IDs foreach (string deviceName in DeviceClassIds) { //lots of info you can get from device name: //Disk&Ven_###&Prod_###&Rev_### -- we want the ### string[] driveInfo = deviceName.Split(new char[] { '&' }); string vendor = driveInfo[1].Replace("Ven_", "").Replace("_", " "); string product = driveInfo[2].Replace("Prod_", "").Replace("_", " "); string revision = driveInfo[3].Replace("Rev_", "").Replace("_", " "); string serial = ""; ArrayList insertionDates = new ArrayList(); //get list of instances string[] instances = USBSTOR.OpenSubKey(deviceName).GetSubKeyNames(); int count = 0; //each unique instance represents a time the device was plugged in //so collect information on each instance foreach (string instanceId in instances) { //if the second character in the instanceId is '&', then we //know the id is made up by windows and manuf did not give one if (instanceId[1] == '&') { serial = "None"; } else { serial = instanceId; } string friendlyName = "[none]"; object friendlyNameValueObj = USBSTOR.OpenSubKey(deviceName + "\\" + instanceId).GetValue("FriendlyName"); if (friendlyNameValueObj != null) { friendlyName = (string)friendlyNameValueObj.ToString(); } //see ntddstor.h - these are GUIDs for disk and volume device interfaces.. string key1 = "SYSTEM\\CurrentControlSet\\Control\\DeviceClasses\\{53f56307-b6bf-11d0-94f2-00a0c91efb8b}"; string key2 = "SYSTEM\\CurrentControlSet\\Control\\DeviceClasses\\{53f5630d-b6bf-11d0-94f2-00a0c91efb8b}"; RegistryKey diskGuid = Registry.LocalMachine.OpenSubKey(key1); RegistryKey volDevGuid = Registry.LocalMachine.OpenSubKey(key2); string[] DeviceClasses1 = diskGuid.GetSubKeyNames(); string[] DeviceClasses2 = volDevGuid.GetSubKeyNames(); //merge two sets of device classes into one string[] allDeviceClasses = new string[DeviceClasses1.Length + DeviceClasses2.Length]; DeviceClasses1.CopyTo(allDeviceClasses, 0); DeviceClasses2.CopyTo(allDeviceClasses, DeviceClasses1.Length); IntPtr lastInsertionDatePtr = (IntPtr)0; IntPtr keyHandle = (IntPtr)0; IntPtr hKey = (IntPtr)0; System.Runtime.InteropServices.ComTypes.FILETIME lastInsertionDate = new System.Runtime.InteropServices.ComTypes.FILETIME(); //get last write date/time foreach (string devclass in allDeviceClasses) { if (devclass.Contains(instanceId)) { //open the registry key using unmanaged API call if (Win32Helper.RegOpenKeyExW(hKey, key1 + "\\" + devclass, 0, 0x00020019, ref keyHandle) == 0 && keyHandle != (IntPtr)(-1)) { //pass 0 to all the vars we dont care about- we only want last write time Win32Helper.RegQueryInfoKeyW(keyHandle, null, (IntPtr)0, (IntPtr)0, (IntPtr)0, (IntPtr)0, (IntPtr)0, (IntPtr)0, (IntPtr)0, (IntPtr)0, (IntPtr)0, lastInsertionDatePtr); Marshal.PtrToStructure(lastInsertionDatePtr, lastInsertionDate); insertionDates.Add(lastInsertionDate.ToString()); } } } //print out summary info on first iteration of instances of this usb drive if (count == 0) { usbdata.AppendLine(" Found USB Device '" + friendlyName + "'"); usbdata.AppendLine(" Serial Num : " + serial); usbdata.AppendLine(" Vendor : " + vendor); usbdata.AppendLine(" Product : " + product); usbdata.AppendLine(" Revision : " + revision); usbdata.AppendLine(" Instances : " + instances.Length); } usbdata.AppendLine(" Date: " + lastInsertionDate.dwHighDateTime.ToString() + "/" + lastInsertionDate.dwLowDateTime.ToString()); count++; } //add how many other insertion dates there were string[] dts = (string[])insertionDates.ToArray(typeof(string)); usbdata.AppendLine(" InsertionDates : " + string.Join(",", dts)); } } return(true); }
internal void From(NativeMethods.WIN32_FIND_DATA findData) { fileAttributes = findData.dwFileAttributes; ftCreationTime = findData.ftCreationTime; ftLastAccessTime = findData.ftLastAccessTime; ftLastWriteTime = findData.ftLastWriteTime; fileSizeHigh = findData.nFileSizeHigh; fileSizeLow = findData.nFileSizeLow; }
internal static extern bool GetFileTime( SafeFileHandle hFile, out FILETIME lpCreationTime, out FILETIME lpLastAccessTime, out FILETIME lpLastWriteTime );
/// <summary> /// Unmarshals a WIN32 FILETIME. /// </summary> public static DateTime GetDateTime(System.Runtime.InteropServices.ComTypes.FILETIME input) { System.Runtime.InteropServices.ComTypes.FILETIME output = new System.Runtime.InteropServices.ComTypes.FILETIME(); output.dwLowDateTime = input.dwLowDateTime; output.dwHighDateTime = input.dwHighDateTime; return ComUtils.GetDateTime(output); }
public static void GetFileTime(SafeFileHandle file, out DateTime creationTime, out DateTime accessedTime, out DateTime modifiedTime) { System.Runtime.InteropServices.ComTypes.FILETIME accessedTimeNative = new System.Runtime.InteropServices.ComTypes.FILETIME(); System.Runtime.InteropServices.ComTypes.FILETIME modifiedTimeNative = new System.Runtime.InteropServices.ComTypes.FILETIME(); System.Runtime.InteropServices.ComTypes.FILETIME createdTimeNative = new System.Runtime.InteropServices.ComTypes.FILETIME(); if (!NativeMethods.GetFileTime(file, out createdTimeNative, out accessedTimeNative, out modifiedTimeNative)) { throw Win32ErrorCode.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } creationTime = FileTimeToDateTime(createdTimeNative); accessedTime = FileTimeToDateTime(accessedTimeNative); modifiedTime = FileTimeToDateTime(modifiedTimeNative); }
private ulong FileTimeToULong(FILETIME time) { return(((ulong)time.dwHighDateTime << 32) + (uint)time.dwLowDateTime); }
private static extern void GetSystemTimeAsFileTime([Out] out FILETIME time);
private static extern bool GetProcessTimes(IntPtr hProcess, out FILETIME creation, out FILETIME exit, out FILETIME kernel, out FILETIME user);
internal static extern bool GetProcessTimes( IntPtr hProcess, out FILETIME lpCreationTime, out FILETIME lpExitTime, out FILETIME lpKernelTime, out FILETIME lpUserTime);
public static extern int MsiSummaryInfoGetProperty(uint summaryInfo, int property, out uint dataType, out int integerValue, ref FILETIME fileTimeValue, StringBuilder stringValueBuf, ref int stringValueBufSize);
internal static extern void PropVariantGetFileTimeElem([In] PropVariant propVar, [In] uint iElem, [Out, MarshalAs(UnmanagedType.Struct)] out System.Runtime.InteropServices.ComTypes.FILETIME pftVal);
private void GetSummaryInformationValue(int index, out uint dataType, out int intValue, out StringBuilder stringValue, out FILETIME timeValue) { var bufSize = 64; stringValue = new StringBuilder(bufSize); timeValue.dwHighDateTime = 0; timeValue.dwLowDateTime = 0; var error = MsiInterop.MsiSummaryInfoGetProperty(this.Handle, index, out dataType, out intValue, ref timeValue, stringValue, ref bufSize); if (234 == error) { stringValue.EnsureCapacity(++bufSize); error = MsiInterop.MsiSummaryInfoGetProperty(this.Handle, index, out dataType, out intValue, ref timeValue, stringValue, ref bufSize); } if (0 != error) { throw new MsiException(error); } }
/// <summary> /// Calls QueryInfoKey and updates _metadata. /// </summary> private void RefreshMetadata() { uint sizeClass = 0; uint countSubKeys = 0, maxSubKeyLen = 0, maxClassLen = 0; uint countValues = 0, maxValueNameLen = 0, maxValueLen = 0; uint securityDescriptorSize = 0; FILETIME lastWrite = new FILETIME(); // Get size of class StringBuilder sbClass = new StringBuilder((int)sizeClass); Win32Result result = OffregNative.QueryInfoKey(_intPtr, sbClass, ref sizeClass, ref countSubKeys, ref maxSubKeyLen, ref maxClassLen, ref countValues, ref maxValueNameLen, ref maxValueLen, ref securityDescriptorSize, ref lastWrite); if (result == Win32Result.ERROR_MORE_DATA) { // The returned size does is in characters (unicode), excluding NULL chars. Increment it to have space sizeClass = sizeClass + 1; // Allocate sbClass = new StringBuilder((int)sizeClass); result = OffregNative.QueryInfoKey(_intPtr, sbClass, ref sizeClass, ref countSubKeys, ref maxSubKeyLen, ref maxClassLen, ref countValues, ref maxValueNameLen, ref maxValueLen, ref securityDescriptorSize, ref lastWrite); if (result != Win32Result.ERROR_SUCCESS) throw new Win32Exception((int)result); } else if (result != Win32Result.ERROR_SUCCESS) throw new Win32Exception((int)result); _metadata.Class = sbClass.ToString(); _metadata.LastWriteTime = lastWrite; _metadata.SubKeysCount = countSubKeys; _metadata.MaxSubKeyLen = maxSubKeyLen; _metadata.MaxClassLen = maxClassLen; _metadata.ValuesCount = countValues; _metadata.MaxValueNameLen = maxValueNameLen; _metadata.MaxValueLen = maxValueLen; // Bytes _metadata.SizeSecurityDescriptor = securityDescriptorSize; }
private static extern int GetThreadTimes( IntPtr hThread, ref FILETIME lpCreationTime, ref FILETIME lpExitTime, ref FILETIME lpKernelTime, ref FILETIME lpUserTime );
private static UInt64 SubtractTimes(FILETIME a, FILETIME b) { ulong aInt = ((UInt64)(a.dwHighDateTime << 32)) | (UInt64)a.dwLowDateTime; ulong bInt = ((UInt64)(b.dwHighDateTime << 32)) | (UInt64)b.dwLowDateTime; return aInt - bInt; }
/// <summary> /// Determines how much actual kernel and user time this thread has actually gotten /// </summary> /// <param name="kernel"></param> /// <param name="user"></param> /// <returns></returns> private bool getAnimalThreadTime(out Int64 kernel, out Int64 user) { if (_threadHandleValid) { var c = new FILETIME(); var e = new FILETIME(); var kernelFileTime = new FILETIME(); var userFileTime = new FILETIME(); var success = (GetThreadTimes(_threadHandle, ref c, ref e, ref kernelFileTime, ref userFileTime) > 0); if (success) { kernel = (((Int64) kernelFileTime.dwHighDateTime) << 32) + kernelFileTime.dwLowDateTime; user = (((Int64) userFileTime.dwHighDateTime) << 32) + userFileTime.dwLowDateTime; return true; } kernel = 0; user = 0; return false; } kernel = 0; user = 0; return false; }
/// <summary> /// Update data /// </summary> private StatusCode UpdateData( HdaItem item, PerformUpdateType updateType, DataValueCollection values, out int[] errors) { errors = null; string methodName = "IOPCHDA_SyncUpdate.Insert"; int dwNumItems = values.Count; int[] phServer = new int[dwNumItems]; System.Runtime.InteropServices.ComTypes.FILETIME[] ftTimeStamps = new System.Runtime.InteropServices.ComTypes.FILETIME[dwNumItems]; object[] vDataValues = new object[dwNumItems]; int[] pdwQualities = new int[dwNumItems]; for (int ii = 0; ii < dwNumItems; ii++) { DataValue value = values[ii]; phServer[ii] = item.ServerHandle; vDataValues[ii] = ComUtils.GetVARIANT(value.WrappedValue); pdwQualities[ii] = Utils.ToInt32(ComUtils.GetHdaQualityCode(value.StatusCode)); ftTimeStamps[ii] = ComUtils.GetFILETIME(value.SourceTimestamp); } IntPtr ppErrors = IntPtr.Zero; try { IOPCHDA_SyncUpdate server = BeginComCall<IOPCHDA_SyncUpdate>(methodName, true); switch (updateType) { case PerformUpdateType.Insert: { server.Insert( dwNumItems, phServer, ftTimeStamps, vDataValues, pdwQualities, out ppErrors); break; } case PerformUpdateType.Update: { server.InsertReplace( dwNumItems, phServer, ftTimeStamps, vDataValues, pdwQualities, out ppErrors); break; } case PerformUpdateType.Replace: { server.Replace( dwNumItems, phServer, ftTimeStamps, vDataValues, pdwQualities, out ppErrors); break; } } // check for error. errors = ComUtils.GetInt32s(ref ppErrors, dwNumItems, true); } catch (Exception e) { ComCallError(methodName, e); return StatusCodes.BadUnexpectedError; } finally { EndComCall(methodName); } return StatusCodes.Good; }
//// public NtStatus SetFileTimeProxy(string rawFileName, ref FILETIME rawCreationTime, ref FILETIME rawLastAccessTime, ref FILETIME rawLastWriteTime, DokanFileInfo rawFileInfo) { var ctime = (rawCreationTime.dwLowDateTime != 0 || rawCreationTime.dwHighDateTime != 0) && (rawCreationTime.dwLowDateTime != -1 || rawCreationTime.dwHighDateTime != -1) ? DateTime.FromFileTime(((long)rawCreationTime.dwHighDateTime << 32) | (uint)rawCreationTime.dwLowDateTime) : (DateTime?)null; var atime = (rawLastAccessTime.dwLowDateTime != 0 || rawLastAccessTime.dwHighDateTime != 0) && (rawLastAccessTime.dwLowDateTime != -1 || rawLastAccessTime.dwHighDateTime != -1) ? DateTime.FromFileTime(((long)rawLastAccessTime.dwHighDateTime << 32) | (uint)rawLastAccessTime.dwLowDateTime) : (DateTime?)null; var mtime = (rawLastWriteTime.dwLowDateTime != 0 || rawLastWriteTime.dwHighDateTime != 0) && (rawLastWriteTime.dwLowDateTime != -1 || rawLastWriteTime.dwHighDateTime != -1) ? DateTime.FromFileTime(((long)rawLastWriteTime.dwHighDateTime << 32) | (uint)rawLastWriteTime.dwLowDateTime) : (DateTime?)null; try { Trace("\nSetFileTimeProxy : " + rawFileName); Trace("\tCreateTime\t" + ctime); Trace("\tAccessTime\t" + atime); Trace("\tWriteTime\t" + mtime); Trace("\tContext\t" + ToTrace(rawFileInfo)); NtStatus result = operations.SetFileTime(rawFileName, ctime, atime, mtime, rawFileInfo); Trace("SetFileTimeProxy : " + rawFileName + " Return : " + result); return result; } #pragma warning disable 0168 catch (Exception ex) #pragma warning restore 0168 { Trace("SetFileTimeProxy : " + rawFileName + " Throw : " + ex.Message); return DokanResult.InvalidParameter; } }
//// public int SetFileTimeProxy(string rawFileName, ref FILETIME rawCreationTime, ref FILETIME rawLastAccessTime, ref FILETIME rawLastWriteTime, DokanFileInfo rawFileInfo) { var ctime = (rawCreationTime.dwLowDateTime != 0 || rawCreationTime.dwHighDateTime != 0) && (rawCreationTime.dwLowDateTime != -1 || rawCreationTime.dwHighDateTime != -1) ? DateTime.FromFileTime(((long)rawCreationTime.dwHighDateTime << 32) | (uint)rawCreationTime.dwLowDateTime) : (DateTime?)null; var atime = (rawLastAccessTime.dwLowDateTime != 0 || rawLastAccessTime.dwHighDateTime != 0) && (rawLastAccessTime.dwLowDateTime != -1 || rawLastAccessTime.dwHighDateTime != -1) ? DateTime.FromFileTime(((long)rawLastAccessTime.dwHighDateTime << 32) | (uint)rawLastAccessTime.dwLowDateTime) : (DateTime?)null; var mtime = (rawLastWriteTime.dwLowDateTime != 0 || rawLastWriteTime.dwHighDateTime != 0) && (rawLastWriteTime.dwLowDateTime != -1 || rawLastWriteTime.dwHighDateTime != -1) ? DateTime.FromFileTime(((long)rawLastWriteTime.dwHighDateTime << 32) | (uint)rawLastWriteTime.dwLowDateTime) : (DateTime?)null; try { return (int)_operations.SetFileTime(rawFileName, ctime, atime, mtime, rawFileInfo); } catch { #if DEBUG throw; #else return ERROR_INVALID_FUNCTION; #endif } }
public static extern bool SystemTimeToFileTime( ref SystemTime lpSystemTime, out System.Runtime.InteropServices.ComTypes.FILETIME lpFileTime);
public static extern int FileTimeToSystemTime( ref System.Runtime.InteropServices.ComTypes.FILETIME fileTime, ref SYSTEMTIME systemTime);
internal void Init(object value) { if (value == null) { varType = (ushort)VarEnum.VT_EMPTY; } else if (value is Array) { Type type = value.GetType(); if (type == typeof(sbyte[])) { InitVector(value as Array, typeof(sbyte), VarEnum.VT_I1); } else if (type == typeof(byte[])) { InitVector(value as Array, typeof(byte), VarEnum.VT_UI1); } else if (value is char[]) { varType = (ushort)VarEnum.VT_LPSTR; pszVal = Marshal.StringToCoTaskMemAnsi(new String(value as char[])); } else if (value is char[][]) { char[][] charArray = value as char[][]; String[] strArray = new String[charArray.GetLength(0)]; for (int i = 0; i < charArray.Length; i++) { strArray[i] = new String(charArray[i] as char[]); } Init(strArray, true); } else if (type == typeof(short[])) { InitVector(value as Array, typeof(short), VarEnum.VT_I2); } else if (type == typeof(ushort[])) { InitVector(value as Array, typeof(ushort), VarEnum.VT_UI2); } else if (type == typeof(int[])) { InitVector(value as Array, typeof(int), VarEnum.VT_I4); } else if (type == typeof(uint[])) { InitVector(value as Array, typeof(uint), VarEnum.VT_UI4); } else if (type == typeof(Int64[])) { InitVector(value as Array, typeof(Int64), VarEnum.VT_I8); } else if (type == typeof(UInt64[])) { InitVector(value as Array, typeof(UInt64), VarEnum.VT_UI8); } else if (value is float[]) { InitVector(value as Array, typeof(float), VarEnum.VT_R4); } else if (value is double[]) { InitVector(value as Array, typeof(double), VarEnum.VT_R8); } else if (value is Guid[]) { InitVector(value as Array, typeof(Guid), VarEnum.VT_CLSID); } else if (value is String[]) { Init(value as String[], false); } else if (value is bool[]) { bool[] boolArray = value as bool[]; short[] array = new short[boolArray.Length]; for (int i = 0; i < boolArray.Length; i++) { array[i] = (short)(boolArray[i] ? -1 : 0); } InitVector(array, typeof(short), VarEnum.VT_BOOL); } else { throw new System.InvalidOperationException(SR.Get(SRID.Image_PropertyNotSupported)); } } else { Type type = value.GetType(); if (value is String) { varType = (ushort)VarEnum.VT_LPWSTR; pwszVal = Marshal.StringToCoTaskMemUni(value as String); } else if (type == typeof(sbyte)) { varType = (ushort)VarEnum.VT_I1; cVal = (sbyte)value; } else if (type == typeof(byte)) { varType = (ushort)VarEnum.VT_UI1; bVal = (byte)value; } else if (type == typeof(System.Runtime.InteropServices.ComTypes.FILETIME)) { varType = (ushort)VarEnum.VT_FILETIME; filetime = (System.Runtime.InteropServices.ComTypes.FILETIME)value; } else if (value is char) { varType = (ushort)VarEnum.VT_LPSTR; pszVal = Marshal.StringToCoTaskMemAnsi(new String(new char[] { (char)value })); } else if (type == typeof(short)) { varType = (ushort)VarEnum.VT_I2; iVal = (short)value; } else if (type == typeof(ushort)) { varType = (ushort)VarEnum.VT_UI2; uiVal = (ushort)value; } else if (type == typeof(int)) { varType = (ushort)VarEnum.VT_I4; intVal = (int)value; } else if (type == typeof(uint)) { varType = (ushort)VarEnum.VT_UI4; uintVal = (uint)value; } else if (type == typeof(Int64)) { varType = (ushort)VarEnum.VT_I8; lVal = (Int64)value; } else if (type == typeof(UInt64)) { varType = (ushort)VarEnum.VT_UI8; ulVal = (UInt64)value; } else if (value is float) { varType = (ushort)VarEnum.VT_R4; fltVal = (float)value; } else if (value is double) { varType = (ushort)VarEnum.VT_R8; dblVal = (double)value; } else if (value is Guid) { byte[] guid = ((Guid)value).ToByteArray(); varType = (ushort)VarEnum.VT_CLSID; pclsidVal = Marshal.AllocCoTaskMem(guid.Length); Marshal.Copy(guid, 0, pclsidVal, guid.Length); } else if (value is bool) { varType = (ushort)VarEnum.VT_BOOL; boolVal = (short)(((bool)value) ? -1 : 0); } else if (value is BitmapMetadataBlob) { Init((value as BitmapMetadataBlob).InternalGetBlobValue(), typeof(byte), VarEnum.VT_BLOB); } else if (value is BitmapMetadata) { IntPtr punkTemp = IntPtr.Zero; BitmapMetadata metadata = value as BitmapMetadata; SafeMILHandle metadataHandle = metadata.InternalMetadataHandle; if (metadataHandle == null || metadataHandle.IsInvalid) { throw new NotImplementedException(); } Guid wicMetadataQueryReader = MILGuidData.IID_IWICMetadataQueryReader; HRESULT.Check(UnsafeNativeMethods.MILUnknown.QueryInterface( metadataHandle, ref wicMetadataQueryReader, out punkTemp)); varType = (ushort)VarEnum.VT_UNKNOWN; punkVal = punkTemp; } else { throw new System.InvalidOperationException(SR.Get(SRID.Image_PropertyNotSupported)); } } }
public uint Def_SetFileTime(string filename, System.Runtime.InteropServices.ComTypes.FILETIME ctime, System.Runtime.InteropServices.ComTypes.FILETIME atime, System.Runtime.InteropServices.ComTypes.FILETIME mtime, IntPtr info) { return(0); }
static extern bool GetThreadTimesNative(SafeThreadHandle hProcess, out System.Runtime.InteropServices.ComTypes.FILETIME lpCreationTime, out System.Runtime.InteropServices.ComTypes.FILETIME lpExitTime, out System.Runtime.InteropServices.ComTypes.FILETIME lpKernelTime, out System.Runtime.InteropServices.ComTypes.FILETIME lpUserTime );
private static DateTime ConvertDateTime(System.Runtime.InteropServices.ComTypes.FILETIME dateTime) { var fileTime = CombineHighLowInts((uint)dateTime.dwHighDateTime, (uint)dateTime.dwLowDateTime); return(DateTime.FromFileTimeUtc(fileTime)); }
static UInt64 GetTimeInTicks(FileTime a) { return(((UInt64)(a.dwHighDateTime << 32)) | (UInt64)a.dwLowDateTime); }
internal static extern bool GetSystemTimes( out FILETIME lpIdleTime, out FILETIME lpKernelTime, out FILETIME lpUserTime);
private UInt64 GetTickDelta(FileTime a, FileTime b) { return(GetTimeInTicks(a) - GetTimeInTicks(b)); }
private static long FileTimeToDateTime(ref System.Runtime.InteropServices.ComTypes.FILETIME val) { return((((long)val.dwHighDateTime) << 32) + val.dwLowDateTime); }
private static TimeSpan GetTimeSpanFromFileTime(System.Runtime.InteropServices.ComTypes.FILETIME time) { return(TimeSpan.FromMilliseconds((((ulong)time.dwHighDateTime << 32) + (uint)time.dwLowDateTime) * 0.000001)); }
internal static extern void InitPropVariantFromFileTime([In] ref System.Runtime.InteropServices.ComTypes.FILETIME pftIn, [Out] PropVariant ppropvar);
public static extern bool FileTimeToSystemTime(ref FILETIME lpFileTime, ref SYSTEMTIME lpSystemTime);
static extern bool GetSystemTimes( out System.Runtime.InteropServices.ComTypes.FILETIME lpIdleTime, out System.Runtime.InteropServices.ComTypes.FILETIME lpKernelTime, out System.Runtime.InteropServices.ComTypes.FILETIME lpUserTime );
//// internal NtStatus SetFileTimeProxy(string rawFileName, ref FILETIME rawCreationTime, ref FILETIME rawLastAccessTime, ref FILETIME rawLastWriteTime, DokanFileInfo rawFileInfo) { var ctime = (rawCreationTime.dwLowDateTime != 0 || rawCreationTime.dwHighDateTime != 0) && (rawCreationTime.dwLowDateTime != -1 || rawCreationTime.dwHighDateTime != -1) ? DateTime.FromFileTime(((long)rawCreationTime.dwHighDateTime << 32) | (uint)rawCreationTime.dwLowDateTime) : (DateTime?)null; var atime = (rawLastAccessTime.dwLowDateTime != 0 || rawLastAccessTime.dwHighDateTime != 0) && (rawLastAccessTime.dwLowDateTime != -1 || rawLastAccessTime.dwHighDateTime != -1) ? DateTime.FromFileTime(((long)rawLastAccessTime.dwHighDateTime << 32) | (uint)rawLastAccessTime.dwLowDateTime) : (DateTime?)null; var mtime = (rawLastWriteTime.dwLowDateTime != 0 || rawLastWriteTime.dwHighDateTime != 0) && (rawLastWriteTime.dwLowDateTime != -1 || rawLastWriteTime.dwHighDateTime != -1) ? DateTime.FromFileTime(((long)rawLastWriteTime.dwHighDateTime << 32) | (uint)rawLastWriteTime.dwLowDateTime) : (DateTime?)null; try { NtStatus result = _operations.SetFileTime(rawFileName, ctime, atime, mtime, rawFileInfo); return(result); } catch (Exception ex) { ServiceRegistration.Get <ILogger>().Warn("Dokan exception: ", ex); return(DokanResult.InvalidParameter); } }
/// <summary> /// Enumerates all subkeys, retrieving both their name and class at the same time. /// </summary> /// <returns>Names and classes of all the subkeys.</returns> public SubKeyContainer[] EnumerateSubKeys() { SubKeyContainer[] results = new SubKeyContainer[_metadata.SubKeysCount]; for (uint item = 0; item < _metadata.SubKeysCount; item++) { uint sizeName = _metadata.MaxSubKeyLen + 1; uint sizeClass = _metadata.MaxClassLen + 1; StringBuilder sbName = new StringBuilder((int)sizeName); StringBuilder sbClass = new StringBuilder((int)sizeClass); FILETIME fileTime = new FILETIME(); Win32Result result = OffregNative.EnumKey(_intPtr, item, sbName, ref sizeName, sbClass, ref sizeClass, ref fileTime); if (result != Win32Result.ERROR_SUCCESS) throw new Win32Exception((int)result); SubKeyContainer container = new SubKeyContainer(); container.Name = sbName.ToString(); container.Class = sbClass.ToString(); container.LastWriteTime = fileTime; results[item] = container; } return results; }
internal void Init(object value) { if (value == null) { varType = (ushort)VarEnum.VT_EMPTY; } else if (value is Array) { Type type = value.GetType(); if (type == typeof(sbyte[])) { InitVector(value as Array, typeof(sbyte), VarEnum.VT_I1); } else if (type == typeof(byte[])) { InitVector(value as Array, typeof(byte), VarEnum.VT_UI1); } else if (value is char[]) { varType = (ushort) VarEnum.VT_LPSTR; pszVal = Marshal.StringToCoTaskMemAnsi(new String(value as char[])); } else if (value is char[][]) { char[][] charArray = value as char[][]; String[] strArray = new String[charArray.GetLength(0)]; for (int i=0; i<charArray.Length; i++) { strArray[i] = new String(charArray[i] as char[]); } Init (strArray, true); } else if (type == typeof(short[])) { InitVector(value as Array, typeof(short), VarEnum.VT_I2); } else if (type == typeof(ushort[])) { InitVector(value as Array, typeof(ushort), VarEnum.VT_UI2); } else if (type == typeof(int[])) { InitVector(value as Array, typeof(int), VarEnum.VT_I4); } else if (type == typeof(uint[])) { InitVector(value as Array, typeof(uint), VarEnum.VT_UI4); } else if (type == typeof(Int64[])) { InitVector(value as Array, typeof(Int64), VarEnum.VT_I8); } else if (type == typeof(UInt64[])) { InitVector(value as Array, typeof(UInt64), VarEnum.VT_UI8); } else if (value is float[]) { InitVector(value as Array, typeof(float), VarEnum.VT_R4); } else if (value is double[]) { InitVector(value as Array, typeof(double), VarEnum.VT_R8); } else if (value is Guid[]) { InitVector(value as Array, typeof(Guid), VarEnum.VT_CLSID); } else if (value is String[]) { Init (value as String[], false); } else if (value is bool[]) { bool[] boolArray =value as bool[]; short[] array = new short[boolArray.Length]; for (int i=0; i<boolArray.Length; i++) { array[i] = (short) (boolArray[i] ? -1 : 0); } InitVector(array, typeof(short), VarEnum.VT_BOOL); } else { throw new System.InvalidOperationException(SR.Get(SRID.Image_PropertyNotSupported)); } } else { Type type = value.GetType(); if (value is String) { varType = (ushort) VarEnum.VT_LPWSTR; pwszVal = Marshal.StringToCoTaskMemUni(value as String); } else if (type == typeof(sbyte)) { varType = (ushort) VarEnum.VT_I1; cVal = (sbyte) value; } else if (type == typeof(byte)) { varType = (ushort) VarEnum.VT_UI1; bVal = (byte) value; } else if (type == typeof(System.Runtime.InteropServices.ComTypes.FILETIME)) { varType = (ushort)VarEnum.VT_FILETIME; filetime = (System.Runtime.InteropServices.ComTypes.FILETIME)value; } else if (value is char) { varType = (ushort)VarEnum.VT_LPSTR; pszVal = Marshal.StringToCoTaskMemAnsi(new String(new char[] { (char)value })); } else if (type == typeof(short)) { varType = (ushort)VarEnum.VT_I2; iVal = (short)value; } else if (type == typeof(ushort)) { varType = (ushort)VarEnum.VT_UI2; uiVal = (ushort)value; } else if (type == typeof(int)) { varType = (ushort)VarEnum.VT_I4; intVal = (int)value; } else if (type == typeof(uint)) { varType = (ushort)VarEnum.VT_UI4; uintVal = (uint)value; } else if (type == typeof(Int64)) { varType = (ushort)VarEnum.VT_I8; lVal = (Int64)value; } else if (type == typeof(UInt64)) { varType = (ushort)VarEnum.VT_UI8; ulVal = (UInt64)value; } else if (value is float) { varType = (ushort)VarEnum.VT_R4; fltVal = (float)value; } else if (value is double) { varType = (ushort)VarEnum.VT_R8; dblVal = (double)value; } else if (value is Guid) { byte[] guid = ((Guid)value).ToByteArray(); varType = (ushort)VarEnum.VT_CLSID; pclsidVal = Marshal.AllocCoTaskMem(guid.Length); Marshal.Copy(guid, 0, pclsidVal, guid.Length); } else if (value is bool) { varType = (ushort)VarEnum.VT_BOOL; boolVal = (short)(((bool)value) ? -1 : 0); } else if (value is BitmapMetadataBlob) { Init((value as BitmapMetadataBlob).InternalGetBlobValue(), typeof(byte), VarEnum.VT_BLOB); } else if (value is BitmapMetadata) { IntPtr punkTemp = IntPtr.Zero; BitmapMetadata metadata = value as BitmapMetadata; SafeMILHandle metadataHandle = metadata.InternalMetadataHandle; if (metadataHandle == null || metadataHandle.IsInvalid) { throw new NotImplementedException(); } Guid wicMetadataQueryReader = MILGuidData.IID_IWICMetadataQueryReader; HRESULT.Check(UnsafeNativeMethods.MILUnknown.QueryInterface( metadataHandle, ref wicMetadataQueryReader, out punkTemp)); varType = (ushort)VarEnum.VT_UNKNOWN; punkVal = punkTemp; } else { throw new System.InvalidOperationException(SR.Get(SRID.Image_PropertyNotSupported)); } } }
internal static unsafe int BuildChain (IntPtr hChainEngine, SafeCertContextHandle pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, ref SafeCertChainHandle ppChainContext) { if (pCertContext == null || pCertContext.IsInvalid) throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_InvalidContextHandle"), "pCertContext"); SafeCertStoreHandle hCertStore = SafeCertStoreHandle.InvalidHandle; if (extraStore != null && extraStore.Count > 0) hCertStore = X509Utils.ExportToMemoryStore(extraStore); CAPI.CERT_CHAIN_PARA ChainPara = new CAPI.CERT_CHAIN_PARA(); // Initialize the structure size. ChainPara.cbSize = (uint) Marshal.SizeOf(ChainPara); // Application policy SafeLocalAllocHandle applicationPolicyHandle = SafeLocalAllocHandle.InvalidHandle; if (applicationPolicy != null && applicationPolicy.Count > 0) { ChainPara.RequestedUsage.dwType = CAPI.USAGE_MATCH_TYPE_AND; ChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint) applicationPolicy.Count; applicationPolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy); ChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = applicationPolicyHandle.DangerousGetHandle(); } // Certificate policy SafeLocalAllocHandle certificatePolicyHandle = SafeLocalAllocHandle.InvalidHandle; if (certificatePolicy != null && certificatePolicy.Count > 0) { ChainPara.RequestedIssuancePolicy.dwType = CAPI.USAGE_MATCH_TYPE_AND; ChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint) certificatePolicy.Count; certificatePolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy); ChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = certificatePolicyHandle.DangerousGetHandle(); } ChainPara.dwUrlRetrievalTimeout = (uint) timeout.Milliseconds; _FILETIME ft = new _FILETIME(); *((long*) &ft) = verificationTime.ToFileTime(); uint flags = X509Utils.MapRevocationFlags(revocationMode, revocationFlag); // Build the chain. if (!CAPI.CAPISafe.CertGetCertificateChain(hChainEngine, pCertContext, ref ft, hCertStore, ref ChainPara, flags, IntPtr.Zero, ref ppChainContext)) return Marshal.GetHRForLastWin32Error(); applicationPolicyHandle.Dispose(); certificatePolicyHandle.Dispose(); return CAPI.S_OK; }
protected override void BuildInternal() { GlobalLog.Enter("RegBlobWebProxyDataBuilder#" + ValidationHelper.HashString(this) + "::BuildInternal() m_Connectoid:" + ValidationHelper.ToString(m_Connectoid)); // DON'T TOUCH THE ORDERING OF THE CALLS TO THE INSTANCE OF ProxyRegBlob bool success = ReadRegSettings(); if (success) { success = ReadInt32() >= IE50StrucSize; } if (!success) { // if registry access fails rely on automatic detection SetAutoDetectSettings(true); return; } // read the rest of the items out ReadInt32(); // incremental version# of current settings (ignored) ProxyTypeFlags proxyFlags = (ProxyTypeFlags)ReadInt32(); // flags GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() proxyFlags:" + ValidationHelper.ToString(proxyFlags)); string addressString = ReadString(); // proxy name string proxyBypassString = ReadString(); // proxy bypass GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() proxyAddressString:" + ValidationHelper.ToString(addressString) + " proxyBypassString:" + ValidationHelper.ToString(proxyBypassString)); // // Once we verify that the flag for proxy is enabled, // Parse UriString that is stored, may be in the form, // of "http=http://http-proxy;ftp="ftp=http://..." must // handle this case along with just a URI. // if ((proxyFlags & ProxyTypeFlags.PROXY_TYPE_PROXY) != 0) { SetProxyAndBypassList(addressString, proxyBypassString); } #if !FEATURE_PAL SetAutoDetectSettings((proxyFlags & ProxyTypeFlags.PROXY_TYPE_AUTO_DETECT) != 0); string autoConfigUrlString = ReadString(); // autoconfig url GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() scriptLocation:" + ValidationHelper.ToString(addressString)); if ((proxyFlags & ProxyTypeFlags.PROXY_TYPE_AUTO_PROXY_URL) != 0) { SetAutoProxyUrl(autoConfigUrlString); } // The final straw against attempting to use the WinInet LKG script location was, it's invalid when IPs have changed even if the // connectoid hadn't. Doing that validation didn't seem worth it (error-prone, expensive, unsupported). #if USE_WINIET_AUTODETECT_CACHE proxyIE5Settings.ReadInt32(); // autodetect flags (ignored) // reuse addressString for lkgScriptLocationString addressString = proxyIE5Settings.ReadString(); // last known good auto-proxy url // read ftLastKnownDetectTime FILETIME ftLastKnownDetectTime = proxyIE5Settings.ReadFileTime(); // Verify if this lkgScriptLocationString has timed out // if (IsValidTimeForLkgScriptLocation(ftLastKnownDetectTime)) { // reuse address for lkgScriptLocation GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() lkgScriptLocation:" + ValidationHelper.ToString(addressString)); if (Uri.TryCreate(addressString, UriKind.Absolute, out address)) { webProxyData.lkgScriptLocation = address; } } else { #if TRAVE SYSTEMTIME st = new SYSTEMTIME(); bool f = SafeNclNativeMethods.FileTimeToSystemTime(ref ftLastKnownDetectTime, ref st); if (f) { GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() ftLastKnownDetectTime:" + ValidationHelper.ToString(st)); } #endif // TRAVE GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() Ignoring Timed out lkgScriptLocation:" + ValidationHelper.ToString(addressString)); // Now rely on automatic detection settings set above // based on the proxy flags (webProxyData.automaticallyDetectSettings). // } #endif /* * // This is some of the rest of the proxy reg key blob parsing. * // * // Read Inte---- IPs * int iftCount = proxyIE5Settings.ReadInt32(); * for (int ift = 0; ift < iftCount; ++ift) { * proxyIE5Settings.ReadInt32(); * } * * // Read lpszAutoconfigSecondaryUrl * string autoconfigSecondaryUrl = proxyIE5Settings.ReadString(); * * // Read dwAutoconfigReloadDelayMins * int autoconfigReloadDelayMins = proxyIE5Settings.ReadInt32(); */ #endif GlobalLog.Leave("RegBlobWebProxyDataBuilder#" + ValidationHelper.HashString(this) + "::BuildInternal()"); }
private int DoBind() { currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_FINDINGRESOURCE, currentUrl); currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_CONNECTING, "Gallio Navigator."); bool success = false; try { GallioNavigatorCommand command = GallioNavigatorCommand.ParseUri(currentUrl); if (command != null) { if (command.Name == "openAttachment") { string path = command.Arguments["path"]; if (!string.IsNullOrEmpty(path)) { currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_SENDINGREQUEST, Path.GetFileName(path)); success = StartOpenAttachmentCommand(path); } } else { currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_SENDINGREQUEST, command.Name); var engine = new GallioNavigatorEngine(true); success = command.Execute(engine); } } } catch (Exception ex) { Debug.WriteLine(String.Format("Failed to process Uri '{0}' due to an exception: {1}.", currentUrl, ex)); } LockData(); int hr; if (success) { if (data != null && (currentBindFlags & BINDF.BINDF_NOWRITECACHE) == 0) { uint dataLength = (uint)data.Length; // Provide mime type. if (dataMimeType != null) { currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_VERIFIEDMIMETYPEAVAILABLE, dataMimeType); } // Determine whether we need to provide the path to the local file. if ((currentBindFlags & BINDF.BINDF_NEEDFILE) != 0 && dataPath != null) { #if false // Not needed at the moment since the file we provide does not need to be in the cache. // Keeping this code in case we decide to provide dynamic content later. StringBuilder cacheFilePathBuilder = new StringBuilder(NativeConstants.MAX_PATH); string extension = Path.GetExtension(dataPath); if (extension.Length != 0) extension = extension.Substring(1); // strip leading '.' NativeMethods.CreateUrlCacheEntry(currentUrl, dataLength, extension, cacheFilePathBuilder, 0); string cacheFilePath = cacheFilePathBuilder.ToString(); DateTime now = DateTime.Now; var nowTime = new System.Runtime.InteropServices.ComTypes.FILETIME() { dwHighDateTime = (int) (now.Ticks >> 32), dwLowDateTime = (int) now.Ticks }; const string headers = "HTTP/1.0 200 OK\r\n\r\n"; File.Copy(dataPath, cacheFilePath, true); NativeMethods.CommitUrlCacheEntry(currentUrl, cacheFilePath, nowTime, nowTime, NativeConstants.NORMAL_CACHE_ENTRY, headers, (uint)headers.Length, extension, null); currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_CACHEFILENAMEAVAILABLE, cacheFilePath); #else currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_CACHEFILENAMEAVAILABLE, dataPath); #endif } // Report all data available. currentProtocolSink.ReportData(BSCF.BSCF_FIRSTDATANOTIFICATION | BSCF.BSCF_LASTDATANOTIFICATION | BSCF.BSCF_DATAFULLYAVAILABLE, dataLength, dataLength); hr = NativeConstants.S_OK; } else { // Aborts the navigation. hr = NativeConstants.INET_E_DATA_NOT_AVAILABLE; } } else { // Reports an invalid Url. hr = NativeConstants.INET_E_INVALID_URL; } currentProtocolSink.ReportResult(hr, 0, null); currentProtocolSink = null; UnlockData(); return hr; }
static extern bool SystemTimeToFileTime([In] ref SYSTEMTIME lpSystemTime, out FILETIME lpFileTime);
public bool Update(int retryAttempt = 0) { try { if (!_initialized) { _initialized = Init(); return _initialized; } FILETIME sysIdle, sysKernel, sysUser; // Check if we can get current system cpu times if (!GetSystemTimes(out sysIdle, out sysKernel, out sysUser)) return false; // Calculate tot system cpu time ulong sysKernelDiff = SubtractTimes(sysKernel, _lastSysKernel); ulong sysUserDiff = SubtractTimes(sysUser, _lastSysUser); ulong sysIdleDiff = SubtractTimes(sysIdle, _lastSysIdle); ulong sysTotal = sysKernelDiff + sysUserDiff; if (!validDiff((long)sysKernelDiff) || !validDiff((long)sysUserDiff) || !validDiff((long)sysIdleDiff)) { //Debug.WriteLine("Stats: Negative Tick Difference"); //Debug.WriteLine("kernel: {0,-20} :: {1,-20} Diff:{2,-20} :: {3} miliseconds", ((UInt64)(sysKernel.dwHighDateTime << 32)) | (UInt64)sysKernel.dwLowDateTime, ((UInt64)(_lastSysKernel.dwHighDateTime << 32)) | (UInt64)_lastSysKernel.dwLowDateTime, sysKernelDiff, TimeSpan.FromTicks((long)sysKernelDiff).TotalMilliseconds); //Debug.WriteLine("user : {0,-20} :: {1,-20} Diff:{2,-20} :: {3} miliseconds", ((UInt64)(sysUser.dwHighDateTime << 32)) | (UInt64)sysUser.dwLowDateTime, ((UInt64)(_lastSysUser.dwHighDateTime << 32)) | (UInt64)_lastSysUser.dwLowDateTime, sysUserDiff, TimeSpan.FromTicks((long)sysUserDiff).TotalMilliseconds); //Debug.WriteLine("idle : {0,-20} :: {1,-20} Diff:{2,-20} :: {3} miliseconds", ((UInt64)(sysIdle.dwHighDateTime << 32)) | (UInt64)sysIdle.dwLowDateTime, ((UInt64)(_lastSysIdle.dwHighDateTime << 32)) | (UInt64)_lastSysIdle.dwLowDateTime, sysIdleDiff, TimeSpan.FromTicks((long)sysIdleDiff).TotalMilliseconds); glitchRecover = true; // mark to recover from glitch _lastSysKernel = sysKernel; _lastSysUser = sysUser; _lastSysIdle = sysIdle; Thread.Sleep(100); // give windows time to recover if (retryAttempt < 3) return Update(); return false; } // Calculate total Cpu usage double totalUsage = sysTotal > 0 ? ((sysTotal - sysIdleDiff) * 100d / sysTotal) : TotalCpuUsage; TotalCpuUsage = totalUsage < 0 ? TotalCpuUsage : totalUsage; var newList = new HashSet<ProcUsage>(); foreach (Process proc in Process.GetProcesses()) { try { // Skip proc with id 0 if (proc.Id == 0) continue; Int64 procTotal; double oldCpuUsage = 0d; ProcUsage p = GetById(proc.Id); if (p != null) { procTotal = proc.TotalProcessorTime.Ticks - p.LastProcTime.Ticks; oldCpuUsage = p.Usage.Cpu; } else procTotal = 0; double usage = glitchRecover ? oldCpuUsage : ((100.0 * procTotal) / sysTotal); // Calculate process CPU Usage // Add Process to list newList.Add(new ProcUsage { Process = proc, Usage = new Usage { Cpu = usage, Memory = proc.PrivateMemorySize64 }, LastProcTime = proc.TotalProcessorTime }); } catch { continue; } Thread.Sleep(1); // be nice for cpu } // Update last system times _lastSysKernel = sysKernel; _lastSysUser = sysUser; _lastSysIdle = sysIdle; // unmark glitch recover if (glitchRecover && retryAttempt < 3) { glitchRecover = false; Update(retryAttempt + 1); // Update again } // Update Process list _procUsageList = newList; } catch (Win32Exception ex) { Logger.Instance.WriteGlobal(ex.ToString()); return false; } catch (Exception ex) { Logger.Instance.WriteGlobal(ex.ToString()); return false; } return true; }
static extern bool FileTimeToSystemTime (ref FILETIME FileTime, ref SYSTEMTIME SystemTime);
private ulong FileTimeToULong(FILETIME time) { return ((ulong)time.dwHighDateTime << 32) + (uint)time.dwLowDateTime; }
/// <summary> /// Converts a file time to DateTime format. /// </summary> /// <param name="filetime">FILETIME structure</param> /// <returns>DateTime structure</returns> public static DateTime FileTimeToDateTime(FILETIME filetime) { var st = new SYSTEMTIME(); FileTimeToSystemTime(ref filetime, ref st); return new DateTime(st.Year, st.Month, st.Day, st.Hour, st.Minute, st.Second, st.Milliseconds); }
/// <summary> /// Insert annotations. /// </summary> private StatusCode InsertAnnotations( HdaItem item, DataValueCollection values, out int[] errors) { errors = null; string methodName = "IOPCHDA_SyncAnnotations.Insert"; int dwNumItems = values.Count; int[] phServer = new int[dwNumItems]; System.Runtime.InteropServices.ComTypes.FILETIME[] ftTimeStamps = new System.Runtime.InteropServices.ComTypes.FILETIME[dwNumItems]; OPCHDA_ANNOTATION[] pAnnotationValues = new OPCHDA_ANNOTATION[dwNumItems]; IntPtr ppErrors; try { for (int ii = 0; ii < dwNumItems; ii++) { DataValue value = values[ii]; phServer[ii] = item.ServerHandle; ftTimeStamps[ii] = ComUtils.GetFILETIME(value.SourceTimestamp); pAnnotationValues[ii] = new OPCHDA_ANNOTATION(); // pass an empty structure if the annotation is not valid. pAnnotationValues[ii].dwNumValues = 0; Annotation annotation = value.GetValue<Annotation>(null); if (annotation != null && !String.IsNullOrEmpty(annotation.Message)) { pAnnotationValues[ii].dwNumValues = 1; pAnnotationValues[ii].ftAnnotationTime = ComUtils.GetFILETIMEs(new DateTime[] { annotation.AnnotationTime }); pAnnotationValues[ii].ftTimeStamps = ComUtils.GetFILETIMEs(new DateTime[] { value.SourceTimestamp }); pAnnotationValues[ii].szAnnotation = ComUtils.GetUnicodeStrings(new string[] { annotation.Message }); pAnnotationValues[ii].szUser = ComUtils.GetUnicodeStrings(new string[] { annotation.UserName }); } } IOPCHDA_SyncAnnotations server = BeginComCall<IOPCHDA_SyncAnnotations>(methodName, true); server.Insert( dwNumItems, phServer, ftTimeStamps, pAnnotationValues, out ppErrors); // check for error. errors = ComUtils.GetInt32s(ref ppErrors, dwNumItems, true); // set bad type error for invalid annotations. for (int ii = 0; ii < dwNumItems; ii++) { if (pAnnotationValues[ii].dwNumValues == 0) { errors[ii] = ResultIds.E_BADTYPE; } } } catch (Exception e) { ComCallError(methodName, e); return StatusCodes.BadUnexpectedError; } finally { EndComCall(methodName); // free allocated memory. for (int ii = 0; ii < dwNumItems; ii++) { if (pAnnotationValues[ii].dwNumValues == 0) { continue; } IntPtr[] pointers = new IntPtr[1]; Marshal.Copy(pAnnotationValues[ii].szUser, pointers, 0, 1); Marshal.FreeCoTaskMem(pointers[0]); Marshal.Copy(pAnnotationValues[ii].szAnnotation, pointers, 0, 1); Marshal.FreeCoTaskMem(pointers[0]); Marshal.FreeCoTaskMem(pAnnotationValues[ii].ftAnnotationTime); Marshal.FreeCoTaskMem(pAnnotationValues[ii].ftTimeStamps); Marshal.FreeCoTaskMem(pAnnotationValues[ii].szUser); Marshal.FreeCoTaskMem(pAnnotationValues[ii].szAnnotation); } } return StatusCodes.Good; }
public void OnDiskFileUpdated(string filename, ref System.Runtime.InteropServices.ComTypes.FILETIME pFT) { throw new NotImplementedException(); }
/// <summary> /// Reads the data for an item at the specified times. /// </summary> private StatusCode ReadAtTime(HdaHistoryReadAtTimeRequest request) { string methodName = "IOPCHDA_SyncRead.ReadAtTime"; IntPtr ppItemValues; IntPtr ppErrors; System.Runtime.InteropServices.ComTypes.FILETIME[] pTimestamps = new System.Runtime.InteropServices.ComTypes.FILETIME[request.ReqTimes.Count]; for (int ii = 0; ii < pTimestamps.Length; ii++) { pTimestamps[ii] = ComUtils.GetFILETIME(request.ReqTimes[ii]); } try { IOPCHDA_SyncRead server = BeginComCall<IOPCHDA_SyncRead>(methodName, true); server.ReadAtTime( pTimestamps.Length, pTimestamps, 1, new int[] { request.ServerHandle }, out ppItemValues, out ppErrors); } catch (Exception e) { ComCallError(methodName, e); return StatusCodes.BadUnexpectedError; } finally { EndComCall(methodName); } // check for error. int[] errors = ComUtils.GetInt32s(ref ppErrors, 1, true); if (errors[0] < 0) { return StatusCodes.BadNodeIdUnknown; } // check if operation halted. request.Completed = true; // unmarshal the results. OPCHDA_ITEM result = (OPCHDA_ITEM)Marshal.PtrToStructure(ppItemValues, typeof(OPCHDA_ITEM)); if (result.dwCount > 0) { object[] values = ComUtils.GetVARIANTs(ref result.pvDataValues, result.dwCount, true); int[] qualities = ComUtils.GetInt32s(ref result.pdwQualities, result.dwCount, true); DateTime[] timestamps = ComUtils.GetDateTimes(ref result.pftTimeStamps, result.dwCount, true); request.Results = new DataValueCollection(result.dwCount); for (int ii = 0; ii < result.dwCount; ii++) { DataValue value = new DataValue(); value.Value = ComUtils.ProcessComValue(values[ii]); value.StatusCode = ComUtils.GetHdaQualityCode(Utils.ToUInt32(qualities[ii])); value.SourceTimestamp = timestamps[ii]; request.Results.Add(value); } } Marshal.FreeCoTaskMem(ppItemValues); if (result.dwCount == 0) { return StatusCodes.GoodNoData; } return StatusCodes.Good; }
public static extern int FileTimeToSystemTime(ref FILETIME fileTime, ref SYSTEMTIME systemTime);
public static bool IsTimestamped(string filename) { try { int encodingType; int contentType; int formatType; IntPtr certStore = IntPtr.Zero; IntPtr cryptMsg = IntPtr.Zero; IntPtr context = IntPtr.Zero; if (!WinCrypt.CryptQueryObject( WinCrypt.CERT_QUERY_OBJECT_FILE, Marshal.StringToHGlobalUni(filename), WinCrypt.CERT_QUERY_CONTENT_FLAG_ALL, WinCrypt.CERT_QUERY_FORMAT_FLAG_ALL, 0, out encodingType, out contentType, out formatType, ref certStore, ref cryptMsg, ref context)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } //expecting contentType=10; CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED //Logger.LogInfo(string.Format("Querying file '{0}':", filename)); //Logger.LogInfo(string.Format(" Encoding Type: {0}", encodingType)); //Logger.LogInfo(string.Format(" Content Type: {0}", contentType)); //Logger.LogInfo(string.Format(" Format Type: {0}", formatType)); //Logger.LogInfo(string.Format(" Cert Store: {0}", certStore.ToInt32())); //Logger.LogInfo(string.Format(" Crypt Msg: {0}", cryptMsg.ToInt32())); //Logger.LogInfo(string.Format(" Context: {0}", context.ToInt32())); // Get size of the encoded message. int cbData = 0; if (!WinCrypt.CryptMsgGetParam( cryptMsg, WinCrypt.CMSG_ENCODED_MESSAGE, //Crypt32.CMSG_SIGNER_INFO_PARAM, 0, IntPtr.Zero, ref cbData)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } var vData = new byte[cbData]; // Get the encoded message. if (!WinCrypt.CryptMsgGetParam( cryptMsg, WinCrypt.CMSG_ENCODED_MESSAGE, //Crypt32.CMSG_SIGNER_INFO_PARAM, 0, vData, ref cbData)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } var signedCms = new SignedCms(); signedCms.Decode(vData); foreach (var signerInfo in signedCms.SignerInfos) { foreach (var unsignedAttribute in signerInfo.UnsignedAttributes) { if (unsignedAttribute.Oid.Value == WinCrypt.szOID_RSA_counterSign) { foreach (var counterSignInfo in signerInfo.CounterSignerInfos) { foreach (var signedAttribute in counterSignInfo.SignedAttributes) { if (signedAttribute.Oid.Value == WinCrypt.szOID_RSA_signingTime) { var fileTime = new FILETIME(); int fileTimeSize = Marshal.SizeOf(fileTime); IntPtr fileTimePtr = Marshal.AllocCoTaskMem(fileTimeSize); Marshal.StructureToPtr(fileTime, fileTimePtr, true); var buffdata = new byte[fileTimeSize]; Marshal.Copy(fileTimePtr, buffdata, 0, fileTimeSize); var buffSize = (uint)buffdata.Length; uint encoding = WinCrypt.X509_ASN_ENCODING | WinCrypt.PKCS_7_ASN_ENCODING; var rsaSigningTime = (UIntPtr)(uint)Marshal.StringToHGlobalAnsi(WinCrypt.szOID_RSA_signingTime); byte[] pbData = signedAttribute.Values[0].RawData; var ucbData = (uint)pbData.Length; bool workie = WinCrypt.CryptDecodeObject(encoding, rsaSigningTime, pbData, ucbData, 0, buffdata, ref buffSize); if (workie) { IntPtr fileTimePtr2 = Marshal.AllocCoTaskMem(buffdata.Length); Marshal.Copy(buffdata, 0, fileTimePtr2, buffdata.Length); var fileTime2 = (FILETIME)Marshal.PtrToStructure(fileTimePtr2, typeof (FILETIME)); long hFT2 = (((long)fileTime2.dwHighDateTime) << 32) + ((uint)fileTime2.dwLowDateTime); DateTime dte = DateTime.FromFileTime(hFT2); Console.WriteLine(dte.ToString()); } else { throw new Win32Exception(Marshal.GetLastWin32Error()); } } } } return true; } } } } catch (Exception) { // no logging } return false; }
public bool Update() { try { FILETIME sysIdle, sysKernel, sysUser; if (!_initialized) { _initialized = Init(); return(_initialized); } // Check if we can get current system cpu times if (!GetSystemTimes(out sysIdle, out sysKernel, out sysUser)) { return(false); } // Calculate tot system cpu time ulong sysKernelDiff = SubtractTimes(sysKernel, _lastSysKernel); ulong sysUserDiff = SubtractTimes(sysUser, _lastSysUser); ulong sysIdleDiff = SubtractTimes(sysIdle, _lastSysIdle); ulong sysTotal = sysKernelDiff + sysUserDiff; if (!validDiff((long)sysKernelDiff) || !validDiff((long)sysUserDiff) || !validDiff((long)sysIdleDiff)) { //Debug.WriteLine("Stats: Negative Tick Difference"); //Debug.WriteLine("kernel: {0,-20} :: {1,-20} Diff:{2,-20} :: {3} miliseconds", ((UInt64)(sysKernel.dwHighDateTime << 32)) | (UInt64)sysKernel.dwLowDateTime, ((UInt64)(_lastSysKernel.dwHighDateTime << 32)) | (UInt64)_lastSysKernel.dwLowDateTime, sysKernelDiff, TimeSpan.FromTicks((long)sysKernelDiff).TotalMilliseconds); //Debug.WriteLine("user : {0,-20} :: {1,-20} Diff:{2,-20} :: {3} miliseconds", ((UInt64)(sysUser.dwHighDateTime << 32)) | (UInt64)sysUser.dwLowDateTime, ((UInt64)(_lastSysUser.dwHighDateTime << 32)) | (UInt64)_lastSysUser.dwLowDateTime, sysUserDiff, TimeSpan.FromTicks((long)sysUserDiff).TotalMilliseconds); //Debug.WriteLine("idle : {0,-20} :: {1,-20} Diff:{2,-20} :: {3} miliseconds", ((UInt64)(sysIdle.dwHighDateTime << 32)) | (UInt64)sysIdle.dwLowDateTime, ((UInt64)(_lastSysIdle.dwHighDateTime << 32)) | (UInt64)_lastSysIdle.dwLowDateTime, sysIdleDiff, TimeSpan.FromTicks((long)sysIdleDiff).TotalMilliseconds); glitchRecover = true; // mark to recover from glitch _lastSysKernel = sysKernel; _lastSysUser = sysUser; _lastSysIdle = sysIdle; Thread.Sleep(100); // give windows time to recover return(Update()); } // Calculate total Cpu usage double totalUsage = sysTotal > 0 ? ((sysTotal - sysIdleDiff) * 100d / sysTotal) : TotalCpuUsage; TotalCpuUsage = totalUsage < 0 ? TotalCpuUsage : totalUsage; var newList = new HashSet <ProcUsage>(); foreach (Process proc in Process.GetProcesses()) { try { // Skip proc with id 0 if (proc.Id == 0) { continue; } Int64 procTotal; double oldCpuUsage = 0d; ProcUsage p = GetById(proc.Id); if (p != null) { procTotal = proc.TotalProcessorTime.Ticks - p.LastProcTime.Ticks; oldCpuUsage = p.Usage.Cpu; } else { procTotal = 0; } double usage = glitchRecover ? oldCpuUsage : ((100.0 * procTotal) / sysTotal); // Calculate process CPU Usage // Add Process to list newList.Add(new ProcUsage { Process = proc, Usage = new Usage { Cpu = usage, Memory = proc.PrivateMemorySize64 }, LastProcTime = proc.TotalProcessorTime }); } catch { continue; } Thread.Sleep(1); // be nice for cpu } // Update last system times _lastSysKernel = sysKernel; _lastSysUser = sysUser; _lastSysIdle = sysIdle; // unmark glitch recover if (glitchRecover) { glitchRecover = false; Update(); // Update again } // Update Process list _procUsageList = newList; } catch (Exception ex) { Logger.Instance.WriteGlobal(ex.ToString()); return(false); } return(true); }