Inter-process communication

RSS for tag

Share data through Handoff, support universal links to your app's content, and display activity-based services to the user using inter-process communication.

Posts under Inter-process communication tag

88 Posts

Post

Replies

Boosts

Views

Activity

FileHandle's readabilityHandler not called when detached from debugger
Hello, I am facing an issue with NSTask (Process), NSPipe (Pipe) and NSFileHandle (FileHandle). I have an app that executes a child process (command line utility) and gets its output via Pipe instances set as standardI/O of Process instance. I can observe two logic flows: Once the child process exits, -[Process readabilityHandler] gets called where I gather the $0.availableData. Once the child process generates output (i.e. print() is executed by the child process), -[Process readabilityHandler] also gets called which makes sense. This is the case when exit() is not called by the child process (i.e. continuous execution). However, when LLDB is detached, #2 is false, i.e. -[Process readabilityHandler] is not called. Wrong behaviour also happens if I don't rely on readabilityHandler, but instead use Notification to receive changes in data availability. In such case, notification gets called continuously with empty data (even though child process does generate the output). If I don't create Pipe instance for standardI/O of the Process, then readabilityHandler does get called, but with an empty data continuously. I have created a DTS #756462540, since this doesn't make any sense. Prerequisites* app is not sandboxed Big Sur 11.0.1 (20B29) Xcode 12.3 (12C33)
5
0
3.7k
May ’23
IOS's Equivalent of Android Service - Or how do I provide processing for other apps to use?
Hello All. We have an app that we developed that receives real time data from a bluetooth device, runs it through AI models, and provides some result based on the input. (Sorry for being vague, IP and all). This all works well both on IOS and Android. However, what we want to allow, is for other apps to be able and read the data that we provide in realtime, and display / use that for their own proposes. On android this works really well using a Service. This allows any app to communicate with a single running instance of the service, bind to it, work with the results, and close it when done. I'm trying to understand how we would replicate this on IOS. It seems that the concept doesn't exist, and with the strict limitations on background processing, we cannot just run our app in the background, and stream the results via say a local TCP server that another app can access. What might be the way to solve this within the platform? we have to keep the BT data streaming, our models running, and allow others to access it via some API/RPC. Is there a solution or some sort of best practice to achieve this?
1
0
2.1k
Apr ’23
How can I use inter process communication?
Hi, I am currently building my own VPN application using NetworkExtension's PacketTunnelProvider. I want to send information from the PacketTunnelProvider to the ViewController when a VPN connection fails and to tell the user why. The code now is as shown below. When the startTunnel() being overwritten is executed, somehow NotificationCenter.default.post(name: NSNotification.Name.NEVPNStatusDidChange, object: nil) is executed and VPNStatusDidChange(_ notification: Notification?) in the ViewController is called and displays some message. I tried to do the same thing by writing NotificationCenter.default.post(name: NSNotification.Name(rawValue: "testnotify"), object: nil) in the PacketTunnelProvider.swift , but it does not work. What is wrong? Here is a part of current PacketTunnelProvider.swift override func startTunnel(options: [String : NSObject]? = nil, completionHandler: @escaping (Error?) -> Void) {   conf = (self.protocolConfiguration as! NETunnelProviderProtocol).providerConfiguration! as [String : AnyObject]   self.setupWSSession()       DispatchQueue.global().async {     while (self.connectionPhase < 5) {       Thread.sleep(forTimeInterval: 0.5)     }     self.tunToWS()   } NotificationCenter.default.post(name: NSNotification.Name(rawValue: "testnotify"), object: nil) } And here is a part of ViewController.swift override func viewDidLoad() {     super.viewDidLoad()     initVPNTunnelProviderManager()     NotificationCenter.default.addObserver(self, selector: #selector(ViewController.VPNStatusDidChange(_:)), name: NSNotification.Name.NEVPNStatusDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.receieve(_:)), name: NSNotification.Name(rawValue: "testnotify"), object: nil)     } @objc func VPNStatusDidChange(_ notification: Notification?) {   print("VPN Status changed:")   let status = self.vpnManager.connection.status   switch status {   case .connecting:     print("Connecting...")     connectButton.setTitle("Disconnect", for: .normal)     break   case .connected:     print("Connected...")     connectButton.setTitle("Disconnect", for: .normal)     break   case .disconnecting:     print("Disconnecting...")     break   case .disconnected:     print("Disconnected...")     connectButton.setTitle("Connect", for: .normal)     break   case .invalid:     print("Invliad")     break   case .reasserting:     print("Reasserting...")     break   } } @objc func receive(_ notification: Notification?) {     print("receive Notification!") }
6
1
2.6k
Mar ’23
No Endpoint Security events for read/write from/to shared memory
Hi, I see no endpoint security events when writing & reading to & from shared memory segments. I used the following for accessing the shared memory: fd = shm_open("/AAA", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); ftruncate(fd, 32) addr = mmap(NULL, 32, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);  Is there a way to monitor shm access? Thx, Moshe.
2
0
1.3k
Jan ’23
Pipe and Poll MacM1.
Hi since couple of day I introspect a bug that my application have on specifically on MacM1. All of this is code in C on a Mac Monterey (begun on Big Sure but updated recently). In nutshell we allow user to send some custom command to OS. In practice what does we do: Create 2 pair pipe (and a thirds one for error but not pertinent here). input parent were the command will be wrote -> output child where the command will read the command. input child where we the child will wrote the output of command-> output parent where we will read the return value. We configure them with "close on exec", "non blocking", "asynchronous" and "FIOSETOWN" raise a signal when data are ready. Forking send the command from child. And then we wait in parent with poll that data is ready in output parent. And this pattern work like a charm on all of our supported platform (including mac x64 Monterey with xcode 14 and an Unix A64v8). But on Mac M1 (tested on big sure, Monterey with xcode 13 an 14), it look like poll never go in state "some datas are ready to be read", even when there are datas ready to read. One of the possible conflict that I can see here, is that our application heavily use SIGIO for other purpose that force us to ignore the EINTR error and just wait that poll successfully return. if that poll basically return the EINTR error as the File descriptor signal the interrupt before poll returning, but the next poll should be instantaneous and success as the data are still ready. So I assume that not the issue here. But there are probably something that I miss. So here is some questions, are there any significant known difference between poll() on x64 or x86, and m1 ? Are there some known issue with poll behaviours on MacM1 ? What can we possibility miss here ?
3
0
1.5k
Oct ’22
[iOS 16 Crash] Crash while getting mach port from CFMessagePortRef
I create a local CFMessagePortRef using CFMessagePortCreateLocal and then use CFMachPortGetPort() to try to get the mach port from it like below: NSString *portIdentifier = [[groupName stringByAppendingString:@"."] stringByAppendingString:sdkId]; NSString *portName = [[portIdentifier stringByAppendingString:@"."] stringByAppendingString:@"mach.port"]; CFMessagePortContext context = {0,(__bridge void *)self,nil,nil,nil}; self.sendPort = CFMessagePortCreateLocal(kCFAllocatorDefault, (__bridge CFStringRef)portName, &callback, &context, false); CFMachPortGetPort(ms->_port); It works till iOS 15 but crashes on iOS 16. Can anyone help? I have defined below definition of __CFMessagePort: struct __CFMessagePort {     CFRuntimeBase _base;     CFLock_t _lock;     CFStringRef _name;     CFMachPortRef _port;        /* immutable; invalidated */     CFMutableDictionaryRef _replies;     int32_t _convCounter;     int32_t _perPID;            /* zero if not per-pid, else pid */     CFMachPortRef _replyPort;        /* only used by remote port; immutable once created; invalidated */     CFRunLoopSourceRef _source;        /* only used by local port; immutable once created; invalidated */     dispatch_source_t _dispatchSource;  /* only used by local port; invalidated */     dispatch_queue_t _dispatchQ;    /* only used by local port */     CFMessagePortInvalidationCallBack _icallout;     CFMessagePortCallBack _callout;    /* only used by local port; immutable */     CFMessagePortCallBackEx _calloutEx;    /* only used by local port; immutable */     CFMessagePortContext _context;    /* not part of remote port; immutable; invalidated */ };
4
0
2.0k
Sep ’22
Synchronizing data between an System Extension and Container App
I'm building a macOS application with an Endpoint Security System Extension. I expect the system extension to always be running (i.e. it's effectively a daemon). My extension will gather information about processes and make that data available to the container app. The container app is a UI app and won't always be running. This means that I can't send data from the system extension at an arbitrary time. As far as I understand it, if I ship a macOS app in the App Store then I can't have a launch agent/daemon. I'm looking for a good way/the recommended way to solve this problem. Some specific thoughts/questions: Is it indeed the case that for an App Store app there's no way to create anything like a daemon? Do System Extensions always run as root? I couldn't see anything explicitly in the docs about this. However, given its effectively a daemon that would make sense. I believe using App Groups could be a solution. Specifically, I can just write data to a file in the Sys Ext and have the container app asynchronously pick that up later. However, since the Sys Ext is running as root, that app group will appear in a system folder and I'm not clear that the container app will actually be able to access that. XPC should be a solution, but then I have to put a lot more business logic in the Sys Ext. Specifically, the Sys Ext will need to keep track of what data has been sent to the Container App. Not a huge issue, but I was hoping to make my Sys Ext as dumb as possible. Longer term, I'd like to make the Sys Ext be interactive rather then just informative. In the language of the API that would mean an auth approach rather than a notify approach. Specifically, I want the user to be alerted when certain processes start and have the choice to block/allow those processes. This necessitates the Sys Ext somehow being able to alert the user. If the Container App isn't open then I guess I can send a local notification? Is that the only approach? Is there another way to handle this situation?
2
0
1.8k
Sep ’22
Simple and Fast IPC mechanism between two shell scripts
I have two shell applications and one starts to run after the other exits. I need to set a flag from the first shell application. From the second shell application, I need to check whether the flag is true or false. What is the simplest way to do it? As they don't run simultaneously I can't use named pipes. Writing to a file seems complicated. What are some other mechanisms to achieve this?
0
0
1.2k
Sep ’22
Why my application does not (always) start when opening a file using Xamarin forms?
I have a weird issue with my iOS part of Xamarin Forms application. I have set up my app to open VCard using this Info.Plist: <?xml version="1.0" encoding="UTF-8"?> <plist version="1.0"> <dict> <!-- Some application keys/values stripped for clarity --> <key>CFBundleDocumentTypes</key> <array> <dict> <key>CFBundleTypeName</key> <string>VCard Files</string> <key>CFBundleTypeRole</key> <string>Viewer</string> <key>LSHandlerRank</key> <string>Alternate</string> <key>LSItemContentTypes</key> <array> <string>public.vcard</string> </array> </dict> </array> <key>LSSupportsOpeningDocumentsInPlace</key> <true/> <!--<key>UISupportsDocumentBrowser</key> <true/>--> </dict> </plist> And it works ... When a VCard is opened in Safari, it shows a preview of that VCard. Using the "Share" button, I can see my application in 2 locations: 1 with an Icon (number 1 on the screenshot), 1 with only text (number 2 on the screenshot). If I use the text button(2), my app opens normally (or goes to foreground if already running) and I'm able to deal with the VCard content, so far so good. But, and here comes the issue, if I use the Icon button(1), my app does not open and the Share panel becomes irresponsible. I have no log from my application (OpenUrl function is not called). The only info about this non-crash comes from the iDevice logs (caught using idevicesyslog) sharingd[67] <Notice>: SUIOpenInAppActivity: Performing open using application [my application package] with options { "__PayloadOptions" = { UIApplicationLaunchOptionsSourceApplicationKey = "com.apple.mobilesafari"; }; "__PromptUnlockDevice" = 1; "__UnlockDevice" = 1; } sharingd(CoreServices)[67] <Error>: LaunchServices: open operation <NSBlockOperation: 0x13fece820> failed with error: Error Domain=NSOSStatusErrorDomain Code=-50 "invalid input parameters" UserInfo={NSDebugDescription=invalid input parameters, _LSLine=172, _LSFunction=-[_LSDOpenClient performOpenOperationWithURL:bundleIdentifier:documentIdentifier:isContentManaged:sourceAuditToken:userInfo:options:delegate:completionHandler:]} sharingd[67] <Notice>: -[SUIOpenInAppActivity openResourceOperation:didFailWithError:] Error Domain=NSOSStatusErrorDomain Code=-50 "invalid input parameters" UserInfo={NSDebugDescription=invalid input parameters, _LSLine=172, _LSFunction=-[_LSDOpenClient performOpenOperationWithURL:bundleIdentifier:documentIdentifier:isContentManaged:sourceAuditToken:userInfo:options:delegate:completionHandler:]} Just in case, here is the relevant AppDelegate.cs part: public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options) { var decodedOptions = new UIApplicationOpenUrlOptions(options); SLogger.LogDebug($"options == {SSilencer.Serialize(decodedOptions)}", true); var openInPlace = decodedOptions.OpenInPlace == true; var isScopedResource = url.StartAccessingSecurityScopedResource(); SLogger.LogDebug($"url == {url}; open in place == {openInPlace}; is scoped resource == {isScopedResource}", true); var urlAsString = url.ToString(); if(urlAsString.StartsWith("file://") && urlAsString.EndsWith(".vcf")) { var data = NSData.FromUrl(url, NSDataReadingOptions.Mapped, out var error); if(error == null) { /* This is where I'm using the data, stripped for clarity */ } else { SLogger.LogError("unable to read content of file; path == " + urlAsString + "; error == " + error.DebugDescription); } } if(isScopedResource) url.StopAccessingSecurityScopedResource(); return true; } From Info.Plist, I tried to change the "LSSupportsOpeningDocumentsInPlace" from true to false, also tried to use "UISupportsDocumentBrowser" true instead of "LSSupportsOpeningDocumentsInPlace", none of those made it. What could I've missed, I'm stuck on this issue for 2 days and I have no clue nor ideas anymore. Thanks for your assistance by advance.
0
0
1.8k
Aug ’22
Develop app to enable keyboard shortcuts for other apps
Hi, I'm completely new to developing iOS/iPadOS apps. But I was hoping to develop an app to give some of my favourite apps keyboard shortcut support. Some of these apps would be Youtube, Songsterr and Spotify. Is this possible with the SDK in any way? So far I've found the IPC on iOS is very limited so I don't have high hopes...
1
0
975
Aug ’22
FileProvider: How to do IPC with a FileProviderExtension
I am attempting to communicate with a FileProviderExtension (NSFileProviderReplicatedExtension) using XPC. I want to allow the controlling application to manage how the extension communicates with the remote service - e.g. tell the extension to sign in (and provide credentials to do so), sign out, etc. I have implemented the NSFileProviderServicing protocol in the extension and provided an NSFileProviderServiceSource (following the FruitBasket sample code). However, I can't see how to get a general connection to the service from the controlling application. The only method I can find is FileManager().fileProviderServicesForItem(at url: URL), which requires a URL for an item managed by the extension. Given the controlling application wants to perform actions like sign in, there is no item in scope and thus no URL. I tried using NSFileProviderManager.documentStorageURL, but this is not available on macos. Any idea how to get the connection without a file URL? Or how to get a general purpose URL that will suffice? Or is there another IPC mechanism I should use?
1
0
1.1k
Aug ’22
No DistributedNotificationCenter.postNotificationName(_:object:userInfo:deliverImmediately:) method available?
When I try: let center = DistributedNotificationCenter.default center.postNotificationName(Notification.Name(rawValue: "SomeName"), object: "SomeString", deliverImmediately: true) I get compiler error: Extra argument 'deliverImmediately' in call. What I'm trying to do is post a distributed notification from FileProvider extension. When I check documentation I see that deliverImmediately parameter exists. Does anyone know what's going on there?
3
0
1.6k
Aug ’22
Excluding activity types for UIActivityViewController: some are still present
I try to exclude some activities from UIActivity. It works as expected when exclusion is done directly with the activity, as with: UIActivity.ActivityType.message, UIActivity.ActivityType.airDrop but not when activity is declared with an init as with: UIActivity.ActivityType(rawValue: "net.whatsapp.WhatsApp.ShareExtension"), UIActivity.ActivityType(rawValue: "com.ifttt.ifttt.share"), So, with the following code: let excludedActivityTypes = [ UIActivity.ActivityType.message, UIActivity.ActivityType.airDrop, UIActivity.ActivityType(rawValue: "net.whatsapp.WhatsApp.ShareExtension"), UIActivity.ActivityType(rawValue: "com.ifttt.ifttt.share") ]         let activityVC = UIActivityViewController(activityItems: [modifiedPdfURL], applicationActivities: nil)          activityVC.excludedActivityTypes = excludedActivityTypes message and airDrop do not show, but WhatsApp and IFTTT still show. I have tested with         activityVC.completionWithItemsHandler = { (activity, success, modifiedItems, error) in             print("activity: \(activity), success: \(success), items: \(modifiedItems), error: \(error)")         } that WhatsApp and IFTTT services are effectively the ones listed here. When selecting WhatsApp, print above gives: activity: Optional(__C.UIActivityType(_rawValue: net.whatsapp.WhatsApp.ShareExtension)), success: false, items: nil, error: nil
4
0
5.4k
Jul ’22
Open App Setting Programmatically
if let url = URL(string:UIApplication.openSettingsURLString) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } }As from apple doc i use above method to open iphone setting from app but unfortuantely its going to app setting rather than IphoneSetting I am using swift version 4.2 not sure whats the issue
9
0
25k
Jun ’22
Can applications communicate with each other directly by XPC if they are all in one bundle?
In my project I have a host application and a husk application. What I want to do is, every time the user launches a new view in the host application, I want to create one more dock icon by launching another instance of husk application. Then the husk application behaves like it is the view itself by monitoring the event of click/quit and send them to the host application through XPC. The XPC tutorial tells me an XPC service embedded in an application is invisible to the processes outside the bundle. To communicate between two foreground applications it seems that I need to create a third helperTool/agent/daemon which venders a Mach/XPC service. But I wonder if I can put husk application inside the bundle of the hose application. So they can directly connect to the XPC service which is also embedded in the same bundle. If the answer is no, maybe NSDistributedNotificationCenter is much better and simpler in my scenario?
7
0
1.6k
Jun ’22
Child process on iOS
Hello, On macOS, I can include a second executable in the app bundle, which the main executable can launch and communicate with via pipes (standard input/output). I've done this before (with app sandbox inheritance). I've read on other forums that this is not possible on iOS. Is that correct? I tried popen() and it always fails with the error "Operation not permitted." 😔 I just wanted to confirm before I move on to using frameworks. Thanks for your time.
1
0
2.1k
May ’22
Passing NSURLCredential in XPC connection fail in decoder
Hi, I’d like to perform client-side certificate authentication from https based connection in macOS. I’m using the method didReceiveChallenge from URLSession. However, I cannot read the keychain directly since my process is running as Daemon, and my client certificate reside in login keychain. So I've followed the guidance from this question https://developer.apple.com/forums/thread/106851, and sent this authentication request to a user-based process which is running in the current user so it has access to the keychain. After I acquire the NSURLCredential object, I’d like to return it back to the Daemon, so it may run the completionHandler with that credential. However, After I successfully create the NSURLCredential in the user process, and send it back using some reply callback. It looks like the object didn’t serialized properly and I get the following error : Exception: decodeObjectForKey: Object of class "NSURLCredential" returned nil from -initWithCoder: while being decoded for key <no key> Here’s my client side code ( I made sure that the server side create a valid NSURLCredential object). and the problem occur after I send the XPC request, right when i’m about to get the callback response (reply) - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate) { [myXpcService getCertIdentityWithAcceptedIssuers:challenge.protectionSpace.distinguishedNames withReply:^(NSURLCredential *cred, NSError *error) { if (error != nil) { completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); } else { completionHandler(NSURLSessionAuthChallengeUseCredential, cred); } }]; } Perhaps anybody can tell me what did I do wrong here ? Does XPC is capable to pass complex objects like NSURLCredentials ? thanks !
12
0
3k
May ’22
How to pass an array of C-structs to an XPC service?
I am trying to pass an array of C-structs to an XPC Service, but the service receives only the first element. Following is the C struct struct MyStruct { char *name; unsigned char v1; unsigned char v2; Status status; // a c-style enum }; and I am using it like this struct MyStruct structs[3] = {{"name1", 0, 0, success}, {"name2", 1,1, success}, {0}}; [[_connectionToService remoteObjectProxy] doSomething:structs]; and doSomething is declared as - (void)doSomething: (struct MyStruct[]) structs; The document Creating XPC Services mentions that C structures and arrays containing only the types listed above are supported, but I am unable to get it to work even for an array of c-strings or ints. Also, there's an API for making synchronous RPC calls but there is no documentation available for it. - (id)synchronousRemoteObjectProxyWithErrorHandler:(void (^)(NSError *error))handler It does seem to block but only if the remote method has a reply block. Is this the expected behaviour? And is it safe to cache the proxy object returned by this method?
3
0
2.2k
Apr ’22
FileHandle's readabilityHandler not called when detached from debugger
Hello, I am facing an issue with NSTask (Process), NSPipe (Pipe) and NSFileHandle (FileHandle). I have an app that executes a child process (command line utility) and gets its output via Pipe instances set as standardI/O of Process instance. I can observe two logic flows: Once the child process exits, -[Process readabilityHandler] gets called where I gather the $0.availableData. Once the child process generates output (i.e. print() is executed by the child process), -[Process readabilityHandler] also gets called which makes sense. This is the case when exit() is not called by the child process (i.e. continuous execution). However, when LLDB is detached, #2 is false, i.e. -[Process readabilityHandler] is not called. Wrong behaviour also happens if I don't rely on readabilityHandler, but instead use Notification to receive changes in data availability. In such case, notification gets called continuously with empty data (even though child process does generate the output). If I don't create Pipe instance for standardI/O of the Process, then readabilityHandler does get called, but with an empty data continuously. I have created a DTS #756462540, since this doesn't make any sense. Prerequisites* app is not sandboxed Big Sur 11.0.1 (20B29) Xcode 12.3 (12C33)
Replies
5
Boosts
0
Views
3.7k
Activity
May ’23
IOS's Equivalent of Android Service - Or how do I provide processing for other apps to use?
Hello All. We have an app that we developed that receives real time data from a bluetooth device, runs it through AI models, and provides some result based on the input. (Sorry for being vague, IP and all). This all works well both on IOS and Android. However, what we want to allow, is for other apps to be able and read the data that we provide in realtime, and display / use that for their own proposes. On android this works really well using a Service. This allows any app to communicate with a single running instance of the service, bind to it, work with the results, and close it when done. I'm trying to understand how we would replicate this on IOS. It seems that the concept doesn't exist, and with the strict limitations on background processing, we cannot just run our app in the background, and stream the results via say a local TCP server that another app can access. What might be the way to solve this within the platform? we have to keep the BT data streaming, our models running, and allow others to access it via some API/RPC. Is there a solution or some sort of best practice to achieve this?
Replies
1
Boosts
0
Views
2.1k
Activity
Apr ’23
How can I use inter process communication?
Hi, I am currently building my own VPN application using NetworkExtension's PacketTunnelProvider. I want to send information from the PacketTunnelProvider to the ViewController when a VPN connection fails and to tell the user why. The code now is as shown below. When the startTunnel() being overwritten is executed, somehow NotificationCenter.default.post(name: NSNotification.Name.NEVPNStatusDidChange, object: nil) is executed and VPNStatusDidChange(_ notification: Notification?) in the ViewController is called and displays some message. I tried to do the same thing by writing NotificationCenter.default.post(name: NSNotification.Name(rawValue: "testnotify"), object: nil) in the PacketTunnelProvider.swift , but it does not work. What is wrong? Here is a part of current PacketTunnelProvider.swift override func startTunnel(options: [String : NSObject]? = nil, completionHandler: @escaping (Error?) -&gt; Void) {   conf = (self.protocolConfiguration as! NETunnelProviderProtocol).providerConfiguration! as [String : AnyObject]   self.setupWSSession()       DispatchQueue.global().async {     while (self.connectionPhase &lt; 5) {       Thread.sleep(forTimeInterval: 0.5)     }     self.tunToWS()   } NotificationCenter.default.post(name: NSNotification.Name(rawValue: "testnotify"), object: nil) } And here is a part of ViewController.swift override func viewDidLoad() {     super.viewDidLoad()     initVPNTunnelProviderManager()     NotificationCenter.default.addObserver(self, selector: #selector(ViewController.VPNStatusDidChange(_:)), name: NSNotification.Name.NEVPNStatusDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.receieve(_:)), name: NSNotification.Name(rawValue: "testnotify"), object: nil)     } @objc func VPNStatusDidChange(_ notification: Notification?) {   print("VPN Status changed:")   let status = self.vpnManager.connection.status   switch status {   case .connecting:     print("Connecting...")     connectButton.setTitle("Disconnect", for: .normal)     break   case .connected:     print("Connected...")     connectButton.setTitle("Disconnect", for: .normal)     break   case .disconnecting:     print("Disconnecting...")     break   case .disconnected:     print("Disconnected...")     connectButton.setTitle("Connect", for: .normal)     break   case .invalid:     print("Invliad")     break   case .reasserting:     print("Reasserting...")     break   } } @objc func receive(_ notification: Notification?) {     print("receive Notification!") }
Replies
6
Boosts
1
Views
2.6k
Activity
Mar ’23
No Endpoint Security events for read/write from/to shared memory
Hi, I see no endpoint security events when writing & reading to & from shared memory segments. I used the following for accessing the shared memory: fd = shm_open("/AAA", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); ftruncate(fd, 32) addr = mmap(NULL, 32, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);  Is there a way to monitor shm access? Thx, Moshe.
Replies
2
Boosts
0
Views
1.3k
Activity
Jan ’23
TN3113: Testing and debugging XPC code with an anonymous listener
Use an anonymous XPC listener to simplify your XPC testing and debugging. View Technote TN3113 &amp;gt;
Replies
0
Boosts
0
Views
1.2k
Activity
Oct ’22
Pipe and Poll MacM1.
Hi since couple of day I introspect a bug that my application have on specifically on MacM1. All of this is code in C on a Mac Monterey (begun on Big Sure but updated recently). In nutshell we allow user to send some custom command to OS. In practice what does we do: Create 2 pair pipe (and a thirds one for error but not pertinent here). input parent were the command will be wrote -&gt; output child where the command will read the command. input child where we the child will wrote the output of command-&gt; output parent where we will read the return value. We configure them with "close on exec", "non blocking", "asynchronous" and "FIOSETOWN" raise a signal when data are ready. Forking send the command from child. And then we wait in parent with poll that data is ready in output parent. And this pattern work like a charm on all of our supported platform (including mac x64 Monterey with xcode 14 and an Unix A64v8). But on Mac M1 (tested on big sure, Monterey with xcode 13 an 14), it look like poll never go in state "some datas are ready to be read", even when there are datas ready to read. One of the possible conflict that I can see here, is that our application heavily use SIGIO for other purpose that force us to ignore the EINTR error and just wait that poll successfully return. if that poll basically return the EINTR error as the File descriptor signal the interrupt before poll returning, but the next poll should be instantaneous and success as the data are still ready. So I assume that not the issue here. But there are probably something that I miss. So here is some questions, are there any significant known difference between poll() on x64 or x86, and m1 ? Are there some known issue with poll behaviours on MacM1 ? What can we possibility miss here ?
Replies
3
Boosts
0
Views
1.5k
Activity
Oct ’22
[iOS 16 Crash] Crash while getting mach port from CFMessagePortRef
I create a local CFMessagePortRef using CFMessagePortCreateLocal and then use CFMachPortGetPort() to try to get the mach port from it like below: NSString *portIdentifier = [[groupName stringByAppendingString:@"."] stringByAppendingString:sdkId]; NSString *portName = [[portIdentifier stringByAppendingString:@"."] stringByAppendingString:@"mach.port"]; CFMessagePortContext context = {0,(__bridge void *)self,nil,nil,nil}; self.sendPort = CFMessagePortCreateLocal(kCFAllocatorDefault, (__bridge CFStringRef)portName, &callback, &context, false); CFMachPortGetPort(ms->_port); It works till iOS 15 but crashes on iOS 16. Can anyone help? I have defined below definition of __CFMessagePort: struct __CFMessagePort {     CFRuntimeBase _base;     CFLock_t _lock;     CFStringRef _name;     CFMachPortRef _port;        /* immutable; invalidated */     CFMutableDictionaryRef _replies;     int32_t _convCounter;     int32_t _perPID;            /* zero if not per-pid, else pid */     CFMachPortRef _replyPort;        /* only used by remote port; immutable once created; invalidated */     CFRunLoopSourceRef _source;        /* only used by local port; immutable once created; invalidated */     dispatch_source_t _dispatchSource;  /* only used by local port; invalidated */     dispatch_queue_t _dispatchQ;    /* only used by local port */     CFMessagePortInvalidationCallBack _icallout;     CFMessagePortCallBack _callout;    /* only used by local port; immutable */     CFMessagePortCallBackEx _calloutEx;    /* only used by local port; immutable */     CFMessagePortContext _context;    /* not part of remote port; immutable; invalidated */ };
Replies
4
Boosts
0
Views
2.0k
Activity
Sep ’22
Synchronizing data between an System Extension and Container App
I'm building a macOS application with an Endpoint Security System Extension. I expect the system extension to always be running (i.e. it's effectively a daemon). My extension will gather information about processes and make that data available to the container app. The container app is a UI app and won't always be running. This means that I can't send data from the system extension at an arbitrary time. As far as I understand it, if I ship a macOS app in the App Store then I can't have a launch agent/daemon. I'm looking for a good way/the recommended way to solve this problem. Some specific thoughts/questions: Is it indeed the case that for an App Store app there's no way to create anything like a daemon? Do System Extensions always run as root? I couldn't see anything explicitly in the docs about this. However, given its effectively a daemon that would make sense. I believe using App Groups could be a solution. Specifically, I can just write data to a file in the Sys Ext and have the container app asynchronously pick that up later. However, since the Sys Ext is running as root, that app group will appear in a system folder and I'm not clear that the container app will actually be able to access that. XPC should be a solution, but then I have to put a lot more business logic in the Sys Ext. Specifically, the Sys Ext will need to keep track of what data has been sent to the Container App. Not a huge issue, but I was hoping to make my Sys Ext as dumb as possible. Longer term, I'd like to make the Sys Ext be interactive rather then just informative. In the language of the API that would mean an auth approach rather than a notify approach. Specifically, I want the user to be alerted when certain processes start and have the choice to block/allow those processes. This necessitates the Sys Ext somehow being able to alert the user. If the Container App isn't open then I guess I can send a local notification? Is that the only approach? Is there another way to handle this situation?
Replies
2
Boosts
0
Views
1.8k
Activity
Sep ’22
Simple and Fast IPC mechanism between two shell scripts
I have two shell applications and one starts to run after the other exits. I need to set a flag from the first shell application. From the second shell application, I need to check whether the flag is true or false. What is the simplest way to do it? As they don't run simultaneously I can't use named pipes. Writing to a file seems complicated. What are some other mechanisms to achieve this?
Replies
0
Boosts
0
Views
1.2k
Activity
Sep ’22
Why my application does not (always) start when opening a file using Xamarin forms?
I have a weird issue with my iOS part of Xamarin Forms application. I have set up my app to open VCard using this Info.Plist: <?xml version="1.0" encoding="UTF-8"?> <plist version="1.0"> <dict> <!-- Some application keys/values stripped for clarity --> <key>CFBundleDocumentTypes</key> <array> <dict> <key>CFBundleTypeName</key> <string>VCard Files</string> <key>CFBundleTypeRole</key> <string>Viewer</string> <key>LSHandlerRank</key> <string>Alternate</string> <key>LSItemContentTypes</key> <array> <string>public.vcard</string> </array> </dict> </array> <key>LSSupportsOpeningDocumentsInPlace</key> <true/> <!--<key>UISupportsDocumentBrowser</key> <true/>--> </dict> </plist> And it works ... When a VCard is opened in Safari, it shows a preview of that VCard. Using the "Share" button, I can see my application in 2 locations: 1 with an Icon (number 1 on the screenshot), 1 with only text (number 2 on the screenshot). If I use the text button(2), my app opens normally (or goes to foreground if already running) and I'm able to deal with the VCard content, so far so good. But, and here comes the issue, if I use the Icon button(1), my app does not open and the Share panel becomes irresponsible. I have no log from my application (OpenUrl function is not called). The only info about this non-crash comes from the iDevice logs (caught using idevicesyslog) sharingd[67] <Notice>: SUIOpenInAppActivity: Performing open using application [my application package] with options { "__PayloadOptions" = { UIApplicationLaunchOptionsSourceApplicationKey = "com.apple.mobilesafari"; }; "__PromptUnlockDevice" = 1; "__UnlockDevice" = 1; } sharingd(CoreServices)[67] <Error>: LaunchServices: open operation <NSBlockOperation: 0x13fece820> failed with error: Error Domain=NSOSStatusErrorDomain Code=-50 "invalid input parameters" UserInfo={NSDebugDescription=invalid input parameters, _LSLine=172, _LSFunction=-[_LSDOpenClient performOpenOperationWithURL:bundleIdentifier:documentIdentifier:isContentManaged:sourceAuditToken:userInfo:options:delegate:completionHandler:]} sharingd[67] <Notice>: -[SUIOpenInAppActivity openResourceOperation:didFailWithError:] Error Domain=NSOSStatusErrorDomain Code=-50 "invalid input parameters" UserInfo={NSDebugDescription=invalid input parameters, _LSLine=172, _LSFunction=-[_LSDOpenClient performOpenOperationWithURL:bundleIdentifier:documentIdentifier:isContentManaged:sourceAuditToken:userInfo:options:delegate:completionHandler:]} Just in case, here is the relevant AppDelegate.cs part: public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options) { var decodedOptions = new UIApplicationOpenUrlOptions(options); SLogger.LogDebug($"options == {SSilencer.Serialize(decodedOptions)}", true); var openInPlace = decodedOptions.OpenInPlace == true; var isScopedResource = url.StartAccessingSecurityScopedResource(); SLogger.LogDebug($"url == {url}; open in place == {openInPlace}; is scoped resource == {isScopedResource}", true); var urlAsString = url.ToString(); if(urlAsString.StartsWith("file://") && urlAsString.EndsWith(".vcf")) { var data = NSData.FromUrl(url, NSDataReadingOptions.Mapped, out var error); if(error == null) { /* This is where I'm using the data, stripped for clarity */ } else { SLogger.LogError("unable to read content of file; path == " + urlAsString + "; error == " + error.DebugDescription); } } if(isScopedResource) url.StopAccessingSecurityScopedResource(); return true; } From Info.Plist, I tried to change the "LSSupportsOpeningDocumentsInPlace" from true to false, also tried to use "UISupportsDocumentBrowser" true instead of "LSSupportsOpeningDocumentsInPlace", none of those made it. What could I've missed, I'm stuck on this issue for 2 days and I have no clue nor ideas anymore. Thanks for your assistance by advance.
Replies
0
Boosts
0
Views
1.8k
Activity
Aug ’22
Mapping memory between DriverKit processes
Having read in the forums that it is possible for dext instances to find and invoke methods on one another, is there any way for one dext process to share a mapped buffer with another? The requirement would be for the buffer to be persistent, something like mappings created by IOConnectMapMemory, which persist until explicitly unmapped.
Replies
0
Boosts
0
Views
1.1k
Activity
Aug ’22
Develop app to enable keyboard shortcuts for other apps
Hi, I'm completely new to developing iOS/iPadOS apps. But I was hoping to develop an app to give some of my favourite apps keyboard shortcut support. Some of these apps would be Youtube, Songsterr and Spotify. Is this possible with the SDK in any way? So far I've found the IPC on iOS is very limited so I don't have high hopes...
Replies
1
Boosts
0
Views
975
Activity
Aug ’22
FileProvider: How to do IPC with a FileProviderExtension
I am attempting to communicate with a FileProviderExtension (NSFileProviderReplicatedExtension) using XPC. I want to allow the controlling application to manage how the extension communicates with the remote service - e.g. tell the extension to sign in (and provide credentials to do so), sign out, etc. I have implemented the NSFileProviderServicing protocol in the extension and provided an NSFileProviderServiceSource (following the FruitBasket sample code). However, I can't see how to get a general connection to the service from the controlling application. The only method I can find is FileManager().fileProviderServicesForItem(at url: URL), which requires a URL for an item managed by the extension. Given the controlling application wants to perform actions like sign in, there is no item in scope and thus no URL. I tried using NSFileProviderManager.documentStorageURL, but this is not available on macos. Any idea how to get the connection without a file URL? Or how to get a general purpose URL that will suffice? Or is there another IPC mechanism I should use?
Replies
1
Boosts
0
Views
1.1k
Activity
Aug ’22
No DistributedNotificationCenter.postNotificationName(_:object:userInfo:deliverImmediately:) method available?
When I try: let center = DistributedNotificationCenter.default center.postNotificationName(Notification.Name(rawValue: "SomeName"), object: "SomeString", deliverImmediately: true) I get compiler error: Extra argument 'deliverImmediately' in call. What I'm trying to do is post a distributed notification from FileProvider extension. When I check documentation I see that deliverImmediately parameter exists. Does anyone know what's going on there?
Replies
3
Boosts
0
Views
1.6k
Activity
Aug ’22
Excluding activity types for UIActivityViewController: some are still present
I try to exclude some activities from UIActivity. It works as expected when exclusion is done directly with the activity, as with: UIActivity.ActivityType.message, UIActivity.ActivityType.airDrop but not when activity is declared with an init as with: UIActivity.ActivityType(rawValue: "net.whatsapp.WhatsApp.ShareExtension"), UIActivity.ActivityType(rawValue: "com.ifttt.ifttt.share"), So, with the following code: let excludedActivityTypes = [ UIActivity.ActivityType.message, UIActivity.ActivityType.airDrop, UIActivity.ActivityType(rawValue: "net.whatsapp.WhatsApp.ShareExtension"), UIActivity.ActivityType(rawValue: "com.ifttt.ifttt.share") ]         let activityVC = UIActivityViewController(activityItems: [modifiedPdfURL], applicationActivities: nil)          activityVC.excludedActivityTypes = excludedActivityTypes message and airDrop do not show, but WhatsApp and IFTTT still show. I have tested with         activityVC.completionWithItemsHandler = { (activity, success, modifiedItems, error) in             print("activity: \(activity), success: \(success), items: \(modifiedItems), error: \(error)")         } that WhatsApp and IFTTT services are effectively the ones listed here. When selecting WhatsApp, print above gives: activity: Optional(__C.UIActivityType(_rawValue: net.whatsapp.WhatsApp.ShareExtension)), success: false, items: nil, error: nil
Replies
4
Boosts
0
Views
5.4k
Activity
Jul ’22
Open App Setting Programmatically
if let url = URL(string:UIApplication.openSettingsURLString) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } }As from apple doc i use above method to open iphone setting from app but unfortuantely its going to app setting rather than IphoneSetting I am using swift version 4.2 not sure whats the issue
Replies
9
Boosts
0
Views
25k
Activity
Jun ’22
Can applications communicate with each other directly by XPC if they are all in one bundle?
In my project I have a host application and a husk application. What I want to do is, every time the user launches a new view in the host application, I want to create one more dock icon by launching another instance of husk application. Then the husk application behaves like it is the view itself by monitoring the event of click/quit and send them to the host application through XPC. The XPC tutorial tells me an XPC service embedded in an application is invisible to the processes outside the bundle. To communicate between two foreground applications it seems that I need to create a third helperTool/agent/daemon which venders a Mach/XPC service. But I wonder if I can put husk application inside the bundle of the hose application. So they can directly connect to the XPC service which is also embedded in the same bundle. If the answer is no, maybe NSDistributedNotificationCenter is much better and simpler in my scenario?
Replies
7
Boosts
0
Views
1.6k
Activity
Jun ’22
Child process on iOS
Hello, On macOS, I can include a second executable in the app bundle, which the main executable can launch and communicate with via pipes (standard input/output). I've done this before (with app sandbox inheritance). I've read on other forums that this is not possible on iOS. Is that correct? I tried popen() and it always fails with the error "Operation not permitted." 😔 I just wanted to confirm before I move on to using frameworks. Thanks for your time.
Replies
1
Boosts
0
Views
2.1k
Activity
May ’22
Passing NSURLCredential in XPC connection fail in decoder
Hi, I’d like to perform client-side certificate authentication from https based connection in macOS. I’m using the method didReceiveChallenge from URLSession. However, I cannot read the keychain directly since my process is running as Daemon, and my client certificate reside in login keychain. So I've followed the guidance from this question https://developer.apple.com/forums/thread/106851, and sent this authentication request to a user-based process which is running in the current user so it has access to the keychain. After I acquire the NSURLCredential object, I’d like to return it back to the Daemon, so it may run the completionHandler with that credential. However, After I successfully create the NSURLCredential in the user process, and send it back using some reply callback. It looks like the object didn’t serialized properly and I get the following error : Exception: decodeObjectForKey: Object of class "NSURLCredential" returned nil from -initWithCoder: while being decoded for key <no key> Here’s my client side code ( I made sure that the server side create a valid NSURLCredential object). and the problem occur after I send the XPC request, right when i’m about to get the callback response (reply) - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate) { [myXpcService getCertIdentityWithAcceptedIssuers:challenge.protectionSpace.distinguishedNames withReply:^(NSURLCredential *cred, NSError *error) { if (error != nil) { completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); } else { completionHandler(NSURLSessionAuthChallengeUseCredential, cred); } }]; } Perhaps anybody can tell me what did I do wrong here ? Does XPC is capable to pass complex objects like NSURLCredentials ? thanks !
Replies
12
Boosts
0
Views
3k
Activity
May ’22
How to pass an array of C-structs to an XPC service?
I am trying to pass an array of C-structs to an XPC Service, but the service receives only the first element. Following is the C struct struct MyStruct { char *name; unsigned char v1; unsigned char v2; Status status; // a c-style enum }; and I am using it like this struct MyStruct structs[3] = {{"name1", 0, 0, success}, {"name2", 1,1, success}, {0}}; [[_connectionToService remoteObjectProxy] doSomething:structs]; and doSomething is declared as - (void)doSomething: (struct MyStruct[]) structs; The document Creating XPC Services mentions that C structures and arrays containing only the types listed above are supported, but I am unable to get it to work even for an array of c-strings or ints. Also, there's an API for making synchronous RPC calls but there is no documentation available for it. - (id)synchronousRemoteObjectProxyWithErrorHandler:(void (^)(NSError *error))handler It does seem to block but only if the remote method has a reply block. Is this the expected behaviour? And is it safe to cache the proxy object returned by this method?
Replies
3
Boosts
0
Views
2.2k
Activity
Apr ’22