FreeRDP
Loading...
Searching...
No Matches
client_cliprdr_file_apple.m
1
19
20#include <errno.h>
21#include <signal.h>
22#include <stdlib.h>
23#include <string.h>
24#include <unistd.h>
25#include <os/lock.h>
26
27#import <AppKit/AppKit.h>
28#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
29
30#include "client_cliprdr_file_apple.h"
31
32static const char s_mime_uri_list[] = "text/uri-list";
33static const char s_mime_text_utf8[] = "text/plain;charset=utf-8";
34
35static NSArray<NSURL *> *get_file_urls(void)
36{
37 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
38 NSDictionary *options = @{NSPasteboardURLReadingFileURLsOnlyKey: @YES};
39 return [pasteboard readObjectsForClasses:@[[NSURL class]] options:options];
40}
41
42char *cliprdr_file_apple_get_uri_list(size_t *size)
43{
44 @autoreleasepool
45 {
46 NSMutableString *list = [NSMutableString string];
47
48 for (NSURL *url in get_file_urls())
49 {
50 /* Finder puts file reference URLs (file:///.file/id=...) on the pasteboard */
51 NSURL *path_url = [url filePathURL];
52 if (!path_url)
53 continue;
54 [list appendFormat:@"%@\r\n", [path_url absoluteString]];
55 }
56
57 if ([list length] == 0)
58 return NULL;
59
60 char *data = strdup([list UTF8String]);
61 if (data && size)
62 *size = strlen(data);
63 return data;
64 }
65}
66
67/* The offers are replaced on the main thread and detached on the channel thread */
68static os_unfair_lock s_lock = OS_UNFAIR_LOCK_INIT;
69static cliprdr_file_context_data_fkt s_data_fkt = NULL;
70static void *s_data_userdata = NULL;
71static NSUInteger s_generation = 0;
72static unsigned s_download_serial = 0;
73
74/* All file presenters share this serial queue: one download at a time, off the main thread */
75static NSOperationQueue *download_queue(void)
76{
77 static NSOperationQueue *queue = nil;
78 static dispatch_once_t once;
79 dispatch_once(&once, ^{
80 queue = [NSOperationQueue new];
81 queue.maxConcurrentOperationCount = 1;
82 queue.name = @"com.freerdp.client.cliprdr.file";
83 });
84 return queue;
85}
86
87/* Remove downloaded files as a coordinated writer: it waits for an application that still
88 * reads them, e.g. the Finder copying a file that was just downloaded. */
89static void remove_path(NSString *path)
90{
91 NSURL *url = [NSURL fileURLWithPath:path isDirectory:YES];
92 NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
93 __block BOOL removed = NO;
94 [coordinator coordinateWritingItemAtURL:url
95 options:NSFileCoordinatorWritingForDeleting
96 error:nil
97 byAccessor:^(NSURL *newURL) {
98 [[NSFileManager defaultManager] removeItemAtURL:newURL
99 error:nil];
100 removed = YES;
101 }];
102 if (!removed)
103 [[NSFileManager defaultManager] removeItemAtURL:url error:nil];
104}
105
106/* The placeholders of one server copy and what downloads them */
107@interface CliprdrFileOffer : NSObject
108@property(nonatomic) cliprdr_file_apple_download_fkt downloadFkt;
109@property(nonatomic) cliprdr_file_apple_release_fkt releaseFkt;
110@property(nonatomic) void *userdata;
111@property(nonatomic, copy) NSString *directory;
112@property(nonatomic, strong) NSMutableArray *presenters;
113- (void)invalidate;
114@end
115
116static CliprdrFileOffer *s_offer = nil;
117static CliprdrFileOffer *s_previous_offer = nil;
118
119@implementation CliprdrFileOffer
120
121/* Stop watching the placeholders. Not on the download queue: it delivers their messages. */
122- (void)invalidate
123{
124 for (id<NSFilePresenter> presenter in self.presenters)
125 [NSFileCoordinator removeFilePresenter:presenter];
126 [self.presenters removeAllObjects];
127}
128
129- (void)dealloc
130{
131 /* The last reference might be the one of a download, on the download queue */
132 NSArray *presenters = [_presenters copy];
133 NSString *directory = _directory;
134 cliprdr_file_apple_release_fkt releaseFkt = _releaseFkt;
135 void *userdata = _userdata;
136
137 dispatch_async(dispatch_get_main_queue(), ^{
138 for (id<NSFilePresenter> presenter in presenters)
139 [NSFileCoordinator removeFilePresenter:presenter];
140 if (releaseFkt)
141 releaseFkt(userdata);
142 if (directory)
143 {
144 dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
145 remove_path(directory);
146 });
147 }
148 });
149}
150
151@end
152
153/* Watches one placeholder. An application that reads a file with file coordination, like
154 * the Finder does to copy it, has to wait until its presenter lets it: this is where the
155 * contents are downloaded. The application waits in its own copy operation only, and the
156 * message arrives on the download queue, so neither it nor this process is blocked. */
157@interface CliprdrFilePresenter : NSObject <NSFilePresenter>
158@property(nonatomic, weak) CliprdrFileOffer *offer;
159@property(nonatomic) size_t index;
160@property(nonatomic, strong) NSURL *url;
161@end
162
163@implementation CliprdrFilePresenter
164
165- (NSURL *)presentedItemURL
166{
167 return self.url;
168}
169
170- (NSOperationQueue *)presentedItemOperationQueue
171{
172 return download_queue();
173}
174
175- (void)relinquishPresentedItemToReader:(void (^)(void (^_Nullable reacquirer)(void)))reader
176{
177 /* This reference keeps the offer and its files until the download returned */
178 CliprdrFileOffer *offer = self.offer;
179
180 /* Better no file than an empty one: the download removes what it could not complete,
181 * and without an offer there is nothing to download from any more */
182 if (offer && offer.downloadFkt)
183 (void)offer.downloadFkt(offer.userdata, self.index);
184 else
185 [[NSFileManager defaultManager] removeItemAtURL:self.url error:nil];
186 reader(nil);
187}
188
189@end
190
191/* Provides the other formats of a server copy (e.g. its text) when they are pasted */
192@interface CliprdrDataProvider : NSObject <NSPasteboardItemDataProvider>
193@property(nonatomic) NSUInteger generation;
194/* pasteboard type -> MIME type the data is requested with */
195@property(nonatomic, strong) NSDictionary<NSPasteboardType, NSString *> *mimeTypes;
196@end
197
198static CliprdrDataProvider *s_provider = nil;
199
200@implementation CliprdrDataProvider
201
202- (void)pasteboard:(NSPasteboard *)pasteboard
203 item:(NSPasteboardItem *)item
204 provideDataForType:(NSPasteboardType)type
205{
206 if (self.generation != s_generation)
207 return;
208
209 NSString *mime = self.mimeTypes[type];
210 if (!mime || !s_data_fkt)
211 return;
212
213 size_t size = 0;
214 const void *data = s_data_fkt(s_data_userdata, [mime UTF8String], &size);
215 if (!data)
216 return;
217
218 if ([type isEqualToString:NSPasteboardTypeString])
219 {
220 /* Applications that paste text get the text of the copy, e.g. the paths */
221 NSString *text = [[NSString alloc] initWithBytes:data
222 length:size
223 encoding:NSUTF8StringEncoding];
224 if (text)
225 [item setString:text forType:type];
226 }
227 else
228 [item setData:[NSData dataWithBytes:data length:size] forType:type];
229}
230
231@end
232
233/* Text becomes the native string, text/uri-list the file items. Everything else keeps its
234 * own type, so the caller still recognises the copy as its own (e.g. by a private type)
235 * when the pasteboard change comes back to it. */
236API_AVAILABLE(macos(11.0))
237static NSDictionary<NSPasteboardType, NSString *> *get_item_types(const char **mime_types,
238 size_t mime_count)
239{
240 NSMutableDictionary<NSPasteboardType, NSString *> *types = [NSMutableDictionary dictionary];
241
242 for (size_t i = 0; i < mime_count; i++)
243 {
244 const char *mime = mime_types[i];
245 if (!mime || (strcmp(mime, s_mime_uri_list) == 0))
246 continue;
247
248 if (strncmp(mime, "text/", 5) == 0)
249 {
250 types[NSPasteboardTypeString] = @(s_mime_text_utf8);
251 continue;
252 }
253
254 NSString *mime_type = [NSString stringWithUTF8String:mime];
255 UTType *uttype = mime_type ? [UTType typeWithMIMEType:mime_type] : nil;
256 if (uttype && !types[uttype.identifier])
257 types[uttype.identifier] = mime_type;
258 }
259 return types;
260}
261
262static NSURL *path_url(const char *path)
263{
264 NSString *str =
265 [[NSFileManager defaultManager] stringWithFileSystemRepresentation:path
266 length:strlen(path)];
267 /* Looks at the placeholder to tell a directory from a file */
268 return str ? [NSURL fileURLWithPath:str] : nil;
269}
270
271BOOL cliprdr_file_apple_offer(const char *directory, const char **paths, const BOOL *present,
272 size_t count, const size_t *top_level, size_t top_level_count,
273 cliprdr_file_apple_download_fkt download_fkt,
274 cliprdr_file_apple_release_fkt release_fkt, void *offer_userdata,
275 const char **mime_types, size_t mime_count,
276 cliprdr_file_context_data_fkt data_fkt, void *data_userdata)
277{
278 if (@available(macOS 11.0, *))
279 {
280 @autoreleasepool
281 {
282 /* From here on the offer frees offer_userdata and the directory, also when
283 * this function fails */
284 CliprdrFileOffer *offer = [CliprdrFileOffer new];
285 offer.downloadFkt = download_fkt;
286 offer.releaseFkt = release_fkt;
287 offer.userdata = offer_userdata;
288 offer.directory = [[NSFileManager defaultManager]
289 stringWithFileSystemRepresentation:directory
290 length:strlen(directory)];
291 offer.presenters = [NSMutableArray array];
292
293 for (size_t i = 0; i < count; i++)
294 {
295 if (!paths[i] || !present[i])
296 continue;
297
298 CliprdrFilePresenter *presenter = [CliprdrFilePresenter new];
299 presenter.offer = offer;
300 presenter.index = i;
301 presenter.url = path_url(paths[i]);
302 if (!presenter.url)
303 return FALSE;
304
305 [offer.presenters addObject:presenter];
306 [NSFileCoordinator addFilePresenter:presenter];
307 }
308
309 CliprdrDataProvider *provider = nil;
310 NSDictionary<NSPasteboardType, NSString *> *mimeTypes =
311 get_item_types(mime_types, mime_count);
312
313 NSMutableArray *items = [NSMutableArray array];
314 for (size_t i = 0; i < top_level_count; i++)
315 {
316 /* A real file URL: an application gets it right away, and waits for the
317 * contents only when it reads the file */
318 NSURL *url = path_url(paths[top_level[i]]);
319 NSPasteboardItem *item = [NSPasteboardItem new];
320 if (!url || ![item setString:[url absoluteString] forType:NSPasteboardTypeFileURL])
321 return FALSE;
322
323 if ((i == 0) && ([mimeTypes count] > 0))
324 {
325 /* NSPasteboardItem does not keep its data provider alive */
326 provider = [CliprdrDataProvider new];
327 provider.mimeTypes = mimeTypes;
328 if (![item setDataProvider:provider forTypes:[mimeTypes allKeys]])
329 return FALSE;
330 }
331 [items addObject:item];
332 }
333
334 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
335 /* Universal Clipboard reads new contents right away, which would download
336 * every copied file. Keep the files on this Mac until they are pasted. */
337 [pasteboard prepareForNewContentsWithOptions:NSPasteboardContentsCurrentHostOnly];
338 if (![pasteboard writeObjects:items])
339 return FALSE;
340
341 /* Keep the previous offer, Finder might still be copying from it */
342 os_unfair_lock_lock(&s_lock);
343 CliprdrFileOffer *oldest = s_previous_offer;
344 s_previous_offer = s_offer;
345 s_offer = offer;
346 s_data_fkt = data_fkt;
347 s_data_userdata = data_userdata;
348 provider.generation = ++s_generation;
349 s_provider = provider;
350 os_unfair_lock_unlock(&s_lock);
351 oldest = nil; /* released without the lock */
352 return TRUE;
353 }
354 }
355
356 if (release_fkt)
357 release_fkt(offer_userdata);
358 [[NSFileManager defaultManager] removeItemAtPath:@(directory) error:nil];
359 return FALSE;
360}
361
362static NSString *const s_download_prefix = @"freerdp-clipboard-";
363
364static NSString *download_root(void)
365{
366 NSString *name = [NSString stringWithFormat:@"%@%d", s_download_prefix, getpid()];
367 return [NSTemporaryDirectory() stringByAppendingPathComponent:name];
368}
369
370/* A process that crashed or was killed could not remove its downloads */
371static void remove_stale_downloads(void)
372{
373 NSFileManager *fm = [NSFileManager defaultManager];
374 NSString *tmp = NSTemporaryDirectory();
375
376 for (NSString *name in [fm contentsOfDirectoryAtPath:tmp error:nil])
377 {
378 if (![name hasPrefix:s_download_prefix])
379 continue;
380
381 const int pid = [[name substringFromIndex:[s_download_prefix length]] intValue];
382 if ((pid <= 0) || (pid == getpid()))
383 continue;
384 /* Keep it unless there is no such process (any more) */
385 if ((kill(pid, 0) == 0) || (errno != ESRCH))
386 continue;
387 [fm removeItemAtPath:[tmp stringByAppendingPathComponent:name] error:nil];
388 }
389}
390
391char *cliprdr_file_apple_new_download_dir(void)
392{
393 @autoreleasepool
394 {
395 static dispatch_once_t once;
396 dispatch_once(&once, ^{
397 dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
398 remove_stale_downloads();
399 });
400 });
401
402 NSFileManager *fm = [NSFileManager defaultManager];
403 NSString *root = download_root();
404
405 NSString *name = [NSString stringWithFormat:@"%u", s_download_serial++];
406 NSString *dir = [root stringByAppendingPathComponent:name];
407 NSDictionary *attributes = @{NSFilePosixPermissions: @0700};
408 if (![fm createDirectoryAtPath:dir
409 withIntermediateDirectories:YES
410 attributes:attributes
411 error:nil])
412 return NULL;
413 return strdup([dir fileSystemRepresentation]);
414 }
415}
416
417void cliprdr_file_apple_detach(void)
418{
419 @autoreleasepool
420 {
421 os_unfair_lock_lock(&s_lock);
422 CliprdrFileOffer *offer = s_offer;
423 CliprdrFileOffer *previous = s_previous_offer;
424 s_offer = nil;
425 s_previous_offer = nil;
426 s_data_fkt = NULL;
427 s_data_userdata = NULL;
428 s_generation++;
429 s_provider = nil;
430 os_unfair_lock_unlock(&s_lock);
431
432 [offer invalidate];
433 [previous invalidate];
434 offer = nil;
435 previous = nil;
436
437 /* The caller cancelled its downloads: wait until the last one returned, it uses
438 * the caller's context. Later messages find no offer any more. */
439 [download_queue() waitUntilAllOperationsAreFinished];
440
441 /* Not as a coordinated writer: that would wait for an application that still
442 * copies a downloaded file, for as long as its copy takes */
443 [[NSFileManager defaultManager] removeItemAtPath:download_root() error:nil];
444 }
445}