/// <summary> /// 接收Socket消息,主要为接收设备返回的指令结果,大部分为Plist,所以函数内将会自行作转换 /// </summary> /// <param name="sock"></param> /// <param name="dict"></param> /// <returns></returns> public object ReceiveMessageFromSocket(int sock) { if (sock < 0) { return(null); } var recvCount = -1; uint dataSize = 0; uint buffer = 0; uint reviceSize = 0; var zero = IntPtr.Zero; do { recvCount = MobileDevice.recv_UInt32(sock, ref buffer, 4, 0); } while (recvCount < 0); if (recvCount != 4) { return(null); } dataSize = MobileDevice.ntohl(buffer);//获取数据总长度 if (dataSize <= 0) { Console.WriteLine("receive size error, dataSize:" + dataSize); return(null); } zero = Marshal.AllocCoTaskMem((int)dataSize); if (zero == IntPtr.Zero) { Console.WriteLine("Could not allocate message buffer."); return(null); } var tempPtr = zero; while (reviceSize < dataSize) { recvCount = MobileDevice.recv(sock, tempPtr, (int)(dataSize - reviceSize), 0); if (recvCount <= -1) { Console.WriteLine("Could not receive secure message: " + recvCount); reviceSize = dataSize + 1; } else { if (recvCount == 0) { Console.WriteLine("receive size is zero. "); break; } tempPtr = new IntPtr(tempPtr.ToInt64() + recvCount); reviceSize += (uint)recvCount; } } var datas = IntPtr.Zero; var srcRef = IntPtr.Zero; if (reviceSize == dataSize) { datas = CoreFoundation.CFDataCreate(CoreFoundation.kCFAllocatorDefault, zero, (int)dataSize); if (datas == IntPtr.Zero) { Console.WriteLine("Could not create CFData for message"); } else { var errorString = IntPtr.Zero; srcRef = CoreFoundation.CFPropertyListCreateFromXMLData(CoreFoundation.kCFAllocatorDefault, datas, CFPropertyListMutabilityOptions.kCFPropertyListImmutable, ref errorString); if (srcRef == IntPtr.Zero) { Console.WriteLine("Could not convert raw xml into a dictionary: " + Convert.ToString(CoreFoundation.ManagedTypeFromCFType(ref errorString))); return(null); } } } if (datas != IntPtr.Zero) { try { CoreFoundation.CFRelease(datas); } catch { } } if (zero != IntPtr.Zero) { Marshal.FreeCoTaskMem(zero); } var result = CoreFoundation.ManagedTypeFromCFType(ref srcRef); if (srcRef != IntPtr.Zero) { CoreFoundation.CFRelease(srcRef); } return(result); }
public TypedPtr <CFString> CFStringCreateWithCString(IntPtr allocator, byte[] buffer) { return(CoreFoundation.CFStringCreateWithCString(allocator, buffer, CFStringBuiltInEncodings.kCFStringEncodingUTF8)); }
public uint CFDictionaryGetTypeID() { return(CoreFoundation.CFDictionaryGetTypeID()); }
public IntPtr CFNumberCreate(IntPtr allocator, CFNumberType theType, ref Int32 Value) { return(CoreFoundation.CFNumberCreate(allocator, theType, ref Value)); }
public uint CFGetTypeID(IntPtr FromInstance) { return(CoreFoundation.CFGetTypeID(FromInstance)); }
public uint CFNumberGetTypeID() { return(CoreFoundation.CFNumberGetTypeID()); }
static void SetMenuItemAttributes(HIMenuItem item, CommandInfo ci, uint refcon) { MenuItemData data = new MenuItemData(); IntPtr text = IntPtr.Zero; try { if (ci.IsArraySeparator) { data.Attributes |= MenuItemAttributes.Separator; } else if (!ci.Visible) { data.Attributes |= MenuItemAttributes.Hidden; } else { data.Attributes &= ~MenuItemAttributes.Hidden; data.CFText = CoreFoundation.CreateString(GetCleanCommandText(ci)); //disable also when MD main window doesn't have toplevel focus, or commands will be //accessible when modal dialogs are active bool disabled = !ci.Enabled || IsGloballyDisabled; data.Enabled = !disabled; if (disabled) { data.Attributes |= MenuItemAttributes.Disabled; } ushort glyphCode, charCode, hardwareCode; MenuAccelModifier mod; if (GetAcceleratorKeys(ci.AccelKey, out glyphCode, out charCode, out hardwareCode, out mod)) { data.CommandKeyModifiers = mod; if (glyphCode != 0) { data.CommandKeyGlyph = glyphCode; data.Attributes ^= MenuItemAttributes.UseVirtualKey; } else if (hardwareCode != 0) { data.CommandVirtualKey = (char)hardwareCode; data.Attributes |= MenuItemAttributes.UseVirtualKey; } else { data.CommandKey = (char)charCode; data.Attributes ^= MenuItemAttributes.UseVirtualKey; } } //else{ //FIXME: remove existing commands if necessary data.Mark = ci.Checked ? ci.CheckedInconsistent ? '-' //FIXME: is this a good symbol for CheckedInconsistent? : (char)MenuGlyphs.Checkmark : '\0'; data.ReferenceConstant = refcon; } HIToolbox.SetMenuItemData(item.MenuRef, item.Index, false, ref data); } finally { if (text != IntPtr.Zero) { CoreFoundation.Release(text); } } }
public Boolean CFStringGetCString(TypedPtr <CFString> theString, byte[] buffer, int bufferSize, CFStringBuiltInEncodings encoding) { return(CoreFoundation.CFStringGetCString((IntPtr)theString, buffer, bufferSize, encoding)); }
internal static SafeCFArrayHandle X509ImportCollection( byte[] bytes, X509ContentType contentType, SafePasswordHandle importPassword, SafeKeychainHandle keychain, bool exportable) { SafeCreateHandle cfPassphrase = s_nullExportString; bool releasePassword = false; int ret; SafeCFArrayHandle collectionHandle; int osStatus; try { if (!importPassword.IsInvalid) { importPassword.DangerousAddRef(ref releasePassword); IntPtr passwordHandle = importPassword.DangerousGetHandle(); if (passwordHandle != IntPtr.Zero) { cfPassphrase = CoreFoundation.CFStringCreateWithCString(passwordHandle); } } ret = AppleCryptoNative_X509ImportCollection( bytes, bytes.Length, contentType, cfPassphrase, keychain, exportable ? 1 : 0, out collectionHandle, out osStatus); if (ret == 1) { return(collectionHandle); } } finally { if (releasePassword) { importPassword.DangerousRelease(); } if (cfPassphrase != s_nullExportString) { cfPassphrase.Dispose(); } } collectionHandle.Dispose(); const int SeeOSStatus = 0; const int ImportReturnedEmpty = -2; const int ImportReturnedNull = -3; switch (ret) { case SeeOSStatus: throw CreateExceptionForOSStatus(osStatus); case ImportReturnedNull: case ImportReturnedEmpty: throw new CryptographicException(); default: Debug.Fail($"Unexpected return value {ret}"); throw new CryptographicException(); } }
public static IntPtr CFStringMakeConstantString(string s) { return(CoreFoundation.StringToCFString(s)); }
protected override bool StorageTryGetValue( string key, Type valueType, TypeCode valueTypeCode, out object value) { using (var cfKey = new CFString(key)) { var valuePtr = CFPreferences.CopyValue( cfKey.Handle, applicationId.Handle, CFPreferences.kCFPreferencesCurrentUser, CFPreferences.kCFPreferencesAnyHost); if (valuePtr == IntPtr.Zero) { value = null; return(false); } var typeId = CoreFoundation.CFGetTypeID(valuePtr); if (typeId == CoreFoundation.CFTypeID.CFBoolean) { value = CFBoolean.ToBoolean(valuePtr); return(true); } if (typeId == CoreFoundation.CFTypeID.CFString) { using (var cfString = new CFString(valuePtr)) value = cfString.ToString(); return(true); } if (typeId == CoreFoundation.CFTypeID.CFNumber) { using (var cfNumber = new CFNumber(valuePtr)) { switch (cfNumber.Type) { case CFNumberType.SInt8: case CFNumberType.Char: value = valueTypeCode == TypeCode.Byte ? cfNumber.ToByte() : (object)cfNumber.ToSByte(); return(true); case CFNumberType.SInt16: case CFNumberType.Short: value = valueTypeCode == TypeCode.UInt16 ? cfNumber.ToUInt16() : (object)cfNumber.ToInt16(); return(true); case CFNumberType.SInt32: case CFNumberType.Int: case CFNumberType.Long: value = valueTypeCode == TypeCode.UInt32 ? cfNumber.ToUInt32() : (object)cfNumber.ToInt32(); return(true); case CFNumberType.SInt64: case CFNumberType.LongLong: case CFNumberType.CFIndex: case CFNumberType.NSInteger: value = valueTypeCode == TypeCode.UInt64 ? cfNumber.ToUInt64() : (object)cfNumber.ToInt64(); return(true); case CFNumberType.Float32: case CFNumberType.Float: value = cfNumber.ToSingle(); return(true); case CFNumberType.Float64: case CFNumberType.Double: case CFNumberType.CGFloat: value = cfNumber.ToDouble(); return(true); } } } if (typeId == CoreFoundation.CFTypeID.CFArray) { try { value = CFArray .FromCFStringArray(valuePtr) ?.ToArray(); return(value != null); } catch { value = null; return(false); } } value = null; return(false); } }
internal static DerSequenceReader SecKeyExport( SafeSecKeyRefHandle key, bool exportPrivate) { // Apple requires all private keys to be exported encrypted, but since we're trying to export // as parsed structures we will need to decrypt it for the user. const string ExportPassword = "******"; SafeCreateHandle exportPassword = exportPrivate ? CoreFoundation.CFStringCreateWithCString(ExportPassword) : s_nullExportString; int ret; SafeCFDataHandle cfData; int osStatus; try { ret = AppleCryptoNative_SecKeyExport( key, exportPrivate ? 1 : 0, exportPassword, out cfData, out osStatus); } finally { if (exportPassword != s_nullExportString) { exportPassword.Dispose(); } } byte[] exportedData; using (cfData) { if (ret == 0) { throw CreateExceptionForOSStatus(osStatus); } if (ret != 1) { Debug.Fail($"AppleCryptoNative_SecKeyExport returned {ret}"); throw new CryptographicException(); } exportedData = CoreFoundation.CFGetData(cfData); } DerSequenceReader reader = new DerSequenceReader(exportedData); if (!exportPrivate) { return(reader); } byte tag = reader.PeekTag(); // PKCS#8 defines two structures, PrivateKeyInfo, which starts with an integer, // and EncryptedPrivateKey, which starts with an encryption algorithm (DER sequence). if (tag == (byte)DerSequenceReader.DerTag.Integer) { return(reader); } const byte ConstructedSequence = DerSequenceReader.ConstructedFlag | (byte)DerSequenceReader.DerTag.Sequence; if (tag == ConstructedSequence) { return(ReadEncryptedPkcs8Blob(ExportPassword, reader)); } Debug.Fail($"Data was neither PrivateKey or EncryptedPrivateKey: {tag:X2}"); throw new CryptographicException(); }
public static ProcessSerialNumber OpenApplication(ApplicationStartInfo application) { if (application == null) { throw new ArgumentNullException("application"); } if (string.IsNullOrEmpty(application.Application) || !System.IO.Directory.Exists(application.Application)) { throw new ArgumentException("Application is not valid"); } var appParams = new LSApplicationParameters(); if (application.NewInstance) { appParams.flags |= LSLaunchFlags.NewInstance; } if (application.Async) { appParams.flags |= LSLaunchFlags.Async; } NSArray argv = null; if (application.Args != null && application.Args.Length > 0) { var args = application.Args; NSObject[] arr = new NSObject[args.Length]; for (int i = 0; i < args.Length; i++) { arr[i] = new NSString(args[i]); } argv = NSArray.FromNSObjects(arr); appParams.argv = argv.Handle; } NSDictionary dict = null; if (application.Environment.Count > 0) { dict = new NSMutableDictionary(); foreach (var kvp in application.Environment) { dict.SetValueForKey(new NSString(kvp.Value), new NSString(kvp.Key)); } appParams.environment = dict.Handle; } var cfUrl = global::MonoMac.CoreFoundation.CFUrl.FromFile(application.Application); ProcessSerialNumber psn; try { appParams.application = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FSRef))); if (!CoreFoundation.CFURLGetFSRef(cfUrl.Handle, appParams.application)) { throw new Exception("Could not create FSRef from CFUrl"); } var status = LSOpenApplication(ref appParams, out psn); if (status != OSStatus.Ok) { throw new Exception("Failed to start process: " + ((int)status).ToString()); } } finally { if (appParams.application != IntPtr.Zero) { Marshal.FreeHGlobal(appParams.application); } appParams.application = IntPtr.Zero; if (dict != null) { dict.Dispose(); //also ensures the NSDictionary is kept alive for the params } if (argv != null) { argv.Dispose(); //also ensures the NSArray is kept alive for the params } } return(psn); }
public TypedPtr <CFString> CFStringCreateWithBytes(IntPtr allocator, byte[] buffer, int bufferSize, CFStringBuiltInEncodings encoding, Boolean isExternalRep) { return(CoreFoundation.CFStringCreateWithBytes(allocator, buffer, bufferSize, encoding, isExternalRep)); }
public CFNumberType CFNumberGetType(TypedPtr <CFNumber> Number) { return(CoreFoundation.CFNumberGetType((IntPtr)Number)); }
public TypedPtr <CFURL> CFURLCreateWithFileSystemPath(IntPtr Allocator, TypedPtr <CFString> FilePath, CFURLPathStyle PathStyle, int isDirectory) { return(CoreFoundation.CFURLCreateWithFileSystemPath(Allocator, (IntPtr)FilePath, PathStyle, isDirectory)); }
public void CFPreferencesSetAppValue(IntPtr Key, IntPtr Value, IntPtr ApplicationID) { CoreFoundation.CFPreferencesSetAppValue(Key, Value, ApplicationID); }
public TypedPtr <CFString> CFURLGetString(IntPtr anURL) { return(CoreFoundation.CFURLGetString(anURL)); }
public void CFDictionarySetValue(TypedPtr <CFDictionary> Dict, /*const*/ IntPtr Key, /*const*/ IntPtr Value) { CoreFoundation.CFDictionarySetValue((IntPtr)Dict, Key, Value); }
public uint CFStringGetTypeID() { return(CoreFoundation.CFStringGetTypeID()); }
public void CFDictionaryGetKeysAndValues(TypedPtr <CFDictionary> Dict, /*const*/ IntPtr[] Keys, /*const*/ IntPtr[] Values) { CoreFoundation.CFDictionaryGetKeysAndValues((IntPtr)Dict, Keys, Values); }
public uint CFBooleanGetTypeID() { return(CoreFoundation.CFBooleanGetTypeID()); }
public Boolean CFStringGetFileSystemRepresentation(TypedPtr <CFString> theString, byte[] buffer, int bufferSize) { return(CoreFoundation.CFStringGetFileSystemRepresentation((IntPtr)theString, buffer, bufferSize)); }
public int CFDictionaryGetCount(TypedPtr <CFDictionary> Dict) { return(CoreFoundation.CFDictionaryGetCount((IntPtr)Dict)); }
public TypedPtr <CFString> __CFStringMakeConstantString(byte[] s) { return(CoreFoundation.__CFStringMakeConstantString(s)); }
public Boolean CFNumberGetValue(TypedPtr <CFNumber> Number, CFNumberType TheType, out float Value) { return(CoreFoundation.CFNumberGetValue((IntPtr)Number, TheType, out Value)); }
/// <summary> /// 发送Socket消息 /// </summary> /// <param name="sock"></param> /// <param name="dict"></param> /// <returns></returns> public bool SendMessageToSocket(int sock, object dict) { var message = CoreFoundation.CFTypeFromManagedType(RuntimeHelpers.GetObjectValue(dict)); return(SendMessageToSocket(sock, message)); }