CSSession.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. //
  2. // Copyright © 2020 osy. All rights reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. #import "CSSession.h"
  17. #import "CSSession+Sharing.h"
  18. #import "CocoaSpice.h"
  19. #import "UTMLogging.h"
  20. #import "UTM-Swift.h"
  21. #import <glib.h>
  22. #import <spice-client.h>
  23. #import <spice/vd_agent.h>
  24. @interface CSSession ()
  25. @property (nonatomic, readwrite, nullable) SpiceSession *session;
  26. @property (nonatomic, readonly) BOOL sessionReadOnly;
  27. @end
  28. @implementation CSSession {
  29. SpiceMainChannel *_main;
  30. }
  31. static UTMPasteboardType utmTypeForClipboardType(guint type)
  32. {
  33. switch (type) {
  34. case VD_AGENT_CLIPBOARD_UTF8_TEXT: {
  35. return UTMPasteboardTypeString;
  36. }
  37. case VD_AGENT_CLIPBOARD_IMAGE_PNG: {
  38. return UTMPasteboardTypePng;
  39. }
  40. case VD_AGENT_CLIPBOARD_IMAGE_BMP: {
  41. return UTMPasteboardTypeBmp;
  42. }
  43. case VD_AGENT_CLIPBOARD_IMAGE_TIFF: {
  44. return UTMPasteboardTypeTiff;
  45. }
  46. case VD_AGENT_CLIPBOARD_IMAGE_JPG: {
  47. return UTMPasteboardTypeJpg;
  48. }
  49. default: {
  50. break;
  51. }
  52. }
  53. return UTMPasteboardTypeString;
  54. }
  55. // helper from spice-util.c
  56. typedef enum {
  57. NEWLINE_TYPE_LF,
  58. NEWLINE_TYPE_CR_LF
  59. } NewlineType;
  60. static gssize get_line(const gchar *str, gsize len,
  61. NewlineType type, gsize *nl_len)
  62. {
  63. const gchar *p, *endl;
  64. gsize nl = 0;
  65. endl = (type == NEWLINE_TYPE_CR_LF) ? "\r\n" : "\n";
  66. p = g_strstr_len(str, len, endl);
  67. if (p) {
  68. len = p - str;
  69. nl = strlen(endl);
  70. }
  71. *nl_len = nl;
  72. return len;
  73. }
  74. static gchar* spice_convert_newlines(const gchar *str, gssize len,
  75. NewlineType from,
  76. NewlineType to)
  77. {
  78. gssize length;
  79. gsize nl;
  80. GString *output;
  81. gint i;
  82. g_return_val_if_fail(str != NULL, NULL);
  83. g_return_val_if_fail(len >= -1, NULL);
  84. /* only 2 supported combinations */
  85. g_return_val_if_fail((from == NEWLINE_TYPE_LF &&
  86. to == NEWLINE_TYPE_CR_LF) ||
  87. (from == NEWLINE_TYPE_CR_LF &&
  88. to == NEWLINE_TYPE_LF), NULL);
  89. if (len == -1)
  90. len = strlen(str);
  91. /* sometime we get \0 terminated strings, skip that, or it fails
  92. to utf8 validate line with \0 end */
  93. else if (len > 0 && str[len-1] == 0)
  94. len -= 1;
  95. /* allocate worst case, if it's small enough, we don't care much,
  96. * if it's big, malloc will put us in mmap'd region, and we can
  97. * over allocate.
  98. */
  99. output = g_string_sized_new(len * 2 + 1);
  100. for (i = 0; i < len; i += length + nl) {
  101. length = get_line(str + i, len - i, from, &nl);
  102. if (length < 0)
  103. break;
  104. g_string_append_len(output, str + i, length);
  105. if (nl) {
  106. /* let's not double \r if it's already in the line */
  107. if (to == NEWLINE_TYPE_CR_LF &&
  108. (output->len == 0 || output->str[output->len - 1] != '\r'))
  109. g_string_append_c(output, '\r');
  110. g_string_append_c(output, '\n');
  111. }
  112. }
  113. return g_string_free(output, FALSE);
  114. }
  115. G_GNUC_INTERNAL
  116. gchar* spice_dos2unix(const gchar *str, gssize len)
  117. {
  118. return spice_convert_newlines(str, len,
  119. NEWLINE_TYPE_CR_LF,
  120. NEWLINE_TYPE_LF);
  121. }
  122. G_GNUC_INTERNAL
  123. gchar* spice_unix2dos(const gchar *str, gssize len)
  124. {
  125. return spice_convert_newlines(str, len,
  126. NEWLINE_TYPE_LF,
  127. NEWLINE_TYPE_CR_LF);
  128. }
  129. static void cs_clipboard_got_from_guest(SpiceMainChannel *main, guint selection,
  130. guint type, const guchar *data, guint size,
  131. gpointer user_data)
  132. {
  133. CSSession *self = (__bridge CSSession *)user_data;
  134. SPICE_DEBUG("clipboard got data");
  135. if (type == VD_AGENT_CLIPBOARD_UTF8_TEXT) {
  136. gchar *conv = NULL;
  137. /* on windows, gtk+ would already convert to LF endings, but
  138. not on unix */
  139. if (spice_main_channel_agent_test_capability(self->_main, VD_AGENT_CAP_GUEST_LINEEND_CRLF)) {
  140. conv = spice_dos2unix((gchar*)data, size);
  141. size = (guint)strlen(conv);
  142. }
  143. NSString *string = [NSString stringWithUTF8String:(conv ? conv : (const char *)data)];
  144. [[UTMPasteboard generalPasteboard] setString:string];
  145. g_free(conv);
  146. } else {
  147. UTMPasteboardType utmType = utmTypeForClipboardType(type);
  148. NSData *pasteData = [NSData dataWithBytes:data length:size];
  149. [[UTMPasteboard generalPasteboard] setData:pasteData forType:utmType];
  150. }
  151. }
  152. static gboolean cs_clipboard_grab(SpiceMainChannel *main, guint selection,
  153. guint32* types, guint32 ntypes,
  154. gpointer user_data)
  155. {
  156. CSSession *self = (__bridge CSSession *)user_data;
  157. if (selection != VD_AGENT_CLIPBOARD_SELECTION_CLIPBOARD) {
  158. SPICE_DEBUG("skipping grab unimplemented selection: %d", selection);
  159. return FALSE;
  160. }
  161. if (self.sessionReadOnly || !self.shareClipboard) {
  162. SPICE_DEBUG("ignoring clipboard_grab");
  163. return TRUE;
  164. }
  165. for (int n = 0; n < ntypes; ++n) {
  166. spice_main_channel_clipboard_selection_request(self->_main, selection,
  167. types[n]);
  168. }
  169. return TRUE;
  170. }
  171. static gboolean cs_clipboard_request(SpiceMainChannel *main, guint selection,
  172. guint type, gpointer user_data)
  173. {
  174. CSSession *self = (__bridge CSSession *)user_data;
  175. if (selection != VD_AGENT_CLIPBOARD_SELECTION_CLIPBOARD) {
  176. SPICE_DEBUG("skipping request unimplemented selection: %d", selection);
  177. return FALSE;
  178. }
  179. if (self.sessionReadOnly || !self.shareClipboard) {
  180. SPICE_DEBUG("ignoring clipboard_request");
  181. return FALSE;
  182. }
  183. UTMPasteboardType utmType = utmTypeForClipboardType(type);
  184. NSData *data = [[UTMPasteboard generalPasteboard] dataForType:utmType];
  185. spice_main_channel_clipboard_selection_notify(self->_main, selection, type, data.bytes, data.length);
  186. return TRUE;
  187. }
  188. static void cs_clipboard_release(SpiceMainChannel *main, guint selection,
  189. gpointer user_data)
  190. {
  191. //CSSession *self = (__bridge CSSession *)user_data;
  192. [[UTMPasteboard generalPasteboard] clearContents];
  193. }
  194. static void cs_channel_new(SpiceSession *session, SpiceChannel *channel,
  195. gpointer user_data)
  196. {
  197. CSSession *self = (__bridge CSSession *)user_data;
  198. if (SPICE_IS_MAIN_CHANNEL(channel)) {
  199. SPICE_DEBUG("Changing main channel from %p to %p", self->_main, channel);
  200. self->_main = SPICE_MAIN_CHANNEL(channel);
  201. g_signal_connect(channel, "main-clipboard-selection-grab",
  202. G_CALLBACK(cs_clipboard_grab), GLIB_OBJC_RETAIN(self));
  203. g_signal_connect(channel, "main-clipboard-selection-request",
  204. G_CALLBACK(cs_clipboard_request), GLIB_OBJC_RETAIN(self));
  205. g_signal_connect(channel, "main-clipboard-selection-release",
  206. G_CALLBACK(cs_clipboard_release), GLIB_OBJC_RETAIN(self));
  207. g_signal_connect(channel, "main-clipboard-selection",
  208. G_CALLBACK(cs_clipboard_got_from_guest), GLIB_OBJC_RETAIN(self));
  209. }
  210. }
  211. static void cs_channel_destroy(SpiceSession *session, SpiceChannel *channel,
  212. gpointer user_data)
  213. {
  214. CSSession *self = (__bridge CSSession *)user_data;
  215. if (SPICE_IS_MAIN_CHANNEL(channel) && SPICE_MAIN_CHANNEL(channel) == self->_main) {
  216. self->_main = NULL;
  217. g_signal_handlers_disconnect_by_func(channel, G_CALLBACK(cs_clipboard_grab), GLIB_OBJC_RELEASE(self));
  218. g_signal_handlers_disconnect_by_func(channel, G_CALLBACK(cs_clipboard_request), GLIB_OBJC_RELEASE(self));
  219. g_signal_handlers_disconnect_by_func(channel, G_CALLBACK(cs_clipboard_release), GLIB_OBJC_RELEASE(self));
  220. g_signal_handlers_disconnect_by_func(channel, G_CALLBACK(cs_clipboard_got_from_guest), GLIB_OBJC_RELEASE(self));
  221. }
  222. }
  223. #pragma mark - Initializers
  224. - (id)init {
  225. if (self = [super init]) {
  226. [[NSNotificationCenter defaultCenter] addObserver:self
  227. selector:@selector(pasteboardDidChange:)
  228. name:UTMPasteboard.changedNotification
  229. object:nil];
  230. [[NSNotificationCenter defaultCenter] addObserver:self
  231. selector:@selector(pasteboardDidRemove:)
  232. name:UTMPasteboard.removedNotification
  233. object:nil];
  234. }
  235. return self;
  236. }
  237. - (id)initWithSession:(nonnull SpiceSession *)session {
  238. self = [self init];
  239. if (self) {
  240. GList *list;
  241. GList *it;
  242. self.session = session;
  243. g_object_ref(session);
  244. // g_get_user_special_dir(G_USER_DIRECTORY_PUBLIC_SHARE) returns NULL so we replace it with a valid value here
  245. [self createDefaultShareReadme];
  246. [self setSharedDirectory:self.defaultPublicShare.path readOnly:NO];
  247. UTMLog(@"%s:%d", __FUNCTION__, __LINE__);
  248. g_signal_connect(session, "channel-new",
  249. G_CALLBACK(cs_channel_new), GLIB_OBJC_RETAIN(self));
  250. g_signal_connect(session, "channel-destroy",
  251. G_CALLBACK(cs_channel_destroy), GLIB_OBJC_RETAIN(self));
  252. list = spice_session_get_channels(session);
  253. for (it = g_list_first(list); it != NULL; it = g_list_next(it)) {
  254. cs_channel_new(session, it->data, (__bridge void *)self);
  255. }
  256. g_list_free(list);
  257. }
  258. return self;
  259. }
  260. - (void)dealloc {
  261. UTMLog(@"%s:%d", __FUNCTION__, __LINE__);
  262. g_signal_handlers_disconnect_by_func(self.session, G_CALLBACK(cs_channel_new), GLIB_OBJC_RELEASE(self));
  263. g_signal_handlers_disconnect_by_func(self.session, G_CALLBACK(cs_channel_destroy), GLIB_OBJC_RELEASE(self));
  264. g_object_unref(self.session);
  265. self.session = NULL;
  266. [[NSNotificationCenter defaultCenter] removeObserver:self
  267. name:UTMPasteboard.changedNotification
  268. object:nil];
  269. [[NSNotificationCenter defaultCenter] removeObserver:self
  270. name:UTMPasteboard.removedNotification
  271. object:nil];
  272. }
  273. #pragma mark - Notification handler
  274. - (void)pasteboardDidChange:(NSNotification *)notification {
  275. UTMLog(@"seen UIPasteboardChangedNotification");
  276. if (!self.shareClipboard || self.sessionReadOnly) {
  277. return;
  278. }
  279. guint32 type = VD_AGENT_CLIPBOARD_NONE;
  280. UTMPasteboard *pb = [UTMPasteboard generalPasteboard];
  281. if ([pb canReadItemForType:UTMPasteboardTypePng]) {
  282. type = VD_AGENT_CLIPBOARD_IMAGE_PNG;
  283. } else if ([pb canReadItemForType:UTMPasteboardTypeBmp]) {
  284. type = VD_AGENT_CLIPBOARD_IMAGE_BMP;
  285. } else if ([pb canReadItemForType:UTMPasteboardTypeTiff]) {
  286. type = VD_AGENT_CLIPBOARD_IMAGE_TIFF;
  287. } else if ([pb canReadItemForType:UTMPasteboardTypeJpg]) {
  288. type = VD_AGENT_CLIPBOARD_IMAGE_JPG;
  289. } else if ([pb canReadItemForType:UTMPasteboardTypeString]) {
  290. type = VD_AGENT_CLIPBOARD_UTF8_TEXT;
  291. } else {
  292. UTMLog(@"pasteboard with unrecognized type");
  293. }
  294. if (spice_main_channel_agent_test_capability(self->_main, VD_AGENT_CAP_CLIPBOARD_BY_DEMAND)) {
  295. spice_main_channel_clipboard_selection_grab(self->_main, VD_AGENT_CLIPBOARD_SELECTION_CLIPBOARD, &type, 1);
  296. }
  297. }
  298. - (void)pasteboardDidRemove:(NSNotification *)notification {
  299. UTMLog(@"seen UIPasteboardRemovedNotification");
  300. if (!self.shareClipboard || self.sessionReadOnly) {
  301. return;
  302. }
  303. guint32 type = VD_AGENT_CLIPBOARD_UTF8_TEXT;
  304. if (spice_main_channel_agent_test_capability(self->_main, VD_AGENT_CAP_CLIPBOARD_BY_DEMAND)) {
  305. spice_main_channel_clipboard_selection_grab(self->_main, VD_AGENT_CLIPBOARD_SELECTION_CLIPBOARD, &type, 1);
  306. }
  307. }
  308. #pragma mark - Instance methods
  309. - (BOOL)sessionReadOnly {
  310. return spice_session_get_read_only(_session);
  311. }
  312. /* This will convert line endings if needed (between Windows/Unix conventions),
  313. * and will make sure 'len' does not take into account any trailing \0 as this could
  314. * cause some confusion guest side.
  315. * The 'len' argument will be modified by this function to the length of the modified
  316. * string
  317. */
  318. - (NSString *)fixupClipboardText:(NSString *)text {
  319. if (spice_main_channel_agent_test_capability(self->_main,
  320. VD_AGENT_CAP_GUEST_LINEEND_CRLF)) {
  321. char *conv = NULL;
  322. conv = spice_unix2dos([text cStringUsingEncoding:NSUTF8StringEncoding], text.length);
  323. text = [NSString stringWithUTF8String:conv];
  324. g_free(conv);
  325. }
  326. return text;
  327. }
  328. @end