Compare commits

...
Author SHA1 Message Date
osy b0b83b7f07 darwin: reopen the port when the VM is restored
Virtualization.framework does not restore the open state of the spice
port when it resumes a saved VM. The host then drops whatever the guest
writes to the port and never completes the write, which wedges the port
until the guest reboots: clipboard sharing stops working in both
directions and restarting the agents does not help.

The virtual RTC sends a message as soon as the VM is restored, so watch
for it and reopen the port before anything is written. Reopening tells
the host that the port is open again. Waiting for the clock change that
follows is too late: timed only steps the clock after an NTP round trip.

Resolves utmapp/UTM#7717

Assisted-by: Claude:claude-opus-5-5
2026-10-14 09:39:24 -07:00
osy 03ff810185 github: force universal archive build
xcodebuild does not read build settings from the shell environment, so
the ARCHS variable used to build GLib and gettext for both
architectures never reached the archive step. On the arm64 macos-15
runner this silently produced an arm64-only xcarchive/pkg instead of a
universal x86_64+arm64 binary.

Pass ARCHS and ONLY_ACTIVE_ARCH explicitly to xcodebuild archive so the
override takes effect regardless of the runner's host architecture.

Resolves #5

Assisted-by: Claude:claude-sonnet-5
2026-09-21 20:37:04 -05:00
osy 948db07d95 github: build on macos-15 runner
Newer Xcode versions only support deploying to macOS 12.0 and newer,
which breaks the project's 10.13 deployment target. Pin the runner to
macos-15, which defaults to Xcode 16.

Assisted-by: Claude:claude-opus-5
2026-09-21 19:37:41 -05:00
osy 7a9d859399 github: build GLib from source for arm64 and x86_64
Homebrew no longer supports x86_64, so installing it under Rosetta fails
in CI and the universal build has no x86_64 GLib to link against.

Build GLib and gettext (for libintl) from pinned upstream releases for
both architectures instead, based on Homebrew's glib formula. The
libraries target macOS 10.13 (11.0 on arm64) to match the project, and
availability errors are enabled to catch any use of newer APIs.

The Xcode project now takes the GLib locations from the
GLIB_ARM64_PREFIX and GLIB_X86_64_PREFIX build settings, which default
to the Homebrew paths so local builds are unchanged. The inputs of the
lipo phase are declared so they can be read with script sandboxing.

Assisted-by: Claude:claude-opus-5
2026-09-21 19:26:34 -05:00
osy 07005a1b0e Merge pull request #4 from pointum/fix-package-quarantine
Clear package quarantine
2026-09-21 17:51:12 -05:00
Maxim Ananov 37a74cf356 darwin: clear package quarantine 2026-08-16 16:13:19 -07:00
osy 15e4c3b63f data: update macOS package script to remove xattributes 2024-12-10 13:36:29 -08:00
osy 5ccfc993f4 readme: add notes for macOS 2024-11-18 01:59:26 -08:00
osy 9070c8ba4d darwin: add script to create installer 2024-11-18 01:48:31 -08:00
osy e4d0eea961 vdagentd: automatically switch session when security is disabled 2024-11-18 01:37:06 -08:00
osy c729770965 darwin: fix launch scripts 2024-11-17 22:34:41 -08:00
osy 38460ed519 darwin: fix build on Xcode 15.4 2024-11-17 20:05:32 -08:00
osy 684267abcb github: add CI 2024-11-17 20:05:32 -08:00
osy b788a2456c darwin: static link GLib, add LaunchDaemon 2024-11-17 13:41:51 -08:00
osy ee9ac60ad6 darwin: automatically download spice headers 2024-11-17 01:39:18 -08:00
osy 47e2539467 vdagent: support macOS NSPasteboard 2024-11-17 01:18:51 -08:00
osy 712c9ed7a6 vdagent: create new macOS agent 2024-11-16 17:45:12 -08:00
osy a395da3eeb vdagentd: add Xcode project for macOS build 2024-11-16 17:41:46 -08:00
Daniel Kahn Gillmor 553cb85f10 systemd services: add Documentation key (point to manpage) 2024-07-12 07:00:28 +00:00
Daniel Kahn Gillmor a3c361d829 Fix minor spelling errors.
This change was performed with:

```
codespell --ignore-words-list 'requestor' -w
```

("requestor" is part of the X11 API, and if we allow codespell to rewrite it it would fail to build)
2024-07-07 12:57:53 -04:00
Fabian Vogt aa08162f03 Switch to spice-vdagent.service by default
Add an [Install] section to the user unit and tell systemd to ignore the
.desktop file explicitly.

Also add missing ordering dependencies. Without this, the service fails if
it is started before e.g. $DISPLAY is set.
2023-02-09 10:22:01 +01:00
Victor Toso bcbbea34d9 vdagent: Remove watch event on vdagent_display_destroy()
To avoid main loop calling it when GIOChannel for x11 was already
destroyed.

Related: https://bugzilla.redhat.com/show_bug.cgi?id=2145004
Signed-off-by: Victor Toso <[email protected]>
2023-01-13 15:33:38 +01:00
Abderrahim Kitouni ed08813fcd Makefile.am: don't create /var/run/spice-vdagentd
/var/run is generally a symlink to /run, which is a tmpfs.
2022-09-28 07:38:52 +02:00
Victor Toso a9bb1752ce Release 0.22.1
Signed-off-by: Victor Toso <[email protected]>
2022-02-14 11:27:07 +01:00
Frediano Ziglio 0717474fec Do not process X11 events in vdagent_x11_create
Processing events requires some more initialisation between
VDAgentDisplay and vdagent_x11.
Postpone that after initialisation.
This fix a crash on Fedora 36, see
https://bugzilla.redhat.com/show_bug.cgi?id=2042877.

Signed-off-by: Frediano Ziglio <[email protected]>
2022-02-14 09:35:55 +00:00
Victor Toso 2289931e94 Release 0.22.0
Signed-off-by: Victor Toso <[email protected]>
2022-02-07 14:57:18 +01:00
Kevin PougetandJoan Bruguera 67090358b3 vdagentd/uinput: Handle side mouse buttons (BTN_SIDE and BTN_EXTRA)
Adds support for handling the side mouse buttons some mouses have, typically
used in web browsers for previous/next website in history.

spice-gtk requires a corresponding patch to capture and forward the buttons.

At the spice and protocol level, the required changes were previously merged:
* https://gitlab.freedesktop.org/spice/spice/-/issues/45
* https://gitlab.freedesktop.org/spice/spice/-/merge_requests/140
* https://gitlab.freedesktop.org/spice/spice-protocol/-/merge_requests/22

This commit is a rebased and revised version of the patch by Kevin Pouget:
https://www.spinics.net/lists/spice-devel/msg42582.html
(I have confirmed with him that it's OK that I submit the updated patches.)

Co-Authored-By: Kevin Pouget <[email protected]>
Co-Authored-By: Joan Bruguera <[email protected]>
2022-01-18 00:54:50 +01:00
Victor Toso 09de02fd5c udscs: udscs_connect: return error to caller
This way we can have the log in one place and avoid flooding the journal.

Signed-off-by: Victor Toso <[email protected]>
2021-12-20 19:09:48 +01:00
Victor Toso 1aa2c06015 vdagent: udscs: limit retry to connect to vdagentd
Related: https://bugzilla.redhat.com/show_bug.cgi?id=2005802
Related: https://bugzilla.redhat.com/show_bug.cgi?id=2028013
Signed-off-by: Victor Toso <[email protected]>
2021-12-20 19:09:48 +01:00
Adrian Bunk 8440e6010d configure.ac: autoconf 2.71 compatibility
"y" is not "set", but both have non-zero lengths.
2021-12-02 10:32:57 +00:00
Rex Dieter 3cd58713c9 Provide systemd user spice-vdagent.service 2021-07-16 11:07:39 -05:00
Maxim Cournoyer 67f3f3ed35 tests: Invoke ps in a way that does not truncate wide output.
By default, 'ps' truncates its output to about 100 characters.  The
test-termination test depends on finding the socket file name in the
output of the 'ps' command; it could fail depending on the file name
length of the directory where the test was run.

* tests/test-termination.c (get_daemon_pid) <ps>: Invoke with the -ww
option to preserve all the output.
2021-05-06 10:45:27 -04:00
Marc-André Lureau 8348ef3c61 Fix g_memdup deprecation warning with glib >= 2.68
Related to:
https://bugzilla.redhat.com/show_bug.cgi?id=1943059

Signed-off-by: Marc-André Lureau <[email protected]>
2021-05-04 13:20:51 +04:00
Chris Mayo 0105b280cb build: replace bashism in configuration for GTK 4
Else with dash as /bin/sh, GTK 4 support cannot be selected.
2021-03-25 19:31:44 +00:00
Julien Ropé 9306f18621 Release 0.21.0
Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2021-01-13 09:52:43 +01:00
Julien Ropé 58d97554e5 Use the Mutter API from display.c
Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-11-19 15:40:13 +01:00
Julien Ropé 73bf836726 Add implementation of the DBUS interface to Mutter.
This can be used to retrieve monitor resolutions directly from the
Mutter compositor under Wayland.
Under environments using a different compositor, the X11 lib will keep
being used.

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-11-19 15:40:02 +01:00
Julien Ropé 21d355974f Move some reusable code at a higher level.
Adding disabled displays to the list is something that we will need to
do
with multiple backends, not just GTK.

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-11-19 15:39:32 +01:00
Julien Ropé 9750013f0e Make the connector mappings available whatever the build options
Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-11-19 15:39:17 +01:00
Jakub Janků 1d40f0e967 ci: run checks only with --with-session-info=none
In the container environment, neither systemd nor
console kit is running, thus test-session-info fails.
To fix the pipeline, run "make distcheck" with the
aforementioned option, which disables this test.

Signed-off-by: Jakub Janků <[email protected]>
2020-11-15 16:59:02 +01:00
Jakub Janků aa792598ea build: test session info only with non-dummy implementation
The test, as it is written at the moment, only makes sense
with console-kit or systemd implementation. With the dummy one,
the test fails, but it's not an error in the vdagent code.

Signed-off-by: Jakub Janků <[email protected]>
2020-11-15 15:46:47 +01:00
Jakub Janků 396c2b2c7d build: test-session-info: include only what's necessary
The test doesn't depend on udscs.c in common_sources,
for example, so don't include it.

Signed-off-by: Jakub Janků <[email protected]>
2020-11-15 15:43:41 +01:00
Jakub Janků 8bffaaf3e5 test-session-info: rename misleading "ck_uid"
The source code refers to "console-kit uid",
but we have console-kit as well as systemd and
dummy implementation of session-info.

Signed-off-by: Jakub Janků <[email protected]>
2020-11-15 15:08:40 +01:00
Frediano Ziglio 5094d5cfe6 Add a test for session_info
Test from Uri, integrated in test suite.

Signed-off-by: Uri Lublin <[email protected]>
Signed-off-by: Frediano Ziglio <[email protected]>
2020-11-03 09:45:08 +00:00
Uri Lublin b7db1c20c9 vdagentd: do not allow to use an already used file-xfer id
Signed-off-by: Uri Lublin <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-11-03 09:44:05 +00:00
Uri Lublin e4bfd1b632 cleanup active_xfers when the client disconnects
Signed-off-by: Uri Lublin <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-11-03 09:43:32 +00:00
Frediano Ziglio 812ca77746 vdagentd: Limit number of agents per session to 1
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Uri Lublin <[email protected]>
2020-10-29 14:59:18 +00:00
Frediano Ziglio 5c50131797 Better check for sessions
Do not allow other users to hijack a session checking that
the process is launched by the owner of the session.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Uri Lublin <[email protected]>
2020-10-29 14:59:18 +00:00
Frediano Ziglio 51c415df82 Avoids user session hijacking
Avoids user hijacking sessions by reusing PID.
In theory an attacker could:
- open a connection to the daemon;
- fork and exit the process but keep the file descriptor open
  (inheriting or duplicating it in forked process);
- force OS to recycle the initial PID, by creating many short lived
  processes.
Daemon would detect the old PID as having the new session.
Check the user to avoid such replacements.

This issue was reported by SUSE security team.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Uri Lublin <[email protected]>
2020-10-29 14:59:18 +00:00
Frediano Ziglio 91caa92238 Avoids unlimited agent connections
Limit the number of agents that can be connected.
Avoids reaching the maximum number of files in a process.
Beside one file descriptor per agent the daemon open just some
other fixed number of files.

This issue was reported by SUSE security team.

Signed-off-by: Frediano Ziglio <[email protected]>
2020-10-29 14:59:18 +00:00
Frediano Ziglio 9d35d8a86f Avoids uncontrolled "active_xfers" allocations
Limit the number of active file transfers possibly causing DoSes
consuming memory in "active_xfers".

This issue was reported by SUSE security team.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Uri Lublin <[email protected]>
2020-10-29 14:59:18 +00:00
Frediano Ziglio 1a8b93ca6a Avoids unchecked file transfer IDs allocation and usage
Avoid agents allocating file transfers.
The "active_xfers" entries are now inserted when client start sending
files.
Also different agents cannot mess with other agent transfers as a
transfer is bound to a single agent.

This issue was reported by SUSE security team.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Uri Lublin <[email protected]>
2020-10-29 14:59:18 +00:00
Frediano Ziglio ce144335ff vdagentd: Avoid calling chmod
Create the socket with the right permissions using umask.
This also prevents possible symlink exploitation in case socket
path is not secure.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Uri Lublin <[email protected]>
2020-10-29 14:59:18 +00:00
Jakub Janků 5a2471e24e x11-randr: fix leak on vdagent_x11 destroy
In vdagent_x11_destroy(), only x11->randr.failed_conf is freed
and x11->randr.{res, outputs, crtcs} are left allocated.

To fix it, create a new function vdagent_x11_randr_destroy()
that frees all randr resources, and call it from vdagent_x11_destroy().

Signed-off-by: Jakub Janků <[email protected]>
2020-10-28 17:07:21 +01:00
Julien Ropé 0c5b8fac09 CI: fix build failure
With latest fedora container using F33, we get gtk4 3.99, where vulkan is
enabled by default.
This require to get the vulkan headers as a dependency.

Signed-off-by: Julien Ropé <[email protected]>
2020-10-27 12:07:24 +01:00
Frediano Ziglio 8698e1e5cc vdagentd: Fix clipboard serial for big endian machines
The GUINT32_TO_LE in case of big endian machine can expand
the argument multiple times so avoid to pass argument that
could have side effects.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Julien Ropé <[email protected]>
2020-10-21 16:19:47 +01:00
Frediano Ziglio aab670b3b7 vdagentd: Simplify handling VD_AGENT_GRAPHICS_DEVICE_INFO
g_free does nothing if pointer is NULL.
device_info and device_info_size will be overwritten in any case.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Julien Ropé <[email protected]>
2020-10-21 16:08:22 +01:00
Frediano Ziglio e73e330e99 vdagentd: Constify vdagent_message_min_size
The array is not supposed to be changed.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Julien Ropé <[email protected]>
2020-10-21 16:06:58 +01:00
Julien Ropé 9574a4299f When using GTK for monitors, we should not update the X11 structures.
X11 events are still used to notify the daemon of monitor resolution
changes, but the X11 structures themselves do not need to be updated,
because we will get all required informations from the GTK library.

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-10-19 17:59:19 +02:00
Julien Ropé 5ab5fe3475 Using GTK, there is no way to modify the monitor resolution.
Since vdagent_x11_set_monitor_config() can work only under the X11
backend, make sure we don't call it when under Wayland - it will fail
anyway.

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-10-19 17:59:11 +02:00
Julien Ropé 6c475b368d Send guest resolution using GDK functions.
- Implement the vdagent_gtk_get_resolutions() function.
  Use gdk_monitor_*() functions to retrieve the resolution of each
monitor. Associate them to the right display ID using the
connector_mapping hash

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-10-19 17:59:03 +02:00
Julien Ropé 4c80090681 Split the "lookup_xrandr_output_for_device_info()" function to reuse
some of it with different backends.

Most display drivers will number their outputs starting with "1", but
some (like older QXL drivers) will start from 0.
As we need to map device names with SPICE display IDs, we need to know
what to expect.

The logic that finds whether we have a O-based index or not is
independent from the backend, and can be reused outside of the X11
implementation.

This commit separates this logic for that purpose, to prevent code
duplication.
- create the has_zero_based_display_id() function to call whatever the
  backend, and learn whether our IDs should be decremented or not.
  Its code is taken out of lookup_xrandr_output_for_device_info()
- keep the lookup_xrandr_output_for_device_info() for x11 implementation
- add parameters to some functions to give them the information that IDs
  should be decremented because of the 0-based index.

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-10-19 17:58:54 +02:00
Julien Ropé d92f37ae06 Prepare mapping based on connector name.
Split the lookup_xrandr_output_for_device_info to access the part
retrieving the expected connector name.
Call that separate function in the "non-X11" part of the code, and use a
hashtable to map Spice display ID to its expected connector name.
This hashtable will later be used when we need to report resolution
changes to the daemon/server.

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-10-19 17:58:43 +02:00
Julien Ropé f59192a021 Copy the 'debug' flag and 'vdagentd' socket into the VDAgentDisplay
structure.

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-10-19 17:58:29 +02:00
Julien Ropé 6e5e6c2ca6 Add a non-X11 function to send the guest resolution to the
daemon/server.

The purpose here is to further separate X11-specific code, and have the
actual sending to the daemon to be out of X11 code, and reusable by
other APIs.

- Replace vdagent_x11_send_daemon_guest_res() with a function that
builds
  and returns the list of monitor resolutions.
- Create the vdagent_display_send_daemon_guest_res() that uses this to
  send the resolutions to the daemon.
- Call this function in place of vdagent_x11_send_daemon_guest_res()

In later commits, we will be able to use a different API to generate
the list of monitor resolution, without having to change the X11 code.

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-10-19 17:58:12 +02:00
Frediano Ziglio 8c4137de70 ci: Upload test results in case of failure
Allows to see tests results in case "make check" fails.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-10-05 09:54:44 +01:00
Jakub Janků 09733a5c81 clipboard: enable copying files from client using webdav
When the user wants to copy files, new spice-gtk can share those
files using the existing phodav server. In that case, it advertises
the VD_AGENT_CLIPBOARD_FILE_LIST type in the clipboard grab message.

Upon request of the clipboard data in the mentioned type, spice-gtk
provides a list of absolute paths in the phodav server - these are
the files that are supposed to be copied/moved.

The role of the vdagent is to:
1) ensure that the phodav share is mounted,
2) adjust the provided paths given the mountpoint,
3) provide the uri list in various formats depending on which one
   was requested (different file managers use differenct formats)

The code that accomplishes these tasks is located in a new file
webdav-cb.c - the main reason for it is that vdagent currently
supports two clibpoard backends: x11, gtk+.

Implement this new feature only in the x11 backend since
the future of the gtk+ one is not clear.

Copy and move was tested with GNOME Nautilus, KDE Dolphin,
Cinnamon Nemo, Mate Caja, Xfce Thunar, LXDE PCManFM, Krusader.
The functionality with other file managers might be limited.

Copying files from the vdagnet side to the client is not
supported yet.

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-09-28 10:46:09 +01:00
Jakub Janků 2e2feeb93b build: require spice-protocol 0.14.3
This adds the VD_AGENT_CLIPBOARD_FILE_LIST
necessary for the following commits.

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-09-28 10:46:06 +01:00
Jakub Janků 0da3211f63 x11: move code to clipboard_data_send_to_requestor()
With the upcoming patch, clipboard data will be sent to the
requestor outside of vdagent_x11_clipboard_data() so
extract the necessary code into a new function to avoid
repetition.

The function takes "take_ownership" argument. If set to True,
the caller doesn't have to free the passed data which will
also be useful with the following changes.

Improve style by adding brackets to single-line if statements.

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-09-28 10:46:03 +01:00
Frediano Ziglio 1f4a994ff1 audio: Change percentage formatting
Use XX% instead of %XX.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-09-25 16:01:21 +01:00
Frediano Ziglio 253539275a audio: Set range instead of reading and adjusting
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-09-25 16:01:19 +01:00
Frediano Ziglio f30becd21f audio: Fix number rounding
Avoid truncation due to integer arithmetic.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-09-25 16:01:14 +01:00
Frediano Ziglio 7e924bcbf0 vdagentd: Better check for vdagent_connection_get_peer_pid results
The function can return -1 and leave "err" to NULL in some cases,
do not check only for "err".

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Julien Ropé <[email protected]>
2020-09-22 12:34:17 +01:00
Frediano Ziglio b894975bed vdagent-connection: Pass "err" to g_credentials_get_unix_pid
Allows to return detailed information if g_credentials_get_unix_pid
fails.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Julien Ropé <[email protected]>
2020-09-22 12:34:04 +01:00
Frediano Ziglio b4479eb9b0 vdagentd: Automatically release "agent_data"
It's not guaranteed that agent_disconnect will release the connection
so avoid to have a dandling pointer.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-09-21 15:22:16 +01:00
Frediano Ziglio 9f768c6037 vdagentd: Make some agent_data variable constant
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-09-21 15:22:14 +01:00
Frediano Ziglio 4983eb1f42 vdagentd: Make pidfilename a constant
No need to be a variable

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-09-21 15:22:11 +01:00
Frediano Ziglio 7e37b05774 vdagentd: Use bool for agent_owns_clipboard and client_connected
More clear (instaed of 0/1) and save some bytes.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-09-21 15:22:09 +01:00
Frediano Ziglio 27805752fe console-kit: Do not mix GLib and libc memory allocations
Use always GLib functions for "seat" and "active_session" fields.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-09-21 15:22:04 +01:00
Julien Ropé ca4dd7e811 Enable GTK4 build with a specific configure option.
- Adding the "--with-gtk4" option to ask for GTK4, keeping it separate
from
  the default "--with-gtk" so that we can still build the agent with
GTK3.
  GTK4 will be used to solve several issues under Wayland related to
  multi-monitor situations.
- Change some calls to be compatible with modified API.
- Also add a build test to CI script.

Important note about the clipboard:
Using the Wayland backend in GTK is introducing new issues with
clipboard
that we can't fix for now.
So when building for GTK4, we will actually not use GTK for the
clipboard.

To achieve this, some build definitions are modified:
- WITH_GTK is kept, but is only used for GTK initialization and header
import
- WITH_GTK is replaced by USE_GTK_FOR_CLIPBOARD for all
clipboard-specific
  code. It is enabled when building with GTK3.
- USE_GTK_FOR_MONITORS is added, and will be used for monitor-specific
  code. It is enabled when building with GTK4.

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-07-29 14:32:34 +02:00
Frediano Ziglio 65f64b805b vdagent-connection: Avoid leak if write callback is cancelled
g_object_unref is not called if out_stream_ready_cb source is
cancelled.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janku <[email protected]>
2020-07-25 14:36:28 +01:00
Frediano Ziglio 87c031a6a8 clipboard: Define "conn" field only using GTK
Not used anywhere else.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-07-22 11:58:32 +01:00
Frediano Ziglio ffba3a0e2d x11: Remove "fd" field
No much reason to cache it, used only in initialization

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-07-22 11:58:29 +01:00
Frediano Ziglio a5932875c2 x11: Move "xrandr_event_base" inside "randr" structure
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-07-22 11:58:27 +01:00
Frediano Ziglio a020b8e925 x11: Remove only written "has_xfixes" field
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2020-07-22 11:58:21 +01:00
Julien Ropé ef54256abf Use RROutput directly in guest_output_map.
No need to allocate a separate variable - the RROutput value can be used
directly in the hashtable.

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-07-15 10:33:38 +01:00
Julien Ropé 1601f4de95 Move more code from x11.c to display.c
Moving the non-X11 part of the code related to
"vdagent_x11_has_icon_on_desktop()".
Turns out most of it is disabled anyway when we build with GTK.

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-07-15 10:33:36 +01:00
Julien Ropé aa75e9d792 Move handle_graphics_device_info code to generic display functions
Most of the code in vdagent_x11_handle_graphics_device_info() is dealing
with SPICE information, only a few of it is X11-specific.
Move that code away from x11-randr.c so that we can use it with Wayland.

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-07-15 10:31:24 +01:00
Julien Ropé 2f025381f8 Split X11-specific code from the core agent code
This commit adds a set of functions (vdagent_display_*) that separates the
agent's code from the underlying backend used for handling monitor
events/settings.
Today, this does not change the behaviour of the agent, as those functions
will just call the existing X11 functions. But we will later add code to
them to support other means of dealing with monitors (i.e: Wayland
support).

Signed-off-by: Julien Ropé <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-07-15 10:31:08 +01:00
Frediano Ziglio 98f05ec1fe ci: Add missing dependency
Code requires libdrm.
In Fedora 31 this was included by some dependent package, but
Fedora 32 requires explicit dependency.

Signed-off-by: Frediano Ziglio <[email protected]>
2020-07-10 09:51:48 +01:00
Jakub Janků 9721c99396 x11: cache atom names in vdagent_x11_get_atom_name()
XGetAtomName() returns a new string that should be freed,
when no longer needed, but the current impl doesn't do that.

To preserve the ease of use for debugging purposes,
cache the atom names and free them when the cache is full
and when the x11 struct is destroyed.

Fixes: https://gitlab.freedesktop.org/spice/linux/vd_agent/-/issues/22

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-06-30 10:58:01 +01:00
Kevin Pouget 8adf50de9a vdagent: replace last call to g_debug(...) by syslog(LOG_DEBUG, ...)
Fixes #21 by avoiding to set `G_MESSAGES_DEBUG=all` to learn that the
vdagent failed to load because of missing virtio channel.

If the debug flag is not set, the vdagent remains silent, as defined
with 149bba9162 / #12.

Signed-off-by: Kevin Pouget <[email protected]>
2020-05-20 11:33:13 +02:00
Frediano Ziglio d0b5f80ada Fix possible compile error using former GLib2 version
We require GLib 2.50 but G_SOURCE_FUNC was introduced in version
2.58. Do the conversion instead of using G_SOURCE_FUNC macro.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-05-11 16:46:10 +01:00
Frediano Ziglio 5654f4d2f9 systemd-login: Avoid a crash on container
On containers dbus could be not running.
In this case dbus.system_connection is NULL and calling
dbus_connection_close on it will cause a crash.
This happens also under Gitlab CI.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-26 15:43:15 +00:00
Frediano Ziglio eeb5620260 test-termination: Check daemon terminates correctly sending SIGTERM
Check for https://gitlab.freedesktop.org/spice/linux/vd_agent/issues/18.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-26 15:43:10 +00:00
Jakub Janků 7b0435ef66 vdagentd: init static uinput before fork
Otherwise the caller doesn't know that the init failed
because we're returning 0 in the parent and 1 in child.

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-03-26 10:27:41 +00:00
Jakub Janků 9b8c0ebb9f vdagentd: work around GLib's fork issues
Creating threads is not compatible with forking as only the thread
that calls fork() is inherited.

Handlers registered with g_unix_signal_add() create a thread so
move these calls after fork.

Also call g_socket_service_start() after fork to avoid creation of
new threads before it is necessary.

Fixes: https://gitlab.freedesktop.org/spice/linux/vd_agent/issues/18

Also see: https://gitlab.gnome.org/GNOME/glib/issues/2073

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2020-03-26 10:27:38 +00:00
Victor Toso bfbb63d3ae Release 0.20.0
Signed-off-by: Victor Toso <[email protected]>
2020-03-10 13:54:29 +01:00
Victor Toso 3b4b4d025d ci: Use meson instead of autotools in spice-protocol
It was dropped in git master.

Signed-off-by: Victor Toso <[email protected]>
2020-03-09 21:31:12 +01:00
Aral Balkan 70d57b3357 Add basic installation instructions to the readme
Acked-by: Victor Toso <[email protected]>
2020-03-09 20:19:22 +01:00
Jakub Janků e6c14d0ecc udscs-server: split initialization
Divide creation of udscs_server into 2 steps:

1) udscs_server_new()
 - allocates new udscs_server struct and inits it

2) udscs_server_listen_to_fd(), udscs_server_listen_to_address()
 - starts accepting new connections

Remove udscs_create_server() and udscs_create_server_for_fd().

This makes the code a bit shorter and nicer.

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-09 20:12:50 +01:00
Jakub Janků ab7901ced4 virtio: use GObject macro
Use G_DECLARE_FINAL_TYPE().

Rename
struct vdagent_virtio_port --> VirtioPort

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-09 20:12:47 +01:00
Jakub Janků 15f710dade udscs: use GObject macro
Use G_DECLARE_FINAL_TYPE().

Rename
struct udscs_connection --> UdscsConnection

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-09 20:12:44 +01:00
Jakub Janků 3257a1f732 introduce VDAgentConnection
1) VDAgentConnection

Add vdagent-connection.{c,h} files,
define a new derivable class VDAgentConnection.

VDAgentConnection uses GIO and therefore integrates well with GMainLoop.

Read messages must begin with a header of a fixed size.
Message body size can vary.

Note:
vdagent_connection_destroy() cancels ongoing I/O-ops
and closes the underlying FD.
However, the I/O-ops do not finish immediately,
but asynchronously in the next iteration of the main loop.
At the beginning of each op, VDAgentConnection is referenced,
so the object isn't finalized until the ops themselves finish.
To solve this, call g_main_context_iteration() before the agent exits.

2) udscs

Make udscs_connection a subclass of VDAgentConnection.

Rewrite udscs_server using GSocketService.
Use GList to store server's connections.

Drop support for select(), remove:
 * udscs_server_fill_fds()
 * udscs_server_handle_fds()

Remove udscs_{set,get}_user_data(). Custom data can be
associated with the GObject using g_object_set_data().

3) virtio_port

Make vdagent_virtio_port a subclass of VDAgentConnection.

Drop support for select(), remove:
 * vdagent_virtio_port_fill_fds()
 * vdagent_virtio_port_handle_fds()

4) vdagentd

Replace the main_loop() with a GMainLoop.

Use g_unix_signal_add() to handle SIGINT, SIGHUP, SIGTERM.
SIGQUIT handling is not supported by GLib.

Integrate the session_info into the loop using
GIOChannel and g_io_add_watch().

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-09 20:12:39 +01:00
Jakub Janků 5c136cb3a3 build: add GIO dependency
Require UNIX-specific GIO package to build spice-vdagent.

This package includes:

- GDBus which is going to be used instead of libdbus in
  console-kit.c and systemd-login.c

- I/O stream classes and networking APIs that are going to
  be used in VDAgentConnection

Version 2.44 is required because of the following definitions:
- g_input_stream_read_all_*
- g_output_stream_write_all_*
- GSimpleIOStream

GIO requires GLib and GObject, so we can depend solely on it.

GLib version across different distributions:
    Fedora 30:    2.60
    Fedora 29:    2.58
    Fedora 28:    2.56

    RHEL 7.6:     2.56
    RHEL 7.5:     2.54
    RHEL 7.4:     2.50

    Debian 10:    2.58
    Debian 9:     2.50
    Debian 8:     2.42

    Ubuntu 19.04: 2.60
    Ubuntu 18.04: 2.56
    Ubuntu 16.04: 2.48

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-09 20:12:34 +01:00
Marc-André Lureau a2fc33cbc7 clipboard: implement CAP_CLIPBOARD_GRAB_SERIAL
Implement the behaviour described in protocol "vdagent: introduce
VD_AGENT_CAP_CLIPBOARD_GRAB_SERIAL".

Signed-off-by: Marc-André Lureau <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-06 10:07:02 +01:00
Marc-André Lureau c9e806722b clipboard: only send release when no immediate grab
Do not send a release event between two grabs, this helps with window
manager interaction issues on peer side.

Advertise this behaviour via a capability introduced in spice-protocol
0.12.16, so the client doesn't need to do some time-based filtering.

(the capability shouldn't need to be negotiated, a client shouldn't
expect a release between two grabs)

Signed-off-by: Marc-André Lureau <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-06 10:06:50 +01:00
Marc-André Lureau 2ad6c158ff clipboard: filter out only our own events
Do not rely on internal state when receiving clipboard events, as this
may race with external events. Use gtk_clipboard_set_with_owner()

Signed-off-by: Marc-André Lureau <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-06 10:06:46 +01:00
Marc-André Lureau aa26d1d95b clipboard: gobject-ify VDAgentClipboards
This will allow easier lifecycle management,
and usage of gtk_clipboard_set_with_owner()

Signed-off-by: Marc-André Lureau <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-06 10:06:43 +01:00
Marc-André Lureau fb69a49828 vdagent: use G_OPTION_FLAG_NONE
Improve readability a bit, reindent slightly.

Signed-off-by: Marc-André Lureau <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-06 10:06:38 +01:00
Marc-André Lureau ff30f58701 configure: bump gobject >= 2.50
This is required for using the new GObject macros.

According to commit 61fc548fe1 ("Bump
GLib version to 2.34"), RHEL6 is no longer supported.

GLib version across some distributions, from repology:
- Debian Stable (9): 2.50.3
- CentOS 7: 2.56.1
- Fedora 26: 2.52.3 (fwiw, Fedora 30: 2.60.0)

Signed-off-by: Marc-André Lureau <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-06 10:06:34 +01:00
Marc-André Lureau 79d012503f configure: depend on gobject
The following patches are going to introduce GObject.  It's not a big
change, since usually glib comes installed with gobject on most systems.

Signed-off-by: Marc-André Lureau <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-06 10:06:31 +01:00
Marc-André Lureau 2c723788c0 clipboard: remove vdagent-selection-id usage
Modernize a bit the code, using gtk_clipboard_get_selection().

Signed-off-by: Marc-André Lureau <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-06 10:06:26 +01:00
Marc-André Lureau e0bfa678ae configure: bump gtk+ >= 3.22
According to repology,
- Debian Stable (9): 3.22.11
- CentOS 7: 3.22.30
- Fedora 26: 3.22.21 (fwiw, Fedora 30: 3.24.7)

Signed-off-by: Marc-André Lureau <[email protected]>
Acked-by: Victor Toso <[email protected]>
2020-03-06 10:06:22 +01:00
Benjamin Berg b67ff71f1b vdagentd: Fix session lookup for new GNOME versions
New GNOME versions have started to manage the session using the systemd
user instance. The effect of this is that the spice-vdagent running in
the user session is forked off (indirectly) from the systemd user
instance and does technically not belong to any session.

The correct way of handling this situation is to simply assume that the
process belongs to the users graphical session. Add a heuristic to find
the graphical session based on the UID, fixing spice-vdagent running on
GNOME 3.34 with systemd integration.

Acked-by: Victor Toso <[email protected]>
2019-10-17 11:53:51 +02:00
Uri Lublin f807e98bb6 virtio-port: handle_fds: make read and write code consistent
A comment and curly brackets for style were added.

Signed-off-by: Uri Lublin <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-08-31 09:23:57 +01:00
Victor Toso 56a65ad1c6 covscan: add comment on false-positive on g_memdup()
Previous commit set last element of orig_argv array to NULL.
That's redundant as g_memdup() uses memcpy() and it would do
just that. Add a comment that the reason for this change is
to workaround clang's warning.

Suggested by Uri.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Uri Lublin <[email protected]>
2019-08-28 14:39:07 +02:00
Victor Toso cedab5fe0e covscan: initialize argv's copy
Otherwise we get a CLANG_WARNING due accessing garbage.

Covscan report:
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:471:9: warning: 1st function call argument is an uninitialized value
 > #        execvp(orig_argv[0], orig_argv);
 > #        ^      ~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:421:24: note: Storing uninitialized value
 > #    char **orig_argv = g_memdup(argv, sizeof(char*) * (argc+1));
 > #                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:434:9: note: Assuming 'error' is equal to NULL
 > #    if (error != NULL) {
 > #        ^~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:434:5: note: Taking false branch
 > #    if (error != NULL) {
 > #    ^
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:442:9: note: Assuming 'portdev' is not equal to NULL
 > #    if (portdev == NULL)
 > #        ^~~~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:442:5: note: Taking false branch
 > #    if (portdev == NULL)
 > #    ^
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:445:9: note: Assuming 'vdagentd_socket' is not equal to NULL
 > #    if (vdagentd_socket == NULL)
 > #        ^~~~~~~~~~~~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:445:5: note: Taking false branch
 > #    if (vdagentd_socket == NULL)
 > #    ^
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:448:30: note: Assuming 'do_daemonize' is 0
 > #    openlog("spice-vdagent", do_daemonize ? LOG_PID : (LOG_PID | LOG_PERROR),
 > #                             ^~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:448:30: note: '?' condition is false
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:451:9: note: Assuming the condition is false
 > #    if (!g_file_test(portdev, G_FILE_TEST_EXISTS)) {
 > #        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:451:5: note: Taking false branch
 > #    if (!g_file_test(portdev, G_FILE_TEST_EXISTS)) {
 > #    ^
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:457:9: note: Assuming 'do_daemonize' is 0
 > #    if (do_daemonize)
 > #        ^~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:457:5: note: Taking false branch
 > #    if (do_daemonize)
 > #    ^
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:468:9: note: Assuming 'version_mismatch' is not equal to 0
 > #    if (version_mismatch) {
 > #        ^~~~~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:468:5: note: Taking true branch
 > #    if (version_mismatch) {
 > #    ^
 > spice-vdagent-0.19.0/src/vdagent/vdagent.c:471:9: note: 1st function call argument is an uninitialized value
 > #        execvp(orig_argv[0], orig_argv);
 > #        ^      ~~~~~~~~~~~~
 > #  469|           syslog(LOG_INFO, "Version mismatch, restarting");
 > #  470|           sleep(1);
 > #  471|->         execvp(orig_argv[0], orig_argv);
 > #  472|       }
 > #  473|

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Uri Lublin <[email protected]>
2019-08-27 16:09:07 +02:00
Victor Toso 83d2dbba24 covscan: avoid false positive on g_clear_pointer()
This is a CLANG_WARNING found by covscan. It is a false positive as
g_clear_pointer() does set vportp to NULL, meaning that the situation
described by covscan below should not be reached. Moving away from
g_clear_pointer() in this specific case just to make our tool happy.

Covscan report:
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:458:9: warning: Use of memory after it is freed
 > #    if (wbuf->write_pos != wbuf->size) {
 > #        ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:268:12: note: Assuming the condition is true
 > #    while (*vportp && (*vportp)->write_buf)
 > #           ^~~~~~~
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:268:12: note: Left side of '&&' is true
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:268:5: note: Loop condition is true.  Entering loop body
 > #    while (*vportp && (*vportp)->write_buf)
 > #    ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:269:9: note: Calling 'vdagent_virtio_port_do_write'
 > #        vdagent_virtio_port_do_write(vportp);
 > #        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:453:5: note: Taking false branch
 > #    if (!wbuf) {
 > #    ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:458:9: note: Assuming the condition is false
 > #    if (wbuf->write_pos != wbuf->size) {
 > #        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:458:5: note: Taking false branch
 > #    if (wbuf->write_pos != wbuf->size) {
 > #    ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:465:9: note: Assuming 'n' is < 0
 > #    if (n < 0) {
 > #        ^~~~~
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:465:5: note: Taking true branch
 > #    if (n < 0) {
 > #    ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:466:13: note: Assuming the condition is false
 > #        if (errno == EINTR)
 > #            ^~~~~~~~~~~~~~
 > /usr/include/errno.h:38:16: note: expanded from macro 'errno'
 > ## define errno (*__errno_location ())
 > #               ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:466:9: note: Taking false branch
 > #        if (errno == EINTR)
 > #        ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:469:9: note: Calling 'vdagent_virtio_port_destroy'
 > #        vdagent_virtio_port_destroy(vportp);
 > #        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:130:5: note: Taking false branch
 > #    if (!vport)
 > #    ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:133:9: note: Assuming the condition is false
 > #    if (vport->disconnect_callback)
 > #        ^~~~~~~~~~~~~~~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:133:5: note: Taking false branch
 > #    if (vport->disconnect_callback)
 > #    ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:137:5: note: Loop condition is true.  Entering loop body
 > #    while (wbuf) {
 > #    ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:140:9: note: Memory is released
 > #        g_free(wbuf);
 > #        ^~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:137:5: note: Loop condition is false. Execution continues on line 144
 > #    while (wbuf) {
 > #    ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:144:5: note: Loop condition is true.  Entering loop body
 > #    for (i = 0; i < VDP_END_PORT; i++) {
 > #    ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:144:5: note: Loop condition is true.  Entering loop body
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:144:5: note: Loop condition is true.  Entering loop body
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:144:5: note: Loop condition is false. Execution continues on line 148
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:149:5: note: Assuming '_p' is null
 > #    g_clear_pointer(vportp, g_free);
 > #    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 > /usr/include/glib-2.0/glib/gmem.h:124:9: note: expanded from macro 'g_clear_pointer'
 > #    if (_p)                                                                    \
 > #        ^~
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:149:5: note: Taking false branch
 > /usr/include/glib-2.0/glib/gmem.h:124:5: note: expanded from macro 'g_clear_pointer'
 > #    if (_p)                                                                    \
 > #    ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:149:5: note: Loop condition is false.  Exiting loop
 > /usr/include/glib-2.0/glib/gmem.h:114:3: note: expanded from macro 'g_clear_pointer'
 > #  G_STMT_START {                                                               \
 > #  ^
 > /usr/include/glib-2.0/glib/gmacros.h:346:23: note: expanded from macro 'G_STMT_START'
 > ##define G_STMT_START  do
 > #                      ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:469:9: note: Returning; memory was released
 > #        vdagent_virtio_port_destroy(vportp);
 > #        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:269:9: note: Returning; memory was released
 > #        vdagent_virtio_port_do_write(vportp);
 > #        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:268:12: note: Left side of '&&' is true
 > #    while (*vportp && (*vportp)->write_buf)
 > #           ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:268:5: note: Loop condition is true.  Entering loop body
 > #    while (*vportp && (*vportp)->write_buf)
 > #    ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:269:9: note: Calling 'vdagent_virtio_port_do_write'
 > #        vdagent_virtio_port_do_write(vportp);
 > #        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:453:5: note: Taking false branch
 > #    if (!wbuf) {
 > #    ^
 > spice-vdagent-0.19.0/src/vdagentd/virtio-port.c:458:9: note: Use of memory after it is freed
 > #    if (wbuf->write_pos != wbuf->size) {
 > #        ^~~~~~~~~~~~~~~
 > #  456|       }
 > #  457|
 > #  458|->     if (wbuf->write_pos != wbuf->size) {
 > #  459|           syslog(LOG_ERR, "do_write: buffer is incomplete!!");
 > #  460|           return;

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-08-27 15:00:53 +02:00
Frediano Ziglio 0b94306d2c x11: Change check to make code scanners not giving warning
Some code scanners (both Coverity and clang one) report that
prev_sel/prev_cond could be unreferenced while NULL.
Change condition to make clear a NULL pointer is not used.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-07-24 10:32:44 +01:00
Victor Toso 66935d134e device-info: remove g_list_length() on compare_addresses()
The g_list_length() function does iterate over both lists to compare
its length. Considering that we use this to check for true/false and
we will iterate again on both lists, we can do so once.

This also avoids covscan/clang warnings:

 | spice-vdagent-0.19.0/src/vdagent/device-info.c:216:27: warning: Access to field 'data' results in a dereference of a null pointer (loaded from variable 'lb')
 | #        PciDevice *devb = lb->data;
 | #                          ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:397:5: note: Taking false branch
 | #    if (!user_pci_addr) {
 | #    ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:407:22: note: Calling 'find_device_at_pci_address'
 | #    char *dev_path = find_device_at_pci_address(user_pci_addr, &vendor_id, &device_id);
 | #                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:329:5: note: Taking true branch
 | #    g_return_val_if_fail(pci_addr != NULL, NULL);
 | #    ^
 | /usr/include/glib-2.0/glib/gmessages.h:594:9: note: expanded from macro 'g_return_val_if_fail'
 | #     if G_LIKELY(expr) { } else                                         \
 | #        ^
 | /usr/include/glib-2.0/glib/gmacros.h:385:43: note: expanded from macro 'G_LIKELY'
 | ##define G_LIKELY(expr) (__builtin_expect (_G_BOOLEAN_EXPR((expr)), 1))
 | #                                          ^
 | /usr/include/glib-2.0/glib/gmacros.h:379:4: note: expanded from macro '_G_BOOLEAN_EXPR'
 | #   if (expr)                                    \
 | #   ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:329:5: note: Taking true branch
 | /usr/include/glib-2.0/glib/gmessages.h:594:6: note: expanded from macro 'g_return_val_if_fail'
 | #     if G_LIKELY(expr) { } else                                         \
 | #     ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:329:5: note: Loop condition is false.  Exiting loop
 | /usr/include/glib-2.0/glib/gmessages.h:593:40: note: expanded from macro 'g_return_val_if_fail'
 | ##define g_return_val_if_fail(expr,val)  G_STMT_START{                   \
 | #                                        ^
 | /usr/include/glib-2.0/glib/gmacros.h:346:23: note: expanded from macro 'G_STMT_START'
 | ##define G_STMT_START  do
 | #                      ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:330:5: note: Taking true branch
 | #    g_return_val_if_fail(device_id != NULL, NULL);
 | #    ^
 | /usr/include/glib-2.0/glib/gmessages.h:594:9: note: expanded from macro 'g_return_val_if_fail'
 | #     if G_LIKELY(expr) { } else                                         \
 | #        ^
 | /usr/include/glib-2.0/glib/gmacros.h:385:43: note: expanded from macro 'G_LIKELY'
 | ##define G_LIKELY(expr) (__builtin_expect (_G_BOOLEAN_EXPR((expr)), 1))
 | #                                          ^
 | /usr/include/glib-2.0/glib/gmacros.h:379:4: note: expanded from macro '_G_BOOLEAN_EXPR'
 | #   if (expr)                                    \
 | #   ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:330:5: note: Taking true branch
 | /usr/include/glib-2.0/glib/gmessages.h:594:6: note: expanded from macro 'g_return_val_if_fail'
 | #     if G_LIKELY(expr) { } else                                         \
 | #     ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:330:5: note: Loop condition is false.  Exiting loop
 | /usr/include/glib-2.0/glib/gmessages.h:593:40: note: expanded from macro 'g_return_val_if_fail'
 | ##define g_return_val_if_fail(expr,val)  G_STMT_START{                   \
 | #                                        ^
 | /usr/include/glib-2.0/glib/gmacros.h:346:23: note: expanded from macro 'G_STMT_START'
 | ##define G_STMT_START  do
 | #                      ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:331:5: note: Taking true branch
 | #    g_return_val_if_fail(vendor_id != NULL, NULL);
 | #    ^
 | /usr/include/glib-2.0/glib/gmessages.h:594:9: note: expanded from macro 'g_return_val_if_fail'
 | #     if G_LIKELY(expr) { } else                                         \
 | #        ^
 | /usr/include/glib-2.0/glib/gmacros.h:385:43: note: expanded from macro 'G_LIKELY'
 | ##define G_LIKELY(expr) (__builtin_expect (_G_BOOLEAN_EXPR((expr)), 1))
 | #                                          ^
 | /usr/include/glib-2.0/glib/gmacros.h:379:4: note: expanded from macro '_G_BOOLEAN_EXPR'
 | #   if (expr)                                    \
 | #   ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:331:5: note: Taking true branch
 | /usr/include/glib-2.0/glib/gmessages.h:594:6: note: expanded from macro 'g_return_val_if_fail'
 | #     if G_LIKELY(expr) { } else                                         \
 | #     ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:331:5: note: Loop condition is false.  Exiting loop
 | /usr/include/glib-2.0/glib/gmessages.h:593:40: note: expanded from macro 'g_return_val_if_fail'
 | ##define g_return_val_if_fail(expr,val)  G_STMT_START{                   \
 | #                                        ^
 | /usr/include/glib-2.0/glib/gmacros.h:346:23: note: expanded from macro 'G_STMT_START'
 | ##define G_STMT_START  do
 | #                      ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:334:5: note: Loop condition is true.  Entering loop body
 | #    for (int i = 0; i < 10; ++i) {
 | #    ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:340:13: note: Assuming the condition is false
 | #        if (stat(dev_path, &buf) != 0) {
 | #            ^~~~~~~~~~~~~~~~~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:340:9: note: Taking false branch
 | #        if (stat(dev_path, &buf) != 0) {
 | #        ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:355:13: note: Assuming the condition is false
 | #        if (realpath(sys_path, device_link) == NULL) {
 | #            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:355:9: note: Taking false branch
 | #        if (realpath(sys_path, device_link) == NULL) {
 | #        ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:361:36: note: Calling 'parse_pci_address_from_sysfs_path'
 | #        PciAddress *drm_pci_addr = parse_pci_address_from_sysfs_path(device_link);
 | #                                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:129:9: note: Assuming 'pos' is non-null
 | #    if (!pos) {
 | #        ^~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:129:5: note: Taking false branch
 | #    if (!pos) {
 | #    ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:136:9: note: Assuming 'pos' is non-null
 | #    if (!pos) {
 | #        ^~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:136:5: note: Taking false branch
 | #    if (!pos) {
 | #    ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:142:9: note: Assuming 'pos' is non-null
 | #    if (!pos) {
 | #        ^~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:142:5: note: Taking false branch
 | #    if (!pos) {
 | #    ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:146:27: note: Calling 'pci_address_new'
 | #    PciAddress *address = pci_address_new();
 | #                          ^~~~~~~~~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:61:12: note: Taking false branch
 | #    return g_new0(PciAddress, 1);
 | #           ^
 | /usr/include/glib-2.0/glib/gmem.h:279:42: note: expanded from macro 'g_new0'
 | ##define g_new0(struct_type, n_structs)                  _G_NEW (struct_type, n_structs, malloc0)
 | #                                                        ^
 | /usr/include/glib-2.0/glib/gmem.h:211:4: note: expanded from macro '_G_NEW'
 | #          if (__s == 1)                                         \
 | #          ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:61:12: note: Left side of '&&' is false
 | /usr/include/glib-2.0/glib/gmem.h:279:42: note: expanded from macro 'g_new0'
 | ##define g_new0(struct_type, n_structs)                  _G_NEW (struct_type, n_structs, malloc0)
 | #                                                        ^
 | /usr/include/glib-2.0/glib/gmem.h:213:40: note: expanded from macro '_G_NEW'
 | #          else if (__builtin_constant_p (__n) &&                \
 | #                                              ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:61:12: note: Null pointer value stored to field 'devices'
 | #    return g_new0(PciAddress, 1);
 | #           ^~~~~~~~~~~~~~~~~~~~~
 | /usr/include/glib-2.0/glib/gmem.h:279:42: note: expanded from macro 'g_new0'
 | ##define g_new0(struct_type, n_structs)                  _G_NEW (struct_type, n_structs, malloc0)
 | #                                                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 | /usr/include/glib-2.0/glib/gmem.h:217:12: note: expanded from macro '_G_NEW'
 | #            __p = g_##func##_n (__n, __s);                      \
 | #                  ^~~~~~~~~~~~~~~~~~~~~~~
 | <scratch space>:76:1: note: expanded from here
 | #g_malloc0_n
 | #^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:146:27: note: Returning from 'pci_address_new'
 | #    PciAddress *address = pci_address_new();
 | #                          ^~~~~~~~~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:149:5: note: Loop condition is true.  Entering loop body
 | #    while (pos) {
 | #    ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:150:26: note: Taking false branch
 | #        PciDevice *dev = g_new0(PciDevice, 1);
 | #                         ^
 | /usr/include/glib-2.0/glib/gmem.h:279:42: note: expanded from macro 'g_new0'
 | ##define g_new0(struct_type, n_structs)                  _G_NEW (struct_type, n_structs, malloc0)
 | #                                                        ^
 | /usr/include/glib-2.0/glib/gmem.h:211:4: note: expanded from macro '_G_NEW'
 | #          if (__s == 1)                                         \
 | #          ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:150:26: note: Left side of '&&' is false
 | /usr/include/glib-2.0/glib/gmem.h:279:42: note: expanded from macro 'g_new0'
 | ##define g_new0(struct_type, n_structs)                  _G_NEW (struct_type, n_structs, malloc0)
 | #                                                        ^
 | /usr/include/glib-2.0/glib/gmem.h:213:40: note: expanded from macro '_G_NEW'
 | #          else if (__builtin_constant_p (__n) &&                \
 | #                                              ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:152:9: note: Taking true branch
 | #        if (!parse_pci_device(pos + 1, next, dev)) {
 | #        ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:154:13: note:  Execution continues on line 159
 | #            break;
 | #            ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:361:36: note: Returning from 'parse_pci_address_from_sysfs_path'
 | #        PciAddress *drm_pci_addr = parse_pci_address_from_sysfs_path(device_link);
 | #                                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:362:9: note: Taking false branch
 | #        if (!drm_pci_addr) {
 | #        ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:367:14: note: Calling 'compare_addresses'
 | #        if (!compare_addresses(pci_addr, drm_pci_addr)) {
 | #             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:207:11: note: Assuming the condition is true
 | #    if (!(a->domain == b->domain
 | #          ^~~~~~~~~~~~~~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:207:11: note: Left side of '&&' is true
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:208:12: note: Assuming the condition is true
 | #        && g_list_length(a->devices) == g_list_length(b->devices))) {
 | #           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:207:5: note: Taking false branch
 | #    if (!(a->domain == b->domain
 | #    ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:212:35: note: 'lb' initialized to a null pointer value
 | #    for (GList *la = a->devices, *lb = b->devices;
 | #                                  ^~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:213:10: note: Assuming 'la' is not equal to NULL
 | #         la != NULL;
 | #         ^~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:212:5: note: Loop condition is true.  Entering loop body
 | #    for (GList *la = a->devices, *lb = b->devices;
 | #    ^
 | spice-vdagent-0.19.0/src/vdagent/device-info.c:216:27: note: Access to field 'data' results in a dereference of a null pointer (loaded from variable 'lb')
 | #        PciDevice *devb = lb->data;
 | #                          ^~
 | #  214|            la = la->next, lb = lb->next) {
 | #  215|           PciDevice *deva = la->data;
 | #  216|->         PciDevice *devb = lb->data;
 | #  217|
 | #  218|           if (deva->slot != devb->slot

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-07-24 10:32:37 +01:00
Frediano Ziglio af8d1948b1 x11: Constify XEvent argument
No reasons to have it mutable.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-07-24 10:32:35 +01:00
Frediano Ziglio 3522667bfa x11: Avoid passing XEvent as value
The structure is not that small and is not necessary to copy
the value.
This also removed a Coverity warning.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-07-24 10:32:32 +01:00
Frediano Ziglio b6dfef73f2 x11-randr: Avoid passing XEvent as value
The structure is not that small and is not necessary to copy
the value.
This also removed a Coverity warning.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-07-24 10:32:23 +01:00
Victor Toso 6bfbd03e83 vdagent: simple fix for address-of-packed-member
Seems to be a false positive but as this message only happens when user
client connects, we can copy this array to make compiling warn free.

 > src/vdagent/vdagent.c: In function ‘daemon_read_complete’:
 > src/vdagent/vdagent.c:226:71: error: taking address of packed member of
 >     ‘struct VDAgentAudioVolumeSync’ may result in an unaligned pointer
 >     value [-Werror=address-of-packed-member]
 >   226 |             vdagent_audio_playback_sync(avs->mute, avs->nchannels, avs->volume);
 >       |                                                                    ~~~^~~~~~~~
 > src/vdagent/vdagent.c:228:69: error: taking address of packed member of
 >     ‘struct VDAgentAudioVolumeSync’ may result in an unaligned pointer
 >     value [-Werror=address-of-packed-member]
 >   228 |             vdagent_audio_record_sync(avs->mute, avs->nchannels, avs->volume);
 >       |                                                                  ~~~^~~~~~~~

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-07-19 12:13:42 +01:00
Victor Toso 7976dc31af x11-randr: simplest fix for address-of-packed-member
The struct type for width/height is uint32_t while we are trying to
access and change it with int* - code can be improved a bit in following
patches but this one fixes the warning by copying the value from the
struct and copying back new value afterwards.

Also:
- Moved variables to internal scope;
- Added braces to inner if;

 > src/vdagent/x11-randr.c: In function ‘zero_base_monitors’:
 >     src/vdagent/x11-randr.c:621:28: error: taking address of packed member of
 >     ‘struct VDAgentMonConfig’ may result in an unaligned pointer value
 > [-Werror=address-of-packed-member]
 >   621 |         mon_width = (int *)&mon_config->monitors[i].width;
 >       |                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 > src/vdagent/x11-randr.c:622:29: error: taking address of packed member of
 >     ‘struct VDAgentMonConfig’ may result in an unaligned pointer value
 >     [-Werror=address-of-packed-member]
 >   622 |         mon_height = (int *)&mon_config->monitors[i].height;
 >       |                             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-07-19 11:49:32 +01:00
Victor Toso 70c5908f8c x11-randr: use glib's MAX and MIN
Since 2861868 "randr: remove monitors.xml on auto-configuration" in
2015-04-10 by Marc-Andre Lureau <[email protected]> this
file includes glib.h and can remove those helpers.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-07-19 11:38:19 +01:00
Victor Toso b6fde1641a vdagent: fix memory leak of g_memdup()
Found by covscan:

 | spice-vdagent-0.19.0/src/vdagent/vdagent.c:432:9: warning: Potential leak of memory pointed to by 'orig_argv'
 | #        g_printerr("Invalid arguments, %s\n", error->message);
 | #        ^
 | spice-vdagent-0.19.0/src/vdagent/vdagent.c:418:24: note: Memory is allocated
 | #    char **orig_argv = g_memdup(argv, sizeof(char*) * (argc+1));
 | #                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/vdagent.c:431:9: note: Assuming 'error' is not equal to NULL
 | #    if (error != NULL) {
 | #        ^~~~~~~~~~~~~
 | spice-vdagent-0.19.0/src/vdagent/vdagent.c:431:5: note: Taking true branch
 | #    if (error != NULL) {
 | #    ^
 | spice-vdagent-0.19.0/src/vdagent/vdagent.c:432:9: note: Potential leak of memory pointed to by 'orig_argv'
 | #        g_printerr("Invalid arguments, %s\n", error->message);
 | #        ^
 | #  430|
 | #  431|       if (error != NULL) {
 | #  432|->         g_printerr("Invalid arguments, %s\n", error->message);
 | #  433|           g_clear_error(&error);
 | #  434|           return -1;

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-07-19 11:37:54 +01:00
Victor Toso f8fa4191db Prepare to 0.19.0 release
Signed-off-by: Victor Toso <[email protected]>
Acked-by: Eduardo Lima (Etrunko) <[email protected]>
2019-04-12 14:42:19 +00:00
Victor Toso 0397089827 build-sys: Add README.md to the tarball
Missed this when adding 'md' prefix to README with
0193a53 in 2019-03-08 by Victor Toso <[email protected]>

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Eduardo Lima (Etrunko) <[email protected]>
2019-04-12 14:41:55 +00:00
Victor Toso c47e073385 build-sys: next spice-protocol is 0.14.0
The requirement to the unreleased spice-protocol was added with
56c2d29 in 2019-01-28 by Lukáš Hrázký <[email protected]> but
next stable release of spice-protocol is 0.14.0

The configure check is correct but seems better to me to check against
a valid release instead of checking with a non existing one.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Eduardo Lima (Etrunko) <[email protected]>
2019-04-12 14:29:43 +00:00
Victor Toso f5a2c1af91 CHANGELOG: Move content from NEWS and delete it
And add some Markdown style.

v1 -> v2:
* Fix NEWS -> CHANGELOG.md in Makefile.am (Jakub)

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2019-03-08 07:10:01 +00:00
Victor Toso beb35c375e CHANGELOG: To use markdown
We will prefer CHANGELOG over NEWS just as matter of Gitlab's.
Followup patch will move NEWS content to CHANGELOG.

This patch renames ChangeLog -> CHANGELOG.md and changes some style to
follow Markdown. Also adds 'News in' string to the title of each
section.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2019-03-08 07:09:57 +00:00
Victor Toso 4452b1d3bd README: Remove non relevant features information
It is not relevant nowadays that *spicec* client was removed and even
monitors_config does not reach spice-vdagent in modern Guests.

Also add block quote for qemu cmdline and system's paths to make it
easier to copy-and-paste.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2019-03-08 07:09:53 +00:00
Victor Toso 0193a537ec Make README a markdown file
This commit only renames it to have .md suffix as that is recognized
by Gitlab.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2019-03-08 07:09:49 +00:00
Victor Toso a257b1c205 Remove TODO
Not something we really use nor we keep it up to date.
One should check/update issues at

    https://gitlab.freedesktop.org/spice/linux/vd_agent/issues

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2019-03-08 07:09:32 +00:00
Jonathon Jongsma 73c1afbf63 Advertise VD_AGENT_CAP_GRAPHICS_DEVICE_INFO
Since we now support the graphics device info message, advertise this
fact when sending capabilities to the server.

Signed-off-by: Jonathon Jongsma <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-03-01 11:02:25 +00:00
Victor Toso d4d489560b gitlab-ci: run singular job for build options
There are two main bottlenecks in CI:
1. Network might be slow for bootstrapping;
2. Big job queues to get a runners to run our jobs.

This patch reduces the three jobs to a single one in order to prevent
long delays when CI resources are scarce which is a common scenario.

No major losses in log should happen. We might add specific .log
files as artifacts if we need them later on.

For completeness, use git clean -xfd for a clean git tree instead of
make distclean.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-03-01 10:49:48 +00:00
Victor Toso 1fe876177a gitlab-ci: remove copr dependency
Instead of relying in copr builds, we should rely on relative branch
in gitlab for spice dependencies such as spice-protocol.

This patch moves the dependencies to a variable and builds
spice-protocol instead of using spice-protocol from nightly spice
copr.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-03-01 10:49:44 +00:00
Victor Toso bfb6136411 gitlab-ci: remove sudo
The jobs already run as root.
Also removes an extra empty line.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-02-27 13:44:43 +00:00
Frediano Ziglio d1bf80c924 Ignore autogenerated test
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-02-27 12:31:42 +00:00
Jakub Janků 3aff78399f x11: invalidate requests for targets on grab from client
If XSetSelectionOwner() is invoked during the time
we are waiting for the requested clipboard targets,
the targets we eventually receive are no longer valid.

To solve this, ignore the same count of target notifications
as we expected at the time we received grab from the client.

Otherwise we end up in a situation when vdagent holds
the clipboard grab in the guest but cannot provide data to the
apps that request it - this can be observed in the log:

    clipboard: received selection request event for target *, while not owning client clipboard

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-02-25 16:57:14 +00:00
Jakub Janků 783ceece02 clipboard: cancel request for targets on grab from client
If gtk_clipboard_set_with_data() is invoked between
gtk_clipboard_request_targets() and the
GtkClipboardTargetsReceivedFunc callback,
the targets we eventually receive are no longer valid.

To solve this, cancel the request in vdagent_clipboard_grab().

Otherwise we end up in a situation when vdagent holds
clipboard grab in the guest but cannot provide data to the
apps that request it - this can be observed in the log:

    CRITICAL **: 20:48:55.782: clipboard_get_cb: assertion 'c->selections[sel_id].owner == OWNER_CLIENT' failed

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-02-22 07:39:53 +00:00
Uri Lublin 9874e30e91 Makefile.am: define check_PROGRAMS once
Also define TESTS once

autoreconf complains when there are multiple definitions of
a variable. In this case (partial error message follows):
    warning: check_PROGRAMS multiply defined

Signed-off-by: Uri Lublin <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-02-20 13:56:25 +00:00
Christophe Fergeau f3408fc916 README: Drop obsolete information
The README still references QEMU < 0.14, and mentions Gerd and Hans
which have not been active on spice-vdagent for a few years.

Signed-off-by: Christophe Fergeau <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-02-05 11:15:38 +00:00
Christophe Fergeau f499a5126e vdagent: Use g_file_test() instead of direct stat call
vdagent.c has a 'file_test' function which tests for the existence of
the /dev entry for the spicevmc channel. glib already provides such a
g_file_test() function, so we can use it instead.

Signed-off-by: Christophe Fergeau <[email protected]>
Acked-by: Jakub Janků <[email protected]>
2019-01-31 11:34:16 +01:00
Christophe Fergeau 149bba9162 vdagent: Silently ignore missing spicevmc device
On most distros, spice-vdagent will be autostarted as part of the
startup of the desktop environment session. This is done by
spice-vdagent.desktop, which has no way of checking if we are in a virt
environment with the needed devices present.

Currently, if /dev/virtio-ports/com.redhat.spice.0 is missing, we log an
error in syslog, and exit with an error exit code. This is too noisy
when autostarting it on a bare metal machine which have no use for
spice-vdagent. This reverts 0159111b to get rid of these warnings in the
session's logs

https://gitlab.freedesktop.org/spice/linux/vd_agent/issues/12

Signed-off-by: Christophe Fergeau <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-01-31 11:34:10 +01:00
Jonathon Jongsma 74570d5f97 Fix coding style
Use brackets everywhere.

Acked-by: Frediano Ziglio <[email protected]>
2019-01-30 08:48:53 +00:00
Jonathon Jongsma 67f3a09c22 Send device info to agent when it connects
Previously, the device info was only sent from the daemon to the session
agent when we receive the device info message from the host. That means
that if the session agent exits and reconnects, the session agent will
not have the device info necessary to translate spice display IDs to
guest device outputs. This patch saves the last device info message that
was received from the host, and re-sends it to the session agent when it
reconnects.

NOTE: this may not be necessary if the server simply re-sends a device
info message when it detects that the agent has connected...

Acked-by: Lukáš Hrázký <[email protected]>
Signed-off-by: Jonathon Jongsma <[email protected]>
2019-01-29 10:11:04 -06:00
Jonathon Jongsma 5ad18905c8 Send display_id down to the vdagentd daemon
Add a display_id field to the structure that we use to send down the
list of guest display resolutions to the vdagentd daemon. This allows us
to map the spice display id to the proper X display for determining
mouse locations, etc.

In the case where we have an mjpeg plugin running in the streaming
agent, we have two spice displays representing the same guest display.
In that scenario, the session agent may maintain the following guest
output mapping:
 spice channel 0 (QXL) => X output 0
 spice channel 1 (streaming-agent) => X output 0

While this is not necessarily a supported scenario, it would be nice if
the cursor input worked properly in this case. The root problem is that
when the session agent sends down the guest xorg resolutions to the
system daemon, it simply loops through the list of xorg displays, and
for each X display it looks up the first spice display ID associated
with it and sends that down to the daemon. In the scenario mentioned
above, since there is only a single X display configured (albeit
represented by two different spice displays), we would send down a
single display resolution to the system daemon:
 - { width=1280, height=1024, x=0, y=0, display_id=0 }

Notice that there is no entry for display_id=1. When the agent receives
a cursor input message for display channel 1, that message will get
passed to the systemn daemon, which will attempt to look up display_id 1
in order to convert the event coordinates to global coordinates. Finding
no entry for display_id=1, the mouse events do not work.

In this patch, when we want to send the guest resolutions down to the
system daemon, we still loop through the list of X outputs, but for each
output we also loop through the guest output mapping table and send a
resolution structure down to the daemon for each registered output
mapping.  This means that in the previously mentioned scenario, we would
send down the following information:
 - { width=1280, height=1024, x=0, y=0, display_id=0 }
 - { width=1280, height=1024, x=0, y=0, display_id=1 }

 This means that when the client sends a mouse event for display_id=1,
 the system daemon knows the coordinates of the guest display associated
 with that ID and can process the mouse event properly.

Acked-by: Lukáš Hrázký <[email protected]>
Signed-off-by: Jonathon Jongsma <[email protected]>
2019-01-29 10:10:59 -06:00
Jonathon Jongsma 5374fcc5e3 Use new function in vdagent_x11_send_daemon_guest_xorg_res()
Rather than getting the current guest resolution in a
VDAgentMonitorsConfig struct and then translating it to a new struct
type for sending down to the daemon, simply use the new function that
was factored out in a previous commit and populate the message struct
directly.

Acked-by: Lukáš Hrázký <[email protected]>
Signed-off-by: Jonathon Jongsma <[email protected]>
2019-01-29 10:10:53 -06:00
Jonathon Jongsma 254b547277 Factor a function out of get_current_mon_config()
When sending the guest xorg resolution to the vdagentd daemon, we get
the current resolution with this function, which returns a
VDAgentMonitorsConfig structure that must then be converted to the
structure that we send to the daemon. Rather than re-using this function
that returns the wrong type, factor out most of the functionality into a
separate function. This function can be used by a new function to return
a type appropriate for sending the xorg resolution to the daemon.

This is necessary because in the next few commits I'll be changing the
vdagentd protocol to send an additional display_id parameter to the
daemon.

Acked-by: Lukáš Hrázký <[email protected]>
Signed-off-by: Jonathon Jongsma <[email protected]>
2019-01-29 10:10:48 -06:00
Jonathon Jongsma d48945fdb6 Use guest output map to determine xrandr output
instead of using the spice display id directly as the xrandr output,
look it up using our new guest output map

Acked-by: Lukáš Hrázký <[email protected]>
Signed-off-by: Jonathon Jongsma <[email protected]>
2019-01-29 10:10:44 -06:00
Jonathon Jongsma 0e7e7b66e9 Make clearer distinctions between output ids
There are basically three ways to refer to an output within vdagent:
  - The index of the array of MonitorConfig message. This is essentially
    a "spice display id"
  - the index of the array of xrandr outputs. This is the "output index"
  - the xrandr output id. This is the "output ID"

Previously, the "spice display id" and the "output index" were treated
as synonymous. But in order to support more complciated setups with
multiple display devices, etc, we need to differentiate these ideas more
clearly. This patch simply renames some variables and a function so that
we can tell more easily which one of these concepts we are dealing with.

Acked-by: Lukáš Hrázký <[email protected]>
Signed-off-by: Jonathon Jongsma <[email protected]>
2019-01-29 10:10:42 -06:00
Jonathon Jongsma 353592e8e1 Look up and store xrandr output in display map
Instead of storing each device address and device display ID in the hash
table, simply use the lookup_xrandr_output_for_device_info() function to
look up the ID of the xrandr output and store that in the hash table.

Acked-by: Lukáš Hrázký <[email protected]>
Signed-off-by: Jonathon Jongsma <[email protected]>
2019-01-29 10:10:35 -06:00
Jonathon Jongsma 8dc490749f Add lookup_xrand_output_for_device_info()
Add a function to look up an xrandr output for a given device display
id. This uses sysfs and the drm subsystem to lookup information about a
graphics device output. It then compares the drm output name to xrandr
output names to try to match that device output to an xrandr output.
This is necesary for guests that have multiple graphics devices.

Acked-by: Lukáš Hrázký <[email protected]>
Signed-off-by: Jonathon Jongsma <[email protected]>
2019-01-29 10:10:31 -06:00
Lukáš Hrázký 56c2d29752 Receive the graphics_device_info message
The graphics_device_info message contains the device display ID
information (device address and device display ID). Stores the data in a
hash table in vdagent.

Signed-off-by: Lukáš Hrázký <[email protected]>
Acked-by: Jonathon Jongsma <[email protected]>
2019-01-28 14:50:08 +01:00
Frediano Ziglio 97aa39a872 test-file-xfers: Make test succeed if run as root
If test is run with root (for instance on Gitlab CI) creating
a file on a directory with no permission will succeed and
test will fail.
Instead create a link trying to create a file in /proc/1
directory (which fails also using root account).

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-01-26 11:51:43 +00:00
Christian Hesse 26e2eab5d2 Update all paths /var/run -> /run
Commit 098268a33c (systemd: Update path
in unit file) was a really incomplete change. Let's change every
occurrence of /var/run to /run.

Signed-off-by: Christian Hesse <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-01-17 12:29:30 +00:00
Frediano Ziglio 61bf8c4565 file-xfer: Do not strip filename if file part has no extension
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-01-16 10:03:47 +00:00
Frediano Ziglio 34f934b03f Fix race condition creating file
Avoid race condition creating file between checking file existence
with stat() and opening with open().
Directly create the file passing the O_EXCL flag.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-01-16 10:03:47 +00:00
Frediano Ziglio 61f99bfa52 Add a test to test file creation
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-01-16 10:03:41 +00:00
Frediano Ziglio 5ab83e3e3d Factor out function to create file
Make easier to test file creation

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-01-16 10:03:38 +00:00
Frediano Ziglio 73147aff7d file-xfers: Allocate file_path after disk space check
Variable is not used. Keep code to create file together.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-01-16 09:46:28 +00:00
Frediano Ziglio aaed86b649 file-xfers: Reuse cleanup code
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-01-16 09:46:26 +00:00
Frediano Ziglio 5be1563147 file-xfers: Initialise correctly AgentFileXferTask::file_fd field
Correct invalid value for a file descriptor is -1, not 0.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2019-01-16 09:46:21 +00:00
Christian Hesse 098268a33c systemd: Update path in unit file
When loading the unit file, systemd 240 logs:

systemd[1]: /usr/lib/systemd/system/spice-vdagentd.service:9: PIDFile=
references path below legacy directory /var/run/, updating
/var/run/spice-vdagentd/spice-vdagentd.pid →
/run/spice-vdagentd/spice-vdagentd.pid; please update the unit file
accordingly.

So update the path.

Signed-off-by: Christian Hesse <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2019-01-15 15:32:50 +00:00
Christophe Fergeau 56d50d2122 systemd: Remove WantedBy=sockets.service in [Install]
.socket systemd units already automatically get a
Before=sockets.service, and the udev rule we have will ensure that when
the appropriate virtio device is there, the socket unit will be started,
so this WantedBy dependency is not needed, and is in part responsible
for these warnings:

[ INFO ] dev-virtio\x2dports-com.redhat.spice.0.device is not active.
[DEPEND] Dependency failed for Activation socket for spice guest agent daemon.

https://bugzilla.redhat.com/show_bug.cgi?id=1545212

Signed-off-by: Christophe Fergeau <[email protected]>
2019-01-08 16:19:58 +01:00
Christophe Fergeau b07420eea0 systemd: Remove unneded virtio-port dependencies
The udev rule already adds SYSTEMD_WANTS=spice-vdagentd.socket
to the relevant virtio devices, which automatically adds Wants=${device}
to spice-vdagentd.socket (see 'systemctl show spice-vdagentd.socket').
Adding a Requisite/After for these ports is at best redundant, and most
likely wrong as this is causing boot time warnings:

[ INFO ] dev-virtio\x2dports-com.redhat.spice.0.device is not active.
[DEPEND] Dependency failed for Activation socket for spice guest agent daemon.

https://bugzilla.redhat.com/show_bug.cgi?id=1545212

Signed-off-by: Christophe Fergeau <[email protected]>
2019-01-08 16:19:58 +01:00
Frediano Ziglio 41ad267d81 Check errors setting standard file descriptors
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2019-01-07 18:15:42 +00:00
Frediano Ziglio 77ef2213aa Ignore some Coverity reports
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2019-01-07 18:15:32 +00:00
Frediano Ziglio c3046c2434 Add missing config.h includes
Make sure all module files include config.h

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2019-01-04 10:48:16 +00:00
Frediano Ziglio 380cab695f Unify config.h inclusion style
Remove HAVE_CONFIG_H check, it is always defined.
Remove indentation of includes, now the include is not in a condition
and also some were indented some not.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2019-01-04 10:48:16 +00:00
Frediano Ziglio 5df766b161 vdagent: Fix restarting agent
We need to pass the original argument list, however argv is modified
by g_option_context_parse so save a copy of the array to make it
possible to restart with the same arguments.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2019-01-04 10:48:16 +00:00
Frediano Ziglio a568953e79 x11: Add a comment explaining a misleading value
People can think that 32 means 32 bit while it is always a long.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2019-01-04 10:32:08 +00:00
Frediano Ziglio b9c61dad55 vdagentd: Tell different tools that we are falling through
Different tools (compilers or analysers) recognise missing break
in switch as possible problems.
Many recognise a "fall through" comment to tell it is wanted.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2019-01-04 10:30:43 +00:00
Frediano Ziglio 8bef579654 Do not include config.h in headers
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jonathon Jongsma <[email protected]>
2019-01-03 22:01:42 +00:00
Frediano Ziglio 0221f7f080 virtio-port: Avoid temporary buffers
Modify directly the new_wbuf->buf buffer instead of writing into
a temporary buffer and then copy in the final one.
This also fixes Coverity warning:

 | uninit_use_in_call: Using uninitialized value "message_header". Field
 | "message_header.data" is uninitialized when calling "memcpy".

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Jonathon Jongsma <[email protected]>
2019-01-03 17:00:55 +00:00
Jonathon Jongsma 7ace167ec2 Fix confusion between output index and crtc index
Get the CRTC ID from the output struct rather than using the
output_index as an index into the array of crtcs

Signed-off-by: Jonathon Jongsma <[email protected]>
Acked-by: Lukáš Hrázký <[email protected]>
2018-12-20 15:53:27 -06:00
Victor Toso cb7dfbe55a x11-randr: Improve argument check
In the current code, output should never be negative but the check
exists after we use the variable as index. Make the check earlier.

This patch also breaks the check in two in order to provide more
accurate error log.

Found by coverity:
  | check_after_sink: You might be using variable "output" before
  | verifying that it is >= 0.

Changes in v2:
- Move overflow check before accessing the arrays (Frediano)

Changes in v3:
- Move the whole check before accessing the arrays.
- Improve commit log.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2018-12-19 18:07:19 +01:00
Victor Toso ac119849a3 After fork, use one expression per line
And use well defined macros for standard file descriptors.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2018-12-19 15:12:54 +01:00
Jonathon Jongsma 761887e07d fix typo in comment
Acked-by: Frediano Ziglio <[email protected]>
2018-12-15 11:08:31 +00:00
Victor Toso a99ba0fe89 vdagent: Do not send empty screen resolution messages
Easier to trigger on Wayland guest by running

> xrandr --output XWAYLAND0 --rotate left

In current master, this causes the spice-vdagentd to disconnect from
the client. In 0.18 branch (latest release), mouse becomes unusable as
mentioned in the referred bug below.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1641723

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2018-11-16 15:23:33 +01:00
Frediano Ziglio d5811d0589 x11-randr: Fix typo in error message
The function name is XRRGetScreenSizeRange not RRGetScreenSizeRange.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2018-11-16 09:20:03 +00:00
Frediano Ziglio 2d6d0d2acd udscs: Avoid file descriptor leak
If connection fails the socket descriptor is not closed causing
a leak.

Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Victor Toso <[email protected]>
2018-11-16 09:19:32 +00:00
Jonathon Jongsma 102b2e753e systemd: use "After" with "Requisite"
The "Requisite" directive is intended to require that the virtio port
device exists before starting the vdagent socket unit. If the device
does not exist, the socket should fail to start. However, without using
"After", the socket will still start even when the device is not
present.

The man page for systemd.unit (v239+) says the following about
'Requisite=':

"Similar to Requires=. However, if the units listed here are not
started already, they will not be started and the starting of this unit
will fail immediately. Requisite= does not imply an ordering
dependency, even if both units are started in the same transaction.
Hence this setting should usually be combined with After=, to ensure
this unit is not started before the other unit."

See also https://github.com/systemd/systemd/issues/4756 for further
details (particularly the following comment:
https://github.com/systemd/systemd/issues/4756#issuecomment-267005324)

Signed-off-by: Jonathon Jongsma <[email protected]>
Acked-by: Lukáš Hrázký <[email protected]>
2018-11-02 11:07:40 -05:00
Jakub Janků b245cbdd59 udscs: simplify traffic logging
Remove @type_to_string, @no_types arguments from
udscs_connect(), udscs_create_server{,_for_fd}().
udscs is used only in vdagent.c and vdagentd.c
and in both cases the args are the same
(vdagentd_messages, VDAGENTD_NO_MESSAGES).

Add debug_print_message_header().

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2018-09-21 21:36:20 +02:00
Jakub Janků 8df6120b7f vdagentd: parse argv using GLib
All command line options now have long names
as they are required by GLib.

So the supported command line options now are:

    -h, --help

    -d, --debug
    -s, --virtio-serial-port-path
    -S, --vdagentd-socket
    -u, --uinput-device
    -f, --fake-uinput
    -x, --foreground
    -o, --one-session
    -X, --disable-session-integration

Change the types of some global variables that hold the options:
- const char * --> gchar *
- int          --> gboolean

Define DEFAULT_UINPUT_DEVICE as "/dev/uinput",
since there's already DEFAULT_VIRTIO_PORT_PATH, VDAGENTD_SOCKET.

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2018-09-19 09:31:46 +02:00
Victor Toso 16e3dc1035 spice-vdagent.desktop: Change autostart to WindowManager stage
It is possible that g_get_user_special_dir() return NULL for
G_USER_DIRECTORY_DESKTOP or G_USER_DIRECTORY_DOWNLOAD; This is a sure
thing to happen in case xdg-user-dirs hasn't been run yet.

Keeping spice-vdagent to run on Initialization stage of
X-GNOME-Autostart-Phase could trigger a race with xdg-user-dirs that
also runs on Initialization, which is the earliest stage possible.

Moving to spice-vdagent to run WindowManager stage avoids the race
with xdg-user-dirs and still runs before any graphical application.

Tested also moving to Desktop stage, which is 4th stage (out of 5) and
worked without apparent drawbacks.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1623947
Signed-off-by: Victor Toso <[email protected]>
Acked-by: Uri Lublin <[email protected]>
2018-09-13 11:26:41 +02:00
Jakub Janků 6ee007ca33 vdagentd: move code to do_agent_file_xfer_status()
Move code handling VDAGENTD_FILE_XFER_STATUS messages
from agent_read_complete() to a separate function
to make the switch statement less cluttered.

Simplify the code a bit.

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2018-09-07 17:00:00 +02:00
Jakub Janků b222ad1011 vdagentd: move code to do_agent_xorg_resolution()
Move code handling VDAGENTD_GUEST_XORG_RESOLUTION messages
from agent_read_complete() to a separate function to make
the switch statement less cluttered.

Remove unnecessary res variable.

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2018-09-07 16:59:58 +02:00
Jakub Janků 819782c48d vport: return void in vdagent_virtio_port_write{, _start}()
The functions would return -1 only if malloc() failed, otherwise 0.
Since malloc() was replaced by g_malloc(), which terminates
the program if the allocation fails, return void instead.

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2018-09-07 16:59:55 +02:00
Jakub Janků 27aa50e629 udscs: return void in udscs_write{, _all}()
The functions would return -1 only if malloc() failed, otherwise 0.
Since malloc() was replaced by g_malloc(), which terminates
the program if the allocation fails, return void instead.

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2018-09-07 16:59:52 +02:00
Jakub Janků 061593ed85 move to GLib memory functions
Some older parts of the code currently use
memory functions defined in stdlib.h
and usually handle allocation errors.

On the other hand, newer parts of the code
and GLib/GTK+ functions themselves commonly use
wrappers provided by GLib that terminate
the program when there isn't enough memory.

So it doesn't make much sense to check for
ENOMEM somewhere, while the program can be
terminated at any time elsewhere.

Unify the code and use GLib wrappers only.

malloc --> g_malloc, g_new
calloc --> g_malloc0, g_new0
free   --> g_free

Use g_clear_pointer where possible
for simplification.

Replace subsequent alloc and memcpy calls
with single g_memdup where possible.

Note: this commit only partially touches
src/vdagent/x11.c as the clipboard-handling
code here should be removed in the future.

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2018-09-07 16:59:43 +02:00
Jakub Janků 542ad5f828 file-xfer: remove obsolete GLIB_CHECK_VERSION
Required GLib version was bumped from 2.28 to 2.34 by
61fc548fe1.

Signed-off-by: Jakub Janků <[email protected]>
Acked-by: Victor Toso <[email protected]>
2018-09-07 09:57:29 +02:00
Jakub Janků 359cceda91 udscs: add udscs_get_peer_pid()
udscs_get_peer_cred() is currently used only in
vdagentd.c to obtain PID, so let's drop udscs_get_peer_cred()
and add udscs_get_peer_pid() instead.

Acked-by: Victor Toso <[email protected]>
2018-08-28 08:38:13 +02:00
Lukáš Hrázký 0a05a7cf39 Improve/add some logging messages
Signed-off-by: Lukáš Hrázký <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2018-08-14 13:07:20 +02:00
Lukáš Hrázký ae0fcf3566 vdagent/x11-randr: rename error_handler to ignore_error_handler
The handler is meant to ignore the X11 error, name it properly.

Signed-off-by: Lukáš Hrázký <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2018-08-14 13:07:16 +02:00
Jakub Janků b22d605184 dummy-session-info: remove session_is_locked()
364b6bba06 introduced
session_info_session_is_locked() in session-info.h, however
dummy-session-info.c implemented session_is_locked() instead,
causing builds with --with-session-info=none to fail.

This was fixed by d66fbb9d12,
but it didn't remove the incorrect session_is_locked().
Acked-by: Frediano Ziglio <[email protected]>
2018-07-23 12:40:54 +02:00
Victor Toso b190b17902 Prepare to 0.18.0 release
Signed-off-by: Victor Toso <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2018-06-06 11:27:15 +02:00
Victor Toso 6013078e7b gitlab-ci: add YAML file
Including some basic building tests.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2018-06-06 11:27:11 +02:00
Victor Toso 7ddd30eebc build-sys: fix summary with yes/no info on --with-gtk
Before this patch, the summary would have 'auto' instead of yes or no
for building with gtk.

Signed-off-by: Victor Toso <[email protected]>
Signed-off-by: Frediano Ziglio <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2018-06-06 11:27:06 +02:00
Victor Toso 9003891d5e build-sys: Add info about options for --with-gtk
To have a similar output to other configure options we have.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2018-06-06 11:27:02 +02:00
Uri Lublin ffdb2704b2 x11-randr: do not assume each output has ncrtc=1
Unlike virtual graphic cards, device-assigned graphic cards can
have more than one crtc per output.

Still we currently pick only a single crtc for each output
(but looping over them to find an active one)

Signed-off-by: Uri Lublin <[email protected]>
Acked-by: Victor Toso <[email protected]>
2018-05-30 12:38:55 +03:00
Jakub Janků 1f332ce3db vdagent: add GTK+ clipboard handling
Acked-by: Victor Toso <[email protected]>
2018-04-10 14:07:33 +02:00
Jakub Janků 2f54062749 vdagent: add new vdagent_clipboard_*() interface
Introduce new functions to handle clipboard,
add new files clipboard.[ch]

This is only a preparatory patch for
following GTK+ clipboard implementation.

Acked-by: Victor Toso <[email protected]>
2018-04-10 14:07:28 +02:00
Jakub Janků a2ef594a2f x11: retireve _NET_WM_NAME using Xlib if GTK+ is missing
This code using Xlib was removed by commit
"x11: retrieve _NET_WM_NAME using GDK"
a4f5c7dcb6.
Bring it back to make GTK+ optional for now.

Acked-by: Victor Toso <[email protected]>
2018-03-05 12:57:44 +01:00
Jakub Janků 694b43b5ce build: make GTK+ optional
Add --with-gtk configure option.
If used, favor GTK+ over Xlib.

Acked-by: Victor Toso <[email protected]>
2018-03-05 12:57:38 +01:00
Jakub Janků 632fba5070 x11: update wms_with_icons_on_desktop[] to support Mate
Since version 1.9.2, Marco sets _NET_WM_NAME to "Metacity (Marco)"
instead of "Marco", see:

http://git.mate-desktop.org/marco/commit/?id=cbf24f5d78719b930fc0cd6c0c80e00e9d62c95a

Add this new value to wms_with_icons_on_desktop[], so that
vdagent_x11_has_icons_on_desktop() returns TRUE.

Acked-by: Victor Toso <[email protected]>
2017-12-11 10:07:22 +01:00
Jakub Janků 8b8f333e55 x11: refetch _NET_WM_NAME in vdagent_x11_has_icons_on_desktop()
Don't cache _NET_WM_NAME, instead refetch it with each
vdagent_x11_has_icons_on_desktop() call so that correct result is returned
even if the window manager changes during the lifetime of vdagent_x11 struct.
Remove char *net_wm_name from vdagent_x11.

Remove x11 argument from vdagent_x11_has_icons_on_desktop().

Acked-by: Victor Toso <[email protected]>
2017-12-11 10:07:22 +01:00
Jakub Janků a4f5c7dcb6 x11: retrieve _NET_WM_NAME using GDK
Get _NET_WM_NAME using gdk_x11_screen_get_window_manager_name().
vdagent_x11_get_wm_name(): return the name instead of setting it.
Return string specifics:
- "unsupported", when not running on X11
- "unknown", when the name cannot be retrieved
Since the return value is never NULL, remove obsolete checks.

Acked-by: Victor Toso <[email protected]>
2017-12-11 10:05:40 +01:00
Jakub Janků d673fc7b8a vdagent: add GTK+
This is a preparatory patch for GTK+ vdagent redesign.

Since most of the vdagent code still uses X11 lib,
force GDK to use X11 backend by calling
gdk_set_allowed_backends("x11").

Acked-by: Victor Toso <[email protected]>
2017-12-11 10:05:36 +01:00
Jonathon Jongsma c65de1b68d Avoid leaking fd when udscs_create_server_for_fd fails
Reported by Frediano Ziglio. if udscs_create_server_for_fd() fails, it
will return NULL and the file descriptor will be leaked. Since the
calling function is the one that created the fd, it should free the fd
if the server could not be created.

Signed-off-by: Jonathon Jongsma <[email protected]>
Acked-by: Victor Toso <[email protected]>
2017-12-01 16:43:13 -06:00
Jonathon Jongsma c74a00e4d9 Don't install udev rules into /lib
Ask udev (via pkg-config) for the appropriate directory to install udev
rules. This is useful for recent distributions (e.g. RHEL7, fedora) that
no longer have a root /lib directory and instead use /usr/lib

Signed-off-by: Jonathon Jongsma <[email protected]>
Acked-by: Victor Toso <[email protected]>
2017-12-01 16:43:03 -06:00
Jonathon Jongsma b7e6f31df8 Avoid leaking udscs file descriptor
This is a  finding from Coverity. In practice it has very little impact
since returning NULL from this function results in the process exiting
with an error.

Signed-off-by: Jonathon Jongsma <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2017-11-29 11:41:40 -06:00
Jonathon Jongsma 8ba174816d Quote the save directory before passing to shell
Thanks to a report from Seth Arnold <[email protected]>:
- vdagent_file_xfers_data() does not escape xfers->save_dir before giving
  it to the shell
- vdagent_file_xfers_data() does not check snprintf() return code; a
  too-long xfers->save_dir could cause the & or ' or any number of other
  characters to go missing.

To fix these issues, we use g_spawn_async(). This avoids the need to
quote the filename and also avoids the snprintf issue.

In the case that the spawn fails, we also print a warning to the syslog
now.

Signed-off-by: Jonathon Jongsma <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2017-11-16 11:14:41 -06:00
Jakub Janků e5bfb1be15 udscs: remove client support for select()
Drop functions:
- udscs_client_fill_fds()
- udscs_client_handle_fds()
These became obsolete with GMainLoop integration.
Move required code to udscs_server_fill_fds()
and udscs_server_handle_fds(), respectively.

Acked-by: Frediano Ziglio <[email protected]>
2017-10-20 14:16:47 +01:00
Jakub Janků 3fcf2e944a vdagent: Use GMainLoop
Replace existing main while-loop with GMainLoop.

Use GIOChannel with g_io_add_watch() to manage IO
from x11 connections in the main loop.

udscs_connect() now internally creates GSources
by calling g_io_add_watch().
This enables GMainLoop integration,
clients no longer need to call
udscs_client_fill_fds() and
udscs_client_handle_fds() in a loop.
Read callback and udscs_write() functions as before.

Signals are also handled in the main loop,
using g_unix_signal_add().
SIGQUIT is currently not supported by GLib.

This enables further GTK+ integration in the future.

Signed-off-by: Victor Toso <[email protected]>
2017-10-20 14:16:47 +01:00
Frediano Ziglio d69a13803b vdagent: Incapsulate iteration state into a VDAgent structure
Related to ongoing work to use GMainLoop and GTK integration

Based on work from Victor Toso <[email protected]>

Acked-by: Jakub Janků <[email protected]>
2017-10-20 14:16:47 +01:00
Victor Toso fe3fc345e1 vdagent: small refactor on udscs setup function
This is mostly a preparatory patch to reduce the usage of globals and
the GMainLoop integration. The changes target one function by:

* Changing its name from client_setup() to client_setup_sync(): As it
  important to clarify that the function block;

* Removing the 'reconnect' argument as the input is the global
  'do_daemonize'. We can use the global here as it is related to
  command line options;

* Changing the return value from 'int' to 'udscs_connection *' as the
  followup patch will remove the global variable 'client'.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2017-10-20 14:16:47 +01:00
Victor Toso 0ffca2b7f1 vdagent: Use glib's commandline parser
As we already depend on glib, let's remove code that glib can take
care of. In this case, we don't need to handle commandline parsing
ourselves.

In regard the global variables:

* static const char * -> static gchar * [only paths]
  path variables: portdev, fx_dir, vdagentd_socket

* static int -> static gboolean
  flags: debug, do_daemonize, x11_sync

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2017-10-20 14:16:47 +01:00
Victor Toso ada1c30d27 vdagent: move file xfer finalize to a function
This patch creates vdagent_finalize_file_xfer() to finalize and stop
file xfer. Moving this code to a function removes some duplication.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2017-10-20 14:16:47 +01:00
Victor Toso 3b49c09fd4 vdagent: move file xfer initialization to a function
This patch creates two functions:
- xfer_get_download_directory()
- vdagent_init_file_xfer()

The logic should be similar as it was before this patch, taking in
consideration the global variables fx_open_dir and fx_dir which are
set from command line.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2017-10-20 14:16:47 +01:00
Jakub Janků 61fc548fe1 Bump GLib version to 2.34
This is required for the following GMainLoop integration,
which utilizes some of the new functions/definitions, namely:

[definition][GLib version]
g_clear_pointer()   2.34
G_SOURCE_REMOVE     2.32
G_SOURCE_CONTINUE   2.32
g_unix_signal_add() 2.30

GLib version accross distributions:
- Fedora 26  2.52
- Fedora 25  2.50
- Fedora 24  2.48
- CentOS 7   2.46
- Debian 9   2.50

RHEL 6 is no longer supported,
so remove README.RHEL-5.

Acked-by: Frediano Ziglio <[email protected]>
2017-10-20 14:16:19 +01:00
Jonathon Jongsma 183e2fec35 Add systemd socket activation
If we are configured to use the systemd init script, also add support
for systemd socket activation. systemd will listen on the socket that is
used to communicate between the session agent and the system daemon.
When the session agent connects, the system daemon will automatically be
started. The socket will be enabled only if the required virtio-port
device exists. The socket is disabled when the device is removed.

This has a couple minor advantages to the previous approach:
  - For VMS that are not running a graphical desktop (and thus no
    session agents are running), the system vdagent daemon won't get
    started at all even if the spice virtio port is configured. Only the
    socket will be enabled. In the previous approach, the system daemon
    was started when the virtio device was added regardless of whether
    it was needed or not.
  - Solves issues related to switching between systemd targets. With the
    previous approach, when a user switches to a different target
    ("systemctl isolate multi-user.target"), spice-vdagentd.target was
    stopped by systemd (since "isolate" by definition stops all targets
    except the one specified). This meant that if the user subsequently
    switched back to graphical.target, the spice-vdagentd.target would
    still be disabled and vdagent functionality would not work. With
    this change, the socket will still be listening after switching to a
    different target, so as soon as a session agent tries to connect to
    the socket, the system daemon will get restarted.

Fixes: rhbz#1340160

Signed-off-by: Jonathon Jongsma <[email protected]>
Acked-by: Victor Toso <[email protected]>
2017-07-24 11:32:21 -05:00
Jakub Janků 78c930e758 file-xfer: Send more detailed error messages
Send VD_AGENT_FILE_XFER_STATUS_VDAGENT_NOT_CONNECTED,
VD_AGENT_FILE_XFER_STATUS_SESSION_LOCKED or
VD_AGENT_FILE_XFER_STATUS_DISABLED instead of general error, when the
given error occurs.

send_file_xfer_status() ensures, these errors are sent only to clients with
VD_AGENT_CAP_FILE_XFER_DETAILED_ERRORS capability.

Acked-by: Victor Toso <[email protected]>
2017-06-30 17:17:32 +02:00
Jakub Janků 3760f8618c file-xfer: Check free space before file transfer
Add function get_free_space_available that retrieves amount of free
space in the given directory. The statvfs may fail even when there's
enough free space (e.g. when not supported by system), in this case
return G_MAXUINT64 so that the transfer isn't terminated groundlessly.

When the file is too big, send VDAgentFileXferStatusMessage with
result VD_AGENT_FILE_XFER_STATUS_NOT_ENOUGH_SPACE and amount of free
space available, if the result isn't supported by client,
send_file_xfer_status() sends VD_AGENT_FILE_XFER_STATUS_ERROR.
Client then terminates the transfer.

Acked-by: Victor Toso <[email protected]>
2017-06-30 17:05:52 +02:00
Jakub Janků ca89a0102c file-xfer: Add support for sending detailed errors
Generalize send_file_xfer_status() to send all file xfer statuses, not
just errors.

Change send_file_xfer_status() to support sending detailed file xfer
status messages with additional error data.

Acked-by: Victor Toso <[email protected]>
2017-06-30 17:05:41 +02:00
Victor Toso 9844732e22 vdagentd-proto: define default virtio-port path
This adds a #define to avoid hardcoding the path in 2 different
places.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2017-05-18 12:06:52 +02:00
Victor Toso 4be96f98ba vdagentd: Do not call session_info_is_user() with invalid session_info
If we pass -X command line option which disables
console-kit/systemd-logind integration, we will have the following
critical being issued:

  CRITICAL **: session_info_is_user: assertion 'si != NULL' failed

This patch avoid it.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Pavel Grunt <[email protected]>
2017-05-18 12:05:42 +02:00
Pavel Grunt d66fbb9d12 vdagentd: Allow to compile without session info
Add a dummy implementation of session_info_session_is_locked

configure supports --with-session-info=none, however the build fails:
 src_spice_vdagentd-vdagentd.o: In function `do_client_file_xfer':
 src/vdagentd/vdagentd.c:336: undefined reference to
                                 `session_info_session_is_locked'
Acked-by: Victor Toso <[email protected]>
2017-05-05 17:28:02 +02:00
Jonathon Jongsma 26f5eca9bb file-xfer: use better names for duplicate files
When transferring the same file multiple times, the vdagent tries to
avoid overwriting an existing file on the guest by appending an integer
to the filename. Instead of just appending the integer to the very end,
we now try to be smarter and append the integer before the file
extension. For example, if we transferred the file "file.doc" twice, the
second copy would have become "file.doc (1)". It is now "file (1).doc".
This matches more closely with the behavior of the Nautilus file manager
as well.

Signed-off-by: Jonathon Jongsma <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2017-05-03 11:14:01 -05:00
Francois Gouget 909b00a5ce vdagent: Spelling and case fixes in comments
Use the official case for Xfce.

Signed-off-by: Francois Gouget <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2017-04-07 17:39:31 +02:00
Francois Gouget 80d9d1f2f8 vdagent: Spelling fixes for the man page and traces
Signed-off-by: Francois Gouget <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2017-04-07 10:51:35 +02:00
Francois Gouget 05706b6e8f vdagentd: Spelling fixes for the man page and traces
Signed-off-by: Francois Gouget <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2017-04-07 10:51:33 +02:00
Francois Gouget 16043df205 vdagentd: Some spelling fixes in comments
Signed-off-by: Francois Gouget <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2017-04-07 10:51:31 +02:00
Francois Gouget 914574ba47 udscs: A spelling fix in a comment
Signed-off-by: Francois Gouget <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2017-04-07 10:51:29 +02:00
Francois Gouget 2f6324d263 README: A couple of spelling fixes and slight rewording
Signed-off-by: Francois Gouget <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2017-04-07 10:51:26 +02:00
Pavel Grunt 69e5fd82bf vdagentd: Handle VD_AGENT_CLIPBOARD_RELEASE
In fact do nothing but avoid a runtime warning
 vdagent_message_clipboard_from_le: code should not be reached

Introduced in 99d9d35831

Acked-by: Victor Toso <[email protected]>
2017-03-23 13:48:30 +01:00
Michal Suchanek 99d9d35831 vdagentd: Do endian swapping.
This allows running big endian and little endian guest side by side using
cut & paste between them.

There is a general design idea that swapping should come as close to
virtio_read/virtio_write as possible. In particular, the protocol
between vdagent and vdagentd is guest-specific and in native endian.
With muliple layers of headers this is a bit tricky. A few message types
have to be swapped fully before passing through vdagentd.

Signed-off-by: Michal Suchanek <[email protected]>
Signed-off-by: Victor Toso <[email protected]>
2017-02-20 11:54:50 +01:00
Christophe Fergeau 3903ebd593 vdagentd: Adjust size checks
Acked-by: Victor Toso <[email protected]>
2017-02-20 11:54:37 +01:00
Christophe Fergeau 72acb448f7 vdagentd: Add missing size checks
Acked-by: Victor Toso <[email protected]>
2017-02-20 11:54:27 +01:00
Victor Toso bf7cb23534 vdagentd: early return on bad message size
The payload size for each message should be the size of the expected
struct or bigger when it contain arrays of no fixed size.

This patch creates:
 * vdagent_message_min_size[] static array with the expected size for
   each message;
 * vdagent_message_check_size() which checks the size of message's
   payload based on the type of message and by using
   vdagent_message_min_size[] as reference"

Signed-off-by: Victor Toso <[email protected]>
Signed-off-by: Michal Suchanek <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2017-02-20 11:53:58 +01:00
Michal Suchanek 85651502e8 vdagentd: Quiet uninitialized variable warning.
With gcc 6.2.1 I cannot build vdagentd because gcc detects msg_type as
potentially uninitialized and vdagentd is built with -Werror.

gcc 4.8.5 does not detect the issue and gcc 7 should be able to tell
that do_client_file_xfer is called only with values of
message_header->type handled in the switch.

Signed-off-by: Michal Suchanek <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2017-01-31 09:26:40 +01:00
Michal Suchanek 10cab3596d Move mouse-specific handling out of virtio_port_read_complete
Move some mouse-specific code from the start of
virtio_port_read_complete to a separate helper
as is the case with other message types.

Signed-off-by: Michal Suchanek <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2017-01-26 08:06:10 +00:00
Pavel Grunt f2e0bb3c45 console-kit: Check session-lock just by IdleHint
gnome-panel in RHEL6 does not emit the Unlock signal when session
is being unlocked making the agent think that the session is locked.

Remove handling of Lock/Unlock signals and keep only IdleHintChanged.

Resolves:
https://bugzilla.redhat.com/show_bug.cgi?id=1412673

Acked-by: Victor Toso <[email protected]>
2017-01-18 10:23:12 +01:00
Francois Gouget 2dc986fcaf udscs: Fix a potential NULL pointer dereference
udscs_server_fill_fds() should accept being passed a NULL pointer.
udscs_server_fill_fds() is dereferencing the 'server' pointer, and then
checks if it's NULL. This commit makes sure the NULL check happens
first.

Signed-off-by: Francois Gouget <[email protected]>
Acked-by: Christophe Fergeau <[email protected]>
2016-12-01 11:28:38 +01:00
Francois Gouget 8f1c3c3135 udscs: Improve the udscs API documentation
Document what happens whenever passing a NULL server or connection
pointer is allowed.
Make it clear that only pathname Unix domain sockets are supported.
Also document when no_types and the type_to_string array are used
and what for.

Signed-off-by: Francois Gouget <[email protected]>
2016-11-30 11:08:27 +01:00
Francois Gouget c943d0b6b2 udscs: The read buffer is always reset to NULL
Tweak the code to clarify that conn->data.buf is set to NULL after the
free() in udscs_read_complete().
Note that this reset is needed to avoid a double-free in
udscs_destroy_connection() if an error occurs while receiving
the next message header.

Signed-off-by: Francois Gouget <[email protected]>
2016-11-28 10:54:56 +01:00
Christophe Fergeau 7324da13b8 x11: More udscs_read_callback memory ownership issues
This time it's vdagent_x11_clipboard_data() which is called from
daemon_read_complete() which was missed and which was still freeing data
it no longer owns.

This fixes https://bugs.freedesktop.org/show_bug.cgi?id=98830
2016-11-24 16:37:50 +01:00
Christophe Fergeau 05d389dc90 vdagent: Fix udscs_read_callback memory ownership bug
Previous commit changed ownership rules for the data passed to the
udscs_read_callback, but forgot to update one of the user.
Both spice-vdagent and spice-vdagentd use an udscs_read_callback, either
from udscs_connect() or udscs_create_server().

The previous commit only updated users of udscs_create_server(). This
caused memory corruption in spice-vdagent which uses udscs_connect().

This fixes https://bugs.freedesktop.org/show_bug.cgi?id=98830
2016-11-23 15:59:23 +01:00
Francois Gouget 5dd6d2a88a udscs: Fix memory ownership issues with udscs_read_callback
Before this commit, udscs_read_callback is supposed to free the 'data'
buffer unless it calls udscs_destroy_connection(). It's currently not
doing this, causing a potential double free in error cases. The udscs
code would also leak the 'data' buffer if no udscs_read_callback is set.

This commit moves ownership of the 'data' buffer to the generic code
calling the udscs_read_callback and fixes the memory management of this
'data' buffer. As the only udscs_read_callback currently implemented is
not keeping pointers to 'data' after it returns, this should not cause
any issues.
2016-11-09 16:45:27 +01:00
Francois Gouget 08ff8d79da vdagentd: Make the 'could not create server socket' message more helpful
EADDRINUSE usually means the socket file was left behind after a crash.

Signed-off-by: Francois Gouget <[email protected]>
2016-11-07 18:47:21 +01:00
Francois Gouget e76db60216 vdagentd: Clean up the usage message
Just cosmetic changes, use capitalization consistently, remove trailings
dots, ...

Signed-off-by: Francois Gouget <[email protected]>
2016-11-07 18:47:21 +01:00
Francois Gouget 3303272d7e vdagentd: Clarify the usage message
udsc is an internal library of sorts that's irrelevant to users.

Signed-off-by: Francois Gouget <[email protected]>
2016-11-07 18:47:19 +01:00
Jeremy Bicha b7e6c56a78 spice-vdagent.desktop: Set NoDisplay=true
Ubuntu's Unity still ships the Startup Applications app
(gnome-session-properties).

Setting NoDisplay=true means this autostart file won't show up in there
since this isn't something we really want users to unknowingly disable
that easily.

Resolves: https://bugs.freedesktop.org/show_bug.cgi?id=98465
2016-10-31 17:27:35 +01:00
Victor Toso 8ce6ca92c6 buildsys: statis typo in configure option
Acked-by: Jonathon Jongsma <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2016-09-30 14:27:29 +02:00
Victor Toso f30a1bbaad build-sys: remove prefix from filenames
Acked-by: Jonathon Jongsma <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2016-09-30 14:27:23 +02:00
Marc-André Lureau 22e32f29a6 build-sys: move user/system to respective dir
Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jonathon Jongsma <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2016-09-30 14:27:11 +02:00
Marc-André Lureau 658fbb8ea6 build-sys: get rid of noinst_HEADERS
Regular headers file should be listed in SOURCES

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jonathon Jongsma <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2016-09-30 14:26:49 +02:00
Victor Toso bfb08d5245 build-sys: reformat Makefile.am
Makes the makefile more readable and easy to change in the next few
commits.

Based on Marc-André Lureau patch.

Acked-by: Jonathon Jongsma <[email protected]>
Acked-by: Frediano Ziglio <[email protected]>
2016-09-30 14:26:44 +02:00
Victor Toso 2192414c40 prepare to v0.17.0 2016-06-10 13:24:51 +02:00
Victor Toso ec843a21b2 systemd-login: check for LockedHint property
Property introduced in v230 of systemd.

Systems that don't have up to date systemd-login will get the
following log message:

"Properties.Get failed (locked-hint) due Unknown property or interface."

Resolves: rhbz#1323623
Acked-by: Pavel Grunt <[email protected]>
2016-06-03 11:13:33 +02:00
Victor Toso 49c421a82c console-kit: implement check for session type
Implementing the function that was introduced in previous commit:
session_info_is_user()

In console-kit we can gather the session type with GetSessionType api
from Session interface. This function is not well documented but seems
reliable enough as GDM was using it [0]

[0] session_is_login_window on gui/simple-greeter/gdm-user-manager.c

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1323640

Acked-by: Jonathon Jongsma <[email protected]>
2016-05-04 09:23:34 +02:00
Victor Toso 4c0e9c965e session-info: check if session belongs to user
session-info back-ends such as console-kit and systemd-login have the
concept of session's class which informs if session belongs to user or
not [0]. We can disable features based on the session class.

[0] Display-Managers are 'Greeter' and Display lock screens are
'lock-screen'

This patch introduces session_info_is_user() and disable file-xfer in
case agent's session does not belong to the 'user' class. As the
session-info data is hold by vdagentd, this patch also introduces
VDAGENTD_FILE_XFER_DISABLE message to disable file-xfer that is done
in vdagent.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1328761

Acked-by: Jonathon Jongsma <[email protected]>
2016-05-04 09:23:32 +02:00
Victor Toso 1700c0244f console-kit: implement check for locked session
We register to read the Lock, Unlock and IdleHintChanged signals from
ConsoleKit.Session. The Lock/Unlock signals should be the right
signals for the job but not all Desktop Managers implement its locking
in a way that trigger those signals. That's why we double-check with
IdleHintChanged signal that it might be triggered by other services
like screen savers.

Acked-by: Jonathon Jongsma <[email protected]>
2016-05-04 09:23:28 +02:00
Victor Toso 364b6bba06 session-info: check for a locked session
Each session back-end can return this information to vdagentd when
requested.

The agent should use this on situations that should not work when
session is locked such as file-transfer-start which is fixed by this
patch.

systemd-login is the only back-end implementing this function at the
moment and I'll address console-kit back-end in a later patch.

Also, this patch makes spice-vdagent depend on dbus for getting the
lock information.

Resolve: https://bugzilla.redhat.com/show_bug.cgi?id=1323623

Acked-by: Jonathon Jongsma <[email protected]>
2016-05-04 09:23:25 +02:00
Victor Toso 0064dca2dd console-kit: fix dangling pointer
Introduced recently by b1b8b71961

Acked-by: Jonathon Jongsma <[email protected]>
2016-05-04 09:23:23 +02:00
Victor Toso 691893864f console-kit: Ignore unrequested messages from dbus
Instead of treating them as errors.

Acked-by: Jonathon Jongsma <[email protected]>
2016-05-04 09:23:20 +02:00
Victor Toso b5f0352e9e vdagentd: send file-xfer status, generic version
Change cancel_file_xfer() helper function to file_xfer_status() so we
can send other status to the client.

Acked-by: Jonathon Jongsma <[email protected]>
2016-05-04 09:22:59 +02:00
Victor Toso b1b8b71961 console-kit: include handler for dbus match
At the moment we request to read signals on ConsoleKit.Seat interface
but later on we will request to read signals on different interface so
moving this to its own function helps.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jonathon Jongsma <[email protected]>
2016-04-28 23:01:54 +02:00
Victor Toso 4c1c73cf74 console-kit: include signal handler function
At the moment we are only reading the ActiveSessionChanged signal from
ConsoleKit.Seat but in a later patch we will be reading a few more
signals so it make sense to move this handler to its own function.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jonathon Jongsma <[email protected]>
2016-04-28 23:01:52 +02:00
Victor Toso 9e3e121e35 console-kit: do not use empty session
DBus might return empty string for active-session, probably in a non
user session (e.g. gdm). It is better to keep the variable as NULL as
we check against that (but never against empty strings).

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jonathon Jongsma <[email protected]>
2016-04-28 23:01:49 +02:00
Victor Toso 15052a375b console-kit: save verbosity level for debugging
Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jonathon Jongsma <[email protected]>
2016-04-28 23:01:45 +02:00
Victor Toso 257d5fc0c1 console-kit: use standard name for session-info var
Console-kit was the first back-end implement to gather session info.
When systemd integration was implemented with logind, we introduced
session-info struct to deal with different back-ends.

The 'ck' var was not changed at the time but it seems right to do so.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jonathon Jongsma <[email protected]>
2016-04-28 23:01:43 +02:00
Victor Toso acd48377ac console-kit: use define for dbus paths
This improves readability of all paths related to dbus methods. This
patch only applies for interfaces and object paths, later one it is
included for signals as well.

Signed-off-by: Victor Toso <[email protected]>
Acked-by: Jonathon Jongsma <[email protected]>
2016-04-28 23:01:33 +02:00
Victor Toso 62da1a3329 remove trailing spaces
Acked-by: Pavel Grunt <[email protected]>
2016-04-11 12:15:14 +02:00
Victor Toso 665926f614 Bump glib to 2.28
Removing glib-compat header as it isn't used anymore.
2016-04-11 11:28:35 +02:00
Christophe Fergeau eb01d32221 buildsys: Support libsystemd in addition to libsystemd-login
Since systemd 209, the various systemd helper libraries are gathered in
a single libsystemd, and libsystemd-login is only built when systemd is
built with compat libraries support. Since commit
https://github.com/systemd/systemd/commit/4de282c
"build-sys: drop libsystemd-{id128,daemon,login,journal}.so compat libs"
(2016-02-12), these compat libraries are no longer available.

This commit checks for both libsystemd and libsystemd-login to ensure we
can build on both older and newer systemd versions.

https://bugs.freedesktop.org/show_bug.cgi?id=94209
2016-03-01 11:55:47 +01:00
Francois Gouget fff3058216 vdagent: Mark vdagent and vdagentd functions static
Signed-off-by: Francois Gouget <[email protected]>
2016-01-05 18:18:10 +01:00
Francois Gouget 6a2effa402 vdagent: Disable the server-side udscs code for vdagent
vdagent only needs the client-side API.

Signed-off-by: Francois Gouget <[email protected]>
2015-11-13 17:57:25 +01:00
Francois Gouget c53af3260a vdagent: Allow disabling the server-side udscs support
To do so define UDSCS_NO_SERVER.
This simplifies reuse in client-only scenarios that don't need peer
credential support for instance.

Signed-off-by: Francois Gouget <[email protected]>
2015-11-13 17:57:25 +01:00
Francois Gouget 69c88c633f vdagent: Group the client and server functions together
This will simplify selectively disabling the server-side code.

Signed-off-by: Francois Gouget <[email protected]>
2015-11-13 17:57:25 +01:00
Francois Gouget 02370e4445 vdagent: VDP_LAST_PORT is redundant with VDP_END_PORT. Remove it
VDP_LAST_PORT is equal to VDP_SERVER_PORT while VDP_END_PORT (defined
in spice-protocol) is VDP_SERVER_PORT + 1 so the code needs to be
adjusted to account for this difference.

Signed-off-by: Francois Gouget <[email protected]>
2015-11-13 17:57:07 +01:00
Christophe Fergeau 0159111b22 vdagent: Return '1' when virtio device cannot be opened
The vdagent process currently exits with an error code set to 0 whenn
the virtio device cannot be opened (for example because it's missing).
This is not consistent with the other failures to startup which set the
exit code to 1. This commit ensures 1 is returned in this situation too.

Resolves: rhbz#1256704
2015-09-15 18:09:03 +02:00
Victor Toso 8c465007b4 vdagentd: fixes small leak
This correctly fixes the leak from reverted patch
4835df0b64

    ==2648== HEAP SUMMARY:
    ==2648==     in use at exit: 104,699 bytes in 1,459 blocks
    ==2648==   total heap usage: 14,177 allocs, 12,718 frees, 1,190,456 bytes allocated
    ==2648==
    ==2648== 16 bytes in 1 blocks are definitely lost in loss record 16 of 130
    ==2648==    at 0x4C29BCF: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==2648==    by 0x10B530: agent_read_complete (vdagentd.c:715)
    ==2648==    by 0x10E8DC: udscs_read_complete (udscs.c:460)
    ==2648==    by 0x10EAFC: udscs_do_read (udscs.c:515)
    ==2648==    by 0x10E490: udscs_client_handle_fds (udscs.c:349)
    ==2648==    by 0x10E402: udscs_server_handle_fds (udscs.c:337)
    ==2648==    by 0x10BAB1: main_loop (vdagentd.c:844)
    ==2648==    by 0x10A3E6: main (vdagentd.c:974)
    ==2648==
    ==2648== LEAK SUMMARY:
    ==2648== definitely lost: 16 bytes in 1 blocks
    ==2648== indirectly lost: 0 bytes in 0 blocks
    ==2648== possibly lost: 41,483 bytes in 1,268 blocks
    ==2648== still reachable: 63,200 bytes in 190 blocks
    ==2648== suppressed: 0 bytes in 0 blocks
    ==2648== Reachable blocks (those to which a pointer was found) are not shown.
    ==2648== To see them, rerun with: --leak-check=full --show-leak-kinds=all
2015-09-15 10:49:37 +02:00
Victor Toso f97751faf0 Revert "uinput: fix small leak of screen_info"
This reverts commit 4835df0b64.

uinput only holds reference to screen_info and should not free it.
The leak should be fixed somewhere else.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1262635
2015-09-15 10:23:06 +02:00
Christophe Fergeau 13a4478521 Prepare for 0.16.0 release 2015-06-30 17:08:42 +02:00
Christophe Fergeau d508979b6b Add -fno-strict-aliasing to default CFLAGS
Compilation breaks with older gcc versions (gcc (GCC) 4.4.7 20120313
(Red Hat 4.4.7-11) on RHEL6) with the following error (due to the
additional use of -Werror in the default CFLAGS)
CC     src/src_spice_vdagent-vdagent-x11-randr.o
cc1: warnings being treated as errors
src/vdagent-x11-randr.c: In function ‘vdagent_x11_randr_handle_event’:
src/vdagent-x11-randr.c:499: error: dereferencing pointer ‘sce’ does break strict-aliasing rules
src/vdagent-x11-randr.c:499: error: dereferencing pointer ‘sce’ does break strict-aliasing rules
src/vdagent-x11-randr.c:498: note: initialized from here
make: *** [src/src_spice_vdagent-vdagent-x11-randr.o] Error 1

Strict aliasing is not something we must have for the agent, and the
alternative would most likely involve an anonymous union, or some
casting. Given that this warning only occurs with these older compilers,
better to go with a fix as non-invasive as possible.

Resolves: https://bugs.freedesktop.org/show_bug.cgi?id=90981
2015-06-17 10:44:13 +02:00
Uri Lublin e7f7876190 man: vdagentd: document -f (fake) and -o (once) command line options
Added by commits: 251637aa23 and 1c25f882a
2015-06-01 17:59:37 +03:00
Christophe Fergeau 9b38dd5d6b Bump minimum spice-protocol version
spice-protocol newer than 0.12.7 is needed for the volume
synchronization bits.
2015-05-27 12:42:33 +02:00
Pavel Grunt 536b63cfaf vdagentd-proto-strings: Add missing string for VDAGENTD_AUDIO_VOLUME_SYNC
Avoids a crash when running spice-vdagent with debug

Backtrace:

 #0  0x0000003dcf647e2c in _IO_vfprintf_internal (s=<value optimized out>, format=<value optimized out>, ap=<value optimized out>) at vfprintf.c:1641
 #1  0x0000003dcf6e4e90 in __vsyslog_chk (pri=<value optimized out>, flag=-1, fmt=0x40f360 "%p received %s, arg1: %u, arg2: %u, size %u", ap=0x7fffffffddc0) at ../misc/syslog.c:222
 #2  0x0000003dcf6e50c0 in __syslog (pri=<value optimized out>, fmt=<value optimized out>) at ../misc/syslog.c:119
 #3  0x000000000040c6da in udscs_read_complete (connp=0x610de8) at src/udscs.c:448
 #4  0x000000000040c8d1 in udscs_do_read (connp=0x610de8) at src/udscs.c:500
 #5  0x000000000040c303 in udscs_client_handle_fds (connp=0x610de8, readfds=0x7fffffffe0a0, writefds=0x7fffffffe020) at src/udscs.c:349
 #6  0x0000000000403d74 in main (argc=3, argv=0x7fffffffe248) at src/vdagent.c:365
2015-04-29 09:16:09 +02:00
Victor Toso 9b0eb8b124 vdagent: volume synchronization from client.
Include the capability of volume sync to set volume or mute to default
sink-input/source-output of guest.
2015-04-24 17:31:20 +02:00
Victor Toso 010dc21f35 audio: add functions to set volume/mute with alsa
This patch includes the vdagent-audio.[ch] files in order to
communicate with backend audio server.

The two functions provide a way to set volume and mute in the guest
by connecting to default mixer control in alsa which is 'Master' for
playback and 'Capture' for record.
2015-04-24 17:31:20 +02:00
Fabiano Fidêncio 6c0160e8a3 Fix implicit declaration of 'g_unlink' (warning)
Related: https://bugzilla.redhat.com/show_bug.cgi?id=1086657
2015-04-12 00:03:28 +02:00
Marc-Andre Lureau a8bbff07b1 randr: handle XRRScreenChangeNotifyEvent
Make sure vdagent follows the current monitor configuration.  This
solves a number of issue where the pointer input is off, because the
uinput tablet isn't reconfigured.

https://bugzilla.redhat.com/show_bug.cgi?id=1086657
2015-04-10 15:57:46 +02:00
Marc-Andre Lureau 28618682ae randr: remove monitors.xml on auto-configuration
GNOME will restore monitors.xml configuration whenever the timestamp
"config > change". The "change" timestamp is the last user applied
configuration, whereas the "config" timestamp is updated when
the screen is updated or ouput/crtc modes are added/removed.

These condition are triggered by vdagent during monitor config. Since we
can't control the timestamps (playing with delay will be inherently
event more racy), the only sane way I can think of is to disable gsd
behaviour. This can be achieved by deleting the ~/.config/monitors.xml,
which is the intended configuration to restore, so vdagent will override
whatever configuration was saved previously.

Somehow, if vdagent would be better integrated with gnome2, it would use
the gnome-rr and/or org.gnome.SettingsDaemon.XRANDR dbus
API. Thanksfully, in gnome3, the monitor auto-configuration has been
merged in.

https://bugzilla.redhat.com/show_bug.cgi?id=1086657
2015-04-10 15:57:46 +02:00
Christophe Fergeau 21f4927531 build-sys: Enable large file support
This is needed on 32 bit machines for drag and drop of large files (>2GB
to work). This fixes https://bugzilla.redhat.com/show_bug.cgi?id=1206663
2015-04-10 12:58:17 +02:00
Christophe Fergeau 8003f9e01f Remove unneeded NULL check
Since previous commit, vdagent_x11_set_monitor_config() will return
early if 'curr' is NULL so we don't need to explicitly check its value.
Issue reported by the Coverity checker.
2015-04-01 10:58:43 +02:00
Christophe Fergeau 7329ad767f Handle get_current_mon_config() failures
get_current_mon_config() can return NULL, but
vdagent_x11_set_monitor_config() was calling it without checking if it's
NULL before dereferencing it.
This issue was pinpointed by Coverity.
2015-04-01 10:58:42 +02:00
Victor Toso 4835df0b64 uinput: fix small leak of screen_info
The following leak is fixed by this patch:
==2648== HEAP SUMMARY:
==2648==     in use at exit: 104,699 bytes in 1,459 blocks
==2648==   total heap usage: 14,177 allocs, 12,718 frees, 1,190,456 bytes allocated
==2648==
==2648== 16 bytes in 1 blocks are definitely lost in loss record 16 of 130
==2648==    at 0x4C29BCF: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==2648==    by 0x10B530: agent_read_complete (vdagentd.c:715)
==2648==    by 0x10E8DC: udscs_read_complete (udscs.c:460)
==2648==    by 0x10EAFC: udscs_do_read (udscs.c:515)
==2648==    by 0x10E490: udscs_client_handle_fds (udscs.c:349)
==2648==    by 0x10E402: udscs_server_handle_fds (udscs.c:337)
==2648==    by 0x10BAB1: main_loop (vdagentd.c:844)
==2648==    by 0x10A3E6: main (vdagentd.c:974)
==2648==
==2648== LEAK SUMMARY:
==2648==    definitely lost: 16 bytes in 1 blocks
==2648==    indirectly lost: 0 bytes in 0 blocks
==2648==      possibly lost: 41,483 bytes in 1,268 blocks
==2648==    still reachable: 63,200 bytes in 190 blocks
==2648==         suppressed: 0 bytes in 0 blocks
==2648== Reachable blocks (those to which a pointer was found) are not shown.
==2648== To see them, rerun with: --leak-check=full --show-leak-kinds=all
2015-03-27 16:42:48 +01:00
Fabiano Fidêncio 4e9b291773 vdagent-file-xfers: only open the file transfer dir when all the files were transferred
Once transferring multiple files is supported, do not bother the user
opening the file transfer directory for each file transferred, just do it
when the last file transfer is finished.
2014-09-18 13:37:27 +02:00
Christophe Fergeau 9ea18740b8 Report an error when file transfers are disabled
This commit sends back a VD_AGENT_FILE_XFER_STATUS_ERROR to clients which
try to transfer files when the agent disabled file transfers (for example
because there is no valid destination directory for the transferred files).
2014-09-18 13:34:26 +02:00
Christophe Fergeau 689dcd35ed Disable file xfer when no suitable destination dir
Currently, if no suitable destination directory can be found, the file
transfer code defaults to using '.' as the destination directory. As this
is unlikely to work, better to just disable file transfers when we end up
in such a situation. This currently happens when spawning spice-vdagent
from gdm where we don't want file transfers to be available anyway.
2014-09-18 13:34:26 +02:00
Christophe Fergeau 7fc4525dce Make creation of 'vdagent_file_xfers' optional
This commit only adds if (vdagent_file_xfers != NULL) {} checks before
calling into the file transfer code. This allows to disable file transfer
handling by setting this variable to NULL.
2014-09-18 13:34:26 +02:00
Christophe Fergeau ec9f11064e Add g_return_if_fail() guards to file xfer public functions
With the next commit, we won't always have a file xfer object available.
This next commit will make sure NULL is never passed to the public file
xfer functions, but it's safer to guard against that anyway in case
this gets broken in the future.
2014-09-18 13:34:26 +02:00
Marc-André Lureau 072fb03fa4 data: remove rsyslog config files
Many systems don't use rsyslog, others don't need seperate syslog files
for vdagent.

With systemd journal, It's possible to filter
spice-vdagent/spice-vdagentd log messages out of /var/log/messages:
journalctl SYSLOG_IDENTIFIER=spice-vdagent SLOG_IDENTIFIER=spice-vdagentd

This simplify spice-vdagent packaging and updates, since there are no
config files to deal with.

Related:
https://bugzilla.redhat.com/show_bug.cgi?id=1136881
2014-09-08 11:34:51 +02:00
Marc-André Lureau 658c4d76e2 Handle STRING selection type
This is to please vncviewer.

https://bugzilla.redhat.com/show_bug.cgi?id=1117764
2014-07-21 12:20:47 +02:00
Marc-André Lureau b87fab52eb Reply to TIMESTAMP requests
Add TIMESTAMP handling,
This is to please vncviewer.

https://bugzilla.redhat.com/show_bug.cgi?id=1117764
2014-07-21 12:20:47 +02:00
Jeremy White 1c25f882a3 Add an option such that the daemon will exit after processing a single session.
Signed-off-by: Jeremy White <[email protected]>
2014-07-10 15:45:16 +03:00
Jeremy White 2f602c03eb Make sure the child is able to connect to the X server before exiting the mainline.
This allows the vdagent to be used in the Xsetup phase of an xdm session;
otherwise, it's X11 connection fails because of the greeter display grab.

The issue is that we daemonize before attempting the X connection.
We then immediately exit the main process; xdm then goes on to invoke the
greeter which performs an exclusive grab on the X server, so the child
connection fails.

The change is to have the main process wait for up to 10 seconds for an 'all clear'
message from the client.  This lets us return a correct status on a real X
error, as well as letting our child successfully connect to the X server.

Signed-off-by: Jeremy White <[email protected]>
2014-07-10 15:45:13 +03:00
Jeremy White 251637aa23 Add an explicit switch to signal fake uinput devices.
Signed-off-by: Jeremy White <[email protected]>
2014-07-10 15:45:11 +03:00
Christophe Fergeau 7d858d5064 Fix gdm autostart path
gdm 3.1.90 (June 2011) changed the path where .desktop files which should
be autostarted with gdm needs to be located.
This used to be $(datadir)/gdm/autostart/LoginWindow and is now
$(datadir)/gdm/greeter/autostart.
This means that when running gdm in a VM in a recent distribution,
arbitrary resizing the VM window will not cause the resolution to be
adjusted. This used to be working in eg RHEL6.

This patch installs the .desktop file to both paths in order to work both
with older and newer gdms.
2014-02-25 16:30:27 +01:00
Marc-André Lureau fa42110482 randr: set physical screen size to keep a constant 96 dpi
Some applications compute DPI based on physcial screen size.  Currently,
the width is reported to be 270mm, regardless of the resolution.  This
patch instead compute a physical screen size to have a constant DPI of
96. Of course, there are possible improvements to this approach (see
fixme), however, since that code is no longer executed with DRM driver,
I don't think we should invest more effort here (I guess DRM driver
relies on xrandr / gnome-settings-daemon to do the right thing, so
physical screen is updated)

https://bugzilla.redhat.com/show_bug.cgi?id=1066094
2014-02-24 22:02:04 +01:00
Jonathon Jongsma 6e2e82e6fb Don't abort if XRRSetCrtcConfig fails
In certain configurations (Fedora 20 or RHEL7 guests on a RHEL6 host), this call
fails, which cause the vdagent to abort. This patch prevents the crash, though
arbitrary resizing is obviously still non-functional in this situation.
2014-02-24 11:50:27 +01:00
Christophe Fergeau 9ae51f3702 randr: Make resolution changing more robust
When running a guest using a KMS QXL driver on a RHEL6 hypervisor,
spice_vdagent would crash on resolution changes with:
X Error of failed request:  BadValue (integer parameter out of range for operation)
  Major opcode of failed request:  139 (RANDR)
  Minor opcode of failed request:  21 (RRSetCrtcConfig)
  Value in failed request:  0x0
  Serial number of failed request:  75
  Current serial number in output stream:  75

(if using a newer QEMU, this will not crash as the resolution codepath is
totally different, see red_dispatcher_use_client_monitors_config() in
spice-server, when using the UMS QXL driver, the crash will not happen
because of
http://cgit.freedesktop.org/xorg/driver/xf86-video-qxl/commit/?id=907d0ff0
).

This crash happens in vdagent_x11_set_monitor_config() because the X server
rejects the request because we are trying to set a CRTC to a size which is
bigger than the current screen (using 'screen' and 'CRTC' as in the RandR
spec at http://www.x.org/releases/X11R7.5/doc/randrproto/randrproto.txt ).

If we resize the screen before changing the CRTCs resolution, then this
error will no longer happen. However, if we first call XRRSetScreenSize()
and then XRRSetCrtcConfig(), the call to XRRSetScreeSize() will fail when
we try to make the screen smaller as there will be active CRTCs which would
be bigger than the screen.

In order to solve these issues, we follow the same process as what mutter
does in meta_monitor_manager_xrandr_apply_configuration()
https://git.gnome.org/browse/mutter/tree/src/core/monitor-xrandr.c#n689:

1. we disable the CRTCs which are off and the ones which are bigger than the
   size we want to set the screen to.
2. we resize the screen with a call to XRRSetScreenSize().
3. we set each CRTCs to their new resolution.
2014-02-24 11:41:09 +01:00
Marc-André Lureau a30c981870 Add VD_AGENT_CAP_MAX_CLIPBOARD support
Do not send clipboard data bigger than last received
VDAgentMaxClipboard.

There is no need to further limit at the session agent, since it is
already OOM safe, and since marhsalling/sending is local, that shouldn't
make any stability or speed difference that deserves the added
complexity.
2014-01-31 12:46:22 +01:00
Marc-André Lureau b8c2890228 Add a warning for unhandled case 2014-01-31 12:46:22 +01:00
Marc-André Lureau ae17559dd0 Add a virtio_write_clipboard() function
Make it easier later to send customized clipboard message
2014-01-31 12:46:22 +01:00
Uri Lublin 29022fdc3b clipboard target_to_type: fix inner loop variable name 2013-11-27 18:38:13 +02:00
81 changed files with 11120 additions and 3610 deletions

No files matched your search

+144
View File
@@ -0,0 +1,144 @@
name: Build
on:
push:
pull_request:
jobs:
build-macos:
name: Build macOS
runs-on: macos-15
env:
GLIB_VERSION: "2.90.0"
GLIB_SHA256: 17d15cac2af80a33271127408e0abc2748eb297c595c2a26409e81e14e7d1b8f
GETTEXT_VERSION: "1.0"
GETTEXT_SHA256: 71132a3fb71e68245b8f2ac4e9e97137d3e5c02f415636eb508ae607bc01add7
# must be <= the project's deployment target
MACOSX_DEPLOYMENT_TARGET: "10.13"
ARCHS: arm64 x86_64
steps:
- name: Checkout
uses: actions/checkout@v3
with:
submodules: recursive
- name: Install build tools
run: |
brew install meson ninja pkgconf
echo "GLIB_PREFIX=$RUNNER_TEMP/glib" >> "$GITHUB_ENV"
- name: Cache GLib
id: cache
uses: actions/cache@v4
with:
path: ${{ runner.temp }}/glib
key: glib-${{ env.GLIB_VERSION }}-gettext-${{ env.GETTEXT_VERSION }}-${{ hashFiles('.github/workflows/build.yaml') }}
- name: Build gettext
if: steps.cache.outputs.cache-hit != 'true'
working-directory: ${{ runner.temp }}
run: |
curl -fsSLO "https://ftp.gnu.org/gnu/gettext/gettext-$GETTEXT_VERSION.tar.xz"
echo "$GETTEXT_SHA256 gettext-$GETTEXT_VERSION.tar.xz" | shasum -a 256 -c -
for arch in $ARCHS; do
rm -rf "gettext-$GETTEXT_VERSION"
tar xf "gettext-$GETTEXT_VERSION.tar.xz"
pushd "gettext-$GETTEXT_VERSION/gettext-runtime"
./configure --host="${arch/arm64/aarch64}-apple-darwin" \
--prefix="$GLIB_PREFIX/$arch" \
--enable-static \
--disable-shared \
--with-included-gettext \
--disable-java \
--disable-csharp \
--disable-libasprintf \
--without-libintl-prefix \
--without-libiconv-prefix \
CC="clang -arch $arch"
make -C intl -j"$(sysctl -n hw.ncpu)"
make -C intl install
popd
done
- name: Build GLib
if: steps.cache.outputs.cache-hit != 'true'
working-directory: ${{ runner.temp }}
run: |
curl -fsSLO "https://download.gnome.org/sources/glib/${GLIB_VERSION%.*}/glib-$GLIB_VERSION.tar.xz"
echo "$GLIB_SHA256 glib-$GLIB_VERSION.tar.xz" | shasum -a 256 -c -
tar xf "glib-$GLIB_VERSION.tar.xz"
# girepository is unused and requires macOS 10.15
sed -i '' "/^subdir('girepository')$/d" "glib-$GLIB_VERSION/meson.build"
sdk="$(xcrun --sdk macosx --show-sdk-path)"
for arch in $ARCHS; do
prefix="$GLIB_PREFIX/$arch"
mkdir -p "$prefix/lib/pkgconfig"
cat > "$prefix/lib/pkgconfig/libffi.pc" <<EOF
Name: libffi
Description: Library supporting Foreign Function Interfaces
Version: 3.4
Cflags: -I$sdk/usr/include/ffi
Libs: -lffi
EOF
# don't depend on Rosetta
[ "$arch" = "$(uname -m)" ] && needs_exe_wrapper=false || needs_exe_wrapper=true
cat > "cross-$arch.ini" <<EOF
[binaries]
c = ['clang', '-arch', '$arch']
cpp = ['clang++', '-arch', '$arch']
objc = ['clang', '-arch', '$arch']
ar = 'ar'
strip = 'strip'
pkg-config = 'pkg-config'
[built-in options]
c_args = ['-I$prefix/include', '-Werror=unguarded-availability-new']
cpp_args = ['-I$prefix/include']
objc_args = ['-I$prefix/include', '-Werror=unguarded-availability-new']
c_link_args = ['-L$prefix/lib']
cpp_link_args = ['-L$prefix/lib']
objc_link_args = ['-L$prefix/lib']
[properties]
needs_exe_wrapper = $needs_exe_wrapper
pkg_config_libdir = ['$prefix/lib/pkgconfig']
# macOS 27+, meson's check ignores availability
has_function_pipe2 = false
[host_machine]
system = 'darwin'
subsystem = 'macos'
kernel = 'xnu'
cpu_family = '${arch/arm64/aarch64}'
cpu = '${arch/arm64/aarch64}'
endian = 'little'
EOF
# SDK has no pcre2 headers; other fallbacks would silently stub out deps (e.g. libintl)
meson setup "build-$arch" "glib-$GLIB_VERSION" \
--cross-file "cross-$arch.ini" \
--prefix="$prefix" \
--buildtype=release \
--default-library=static \
--wrap-mode=nofallback \
--force-fallback-for=libpcre2-8 \
-Dbsymbolic_functions=false \
-Ddtrace=disabled \
-Dintrospection=disabled \
-Dnls=disabled \
-Dman-pages=disabled \
-Ddocumentation=false \
-Dtests=false
meson compile -C "build-$arch"
meson install -C "build-$arch"
done
- name: Build
run: |
xcodebuild archive -scheme vd_agent -archivePath vd_agent.xcarchive \
ARCHS="$ARCHS" ONLY_ACTIVE_ARCH=NO \
GLIB_ARM64_PREFIX="$GLIB_PREFIX/arm64" \
GLIB_X86_64_PREFIX="$GLIB_PREFIX/x86_64"
- name: Archive
run: tar -acf vd_agent.xcarchive.tgz vd_agent.xcarchive
- name: Upload
uses: actions/upload-artifact@v4
with:
name: vd_agent-macOS
path: vd_agent.xcarchive.tgz
+9 -3
View File
@@ -1,13 +1,17 @@
*~
*.o
.deps
.dirstamp
data/spice-vdagent*.1
src/config.h
src/config.h.in
src/spice-vdagent
src/spice-vdagentd
src/stamp-h1
src/*.o
src/.deps
src/.dirstamp
tests/test-*.log
tests/test-*.trs
tests/test-file-xfers
tests/test-device-info
config.log
config.status
aclocal.m4
@@ -19,3 +23,5 @@ install-sh
Makefile.in
Makefile
missing
test-driver
test-suite.log
+58
View File
@@ -0,0 +1,58 @@
image: fedora:latest
variables:
DEPS_COMMON: git libtool make python3 python3-six redhat-rpm-config
bzip2 python3-pyparsing meson ninja-build gtk-doc glib2-devel
gettext gettext-devel libpciaccess-devel alsa-lib-devel
libXfixes-devel libX11-devel libXrandr-devel libXinerama-devel
gtk3-devel dbus-devel systemd-devel procps-ng libdrm-devel gtk4-devel
vulkan-headers
DISTCHECK_CONFIGURE_FLAGS:
--with-session-info=none
before_script:
- dnf install -y $DEPS_COMMON
- git clone https://gitlab.freedesktop.org/spice/spice-protocol.git
- meson --buildtype=release spice-protocol build-spice-protocol --prefix=/usr --werror
- ninja -C build-spice-protocol install
fedora-autotools:
script:
- ./autogen.sh
- make
- git clean -xfd
- ./autogen.sh --with-session-info=none
- make distcheck --environment-overrides
- git clean -xfd
- ./autogen.sh --with-session-info=systemd --with-init-script=systemd+redhat
- make
- make install
- make uninstall
- git clean -xfd
- ./autogen.sh --with-session-info=console-kit --with-init-script=redhat
- make
- make install
- make uninstall
- git clean -xfd
- ./autogen.sh --with-gtk=no --with-session-info=none
- make
- make install
- make uninstall
- git clean -xfd
- ./autogen.sh --with-gtk4
- make
- make install
- make uninstall
- git clean -xfd
artifacts:
expire_in: '1 week'
when: on_failure
paths:
- test-suite.log
- tests/test*.log
+186
View File
@@ -0,0 +1,186 @@
Gitlab markdown format support linking to Issues (#) and Merge requests (!) and more, see below:
https://gitlab.freedesktop.org/spice/linux/vd_agent/-/blob/master/CHANGELOG.md
News in spice-vdagent 0.22.1
===========================
* !42 - Fix crash on startup of session agent
News in spice-vdagent 0.22.0
===========================
* !40 - Handle side mouse buttons
* !39 - Set retry limit to connect to vdagentd and improve logging error
* !35 - Fix deprecation warning
* !37 - Provide systemd spice-vdagent.service
News in spice-vdagent 0.21.0
============================
* Security fixes:
CVE-2020-25650, CVE-2020-25651, CVE-2020-25652, CVE-2020-25653
* Fix shutdown issue due to incompatible thread/fork uses with GLib
* Fix mouse pointer issues under Wayland
* Fix a crash when running without dbus (e.g: within containers)
* !9 - Introduce optional GTK4 support for monitor management
* !13 - Enable copying files from client using webdav
* Bump spice-protocol dependency to v0.14.3
News in spice-vdagent 0.20.0
============================
* Add gio-unix and gobject dependency >= 2.50
* Bump gtk+ >= 3.22 (optional dependency)
* Last release with gtk+ being optional
* !4 - Race fixes between client and guest clipboard
* !2 - Fix session lookup for new GNOME versions
* !3 - Now using GMainLoop and GIO to handle I/O of messages
* Several minor covscan fixes
News in spice-vdagent 0.19.0
============================
* Add libdrm dependency
* Fix file descriptor leak on failed connections
* Handle new VD_AGENT_GRAPHICS_DEVICE_INFO message advertised by
VD_AGENT_CAP_GRAPHICS_DEVICE_INFO capability
* Session agent autostart changed to WindowManager ([rhbz#1623947])
This fixes possible race with xdg-user-dirs
* Fix of sending empty screen resolution messages ([rhbz#1641723])
* Fix 'Dependency failed for Activation socket' with systemd ([rhbz#1545212])
* Fix error messages about on selecting text on host ([rhbz#1594876])
this was also fixed with Gtk backend
* Update paths from /var/run → /run
* Fix Session agent restart
* Add test for file creation
* Prefer GLib memory functions stdlib.h ones
* Several code and logs improvements
[rhbz#1623947]: https://bugzilla.redhat.com/show_bug.cgi?id=1623947
[rhbz#1641723]: https://bugzilla.redhat.com/show_bug.cgi?id=1641723
[rhbz#1545212]: https://bugzilla.redhat.com/show_bug.cgi?id=1545212
[rhbz#1594876]: https://bugzilla.redhat.com/show_bug.cgi?id=1594876
News in spice-vdagent 0.18.0
============================
* Add GTK+ framework to handle x11 backend such as clipboard
* Deprecate X11 backend in favor of GTK+ framework
* Ask pkg-config to appropriate directory to install udev rules
* Fix leak of udscs's file descriptor
* Better quote directory path when calling xdg-open to save file transfer
* Bump GLib to 2.34
* Add systemd socket activation (rhbz#1340160)
* Add support to detailed errors on file transfers
* Add check for available free space in guest before starting a file transfer
* Use better names for duplicated files on file transfer
* Improve support on big endian guests (#5)
* Use IdleHint to check if a session is locked over console-kit (rhbz#1412673)
* Fixes double free on errors over udscs by improving memory ownership
* Hide autostart file on Unity
* Improve command line messages for vdagentd
* Fix typo in --enable-static-uinput configure option
* Code repository moved to gitlab.freedesktop.org
News in spice-vdagent 0.17.0
============================
* Denies file-transfer in locked sessions
* systems under systemd (rhbz#1323623)
* systems under console-kit (rhbz#1323630)
* Denies file-transfer in login screen
* systems under systemd (rhbz#1328761)
* systems under console-kit (rhbz#1323640)
* Bump glib version to 2.28
* Set exit code to 1 instead of 0 when virtio device cannot be opened
* Fix double-free on uinput->screen_info (rhbz#1262635)
* Code improvement over unix domain client server support (udcs)
* Fix build compatibility with different libsystemd versions (fdo#94209)
News in spice-vdagent 0.16.0
============================
* Add audio volume synchronization support
* Add support for maximum clipboard size
* Add support for more clipboard targets (STRING and TIMESTAMP)
* Improve handling of transfers of multiple files
* Fix transfer of >2GB files on 32 bit systems
* XSpice improvements
* Various bug fixes related to resolution changes
News in spice-vdagent 0.15.0
============================
* Xspice support
* Release clipboard on client disconnect if owned by client (rhbz#1003977)
* Turn some error messages into debugging messages (rhbz#918310)
* Not having the virtio channel is not an error; instead silently do nothing
News in spice-vdagent 0.14.0
============================
* More multi-monitor and arbitrary resolution support bugfixes
* Add support for file transfers from client to guest
* Add support for setups with multiple Screens (multiple qxl devices each
mapped to their own screen), limitations:
* Max one monitor per Screen / qxl device
* All monitors / Screens must have the same resolution
* No client -> guest resolution syncing
* Add spice-vdagent -X cmdline option, which runtime disables console-kit /
systemd-logind integration for setups where these are not used
* Add manpages for spice-vdagent and spice-vdagentd
News in spice-vdagent 0.12.1
============================
* Various bugfixes for multi-monitor and arbitrary resolution support
* Requires libXrandr >= 1.3, Note 0.12.0 also required this, but did not
check for it. For older distributions use 0.10.1
News in spice-vdagent 0.12.0
============================
* Full multi-monitor and arbitrary resolution support, this requires a new
enough xorg-x11-drv-qxl driver, as well as a new enough host
* systemd service support, using systemd hardware activation
* Use syslog for logging, rather then logging to private log files
News in spice-vdagent 0.10.1
============================
* Fix a race condition when opening the vdagent virtio serial port, which
caused it to get opened / closed in rapid succession a number of times
on vm boot
News in spice-vdagent 0.10.0
============================
* Add limited support for multiple displays, see README
* Add support for RHEL-5 (and other distributions with a non hotplug
capable Xorg and/or no console-kit), see README.RHEL-5
* Add support for using libsystemd-logind as session information source
instead of console-kit
News in spice-vdagent 0.8.1
===========================
* In daemon mode the session vdagent now retries connecting to the system
vdagentd every second, once a connection is made a version check is done,
if the version differs (which only happens on an upgrade from one version
to the next) the session vdagent re-execs itself (Marc-André Lureau)
News in spice-vdagent 0.8.0
===========================
* Add support for copy and paste using the primary selection, to use this
you need a spice-gtk widget based client and the latest spice-gtk code
(Marc-André Lureau and Hans de Goede)
* Autotoolized (Christophe Fergeau)
* Allow building without consolekit, for systems which don't have ck, such
as RHEL-5 (Christophe Fergeau)
* Various small bugfixes (Hans de Goede)
News in spice-vdagent 0.6.3
===========================
* Initial release, starting with version nr 0.6.3, to indicate that it
more or less supports all parts of the cdagent protocol in spice-protocol
and spice 0.6.3
-69
View File
@@ -1,69 +0,0 @@
spice-vdagent-0.15.0
--------------------
* Xspice support
* Release clipboard on client disconnect if owned by client (rhbz#1003977)
* Turn some error messages into debugging messages (rhbz#918310)
* Not having the virtio channel is not an error; instead silently do nothing
spice-vdagent-0.14.0
--------------------
* More multi-monitor and arbritary resolution support bugfixes
* Add support for file transfers from client to guest
* Add support for setups with multiple Screens (multiple qxl devices each
mapped to their own screen), limitations:
-Max one monitor per Screen / qxl device
-All monitors / Screens must have the same resolution
-No client -> guest resolution syncing
* Add spice-vdagent -X cmdline option, which runtime disables console-kit /
systemd-logind integration for setups where these are not used
* Add manpages for spice-vdagent and spice-vdagentd
spice-vdagent-0.12.1
--------------------
* Various bugfixes for multi-monitor and arbritary resolution support
* Requires libXrandr >= 1.3, Note 0.12.0 also required this, but did not
check for it. For older distributions use 0.10.1
spice-vdagent-0.12.0
--------------------
* Full multi-monitor and arbritary resolution support, this requires a new
enough xorg-x11-drv-qxl driver, as well as a new enough host
* systemd service support, using systemd hardware acivation
* Use syslog for logging, rather then logging to private log files
spice-vdagent-0.10.1
--------------------
* Fix a race condition when opening the vdagent virtio serial port, which
caused it to get opened / closed in rapid succession a number of times
on vm boot
spice-vdagent-0.10.0
--------------------
* Add limited support for multiple displays, see README
* Add support for RHEL-5 (and other distributions with a non hotplug
capable Xorg and/or no console-kit), see README.RHEL-5
* Add support for using libsystemd-logind as session information source
instead of console-kit
spice-vdagent-0.8.1
-------------------
* In daemon mode the session vdagent now retries connecting to the system
vdagentd every second, once a connection is made a version check is done,
if the version differs (which only happens on an upgrade from one version
to the next) the sesion vdagent re-execs itself (Marc-André Lureau)
spice-vdagent-0.8.0
-------------------
* Add support for copy and paste using the primary selection, to use this
you need a spice-gtk widget based client and the latest spice-gtk code
(Marc-André Lureau and Hans de Goede)
* Autotoolized (Christophe Fergeau)
* Allow building without consolekit, for systems which don't have ck, such
as RHEL-5 (Christophe Fergeau)
* Various small bugfixes (Hans de Goede)
spice-vdagent-0.6.3
-------------------
* Initial release, starting with version nr 0.6.3, to indicate that it
more or less supports all parts of the cdagent protocol in spice-protocol
and spice 0.6.3
+156 -40
View File
@@ -3,53 +3,155 @@ NULL =
bin_PROGRAMS = src/spice-vdagent
sbin_PROGRAMS = src/spice-vdagentd
check_PROGRAMS = tests/test-file-xfers
TESTS = $(check_PROGRAMS)
src_spice_vdagent_CFLAGS = $(X_CFLAGS) $(SPICE_CFLAGS) $(GLIB2_CFLAGS)
src_spice_vdagent_LDADD = $(X_LIBS) $(SPICE_LIBS) $(GLIB2_LIBS)
src_spice_vdagent_SOURCES = src/vdagent.c src/vdagent-x11.c src/vdagent-x11-randr.c src/vdagent-file-xfers.c src/udscs.c
common_sources = \
src/udscs.c \
src/udscs.h \
src/vdagent-connection.c \
src/vdagent-connection.h \
src/vdagentd-proto-strings.h \
src/vdagentd-proto.h \
$(NULL)
src_spice_vdagent_CFLAGS = \
$(DRM_CFLAGS) \
$(X_CFLAGS) \
$(SPICE_CFLAGS) \
$(GIO2_CFLAGS) \
$(GTK_CFLAGS) \
$(ALSA_CFLAGS) \
-I$(srcdir)/src \
-DUDSCS_NO_SERVER \
$(NULL)
src_spice_vdagent_LDADD = \
$(DRM_LIBS) \
$(X_LIBS) \
$(SPICE_LIBS) \
$(GIO2_LIBS) \
$(GTK_LIBS) \
$(ALSA_LIBS) \
$(NULL)
src_spice_vdagent_SOURCES = \
$(common_sources) \
src/vdagent/audio.c \
src/vdagent/audio.h \
src/vdagent/clipboard.c \
src/vdagent/clipboard.h \
src/vdagent/webdav-cb.c \
src/vdagent/webdav-cb.h \
src/vdagent/device-info.c \
src/vdagent/device-info.h \
src/vdagent/display.c \
src/vdagent/display.h \
src/vdagent/file-xfers.c \
src/vdagent/file-xfers.h \
src/vdagent/mutter.c \
src/vdagent/mutter.h \
src/vdagent/x11-priv.h \
src/vdagent/x11-randr.c \
src/vdagent/x11.c \
src/vdagent/x11.h \
src/vdagent/vdagent.c \
$(NULL)
tests_test_file_xfers_CFLAGS = \
$(SPICE_CFLAGS) \
$(GIO2_CFLAGS) \
-I$(srcdir)/src \
-I$(srcdir)/src/vdagent \
-DUDSCS_NO_SERVER \
$(NULL)
tests_test_file_xfers_LDADD = \
$(SPICE_LIBS) \
$(GIO2_LIBS) \
$(NULL)
tests_test_file_xfers_SOURCES = \
$(common_sources) \
src/vdagent/file-xfers.c \
src/vdagent/file-xfers.h \
tests/test-file-xfers.c \
$(NULL)
src_spice_vdagentd_CFLAGS = \
$(DBUS_CFLAGS) \
$(LIBSYSTEMD_DAEMON_CFLAGS) \
$(LIBSYSTEMD_LOGIN_CFLAGS) \
$(PCIACCESS_CFLAGS) \
$(SPICE_CFLAGS) \
$(GIO2_CFLAGS) \
$(PIE_CFLAGS) \
-I$(srcdir)/src \
$(NULL)
src_spice_vdagentd_LDADD = \
$(DBUS_LIBS) \
$(LIBSYSTEMD_DAEMON_LIBS) \
$(LIBSYSTEMD_LOGIN_LIBS) \
$(PCIACCESS_LIBS) \
$(SPICE_LIBS) \
$(GIO2_LIBS) \
$(PIE_LDFLAGS) \
$(NULL)
src_spice_vdagentd_SOURCES = \
$(common_sources) \
src/vdagentd/vdagentd.c \
src/vdagentd/session-info.h \
src/vdagentd/uinput.c \
src/vdagentd/uinput.h \
src/vdagentd/xorg-conf.c \
src/vdagentd/xorg-conf.h \
src/vdagentd/virtio-port.c \
src/vdagentd/virtio-port.h \
$(NULL)
tests_test_session_info_CFLAGS = \
$(DBUS_CFLAGS) \
$(GIO2_CFLAGS) \
-I$(srcdir)/src \
-I$(srcdir)/src/vdagentd \
$(NULL)
tests_test_session_info_LDADD = \
$(DBUS_LIBS) \
$(GIO2_LIBS) \
$(NULL)
tests_test_session_info_SOURCES = \
src/vdagentd/session-info.h \
tests/test-session-info.c \
$(NULL)
src_spice_vdagentd_CFLAGS = $(DBUS_CFLAGS) $(LIBSYSTEMD_LOGIN_CFLAGS) \
$(PCIACCESS_CFLAGS) $(SPICE_CFLAGS) $(GLIB2_CFLAGS) $(PIE_CFLAGS)
src_spice_vdagentd_LDADD = $(DBUS_LIBS) $(LIBSYSTEMD_LOGIN_LIBS) \
$(PCIACCESS_LIBS) $(SPICE_LIBS) $(GLIB2_LIBS) $(PIE_LDFLAGS)
src_spice_vdagentd_SOURCES = src/vdagentd.c \
src/vdagentd-uinput.c \
src/vdagentd-xorg-conf.c \
src/vdagent-virtio-port.c \
src/udscs.c
if HAVE_CONSOLE_KIT
src_spice_vdagentd_SOURCES += src/console-kit.c
src_spice_vdagentd_SOURCES += src/vdagentd/console-kit.c
tests_test_session_info_SOURCES += src/vdagentd/console-kit.c
check_PROGRAMS += tests/test-session-info
else
if HAVE_LIBSYSTEMD_LOGIN
src_spice_vdagentd_SOURCES += src/systemd-login.c
src_spice_vdagentd_SOURCES += src/vdagentd/systemd-login.c
tests_test_session_info_CFLAGS += $(LIBSYSTEMD_LOGIN_CFLAGS)
tests_test_session_info_LDADD += $(LIBSYSTEMD_LOGIN_LIBS)
tests_test_session_info_SOURCES += src/vdagentd/systemd-login.c
check_PROGRAMS += tests/test-session-info
else
src_spice_vdagentd_SOURCES += src/dummy-session-info.c
src_spice_vdagentd_SOURCES += src/vdagentd/dummy-session-info.c
endif
endif
noinst_HEADERS = src/glib-compat.h \
src/session-info.h \
src/udscs.h \
src/vdagent-file-xfers.h \
src/vdagent-virtio-port.h \
src/vdagent-x11.h \
src/vdagent-x11-priv.h \
src/vdagentd-proto.h \
src/vdagentd-proto-strings.h \
src/vdagentd-uinput.h \
src/vdagentd-xorg-conf.h
xdgautostartdir = $(sysconfdir)/xdg/autostart
xdgautostart_DATA = $(top_srcdir)/data/spice-vdagent.desktop
gdmautostartdir = $(datadir)/gdm/autostart/LoginWindow
gdmautostartdir = $(datadir)/gdm/greeter/autostart
gdmautostart_DATA = $(top_srcdir)/data/spice-vdagent.desktop
install-data-local:
$(mkdir_p) $(DESTDIR)$(localstatedir)/run/spice-vdagentd
rsyslogdir = $(sysconfdir)/rsyslog.d
rsyslog_DATA = $(top_srcdir)/data/rsyslog.d/spice-vdagentd.conf
gdmautostart2dir = $(datadir)/gdm/autostart/LoginWindow
gdmautostart2_DATA = $(top_srcdir)/data/spice-vdagent.desktop
if INIT_SCRIPT_RED_HAT
initdir = $(sysconfdir)/rc.d/init.d
@@ -60,9 +162,13 @@ if INIT_SCRIPT_SYSTEMD
systemdunitdir = $(SYSTEMDSYSTEMUNITDIR)
systemdunit_DATA = \
$(top_srcdir)/data/spice-vdagentd.service \
$(top_srcdir)/data/spice-vdagentd.target
$(top_srcdir)/data/spice-vdagentd.socket
udevrulesdir = /lib/udev/rules.d
userunitdir = $(SYSTEMDUSERUNITDIR)
userunit_DATA = \
$(top_srcdir)/data/spice-vdagent.service
udevrulesdir = $(udevdir)/rules.d
udevrules_DATA = $(top_srcdir)/data/70-spice-vdagentd.rules
tmpfilesdir = $(prefix)/lib/tmpfiles.d
@@ -70,17 +176,20 @@ tmpfiles_DATA = $(top_srcdir)/data/tmpfiles.d/spice-vdagentd.conf
endif
manpagedir = $(mandir)/man1
manpage_DATA = data/spice-vdagent.1 \
data/spice-vdagentd.1
manpage_DATA = \
data/spice-vdagent.1 \
data/spice-vdagentd.1 \
$(NULL)
EXTRA_DIST = \
README.RHEL-5 \
README.md \
CHANGELOG.md \
data/70-spice-vdagentd.rules \
data/rsyslog.d/spice-vdagentd.conf \
data/spice-vdagent.desktop \
data/spice-vdagent.service \
data/spice-vdagentd \
data/spice-vdagentd.service \
data/spice-vdagentd.target \
data/spice-vdagentd.socket \
data/tmpfiles.d/spice-vdagentd.conf \
data/xorg.conf.RHEL-5 \
$(NULL)
@@ -88,3 +197,10 @@ EXTRA_DIST = \
DISTCHECK_CONFIGURE_FLAGS = \
--with-init-script=redhat \
$(NULL)
tests_test_device_info_LDADD = $(src_spice_vdagent_LDADD)
tests_test_device_info_CFLAGS = $(src_spice_vdagent_CFLAGS)
check_PROGRAMS += tests/test-device-info
check_PROGRAMS += tests/test-termination
-69
View File
@@ -1,69 +0,0 @@
Spice agent for Linux
=====================
The spice agent for Linux consists of 2 parts, a daemon spice-vdagentd and
a per X-session process spice-vdagent. The daemon gets started in Spice guests
through a Sys-V initscript or a systemd unit. The per X-session gets
automatically started in desktop environments which honor /etc/xdg/autostart,
and under gdm.
The main daemon needs to know which X-session daemon is in the currently
active X-session (think switch user functionality) for this console kit or
systemd-logind (compile time option) is used. If no session info is
available only one X-session agent is allowed.
Features:
* Client mouse mode (no need to grab mouse by client, no mouse lag)
this is handled by the daemon by feeding mouse events into the kernel
via uinput. This will only work if the active X-session is running a
spice-vdagent process so that its resolution can be determined.
* Automatic adjustment of the X-session resolution to the client resolution
* Support of copy and paste (text and images) between the active X-session
and the client. This supports both the primary selection and the clipboard.
* Support for transfering files from the client to the agent
* Full support for multiple displays using Xrandr, this requires a new
enough xorg-x11-drv-qxl driver, as well as a new enough host.
* Limited support for multiple displays using Xinerama, prerequisites:
* A new enough Xorg-server. For Fedora atleast Fedora-17, for RHEL-6 atleast
xorg-x11-server-1.10.4-6.el6_2.3
* A vm configured with multiple qxl devices
* A guest running the latest spice-vdagent
Then connect to the vm with the multiple monitor client which you want to
use it with using: "spicec --full-screen=auto-config" (or the user portal
equivalent). At this point the agent will write out a:
/var/run/spice-vdagentd/xorg.conf.spice file. With all the necessary magic
to get Xinerama working. Move this file to /etc/X11/xorg.conf, then kill
Xorg so that it will get restarted and you should be good to go.
* Limited support for setups with multiple Screens (multiple qxl devices each
mapped to their own screen), limitations:
-Max one monitor per Screen / qxl device
-All monitors / Screens must have the same resolution
-No client -> guest resolution syncing
All vdagent communications on the guest side run over a single pipe which
gets presented to the guest os as a virtio serial port.
Under windows this virtio serial port has the following name:
\\\\.\\Global\\com.redhat.spice.0
Under Linux this virtio serial port has the following name:
/dev/virtio-ports/com.redhat.spice.0
To enable the virtio serial port you need to pass the following params on
the qemu cmdline:
For qemu < 0.14.0:
-device spicevmc
For qemu >= 0.14.0:
-device virtio-serial-pci,id=virtio-serial0,max_ports=16,bus=pci.0,addr=0x5 \
-chardev spicevmc,name=vdagent,id=vdagent \
-device \
virtserialport,nr=1,bus=virtio-serial0.0,chardev=vdagent,name=com.redhat.spice.0
Enjoy,
Gerd & Hans
--
Gerd Hoffmann <[email protected]>
Hans de Goede <[email protected]>
-34
View File
@@ -1,34 +0,0 @@
spice-vdagent and RHEL-5 README
-------------------------------
spice-vdagent can also be used inside RHEL-5 guests, if, and only if, they
are hosted on a host which uses virtio-serial as the agent channel. Note
that older hosts, such as qemu shipped with RHEL-5 for example, use
a custom pci device (the spicevmc device) for the agent channel and
there is no Linux support for this device so spice-vdagent does not work
inside guests hosted on such hosts! Hosts based on RHEL-6 or Fedora 15
and newer for example, are fine.
spice-vdagent relies on ConsoleKit to determine the active session, since
RHEL-5 has no ConsoleKit it cannot do this on RHEL-5, therefor only 1
active X-session is supported with RHEL-5. If you try to start multiple
sessions by running multiple X-servers the agent will disable itself.
Since the RHEL-5 X-server does not support hotplugging of input devices,
spice-vdagentd must be started before the X-server, so that it can create
the uinput tablet device it uses for agent mouse mode.
This also means that you must use a customized xorg.conf to teach the
X-server about the uinput device. An example xorg.conf is included with
spice-vdagent. After installing spice-vdagent, first start spice-vdagentd,
and then copy this file to /etc/X11/xorg.conf and restart your X-server.
Note: the sample xorg.conf assumes that the vm has been configured to *not*
use a usb tablet device, since there is no need for one with the agent and
usb emulation takes a significant amount of CPU.
Building from source for RHEL-5
-------------------------------
If you're building spice-vdagent from source on RHEL-5, you must pass
--disable-console-kit --enable-static-uinput to ./configure!
+110
View File
@@ -0,0 +1,110 @@
Spice agent for Linux and macOS
===============================
### Linux
The spice agent for Linux consists of 2 parts, a daemon spice-vdagentd and
a per X-session process spice-vdagent. The daemon gets started in Spice guests
through a Sys-V initscript or a systemd unit. The per X-session gets
automatically started in desktop environments which honor /etc/xdg/autostart,
and under gdm.
The main daemon needs to know which X-session daemon is in the currently
active X-session (think switch user functionality) for this console kit or
systemd-logind (compile time option) is used. If no session info is
available only one X-session agent is allowed.
Features:
* Client mouse mode (no need to grab mouse by client, no mouse lag)
this is handled by the daemon by feeding mouse events into the kernel
via uinput. This will only work if the active X-session is running a
spice-vdagent process so that its resolution can be determined.
* Automatic adjustment of the X-session resolution to the client resolution
* Support of copy and paste (text and images) between the active X-session
and the client. This supports both the primary selection and the clipboard.
* Support for transferring files from the client to the agent
* Full support for multiple displays using Xrandr, this requires a new
enough xorg-x11-drv-qxl driver, as well as a new enough host.
* Limited support for multiple displays using Xinerama.
* Limited support for setups with multiple Screens (multiple qxl devices each
mapped to their own screen)
### macOS
Similar to Linux, the SPICE agent has a LaunchDaemon spice-vdagentd which
handles communication with the console port and a LaunchAgent spice-vdagent
that runs for each logged in user. Note that there is no protection against
one logged in user from snooping another user's clipboard when this is running.
The macOS agent currently only supports clipboard features.
## Install (Linux)
From inside your virtual machine (e.g., GNOME Boxes), use your guest system’s
package manager to install.
For example, if you’re running a Debian/Ubuntu derivative in a VM, use:
```shell
sudo apt install spice-vdagent
```
## Build (macOS)
Currently, you can only build on Apple Silicon Macs with Homebrew installed in
both native and Rosetta. This is because we require GLib installed in both
architectures at the default location.
>>>
$ /opt/homebrew/bin/brew install glib # arm64
$ /usr/local/bin/brew install glib # x86_64
>>>
Alternatively, GLib can be built from source for each architecture (see
`.github/workflows/build.yaml`) and the install prefixes passed to Xcode
with `GLIB_ARM64_PREFIX=... GLIB_X86_64_PREFIX=...`.
Then, you can build the project with Xcode or `xcodebuild`
>>>
$ xcodebuild archive -scheme vd_agent -archivePath vd_agent.xcarchive
>>>
Afterwards, you can sign the output and create an installer package with a paid
Apple Developer certificate (Developer ID Application and Developer ID
Installer are both needed).
>>>
$ ./package_macos.sh vd_agent.xcarchive spice-vdagent-x.yy.pkg
>>>
You may then wish to notarize it before distributing.
## How it works
All vdagent communications on the guest side run over a single pipe which
gets presented to the guest os as a virtio serial port.
Under windows this virtio serial port has the following name:
>>>
\\\\.\\Global\\com.redhat.spice.0
>>>
Under Linux this virtio serial port has the following name:
>>>
/dev/virtio-ports/com.redhat.spice.0
>>>
Under macOS this virtio serial port has the following name:
>>>
/dev/tty.com.redhat.spice.0
>>>
To enable the virtio serial port you need to pass the following params on
the qemu cmdline:
>>>
-device virtio-serial-pci,id=virtio-serial0,max_ports=16,bus=pci.0,addr=0x5 \
-chardev spicevmc,name=vdagent,id=vdagent \
-device virtserialport,nr=1,bus=virtio-serial0.0,chardev=vdagent,name=com.redhat.spice.0
>>>
-3
View File
@@ -1,3 +0,0 @@
Maybe:
-Add support for selections with a target of STRING, which are
ISO Latin-1 strings, which we could support through iconv
+77 -20
View File
@@ -1,5 +1,5 @@
AC_PREREQ(2.59)
AC_INIT([spice-vdagent], [0.15.0])
AC_INIT([spice-vdagent], [0.22.1])
AC_CONFIG_SRCDIR([configure.ac])
AM_CONFIG_HEADER([src/config.h])
@@ -10,6 +10,7 @@ m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])])
AC_PROG_CC
AM_PROG_CC_C_O
AC_HEADER_STDC
AC_SYS_LARGEFILE
AC_PROG_INSTALL
AC_PROG_LN_S
AC_DEFINE(_GNU_SOURCE, [1], [Enable GNU extensions])
@@ -63,7 +64,49 @@ AC_MSG_RESULT($with_init_script)
if test "x$init_systemd" = "xyes"; then
SYSTEMDSYSTEMUNITDIR=`${PKG_CONFIG} systemd --variable=systemdsystemunitdir`
SYSTEMDUSERUNITDIR=`${PKG_CONFIG} systemd --variable=systemduserunitdir`
AC_SUBST(SYSTEMDSYSTEMUNITDIR)
AC_SUBST(SYSTEMDUSERUNITDIR)
# earlier versions of systemd require a separate libsystemd-daemon library
PKG_CHECK_MODULES([LIBSYSTEMD_DAEMON],
[libsystemd >= 209],
[have_libsystemd_daemon="yes"],
[have_libsystemd_daemon="no"])
if test "$have_libsystemd_daemon" = "yes"; then
AC_DEFINE([WITH_SYSTEMD_SOCKET_ACTIVATION], [1], [If defined, vdagentd will support socket activation with systemd] )
fi
fi
AC_ARG_WITH([gtk],
[AS_HELP_STRING(
[--with-gtk=@<:@auto/yes/no@:>@],
[Use GTK+ instead of Xlib @<:@default=auto@:>@])],
[],
[with_gtk="auto"])
AC_ARG_WITH([gtk4],
[AS_HELP_STRING(
[--with-gtk4=@<:@yes/no@:>@],
[Use GTK4 instead of Xlib @<:@default=no@:>@])],
[],
[with_gtk4="no"])
if test "x$with_gtk4" = "xyes"; then
PKG_CHECK_MODULES([GTK], [gtk4 >= 3.98], [
AC_DEFINE([WITH_GTK], [1], [If defined, load GTK+ libraries])
AC_DEFINE([USE_GTK_FOR_MONITORS], [1], [If defined, use GTK for monitor resolution instead of XRandr])
with_gtk="yes"
], [
AC_MSG_ERROR([GTK4 requested but not found])
with_gtk="no"])
else
if test "x$with_gtk" != "xno"; then
PKG_CHECK_MODULES([GTK], [gtk+-3.0 >= 3.22], [
AC_DEFINE([WITH_GTK], [1], [If defined, load GTK+ libraries])
AC_DEFINE([USE_GTK_FOR_CLIPBOARD], [1], [If defined, use GTK for clipboard features])
with_gtk="yes"
], [
AS_IF([test "x$with_gtk" = "xyes"], [AC_MSG_ERROR([GTK+ requested but not found])])
with_gtk="no"])
fi
fi
AC_ARG_ENABLE([pciaccess],
@@ -72,19 +115,33 @@ AC_ARG_ENABLE([pciaccess],
[enable_pciaccess="yes"])
AC_ARG_ENABLE([static-uinput],
[AS_HELP_STRING([--enable-statis-uinput], [Enable use of a fixed, static uinput device for X-servers without hotplug support (default: no)])],
[AS_HELP_STRING([--enable-static-uinput], [Enable use of a fixed, static uinput device for X-servers without hotplug support (default: no)])],
[enable_static_uinput="$enableval"],
[enable_static_uinput="no"])
PKG_CHECK_MODULES([GLIB2], [glib-2.0 >= 2.12])
PKG_CHECK_MODULES([GIO2], [gio-unix-2.0 >= 2.50])
PKG_CHECK_MODULES(X, [xfixes xrandr >= 1.3 xinerama x11])
PKG_CHECK_MODULES(SPICE, [spice-protocol >= 0.12.5])
PKG_CHECK_MODULES(SPICE, [spice-protocol >= 0.14.3])
PKG_CHECK_MODULES(ALSA, [alsa >= 1.0.22])
PKG_CHECK_MODULES([DBUS], [dbus-1])
PKG_CHECK_MODULES([DRM], [libdrm])
PKG_CHECK_MODULES([GLIB], [glib-2.0 >= 2.68], [], [
AC_DEFINE(g_memdup2, g_memdup, [GLib2 < 2.68 compatibility])
])
if test "$with_session_info" = "auto" || test "$with_session_info" = "systemd"; then
PKG_CHECK_MODULES([LIBSYSTEMD_LOGIN],
[libsystemd-login >= 42],
[libsystemd >= 209],
[have_libsystemd_login="yes"],
[have_libsystemd_login="no"])
if test "$have_libsystemd_login" = "no"; then
# for backward compatibility with older systemd versions
PKG_CHECK_MODULES([LIBSYSTEMD_LOGIN],
[libsystemd-login >= 42],
[have_libsystemd_login="yes"],
[have_libsystemd_login="no"])
fi
if test x"$have_libsystemd_login" = "xno" && test "$with_session_info" = "systemd"; then
AC_MSG_ERROR([libsystemd-login support explicitly requested, but some required packages are not available])
fi
@@ -97,20 +154,14 @@ else
fi
AM_CONDITIONAL(HAVE_LIBSYSTEMD_LOGIN, test x"$have_libsystemd_login" = "xyes")
#udevdir
udevdir=$($PKG_CONFIG --variable=udevdir udev)
AC_SUBST(udevdir)
if test "$with_session_info" = "auto" || test "$with_session_info" = "console-kit"; then
PKG_CHECK_MODULES([DBUS],
[dbus-1],
[have_console_kit="yes"],
[have_console_kit="no"])
if test x"$have_console_kit" = "xno" && test "$with_session_info" = "console-kit"; then
AC_MSG_ERROR([console-kit support explicitly requested, but some required packages are not available])
fi
if test x"$have_console_kit" = "xyes"; then
AC_DEFINE([HAVE_CONSOLE_KIT], [1], [If defined, vdagentd will be compiled with ConsoleKit support])
with_session_info="console-kit"
else
with_session_info="none"
fi
AC_DEFINE([HAVE_CONSOLE_KIT], [1], [If defined, vdagentd will be compiled with ConsoleKit support])
have_console_kit="yes"
with_session_info="console-kit"
else
have_console_kit="no"
fi
@@ -127,8 +178,8 @@ if test x"$enable_static_uinput" = "xyes" ; then
fi
# If no CFLAGS are set, set some sane default CFLAGS
if test "$ac_test_CFLAGS" != set; then
DEFAULT_CFLAGS="-Wall -Werror -Wp,-D_FORTIFY_SOURCE=2 -fstack-protector --param=ssp-buffer-size=4"
if test -z "$ac_test_CFLAGS"; then
DEFAULT_CFLAGS="-Wall -Werror -Wp,-D_FORTIFY_SOURCE=2 -fno-strict-aliasing -fstack-protector --param=ssp-buffer-size=4"
for F in $DEFAULT_CFLAGS; do
AC_MSG_CHECKING([whether $CC supports $F])
save_CFLAGS="$CFLAGS"
@@ -141,6 +192,9 @@ if test "$ac_test_CFLAGS" != set; then
done
fi
# Always enabled for autoconf targets
AC_DEFINE([WITH_SESSION_SECURITY], [1], [If undefined and there is no session info, only one session agent is allowed] )
AC_ARG_ENABLE([pie],
AS_HELP_STRING([--enable-pie=@<:@auto/yes/no@:>@],
[Enable position-independent-executable support (for spice-vdagentd)@<:@default=auto@:>@]),
@@ -195,6 +249,9 @@ AC_MSG_NOTICE([
install RH initscript: ${init_redhat}
install systemd service: ${init_systemd}
udevdir: ${udevdir}
use GTK+: ${with_gtk}
Now type 'make' to build $PACKAGE
+1 -1
View File
@@ -1 +1 @@
ACTION=="add", SUBSYSTEM=="virtio-ports", ENV{DEVLINKS}=="/dev/virtio-ports/com.redhat.spice.0", ENV{SYSTEMD_WANTS}="spice-vdagentd.target"
ACTION=="add", SUBSYSTEM=="virtio-ports", ENV{DEVLINKS}=="/dev/virtio-ports/com.redhat.spice.0", ENV{SYSTEMD_WANTS}="spice-vdagentd.socket"
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<dict>
<key>Crashed</key>
<false/>
</dict>
<key>Label</key>
<string>com.redhat.spice.vdagent</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/spice-vdagent</string>
<string>-x</string>
<string>-S</string>
<string>/var/run/spice-vdagent-sock</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
+28
View File
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<dict>
<key>Crashed</key>
<false/>
</dict>
<key>Label</key>
<string>com.redhat.spice.vdagentd</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/spice-vdagentd</string>
<string>-x</string>
<string>-s</string>
<string>/dev/tty.com.redhat.spice.0</string>
<string>-S</string>
<string>/var/run/spice-vdagent-sock</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/var/log/spice-vdagentd.stderr.log</string>
<key>StandardOutPath</key>
<string>/var/log/spice-vdagentd.stdout.log</string>
</dict>
</plist>
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -e
GUI_USER=$(stat -f%Su /dev/console)
GUI_UID=$(id -u $GUI_USER)
/bin/launchctl load /Library/LaunchDaemons/com.redhat.spice.vdagentd.plist
if [ "$GUI_USER" != "root" ]; then
/bin/launchctl asuser $GUI_UID /bin/launchctl load /Library/LaunchAgents/com.redhat.spice.vdagent.plist
fi
-4
View File
@@ -1,4 +0,0 @@
# A template to for higher precision timestamps + severity logging
$template SpiceTmpl,"%TIMESTAMP%.%TIMESTAMP:::date-subseconds% %syslogtag% %syslogseverity-text%:%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n"
:programname, startswith, "spice-vdagent" /var/log/spice-vdagent.log;SpiceTmpl
+1 -1
View File
@@ -21,7 +21,7 @@ resolution, to the number of client windows and their resolution
Support of copy and paste (text and images) between the active X11 session
and the client, this supports both the primary selection and the clipboard
.P
Support for transfering files from the client to the agent
Support for transferring files from the client to the agent
.SH OPTIONS
.TP
\fB-h\fP
+3 -1
View File
@@ -5,4 +5,6 @@ Exec=/usr/bin/spice-vdagent
Terminal=false
Type=Application
Categories=
X-GNOME-Autostart-Phase=Initialization
X-GNOME-Autostart-Phase=WindowManager
NoDisplay=true
X-systemd-skip=true
+11
View File
@@ -0,0 +1,11 @@
[Unit]
Description=Spice guest session agent
Documentation=man:spice-vdagent(1)
# Make sure the display is reachable
After=graphical-session.target
[Service]
ExecStart=/usr/bin/spice-vdagent -x
[Install]
WantedBy=graphical-session.target
+2 -2
View File
@@ -27,7 +27,7 @@
exec="/usr/sbin/spice-vdagentd"
prog="spice-vdagentd"
port="/dev/virtio-ports/com.redhat.spice.0"
pid="/var/run/spice-vdagentd/spice-vdagentd.pid"
pid="/run/spice-vdagentd/spice-vdagentd.pid"
[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog
@@ -38,7 +38,7 @@ start() {
[ -c $port ] || exit 0
modprobe uinput > /dev/null 2>&1
# In case the previous running vdagentd crashed
rm -f /var/run/spice-vdagentd/spice-vdagent-sock
rm -f /run/spice-vdagentd/spice-vdagent-sock
echo -n $"Starting $prog: "
daemon --pidfile $pid $exec $SPICE_VDAGENTD_EXTRA_ARGS
retval=$?
+8 -1
View File
@@ -20,7 +20,7 @@ resolution, to the number of client windows and their resolution
Support of copy and paste (text and images) between the active X11 session
and the client, this supports both the primary selection and the clipboard
.P
Support for transfering files from the client to the agent
Support for transferring files from the client to the agent
.SH OPTIONS
.TP
\fB-h\fP
@@ -29,6 +29,13 @@ Print a short description of all command line options
\fB-d\fP
Log debug messages (use twice for extra info)
.TP
\fB-f\fP
Treat uinput device as fake; no ioctls.
This is useful in combination with Xspice.
.TP
\fB-o\fP
The daemon will exit after processing a single session.
.TP
\fB-s\fP \fIport\fR
Set virtio serial \fIport\fR (default: /dev/virtio-ports/com.redhat.spice.0)
.TP
+5 -6
View File
@@ -1,17 +1,16 @@
[Unit]
Description=Agent daemon for Spice guests
Documentation=man:spice-vdagentd(1)
After=dbus.target
# TODO we should use:
#Requires=spice-vdagentd.socket
Requires=spice-vdagentd.socket
[Service]
Type=forking
EnvironmentFile=-/etc/sysconfig/spice-vdagentd
ExecStartPre=/bin/rm -f /var/run/spice-vdagentd/spice-vdagent-sock
ExecStart=/usr/sbin/spice-vdagentd $SPICE_VDAGENTD_EXTRA_ARGS
PIDFile=/var/run/spice-vdagentd/spice-vdagentd.pid
PIDFile=/run/spice-vdagentd/spice-vdagentd.pid
PrivateTmp=true
Restart=on-failure
[Install]
WantedBy=spice-vdagentd.target
Also=spice-vdagentd.socket
+5
View File
@@ -0,0 +1,5 @@
[Unit]
Description=Activation socket for spice guest agent daemon
[Socket]
ListenStream=/run/spice-vdagentd/spice-vdagent-sock
-2
View File
@@ -1,2 +0,0 @@
[Unit]
Description=Agent daemon for Spice guests
+1 -1
View File
@@ -1,2 +1,2 @@
# spice-vdagentd needs this and does not create it itself
d /var/run/spice-vdagentd 0755 root root -
d /run/spice-vdagentd 0755 root root -
+49
View File
@@ -0,0 +1,49 @@
#!/bin/sh
set -e
VERSION="0.22.1"
INPUT_ARCHIVE="$1"
OUTPUT_PKG="$2"
TMP_ROOT="/tmp/package.$$"
TMP_COMPONENT="/tmp/Vdagent.pkg"
command -v realpath >/dev/null 2>&1 || realpath() {
[[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}
BASEDIR="$(dirname "$(realpath $0)")"
cp -a "$INPUT_ARCHIVE/Products" "$TMP_ROOT"
xattr -cr "$TMP_ROOT"
codesign --sign "Developer ID Application" \
--force \
--identifier com.redhat.spice.vdagentd \
--preserve-metadata=entitlements,requirements,flags,runtime \
--timestamp \
"$TMP_ROOT/usr/local/bin/spice-vdagentd"
codesign --sign "Developer ID Application" \
--force \
--identifier com.redhat.spice.vdagent \
--preserve-metadata=entitlements,requirements,flags,runtime \
--timestamp \
"$TMP_ROOT/usr/local/bin/spice-vdagent"
pkgbuild --root "$TMP_ROOT" \
--identifier com.redhat.spice.vdagent \
--version "$VERSION" \
--install-location / \
--scripts "$BASEDIR/data/install_scripts" \
"$TMP_COMPONENT"
productbuild --package "$TMP_COMPONENT" \
--identifier com.redhat.spice.vdagent \
--version "$VERSION" \
--sign "Developer ID Installer" \
"$OUTPUT_PKG"
rm "$TMP_COMPONENT"
rm -r "$TMP_ROOT"
-354
View File
@@ -1,354 +0,0 @@
/* console-kit.c vdagentd ConsoleKit integration code
Copyright 2010-2012 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "session-info.h"
#include <dbus/dbus.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
struct session_info {
DBusConnection *connection;
int fd;
char *seat;
char *active_session;
};
static char *console_kit_get_first_seat(struct session_info *ck);
static char *console_kit_check_active_session_change(struct session_info *ck);
struct session_info *session_info_create(int verbose)
{
struct session_info *ck;
DBusError error;
char match[1024];
ck = calloc(1, sizeof(*ck));
if (!ck)
return NULL;
dbus_error_init(&error);
ck->connection = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
if (ck->connection == NULL || dbus_error_is_set(&error)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "Unable to connect to system bus: %s",
error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "Unable to connect to system bus");
free(ck);
return NULL;
}
if (!dbus_connection_get_unix_fd(ck->connection, &ck->fd)) {
syslog(LOG_ERR, "Unable to get connection fd");
session_info_destroy(ck);
return NULL;
}
if (!console_kit_get_first_seat(ck)) {
session_info_destroy(ck);
return NULL;
}
/* Register for active session changes */
snprintf(match, sizeof(match),
"type='signal',interface='org.freedesktop.ConsoleKit.Seat',"
"path='%s',member='ActiveSessionChanged'", ck->seat);
dbus_error_init(&error);
dbus_bus_add_match(ck->connection, match, &error);
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "Match Error (%s)", error.message);
session_info_destroy(ck);
return NULL;
}
return ck;
}
void session_info_destroy(struct session_info *ck)
{
if (!ck)
return;
dbus_connection_close(ck->connection);
free(ck->seat);
free(ck->active_session);
free(ck);
}
int session_info_get_fd(struct session_info *ck)
{
return ck->fd;
}
static char *console_kit_get_first_seat(struct session_info *ck)
{
DBusError error;
DBusMessage *message = NULL;
DBusMessage *reply = NULL;
DBusMessageIter iter, subiter;
int type;
char *seat = NULL;
message = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
"/org/freedesktop/ConsoleKit/Manager",
"org.freedesktop.ConsoleKit.Manager",
"GetSeats");
if (message == NULL) {
syslog(LOG_ERR, "Unable to create dbus message");
goto exit;
}
dbus_error_init(&error);
reply = dbus_connection_send_with_reply_and_block(ck->connection,
message,
-1,
&error);
if (reply == NULL || dbus_error_is_set(&error)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "GetSeats failed: %s", error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "GetSeats failed");
goto exit;
}
dbus_message_iter_init(reply, &iter);
type = dbus_message_iter_get_arg_type(&iter);
if (type != DBUS_TYPE_ARRAY) {
syslog(LOG_ERR,
"expected an array return value, got a '%c' instead", type);
goto exit;
}
dbus_message_iter_recurse(&iter, &subiter);
type = dbus_message_iter_get_arg_type(&subiter);
if (type != DBUS_TYPE_OBJECT_PATH) {
syslog(LOG_ERR,
"expected an object path element, got a '%c' instead", type);
goto exit;
}
dbus_message_iter_get_basic(&subiter, &seat);
ck->seat = strdup(seat);
exit:
if (reply != NULL) {
dbus_message_unref(reply);
}
if (message != NULL) {
dbus_message_unref(message);
}
return ck->seat;
}
const char *session_info_get_active_session(struct session_info *ck)
{
DBusError error;
DBusMessage *message = NULL;
DBusMessage *reply = NULL;
char *session = NULL;
if (!ck)
return NULL;
if (ck->active_session)
return console_kit_check_active_session_change(ck);
message = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
ck->seat,
"org.freedesktop.ConsoleKit.Seat",
"GetActiveSession");
if (message == NULL) {
syslog(LOG_ERR, "Unable to create dbus message");
goto exit;
}
dbus_error_init(&error);
reply = dbus_connection_send_with_reply_and_block(ck->connection,
message,
-1,
&error);
if (reply == NULL || dbus_error_is_set(&error)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "GetActiveSession failed: %s", error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "GetActiveSession failed");
goto exit;
}
dbus_error_init(&error);
if (!dbus_message_get_args(reply,
&error,
DBUS_TYPE_OBJECT_PATH, &session,
DBUS_TYPE_INVALID)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "error get ssid from reply: %s", error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "error getting ssid from reply");
session = NULL;
goto exit;
}
ck->active_session = strdup(session);
exit:
if (reply != NULL) {
dbus_message_unref(reply);
}
if (message != NULL) {
dbus_message_unref(message);
}
/* In case the session was changed while we were running */
return console_kit_check_active_session_change(ck);
}
char *session_info_session_for_pid(struct session_info *ck, uint32_t pid)
{
DBusError error;
DBusMessage *message = NULL;
DBusMessage *reply = NULL;
DBusMessageIter args;
char *ssid = NULL;
if (!ck)
return NULL;
message = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
"/org/freedesktop/ConsoleKit/Manager",
"org.freedesktop.ConsoleKit.Manager",
"GetSessionForUnixProcess");
if (message == NULL) {
syslog(LOG_ERR, "Unable to create dbus message");
goto exit;
}
dbus_message_iter_init_append(message, &args);
if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &pid)) {
syslog(LOG_ERR, "Unable to append dbus message args");
goto exit;
}
dbus_error_init(&error);
reply = dbus_connection_send_with_reply_and_block(ck->connection,
message,
-1,
&error);
if (reply == NULL || dbus_error_is_set(&error)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "GetSessionForUnixProcess failed: %s",
error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "GetSessionForUnixProces failed");
goto exit;
}
dbus_error_init(&error);
if (!dbus_message_get_args(reply,
&error,
DBUS_TYPE_OBJECT_PATH, &ssid,
DBUS_TYPE_INVALID)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "error get ssid from reply: %s", error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "error getting ssid from reply");
ssid = NULL;
goto exit;
}
ssid = strdup(ssid);
exit:
if (reply != NULL) {
dbus_message_unref(reply);
}
if (message != NULL) {
dbus_message_unref(message);
}
return ssid;
}
static char *console_kit_check_active_session_change(struct session_info *ck)
{
DBusMessage *message = NULL;
DBusMessageIter iter;
char *session;
int type;
/* non blocking read of the next available message */
dbus_connection_read_write(ck->connection, 0);
while ((message = dbus_connection_pop_message(ck->connection))) {
if (dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL) {
const char *member = dbus_message_get_member (message);
if (!strcmp(member, "NameAcquired")) {
dbus_message_unref(message);
continue;
}
if (strcmp(member, "ActiveSessionChanged")) {
syslog(LOG_ERR, "unexpected signal member: %s", member);
dbus_message_unref(message);
continue;
}
} else {
syslog(LOG_ERR, "received non signal message!");
dbus_message_unref(message);
continue;
}
free(ck->active_session);
ck->active_session = NULL;
dbus_message_iter_init(message, &iter);
type = dbus_message_iter_get_arg_type(&iter);
/* Session should be an object path, but there is a bug in
ConsoleKit where it sends a string rather then an object_path
accept object_path too in case the bug ever gets fixed */
if (type != DBUS_TYPE_STRING && type != DBUS_TYPE_OBJECT_PATH) {
syslog(LOG_ERR,
"ActiveSessionChanged message has unexpected type: '%c'",
type);
dbus_message_unref(message);
continue;
}
dbus_message_iter_get_basic(&iter, &session);
ck->active_session = strdup(session);
dbus_message_unref(message);
/* non blocking read of the next available message */
dbus_connection_read_write(ck->connection, 0);
}
return ck->active_session;
}
+320
View File
@@ -0,0 +1,320 @@
/*
* Copyright (C) 2024 osy
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import AppKit
import ArgumentParser
import ObjectiveC
let DEFAULT_VDAGENTD_SOCKET = "/run/spice-vdagentd/spice-vdagent-sock"
typealias VdagentConnection = OpaquePointer
@main
struct Vdagent: ParsableCommand {
static var configuration = CommandConfiguration(
commandName: "spice-vdagent")
@Flag(name: .shortAndLong, help: "Enable debug")
var debug = false
@Option(name: [.customLong("vdagentd-socket"), .customShort("S")], help: ArgumentHelp("Set spice-vdagentd socket", valueName: "path"))
var socketPath = DEFAULT_VDAGENTD_SOCKET
@Flag(name: [.customLong("foreground"), .customShort("x")], help: "Do not daemonize the agent")
var foreground = false
func startVdagent() throws {
let cb = vdagent_cb_t(clipboard_request: host_clipboard_request,
clipboard_grab: host_clipboard_grab,
clipboard_data: host_clipboard_data,
clipboard_release: host_clipboard_release,
client_disconnected: host_client_disconnected,
agent_connected: host_agent_connected,
agent_disconnected: host_agent_disconnected)
let host = VdagentHost()
if debug {
vdagent_set_debug(1)
}
if !foreground {
throw VdagentError.unimplementedDaemon
}
let ctx = Unmanaged.passRetained(host)
defer {
ctx.release()
}
withUnsafePointer(to: cb) { cb in
_ = vdagent_start(socketPath, cb, ctx.toOpaque())
}
}
func run() {
let vdagentQueue = DispatchQueue(label: "SPICE vdagent main loop", qos: .userInteractive)
vdagentQueue.async {
do {
try self.startVdagent()
Self.exit()
} catch {
Self.exit(withError: error)
}
}
RunLoop.current.run()
}
}
private class VdagentHost: NSObject {
typealias Item = (lock: DispatchSemaphore, item: NSPasteboardItem)
private var lastItem: Item?
private var lastUpdateCount: Int = -1
private var updateTimer: Timer?
private var lastAgent: VdagentConnection? {
willSet {
if let agent = lastAgent {
vdagent_unref(agent)
}
}
}
func clipboardRequest(_ agent: VdagentConnection, sel: vdagent_clipboard_select_t, type: vdagent_clipboard_type_t) throws {
let pasteboard = try pasteboard(for: sel)
let pasteboardType = try pasteboardType(for: type)
guard let data = pasteboard.data(forType: pasteboardType) else {
throw VdagentError.dataNotAvailable
}
try data.withUnsafeBytes<Void> { buffer in
vdagent_clipboard_data(agent, sel, type, buffer.baseAddress, UInt32(data.count))
}
}
func clipboardGrab(_ agent: VdagentConnection, sel: vdagent_clipboard_select_t, types: [vdagent_clipboard_type_t]) throws {
let pasteboard = try pasteboard(for: sel)
let pasteboardTypes = types.compactMap { try? pasteboardType(for: $0) }
let item = NSPasteboardItem()
item.setDataProvider(self, forTypes: pasteboardTypes)
item.connectionAgent = agent
lastUpdateCount = pasteboard.changeCount + 1
pasteboard.prepareForNewContents(with: .currentHostOnly)
pasteboard.writeObjects([item])
}
func clipboardData(_ agent: VdagentConnection, sel: vdagent_clipboard_select_t, type: vdagent_clipboard_type_t, data: Data) throws {
let pasteboard = try pasteboard(for: sel)
let pasteboardType = try pasteboardType(for: type)
let success: Bool
if let (lock, item) = lastItem {
lastItem = nil
if item.types.contains(pasteboardType) {
success = item.setData(data, forType: pasteboardType)
} else {
success = false
}
lock.signal()
} else {
// unsolicited clipboard data
lastUpdateCount = pasteboard.changeCount + 1
success = pasteboard.setData(data, forType: pasteboardType)
}
if !success {
throw VdagentError.failedToWritePasteboard
}
}
func clipboardRelease(_ agent: VdagentConnection, sel: vdagent_clipboard_select_t) throws {
}
func guestUpdate(_ agent: VdagentConnection) {
let pasteboard = NSPasteboard.general
let newCount = pasteboard.changeCount
if newCount != lastUpdateCount, let pasteboardTypes = pasteboard.types {
lastUpdateCount = newCount
let types = pasteboardTypes.compactMap { clipboardType(for: $0) }
if !types.isEmpty {
vdagent_clipboard_grab(agent, VDAgentClipboardSelectClipboard, types, Int32(types.count))
}
}
}
func clientDisconnected(_ agent: VdagentConnection) {
}
func agentConnected(_ agent: VdagentConnection) {
let agent = vdagent_ref(agent)!
// need to synchronize with RunLoop
RunLoop.main.perform {
self.lastAgent = agent
let timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in
self?.guestUpdate(agent)
}
self.updateTimer = timer
RunLoop.main.add(timer, forMode: .default)
}
}
func agentDisconnected(_ agent: VdagentConnection) {
updateTimer?.invalidate()
// need to synchronize with RunLoop
RunLoop.main.perform {
self.updateTimer = nil
self.lastAgent = nil
}
}
}
private extension VdagentHost {
private func pasteboard(for sel: vdagent_clipboard_select_t) throws -> NSPasteboard {
switch sel {
case VDAgentClipboardSelectClipboard: return .general
default: throw VdagentError.unsupportedClipboardSelection(sel)
}
}
private func pasteboardType(for type: vdagent_clipboard_type_t) throws -> NSPasteboard.PasteboardType {
switch type {
case VDAgentClipboardTypeImageTIFF: return .tiff
case VDAgentClipboardTypeImagePNG: return .png
case VDAgentClipboardTypeUTF8Text: return .string
default: throw VdagentError.unsupportedDataType(type)
}
}
private func clipboardType(for type: NSPasteboard.PasteboardType) -> vdagent_clipboard_type_t? {
switch type {
case .tiff: return VDAgentClipboardTypeImageTIFF
case .png: return VDAgentClipboardTypeImagePNG
case .string: return VDAgentClipboardTypeUTF8Text
default: return nil
}
}
}
extension VdagentHost: NSPasteboardItemDataProvider {
func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: NSPasteboard.PasteboardType) {
guard let type = clipboardType(for: type) else {
print("Error: unsupported pasteboard type \(type)")
return
}
lastItem = (DispatchSemaphore(value: 0), item)
vdagent_clipboard_request(item.connectionAgent, VDAgentClipboardSelectClipboard, type)
guard lastItem!.lock.wait(timeout: .now() + .seconds(5)) == .success else {
lastItem = nil
print("Error: timed out waiting for clipboard data")
return
}
}
}
private enum VdagentError: Error {
case unimplementedDaemon
case unsupportedClipboardSelection(vdagent_clipboard_select_t)
case unsupportedDataType(vdagent_clipboard_type_t)
case dataNotAvailable
case failedToWritePasteboard
}
extension VdagentError: LocalizedError {
var errorDescription: String? {
switch self {
case .unimplementedDaemon:
return "Daemon mode is not implemented, please run with '-x'."
case .unsupportedClipboardSelection(let sel):
return "Unsupported clipboard selection: \(sel)"
case .unsupportedDataType(let type):
return "Unsupported clipboard data type: \(type)"
case .dataNotAvailable:
return "Data not available"
case .failedToWritePasteboard:
return "Failed to write to pasteboard"
}
}
}
private var AssociatedAgentConnection: UInt8 = 0
extension NSPasteboardItem {
var connectionAgent: VdagentConnection? {
get {
return objc_getAssociatedObject(self, &AssociatedAgentConnection) as? VdagentConnection
}
set {
objc_setAssociatedObject(self, &AssociatedAgentConnection, newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
private func withError(_ callback: () throws -> Void) -> Bool {
do {
try callback()
return true
} catch {
print("Error: \(error.localizedDescription)")
return false
}
}
private func host_clipboard_request(_ agent: VdagentConnection!, ctx: UnsafeMutableRawPointer!, sel: vdagent_clipboard_select_t, type: vdagent_clipboard_type_t) -> Bool {
withError {
let host = Unmanaged<VdagentHost>.fromOpaque(ctx).takeUnretainedValue()
try host.clipboardRequest(agent, sel: sel, type: type)
}
}
private func host_clipboard_grab(_ agent: VdagentConnection!, ctx: UnsafeMutableRawPointer!, sel: vdagent_clipboard_select_t, types: UnsafePointer<vdagent_clipboard_type_t>?, n_types: UInt32) -> Bool {
withError {
let host = Unmanaged<VdagentHost>.fromOpaque(ctx).takeUnretainedValue()
let _types = Array(UnsafeBufferPointer(start: types!, count: Int(n_types)))
try host.clipboardGrab(agent, sel: sel, types: _types)
}
}
private func host_clipboard_data(_ agent: VdagentConnection!, ctx: UnsafeMutableRawPointer!, sel: vdagent_clipboard_select_t, type: vdagent_clipboard_type_t, data: UnsafePointer<UInt8>?, size: UInt32) -> Bool {
withError {
let host = Unmanaged<VdagentHost>.fromOpaque(ctx).takeUnretainedValue()
let _data: Data
if let data = data {
_data = Data(bytes: data, count: Int(size))
} else {
_data = Data()
}
try host.clipboardData(agent, sel: sel, type: type, data: _data)
}
}
private func host_clipboard_release(_ agent: VdagentConnection!, ctx: UnsafeMutableRawPointer!, sel: vdagent_clipboard_select_t) -> Bool {
withError {
let host = Unmanaged<VdagentHost>.fromOpaque(ctx).takeUnretainedValue()
try host.clipboardRelease(agent, sel: sel)
}
}
private func host_client_disconnected(_ agent: VdagentConnection!, ctx: UnsafeMutableRawPointer!) {
let host = Unmanaged<VdagentHost>.fromOpaque(ctx).takeUnretainedValue()
host.clientDisconnected(agent)
}
private func host_agent_connected(_ agent: VdagentConnection!, ctx: UnsafeMutableRawPointer!) {
let host = Unmanaged<VdagentHost>.fromOpaque(ctx).takeUnretainedValue()
host.agentConnected(agent)
}
private func host_agent_disconnected(_ agent: VdagentConnection!, ctx: UnsafeMutableRawPointer!) {
let host = Unmanaged<VdagentHost>.fromOpaque(ctx).takeUnretainedValue()
host.agentDisconnected(agent)
}
+103
View File
@@ -0,0 +1,103 @@
/* src/config.h.in. Generated from configure.ac by autoheader. */
/* If defined, vdagentd will be compiled with ConsoleKit support */
#undef HAVE_CONSOLE_KIT
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* If defined, vdagentd will be compiled with libsystemd-login support */
#undef HAVE_LIBSYSTEMD_LOGIN
/* If defined, vdagentd will be compiled with pciaccess support */
#undef HAVE_PCIACCESS
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdio.h> header file. */
#define HAVE_STDIO_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Name of package */
#define PACKAGE "spice-vdagent"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT ""
/* Define to the full name of this package. */
#define PACKAGE_NAME "spice-vdagent"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "spice-vdagent 0.22.1"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "spice-vdagent"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "0.22.1"
/* Define to 1 if all of the C89 standard headers exist (not just the ones
required in a freestanding environment). This macro is provided for
backward compatibility; new code need not use it. */
#define STDC_HEADERS 1
/* If defined, use GTK for clipboard features */
#undef USE_GTK_FOR_CLIPBOARD
/* If defined, use GTK for monitor resolution instead of XRandr */
#undef USE_GTK_FOR_MONITORS
/* Version number of package */
#define VERSION "0.22.1"
/* If defined, load GTK+ libraries */
#undef WITH_GTK
/* If undefined and there is no session info, only one session agent is
allowed */
#undef WITH_SESSION_SECURITY
/* If defined, vdagentd will use a static uinput device */
#undef WITH_STATIC_UINPUT
/* If defined, vdagentd will support socket activation with systemd */
#undef WITH_SYSTEMD_SOCKET_ACTIVATION
/* Number of bits in a file offset, on hosts where this is settable. */
#define _FILE_OFFSET_BITS 64
/* Enable GNU extensions */
#define _GNU_SOURCE 1
/* Define to 1 on platforms where this makes off_t a 64-bit type. */
#define _LARGE_FILES 1
/* Number of bits in time_t, on hosts where this is settable. */
#define _TIME_BITS 64
/* Define to 1 on platforms where this makes time_t a 64-bit type. */
#undef __MINGW_USE_VC2005_COMPAT
/* GLib2 < 2.68 compatibility */
#undef g_memdup2
+477
View File
@@ -0,0 +1,477 @@
/*
* Copyright (C) 2024 osy
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <syslog.h>
#include <sys/socket.h>
#include <glib-unix.h>
#include <spice/vd_agent.h>
#include "udscs.h"
#include "vdagentd-proto.h"
#include "vdagent.h"
#define MAX_RETRY_CONNECT_SYSTEM_AGENT 60
G_BEGIN_DECLS
#define VDAGENT_TYPE_VDAGENT (vdagent_get_type())
G_DECLARE_FINAL_TYPE(VDAgent, vdagent, VDAGENT, VDAGENT, GObject)
struct _VDAgent {
GObject parent_instance;
UdscsConnection *conn;
gint udscs_num_retry;
const vdagent_cb_t *cb;
void *ctx;
GMainLoop *loop;
};
G_END_DECLS
G_DEFINE_TYPE(VDAgent, vdagent, G_TYPE_OBJECT)
static int quit = 0;
static int parent_socket = -1;
static int version_mismatch = 0;
/* Command line options */
static gboolean debug = FALSE;
static gchar *vdagentd_socket = NULL;
static void vdagent_quit_loop(VDAgent *agent)
{
if (agent->cb && agent->cb->agent_disconnected) {
agent->cb->agent_disconnected(agent, agent->ctx);
}
if (agent->loop) {
g_main_loop_quit(agent->loop);
}
}
static gboolean vdagent_signal_handler(gpointer user_data)
{
VDAgent *agent = user_data;
quit = TRUE;
vdagent_quit_loop(agent);
return G_SOURCE_REMOVE;
}
static void vdagent_dispose(GObject *object)
{
VDAgent *agent = VDAGENT_VDAGENT(object);
g_clear_pointer(&agent->conn, vdagent_connection_destroy);
while (g_source_remove_by_user_data(agent))
continue;
g_clear_pointer(&agent->loop, g_main_loop_unref);
G_OBJECT_CLASS(vdagent_parent_class)->dispose(object);
}
static void vdagent_class_init(VDAgentClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS(klass);
object_class->dispose = vdagent_dispose;
}
static void vdagent_init(VDAgent *self)
{
self->loop = g_main_loop_new(NULL, FALSE);
}
static VDAgent *vdagent_new(const vdagent_cb_t *cb, void *ctx)
{
VDAgent *agent = g_object_new(VDAGENT_TYPE_VDAGENT, NULL);
agent->cb = cb;
agent->ctx = ctx;
g_unix_signal_add(SIGINT, vdagent_signal_handler, agent);
g_unix_signal_add(SIGHUP, vdagent_signal_handler, agent);
g_unix_signal_add(SIGTERM, vdagent_signal_handler, agent);
return agent;
}
void vdagent_set_debug(int debugOption)
{
debug = debugOption;
}
static guint32 convert_clipboard_type_to_raw(vdagent_clipboard_type_t type)
{
switch (type) {
case VDAgentClipboardTypeUTF8Text: return VD_AGENT_CLIPBOARD_UTF8_TEXT;
case VDAgentClipboardTypeImagePNG: return VD_AGENT_CLIPBOARD_IMAGE_PNG;
case VDAgentClipboardTypeImageBMP: return VD_AGENT_CLIPBOARD_IMAGE_BMP;
case VDAgentClipboardTypeImageTIFF: return VD_AGENT_CLIPBOARD_IMAGE_TIFF;
case VDAgentClipboardTypeImageJPG: return VD_AGENT_CLIPBOARD_IMAGE_JPG;
case VDAgentClipboardTypeNone:
default: return VD_AGENT_CLIPBOARD_NONE;
}
}
static vdagent_clipboard_type_t convert_raw_to_clipboard_type(guint32 type)
{
switch (type) {
case VD_AGENT_CLIPBOARD_UTF8_TEXT: return VDAgentClipboardTypeUTF8Text;
case VD_AGENT_CLIPBOARD_IMAGE_PNG: return VDAgentClipboardTypeImagePNG;
case VD_AGENT_CLIPBOARD_IMAGE_BMP: return VDAgentClipboardTypeImageBMP;
case VD_AGENT_CLIPBOARD_IMAGE_TIFF: return VDAgentClipboardTypeImageTIFF;
case VD_AGENT_CLIPBOARD_IMAGE_JPG: return VDAgentClipboardTypeImageJPG;
case VD_AGENT_CLIPBOARD_NONE:
default: return VDAgentClipboardTypeNone;
}
}
static guint32 convert_clipboard_select_to_raw(vdagent_clipboard_select_t sel)
{
switch (sel) {
case VDAgentClipboardSelectPrimary: return VD_AGENT_CLIPBOARD_SELECTION_PRIMARY;
case VDAgentClipboardSelectSecondary: return VD_AGENT_CLIPBOARD_SELECTION_SECONDARY;
case VDAgentClipboardSelectClipboard:
default: return VD_AGENT_CLIPBOARD_SELECTION_CLIPBOARD;
}
}
static vdagent_clipboard_select_t convert_raw_to_clipboard_select(guint32 sel)
{
switch (sel) {
case VD_AGENT_CLIPBOARD_SELECTION_PRIMARY: return VDAgentClipboardSelectPrimary;
case VD_AGENT_CLIPBOARD_SELECTION_SECONDARY: return VDAgentClipboardSelectSecondary;
case VD_AGENT_CLIPBOARD_SELECTION_CLIPBOARD:
default: return VDAgentClipboardSelectClipboard;
}
}
static void daemon_clipboard_request(VDAgent *agent,
guint sel_id, guint type)
{
if (agent->cb && agent->cb->clipboard_request) {
if (!agent->cb->clipboard_request(agent, agent->ctx,
convert_raw_to_clipboard_select(sel_id),
convert_raw_to_clipboard_type(type))) {
udscs_write(agent->conn, VDAGENTD_CLIPBOARD_DATA, sel_id,
VD_AGENT_CLIPBOARD_NONE, NULL, 0);
}
} else {
syslog(LOG_WARNING, "%s: no callback installed", __func__);
}
}
static void daemon_clipboard_grab(VDAgent *agent,
guint sel_id, guint32 *types, guint n_types)
{
if (agent->cb && agent->cb->clipboard_grab) {
vdagent_clipboard_type_t *_types = calloc(n_types, sizeof(*_types));
if (_types) {
for (int i = 0; i < n_types; i++) {
_types[i] = convert_raw_to_clipboard_type(types[i]);
}
agent->cb->clipboard_grab(agent, agent->ctx,
convert_raw_to_clipboard_select(sel_id),
_types, n_types);
free(_types);
}
} else {
syslog(LOG_WARNING, "%s: no callback installed", __func__);
}
}
static void daemon_clipboard_data(VDAgent *agent,
guint sel_id, guint32 type,
guchar *data, guint size)
{
if (agent->cb && agent->cb->clipboard_data) {
agent->cb->clipboard_data(agent, agent->ctx,
convert_raw_to_clipboard_select(sel_id),
convert_raw_to_clipboard_type(type),
data, size);
} else {
syslog(LOG_WARNING, "%s: no callback installed", __func__);
}
}
static void daemon_clipboard_release(VDAgent *agent, guint sel_id)
{
if (agent->cb && agent->cb->clipboard_release) {
agent->cb->clipboard_release(agent, agent->ctx,
convert_raw_to_clipboard_select(sel_id));
} else {
syslog(LOG_WARNING, "%s: no callback installed", __func__);
}
}
static void daemon_read_complete(UdscsConnection *conn,
struct udscs_message_header *header, uint8_t *data)
{
VDAgent *agent = g_object_get_data(G_OBJECT(conn), "agent");
switch (header->type) {
case VDAGENTD_CLIPBOARD_REQUEST:
daemon_clipboard_request(agent, header->arg1, header->arg2);
break;
case VDAGENTD_CLIPBOARD_GRAB:
daemon_clipboard_grab(agent, header->arg1, (guint32 *)data, header->size / sizeof(guint32));
break;
case VDAGENTD_CLIPBOARD_DATA:
daemon_clipboard_data(agent, header->arg1, header->arg2, data, header->size);
break;
case VDAGENTD_CLIPBOARD_RELEASE:
daemon_clipboard_release(agent, header->arg1);
break;
case VDAGENTD_VERSION:
if (strcmp((char *)data, VERSION) != 0) {
syslog(LOG_INFO, "vdagentd version mismatch: got %s expected %s",
data, VERSION);
vdagent_quit_loop(agent);
version_mismatch = 1;
}
break;
case VDAGENTD_CLIENT_DISCONNECTED:
if (agent->cb && agent->cb->client_disconnected) {
agent->cb->client_disconnected(agent, agent->ctx);
}
break;
default:
syslog(LOG_ERR, "Unknown message from vdagentd type: %d, ignoring",
header->type);
}
}
static void daemon_error_cb(VDAgentConnection *conn, GError *err)
{
VDAgent *agent = g_object_get_data(G_OBJECT(conn), "agent");
if (err) {
syslog(LOG_ERR, "%s", err->message);
g_error_free(err);
}
g_clear_pointer(&conn, vdagent_connection_destroy);
vdagent_quit_loop(agent);
}
static gboolean vdagent_init_async_cb(gpointer user_data)
{
VDAgent *agent = user_data;
GError *err = NULL;
agent->conn = udscs_connect(vdagentd_socket,
daemon_read_complete,
daemon_error_cb,
debug,
&err);
if (agent->conn == NULL) {
if (agent->udscs_num_retry == MAX_RETRY_CONNECT_SYSTEM_AGENT) {
syslog(LOG_WARNING,
"Failed to connect to spice-vdagentd at %s (tried %d times)",
vdagentd_socket, agent->udscs_num_retry);
g_error_free(err);
goto err_init;
}
if (agent->udscs_num_retry == 0) {
/* Log only when it fails and at the end */
syslog(LOG_DEBUG,
"Failed to connect with spice-vdagentd due '%s'. Trying again in 1s",
err->message);
}
g_error_free(err);
agent->udscs_num_retry++;
g_timeout_add_seconds(1, vdagent_init_async_cb, agent);
return G_SOURCE_REMOVE;
}
if (agent->udscs_num_retry != 0) {
syslog(LOG_DEBUG,
"Connected with spice-vdagentd after %d attempts",
agent->udscs_num_retry);
}
agent->udscs_num_retry = 0;
g_object_set_data(G_OBJECT(agent->conn), "agent", agent);
if (agent->cb && agent->cb->agent_connected) {
agent->cb->agent_connected(agent, agent->ctx);
}
return G_SOURCE_REMOVE;
err_init:
vdagent_quit_loop(agent);
quit = TRUE;
return G_SOURCE_REMOVE;
}
int vdagent_start(const char *socketPath, const vdagent_cb_t *cb, void *ctx)
{
VDAgent *agent;
if (socketPath == NULL)
vdagentd_socket = g_strdup(VDAGENTD_SOCKET);
else
vdagentd_socket = g_strdup(socketPath);
openlog("spice-vdagent", LOG_PID | LOG_PERROR, LOG_USER);
syslog(LOG_INFO, "vdagent started");
reconnect:
if (version_mismatch) {
syslog(LOG_INFO, "Version mismatch, restarting");
sleep(1);
}
agent = vdagent_new(cb, ctx);
g_timeout_add(0, vdagent_init_async_cb, agent);
g_main_loop_run(agent->loop);
g_clear_object(&agent);
/* allow the VDAgentConnection to finalize properly */
g_main_context_iteration(NULL, FALSE);
if (!quit)
goto reconnect;
g_free(vdagentd_socket);
return 0;
}
VDAgent *vdagent_ref(VDAgent *agent)
{
return VDAGENT_VDAGENT(g_object_ref(agent));
}
void vdagent_unref(VDAgent *agent)
{
g_object_unref(agent);
}
typedef struct {
UdscsConnection *conn;
struct udscs_message_header hdr;
const uint8_t *data;
GMutex mutex;
GCond cond;
gboolean is_done;
} vdagent_write_params_t;
static gboolean _vdagent_write_cb(gpointer user_data)
{
vdagent_write_params_t *params = (vdagent_write_params_t *)user_data;
udscs_write(params->conn,
params->hdr.type,
params->hdr.arg1,
params->hdr.arg2,
params->data,
params->hdr.size);
g_mutex_lock(&params->mutex);
params->is_done = TRUE;
g_cond_signal(&params->cond);
g_mutex_unlock(&params->mutex);
return G_SOURCE_REMOVE;
}
// write can happen from any thread so we need to synchronize it with the main context
static void vdagent_write(VDAgent *agent, uint32_t type, uint32_t arg1,
uint32_t arg2, const uint8_t *data, uint32_t size)
{
vdagent_write_params_t params = {
.conn = agent->conn,
.hdr.type = type,
.hdr.arg1 = arg1,
.hdr.arg2 = arg2,
.hdr.size = size,
.data = data,
};
// if we have the main context
if (g_main_context_acquire(NULL)) {
// we can call udscs_write directly
udscs_write(agent->conn, type,
arg1, arg2, data, size);
g_main_context_release(NULL);
} else {
// we have to synchronize with main context
g_mutex_init(&params.mutex);
g_cond_init(&params.cond);
g_mutex_lock(&params.mutex);
g_main_context_invoke(NULL, _vdagent_write_cb, &params);
while (!params.is_done) {
g_cond_wait(&params.cond, &params.mutex);
}
g_mutex_unlock(&params.mutex);
}
}
void vdagent_clipboard_request(VDAgent *agent, vdagent_clipboard_select_t sel, vdagent_clipboard_type_t type)
{
vdagent_write(agent,
VDAGENTD_CLIPBOARD_REQUEST,
convert_clipboard_select_to_raw(sel),
convert_clipboard_type_to_raw(type),
NULL, 0);
}
void vdagent_clipboard_grab(VDAgent *agent, vdagent_clipboard_select_t sel,
const vdagent_clipboard_type_t *types, int n_types)
{
guint32 *_types = calloc(n_types, sizeof(*_types));
if (!_types) {
syslog(LOG_ERR, "out of memory");
return;
}
for (int i = 0; i < n_types; i++) {
_types[i] = convert_clipboard_type_to_raw(types[i]);
}
vdagent_write(agent,
VDAGENTD_CLIPBOARD_GRAB,
convert_clipboard_select_to_raw(sel),
0,
(uint8_t *)_types, n_types * sizeof(guint32));
free(_types);
}
void vdagent_clipboard_data(VDAgent *agent, vdagent_clipboard_select_t sel,
vdagent_clipboard_type_t type, const unsigned char *data, unsigned int size)
{
vdagent_write(agent,
VDAGENTD_CLIPBOARD_DATA,
convert_clipboard_select_to_raw(sel),
convert_clipboard_type_to_raw(type),
data, size);
}
void vdagent_clipboard_release(VDAgent *agent, vdagent_clipboard_select_t sel)
{
vdagent_write(agent,
VDAGENTD_CLIPBOARD_RELEASE,
convert_clipboard_select_to_raw(sel),
0,
NULL, 0);
}
+73
View File
@@ -0,0 +1,73 @@
/*
* Copyright (C) 2024 osy
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef vddagent_h
#define vddagent_h
#include <stdbool.h>
typedef struct _VDAgent VDAgent;
typedef enum {
VDAgentClipboardTypeNone,
VDAgentClipboardTypeUTF8Text,
VDAgentClipboardTypeImagePNG,
VDAgentClipboardTypeImageBMP,
VDAgentClipboardTypeImageTIFF,
VDAgentClipboardTypeImageJPG,
} vdagent_clipboard_type_t;
typedef enum {
VDAgentClipboardSelectClipboard,
VDAgentClipboardSelectPrimary,
VDAgentClipboardSelectSecondary,
} vdagent_clipboard_select_t;
typedef bool (*vdagent_clipboard_request_cb)(VDAgent *agent, void *ctx, vdagent_clipboard_select_t sel, vdagent_clipboard_type_t type);
typedef bool (*vdagent_clipboard_grab_cb)(VDAgent *agent, void *ctx, vdagent_clipboard_select_t sel,
const vdagent_clipboard_type_t *types, unsigned int n_types);
typedef bool (*vdagent_clipboard_data_cb)(VDAgent *agent, void *ctx, vdagent_clipboard_select_t sel,
vdagent_clipboard_type_t type, const unsigned char *data, unsigned int size);
typedef bool (*vdagent_clipboard_release_cb)(VDAgent *agent, void *ctx, vdagent_clipboard_select_t sel);
typedef void (*vdagent_client_disconnected_cb)(VDAgent *agent, void *ctx);
typedef void (*vdagent_agent_connected_cb)(VDAgent *agent, void *ctx);
typedef void (*vdagent_agent_disconnected_cb)(VDAgent *agent, void *ctx);
typedef struct {
vdagent_clipboard_request_cb clipboard_request;
vdagent_clipboard_grab_cb clipboard_grab;
vdagent_clipboard_data_cb clipboard_data;
vdagent_clipboard_release_cb clipboard_release;
vdagent_client_disconnected_cb client_disconnected;
vdagent_agent_connected_cb agent_connected;
vdagent_agent_disconnected_cb agent_disconnected;
} vdagent_cb_t;
void vdagent_set_debug(int debugOption);
int vdagent_start(const char *socketPath, const vdagent_cb_t *cb, void *ctx);
VDAgent *vdagent_ref(VDAgent *agent);
void vdagent_unref(VDAgent *agent);
void vdagent_clipboard_request(VDAgent *agent, vdagent_clipboard_select_t sel, vdagent_clipboard_type_t type);
void vdagent_clipboard_grab(VDAgent *agent, vdagent_clipboard_select_t sel,
const vdagent_clipboard_type_t *types, int n_types);
void vdagent_clipboard_data(VDAgent *agent, vdagent_clipboard_select_t sel,
vdagent_clipboard_type_t type, const unsigned char *data, unsigned int size);
void vdagent_clipboard_release(VDAgent *agent, vdagent_clipboard_select_t sel);
#endif /* vddagent_h */
-106
View File
@@ -1,106 +0,0 @@
/* systemd-login.c vdagentd libsystemd-login integration code
Copyright 2012 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "session-info.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <systemd/sd-login.h>
struct session_info {
int verbose;
sd_login_monitor *mon;
char *session;
};
struct session_info *session_info_create(int verbose)
{
struct session_info *si;
int r;
si = calloc(1, sizeof(*si));
if (!si)
return NULL;
si->verbose = verbose;
r = sd_login_monitor_new("session", &si->mon);
if (r < 0) {
syslog(LOG_ERR, "Error creating login monitor: %s", strerror(-r));
free(si);
return NULL;
}
return si;
}
void session_info_destroy(struct session_info *si)
{
if (!si)
return;
sd_login_monitor_unref(si->mon);
free(si->session);
free(si);
}
int session_info_get_fd(struct session_info *si)
{
return sd_login_monitor_get_fd(si->mon);
}
const char *session_info_get_active_session(struct session_info *si)
{
int r;
char *old_session = si->session;
si->session = NULL;
r = sd_seat_get_active("seat0", &si->session, NULL);
/* ENOENT happens when a seat is switching from one session to another */
if (r < 0 && r != -ENOENT)
syslog(LOG_ERR, "Error getting active session: %s",
strerror(-r));
if (si->verbose && si->session &&
(!old_session || strcmp(old_session, si->session)))
syslog(LOG_INFO, "Active session: %s", si->session);
sd_login_monitor_flush(si->mon);
free(old_session);
return si->session;
}
char *session_info_session_for_pid(struct session_info *si, uint32_t pid)
{
int r;
char *session = NULL;
r = sd_pid_get_session(pid, &session);
if (r < 0)
syslog(LOG_ERR, "Error getting session for pid %u: %s",
pid, strerror(-r));
else if (si->verbose)
syslog(LOG_INFO, "Session for pid %u: %s", pid, session);
return session;
}
+235 -482
View File
@@ -9,555 +9,308 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <glib-unix.h>
#include <gio/gunixsocketaddress.h>
#include "udscs.h"
#include "vdagentd-proto-strings.h"
#include "vdagent-connection.h"
struct udscs_buf {
uint8_t *buf;
size_t pos;
size_t size;
struct udscs_buf *next;
};
// Maximum number of connected agents.
// Avoid DoS from agents.
// As each connection end up taking a file descriptor is good to have a limit
// less than the number of file descriptors in the process (by default 1024).
#define MAX_CONNECTED_AGENTS 128
struct udscs_connection {
int fd;
const char * const *type_to_string;
int no_types;
struct _UdscsConnection {
VDAgentConnection parent_instance;
int debug;
struct ucred peer_cred;
void *user_data;
/* Read stuff, single buffer, separate header and data buffer */
int header_read;
struct udscs_message_header header;
struct udscs_buf data;
/* Writes are stored in a linked list of buffers, with both the header
+ data for a single message in 1 buffer. */
struct udscs_buf *write_buf;
/* Callbacks */
udscs_read_callback read_callback;
udscs_disconnect_callback disconnect_callback;
struct udscs_connection *next;
struct udscs_connection *prev;
};
struct udscs_server {
int fd;
const char * const *type_to_string;
int no_types;
int debug;
struct udscs_connection connections_head;
udscs_connect_callback connect_callback;
udscs_read_callback read_callback;
udscs_disconnect_callback disconnect_callback;
};
G_DEFINE_TYPE(UdscsConnection, udscs_connection, VDAGENT_TYPE_CONNECTION)
static void udscs_do_write(struct udscs_connection **connp);
static void udscs_do_read(struct udscs_connection **connp);
struct udscs_server *udscs_create_server(const char *socketname,
udscs_connect_callback connect_callback,
udscs_read_callback read_callback,
udscs_disconnect_callback disconnect_callback,
const char * const type_to_string[], int no_types, int debug)
static void debug_print_message_header(UdscsConnection *conn,
struct udscs_message_header *header,
const gchar *direction)
{
int c;
struct sockaddr_un address;
struct udscs_server *server;
const gchar *type = "invalid message";
server = calloc(1, sizeof(*server));
if (!server)
return NULL;
server->type_to_string = type_to_string;
server->no_types = no_types;
server->debug = debug;
server->fd = socket(PF_UNIX, SOCK_STREAM, 0);
if (server->fd == -1) {
syslog(LOG_ERR, "creating unix domain socket: %m");
free(server);
return NULL;
}
address.sun_family = AF_UNIX;
snprintf(address.sun_path, sizeof(address.sun_path), "%s", socketname);
c = bind(server->fd, (struct sockaddr *)&address, sizeof(address));
if (c != 0) {
syslog(LOG_ERR, "bind %s: %m", socketname);
free(server);
return NULL;
}
c = listen(server->fd, 5);
if (c != 0) {
syslog(LOG_ERR, "listen: %m");
free(server);
return NULL;
}
server->connect_callback = connect_callback;
server->read_callback = read_callback;
server->disconnect_callback = disconnect_callback;
return server;
}
void udscs_destroy_server(struct udscs_server *server)
{
struct udscs_connection *conn, *next_conn;
if (!server)
if (conn == NULL || conn->debug == FALSE)
return;
conn = server->connections_head.next;
while (conn) {
next_conn = conn->next;
udscs_destroy_connection(&conn);
conn = next_conn;
}
close(server->fd);
free(server);
if (header->type < G_N_ELEMENTS(vdagentd_messages))
type = vdagentd_messages[header->type];
syslog(LOG_DEBUG, "%p %s %s, arg1: %u, arg2: %u, size %u",
conn, direction, type, header->arg1, header->arg2, header->size);
}
struct udscs_connection *udscs_connect(const char *socketname,
udscs_read_callback read_callback,
udscs_disconnect_callback disconnect_callback,
const char * const type_to_string[], int no_types, int debug)
static gsize conn_handle_header(VDAgentConnection *conn,
gpointer header_buf)
{
int c;
struct sockaddr_un address;
struct udscs_connection *conn;
return ((struct udscs_message_header *)header_buf)->size;
}
conn = calloc(1, sizeof(*conn));
if (!conn)
static void conn_handle_message(VDAgentConnection *conn,
gpointer header_buf,
gpointer data)
{
UdscsConnection *self = UDSCS_CONNECTION(conn);
struct udscs_message_header *header = header_buf;
debug_print_message_header(self, header, "received");
self->read_callback(self, header, data);
}
static void udscs_connection_init(UdscsConnection *self)
{
}
static void udscs_connection_finalize(GObject *obj)
{
UdscsConnection *self = UDSCS_CONNECTION(obj);
if (self->debug) {
syslog(LOG_DEBUG, "%p disconnected", self);
}
G_OBJECT_CLASS(udscs_connection_parent_class)->finalize(obj);
}
static void udscs_connection_class_init(UdscsConnectionClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
VDAgentConnectionClass *conn_class = VDAGENT_CONNECTION_CLASS(klass);
gobject_class->finalize = udscs_connection_finalize;
conn_class->handle_header = conn_handle_header;
conn_class->handle_message = conn_handle_message;
}
UdscsConnection *udscs_connect(const char *socketname,
udscs_read_callback read_callback,
VDAgentConnErrorCb error_cb,
int debug,
GError **err)
{
GIOStream *io_stream;
UdscsConnection *conn;
io_stream = vdagent_socket_connect(socketname, err);
if (*err) {
return NULL;
}
conn->type_to_string = type_to_string;
conn->no_types = no_types;
conn = g_object_new(UDSCS_TYPE_CONNECTION, NULL);
conn->debug = debug;
conn->fd = socket(PF_UNIX, SOCK_STREAM, 0);
if (conn->fd == -1) {
syslog(LOG_ERR, "creating unix domain socket: %m");
free(conn);
return NULL;
}
address.sun_family = AF_UNIX;
snprintf(address.sun_path, sizeof(address.sun_path), "%s", socketname);
c = connect(conn->fd, (struct sockaddr *)&address, sizeof(address));
if (c != 0) {
if (conn->debug) {
syslog(LOG_DEBUG, "connect %s: %m", socketname);
}
free(conn);
return NULL;
}
conn->read_callback = read_callback;
conn->disconnect_callback = disconnect_callback;
vdagent_connection_setup(VDAGENT_CONNECTION(conn),
io_stream,
FALSE,
sizeof(struct udscs_message_header),
error_cb);
if (conn->debug)
if (conn->debug) {
syslog(LOG_DEBUG, "%p connected to %s", conn, socketname);
}
return conn;
}
void udscs_destroy_connection(struct udscs_connection **connp)
{
struct udscs_buf *wbuf, *next_wbuf;
struct udscs_connection *conn = *connp;
if (!conn)
return;
if (conn->disconnect_callback)
conn->disconnect_callback(conn);
wbuf = conn->write_buf;
while (wbuf) {
next_wbuf = wbuf->next;
free(wbuf->buf);
free(wbuf);
wbuf = next_wbuf;
}
free(conn->data.buf);
if (conn->next)
conn->next->prev = conn->prev;
if (conn->prev)
conn->prev->next = conn->next;
close(conn->fd);
if (conn->debug)
syslog(LOG_DEBUG, "%p disconnected", conn);
free(conn);
*connp = NULL;
}
struct ucred udscs_get_peer_cred(struct udscs_connection *conn)
{
return conn->peer_cred;
}
int udscs_server_fill_fds(struct udscs_server *server, fd_set *readfds,
fd_set *writefds)
{
struct udscs_connection *conn;
int nfds = server->fd + 1;
if (!server)
return -1;
FD_SET(server->fd, readfds);
conn = server->connections_head.next;
while (conn) {
int conn_nfds = udscs_client_fill_fds(conn, readfds, writefds);
if (conn_nfds > nfds)
nfds = conn_nfds;
conn = conn->next;
}
return nfds;
}
int udscs_client_fill_fds(struct udscs_connection *conn, fd_set *readfds,
fd_set *writefds)
{
if (!conn)
return -1;
FD_SET(conn->fd, readfds);
if (conn->write_buf)
FD_SET(conn->fd, writefds);
return conn->fd + 1;
}
static void udscs_server_accept(struct udscs_server *server) {
struct udscs_connection *new_conn, *conn;
struct sockaddr_un address;
socklen_t length = sizeof(address);
int r, fd;
fd = accept(server->fd, (struct sockaddr *)&address, &length);
if (fd == -1) {
if (errno == EINTR)
return;
syslog(LOG_ERR, "accept: %m");
return;
}
new_conn = calloc(1, sizeof(*conn));
if (!new_conn) {
syslog(LOG_ERR, "out of memory, disconnecting new client");
close(fd);
return;
}
new_conn->fd = fd;
new_conn->type_to_string = server->type_to_string;
new_conn->no_types = server->no_types;
new_conn->debug = server->debug;
new_conn->read_callback = server->read_callback;
new_conn->disconnect_callback = server->disconnect_callback;
length = sizeof(new_conn->peer_cred);
r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &new_conn->peer_cred, &length);
if (r != 0) {
syslog(LOG_ERR, "Could not get peercred, disconnecting new client");
close(fd);
free(new_conn);
return;
}
conn = &server->connections_head;
while (conn->next)
conn = conn->next;
new_conn->prev = conn;
conn->next = new_conn;
if (server->debug)
syslog(LOG_DEBUG, "new client accepted: %p, pid: %d",
new_conn, (int)new_conn->peer_cred.pid);
if (server->connect_callback)
server->connect_callback(new_conn);
}
void udscs_server_handle_fds(struct udscs_server *server, fd_set *readfds,
fd_set *writefds)
{
struct udscs_connection *conn, *next_conn;
if (!server)
return;
if (FD_ISSET(server->fd, readfds))
udscs_server_accept(server);
conn = server->connections_head.next;
while (conn) {
/* conn maybe destroyed by udscs_client_handle_fds (when disconnected),
so get the next connection first. */
next_conn = conn->next;
udscs_client_handle_fds(&conn, readfds, writefds);
conn = next_conn;
}
}
void udscs_client_handle_fds(struct udscs_connection **connp, fd_set *readfds,
fd_set *writefds)
{
if (!*connp)
return;
if (FD_ISSET((*connp)->fd, readfds))
udscs_do_read(connp);
if (*connp && FD_ISSET((*connp)->fd, writefds))
udscs_do_write(connp);
}
int udscs_write(struct udscs_connection *conn, uint32_t type, uint32_t arg1,
void udscs_write(UdscsConnection *conn, uint32_t type, uint32_t arg1,
uint32_t arg2, const uint8_t *data, uint32_t size)
{
struct udscs_buf *wbuf, *new_wbuf;
gpointer buf;
guint buf_size;
struct udscs_message_header header;
new_wbuf = malloc(sizeof(*new_wbuf));
if (!new_wbuf)
return -1;
new_wbuf->pos = 0;
new_wbuf->size = sizeof(header) + size;
new_wbuf->next = NULL;
new_wbuf->buf = malloc(new_wbuf->size);
if (!new_wbuf->buf) {
free(new_wbuf);
return -1;
}
buf_size = sizeof(header) + size;
buf = g_malloc(buf_size);
header.type = type;
header.arg1 = arg1;
header.arg2 = arg2;
header.size = size;
memcpy(new_wbuf->buf, &header, sizeof(header));
memcpy(new_wbuf->buf + sizeof(header), data, size);
memcpy(buf, &header, sizeof(header));
memcpy(buf + sizeof(header), data, size);
if (conn->debug) {
if (type < conn->no_types)
syslog(LOG_DEBUG, "%p sent %s, arg1: %u, arg2: %u, size %u",
conn, conn->type_to_string[type], arg1, arg2, size);
else
syslog(LOG_DEBUG,
"%p sent invalid message %u, arg1: %u, arg2: %u, size %u",
conn, type, arg1, arg2, size);
}
debug_print_message_header(conn, &header, "sent");
if (!conn->write_buf) {
conn->write_buf = new_wbuf;
return 0;
}
/* maybe we should limit the write_buf stack depth ? */
wbuf = conn->write_buf;
while (wbuf->next)
wbuf = wbuf->next;
wbuf->next = new_wbuf;
return 0;
vdagent_connection_write(VDAGENT_CONNECTION(conn), buf, buf_size);
}
int udscs_server_write_all(struct udscs_server *server,
#ifndef UDSCS_NO_SERVER
/* ---------- Server-side implementation ---------- */
struct udscs_server {
GSocketService *service;
GList *connections;
int debug;
udscs_connect_callback connect_callback;
udscs_read_callback read_callback;
VDAgentConnErrorCb error_cb;
};
static gboolean udscs_server_accept_cb(GSocketService *service,
GSocketConnection *socket_conn,
GObject *source_object,
gpointer user_data);
struct udscs_server *udscs_server_new(
udscs_connect_callback connect_callback,
udscs_read_callback read_callback,
VDAgentConnErrorCb error_cb,
int debug)
{
struct udscs_server *server;
server = g_new0(struct udscs_server, 1);
server->debug = debug;
server->connect_callback = connect_callback;
server->read_callback = read_callback;
server->error_cb = error_cb;
server->service = g_socket_service_new();
g_socket_service_stop(server->service);
g_signal_connect(server->service, "incoming",
G_CALLBACK(udscs_server_accept_cb), server);
return server;
}
void udscs_server_listen_to_socket(struct udscs_server *server,
gint fd,
GError **err)
{
GSocket *socket;
socket = g_socket_new_from_fd(fd, err);
if (socket == NULL) {
return;
}
g_socket_listener_add_socket(G_SOCKET_LISTENER(server->service),
socket, NULL, err);
g_object_unref(socket);
}
void udscs_server_listen_to_address(struct udscs_server *server,
const gchar *addr,
GError **err)
{
GSocketAddress *sock_addr;
sock_addr = g_unix_socket_address_new(addr);
g_socket_listener_add_address(G_SOCKET_LISTENER(server->service),
sock_addr,
G_SOCKET_TYPE_STREAM,
G_SOCKET_PROTOCOL_DEFAULT,
NULL, NULL, err);
g_object_unref(sock_addr);
}
void udscs_server_start(struct udscs_server *server)
{
g_socket_service_start(server->service);
}
void udscs_server_destroy_connection(struct udscs_server *server,
UdscsConnection *conn)
{
server->connections = g_list_remove(server->connections, conn);
vdagent_connection_destroy(conn);
}
void udscs_destroy_server(struct udscs_server *server)
{
if (!server)
return;
g_list_free_full(server->connections, vdagent_connection_destroy);
g_object_unref(server->service);
g_free(server);
}
static gboolean udscs_server_accept_cb(GSocketService *service,
GSocketConnection *socket_conn,
GObject *source_object,
gpointer user_data)
{
struct udscs_server *server = user_data;
UdscsConnection *new_conn;
/* prevents DoS having too many agents attached */
if (g_list_length(server->connections) >= MAX_CONNECTED_AGENTS) {
syslog(LOG_ERR, "Too many agents connected");
return TRUE;
}
new_conn = g_object_new(UDSCS_TYPE_CONNECTION, NULL);
new_conn->debug = server->debug;
new_conn->read_callback = server->read_callback;
g_object_ref(socket_conn);
vdagent_connection_setup(VDAGENT_CONNECTION(new_conn),
G_IO_STREAM(socket_conn),
FALSE,
sizeof(struct udscs_message_header),
server->error_cb);
server->connections = g_list_prepend(server->connections, new_conn);
if (server->debug)
syslog(LOG_DEBUG, "new client accepted: %p", new_conn);
if (server->connect_callback)
server->connect_callback(new_conn);
return TRUE;
}
void udscs_server_write_all(struct udscs_server *server,
uint32_t type, uint32_t arg1, uint32_t arg2,
const uint8_t *data, uint32_t size)
{
struct udscs_connection *conn;
conn = server->connections_head.next;
while (conn) {
if (udscs_write(conn, type, arg1, arg2, data, size))
return -1;
conn = conn->next;
GList *l;
for (l = server->connections; l; l = l->next) {
udscs_write(UDSCS_CONNECTION(l->data), type, arg1, arg2, data, size);
}
return 0;
}
int udscs_server_for_all_clients(struct udscs_server *server,
udscs_for_all_clients_callback func, void *priv)
{
int r = 0;
struct udscs_connection *conn, *next_conn;
GList *l, *next;
if (!server)
return 0;
conn = server->connections_head.next;
while (conn) {
/* Get next conn as func may destroy the current conn */
next_conn = conn->next;
r += func(&conn, priv);
conn = next_conn;
l = server->connections;
while (l) {
next = l->next;
r += func(l->data, priv);
l = next;
}
return r;
}
static void udscs_read_complete(struct udscs_connection **connp)
{
struct udscs_connection *conn = *connp;
if (conn->debug) {
if (conn->header.type < conn->no_types)
syslog(LOG_DEBUG,
"%p received %s, arg1: %u, arg2: %u, size %u",
conn, conn->type_to_string[conn->header.type],
conn->header.arg1, conn->header.arg2, conn->header.size);
else
syslog(LOG_DEBUG,
"%p received invalid message %u, arg1: %u, arg2: %u, size %u",
conn, conn->header.type, conn->header.arg1, conn->header.arg2,
conn->header.size);
}
if (conn->read_callback) {
conn->read_callback(connp, &conn->header, conn->data.buf);
if (!*connp) /* Was the connection disconnected by the callback ? */
return;
}
conn->header_read = 0;
memset(&conn->data, 0, sizeof(conn->data));
}
static void udscs_do_read(struct udscs_connection **connp)
{
ssize_t n;
size_t to_read;
uint8_t *dest;
struct udscs_connection *conn = *connp;
if (conn->header_read < sizeof(conn->header)) {
to_read = sizeof(conn->header) - conn->header_read;
dest = (uint8_t *)&conn->header + conn->header_read;
} else {
to_read = conn->data.size - conn->data.pos;
dest = conn->data.buf + conn->data.pos;
}
n = read(conn->fd, dest, to_read);
if (n < 0) {
if (errno == EINTR)
return;
syslog(LOG_ERR, "reading unix domain socket: %m, disconnecting %p",
conn);
}
if (n <= 0) {
udscs_destroy_connection(connp);
return;
}
if (conn->header_read < sizeof(conn->header)) {
conn->header_read += n;
if (conn->header_read == sizeof(conn->header)) {
if (conn->header.size == 0) {
udscs_read_complete(connp);
return;
}
conn->data.pos = 0;
conn->data.size = conn->header.size;
conn->data.buf = malloc(conn->data.size);
if (!conn->data.buf) {
syslog(LOG_ERR, "out of memory, disconnecting %p", conn);
udscs_destroy_connection(connp);
return;
}
}
} else {
conn->data.pos += n;
if (conn->data.pos == conn->data.size)
udscs_read_complete(connp);
}
}
static void udscs_do_write(struct udscs_connection **connp)
{
ssize_t n;
size_t to_write;
struct udscs_connection *conn = *connp;
struct udscs_buf* wbuf = conn->write_buf;
if (!wbuf) {
syslog(LOG_ERR,
"%p do_write called on a connection without a write buf ?!",
conn);
return;
}
to_write = wbuf->size - wbuf->pos;
n = write(conn->fd, wbuf->buf + wbuf->pos, to_write);
if (n < 0) {
if (errno == EINTR)
return;
syslog(LOG_ERR, "writing to unix domain socket: %m, disconnecting %p",
conn);
udscs_destroy_connection(connp);
return;
}
wbuf->pos += n;
if (wbuf->pos == wbuf->size) {
conn->write_buf = wbuf->next;
free(wbuf->buf);
free(wbuf);
}
}
void udscs_set_user_data(struct udscs_connection *conn, void *data)
{
conn->user_data = data;
}
void *udscs_get_user_data(struct udscs_connection *conn)
{
if (!conn)
return NULL;
return conn->user_data;
}
#endif
+94 -79
View File
@@ -7,12 +7,12 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
@@ -22,103 +22,118 @@
#ifndef __UDSCS_H
#define __UDSCS_H
#include <stdio.h>
#include <stdint.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <glib-object.h>
#include "vdagent-connection.h"
G_BEGIN_DECLS
#define UDSCS_TYPE_CONNECTION udscs_connection_get_type()
G_DECLARE_FINAL_TYPE(UdscsConnection, udscs_connection, UDSCS, CONNECTION, VDAgentConnection)
/* ---------- Generic bits and client-side API ---------- */
struct udscs_connection;
struct udscs_server;
struct udscs_message_header {
uint32_t type;
uint32_t arg1;
uint32_t arg2;
uint32_t size;
uint32_t size;
};
/* Callbacks with this type will be called when a new connection to a
server is accepted. */
typedef void (*udscs_connect_callback)(struct udscs_connection *conn);
/* Callbacks with this type will be called when a complete message has been
received. The callback may call udscs_destroy_connection, in which case
*connp must be made NULL (which udscs_destroy_connection takes care of) */
typedef void (*udscs_read_callback)(struct udscs_connection **connp,
* received. The callback does not own the data buffer and should not free it.
* The data buffer will be freed shortly after the read callback returns.
*/
typedef void (*udscs_read_callback)(UdscsConnection *conn,
struct udscs_message_header *header, uint8_t *data);
/* Callback type for udscs_server_for_all_clients. Clients can be disconnected
from this callback just like with a read callback. */
typedef int (*udscs_for_all_clients_callback)(struct udscs_connection **connp,
void *priv);
/* Callbacks with this type will be called when the connection is disconnected.
Note:
1) udscs will destroy the connection in question itself after
this callback has completed!
2) This callback is always called, even if the disconnect is initiated
by the udscs user through returning -1 from a read callback, or
by explictly calling udscs_destroy_connection */
typedef void (*udscs_disconnect_callback)(struct udscs_connection *conn);
/* Create a unix domain socket named name and start listening on it. */
struct udscs_server *udscs_create_server(const char *socketname,
udscs_connect_callback connect_callback,
/* Connect to the unix domain socket specified by socketname.
* Only sockets bound to a pathname are supported.
*
* If debug is true then the events on this connection will be traced.
* This includes the incoming and outgoing message names.
*
* In case of failure, returns NULL and set @err with reason.
*/
UdscsConnection *udscs_connect(const char *socketname,
udscs_read_callback read_callback,
udscs_disconnect_callback disconnect_callback,
const char * const type_to_string[], int no_types, int debug);
void udscs_destroy_server(struct udscs_server *server);
/* Connect to a unix domain socket named name. */
struct udscs_connection *udscs_connect(const char *socketname,
udscs_read_callback read_callback,
udscs_disconnect_callback disconnect_callback,
const char * const type_to_string[], int no_types, int debug);
/* The contents of connp will be made NULL */
void udscs_destroy_connection(struct udscs_connection **connp);
/* Given an udscs server or client fill the fd_sets pointed to by readfds and
writefds for select() usage.
Return value: value of the highest fd + 1 */
int udscs_server_fill_fds(struct udscs_server *server, fd_set *readfds,
fd_set *writefds);
int udscs_client_fill_fds(struct udscs_connection *conn, fd_set *readfds,
fd_set *writefds);
/* Handle any events flagged by select for the given udscs server or client. */
void udscs_server_handle_fds(struct udscs_server *server, fd_set *readfds,
fd_set *writefds);
/* Note the connection may be destroyed (when disconnected) by this call
in this case the disconnect calllback will get called before the
destruction and the contents of connp will be made NULL */
void udscs_client_handle_fds(struct udscs_connection **connp, fd_set *readfds,
fd_set *writefds);
VDAgentConnErrorCb error_cb,
int debug,
GError **err);
/* Queue a message for delivery to the client connected through conn.
Returns 0 on success -1 on error (only happens when malloc fails) */
int udscs_write(struct udscs_connection *conn, uint32_t type, uint32_t arg1,
*/
void udscs_write(UdscsConnection *conn, uint32_t type, uint32_t arg1,
uint32_t arg2, const uint8_t *data, uint32_t size);
#ifndef UDSCS_NO_SERVER
/* ---------- Server-side API ---------- */
struct udscs_server;
/* Callbacks with this type will be called when a new connection to a
* server is accepted.
*/
typedef void (*udscs_connect_callback)(UdscsConnection *conn);
/* Initialize a new udscs_server struct.
*
* If debug is true then the events on this socket and related individual
* connections will be traced.
* This includes the incoming and outgoing message names.
*/
struct udscs_server *udscs_server_new(
udscs_connect_callback connect_callback,
udscs_read_callback read_callback,
VDAgentConnErrorCb error_cb,
int debug);
/* Start listening on a pre-configured socket specified by the given @fd.
* This can be used with systemd socket activation, etc. */
void udscs_server_listen_to_socket(struct udscs_server *server,
gint fd,
GError **err);
/* Create a new socket, bind it to @address and start listening on it. */
void udscs_server_listen_to_address(struct udscs_server *server,
const gchar *addr,
GError **err);
void udscs_server_start(struct udscs_server *server);
void udscs_server_destroy_connection(struct udscs_server *server,
UdscsConnection *conn);
/* Close all the server's connections and releases the corresponding
* resources.
* Does nothing if server is NULL.
*/
void udscs_destroy_server(struct udscs_server *server);
/* Like udscs_write, but then send the message to all clients connected to
the server */
int udscs_server_write_all(struct udscs_server *server,
uint32_t type, uint32_t arg1, uint32_t arg2,
const uint8_t *data, uint32_t size);
* the server.
*/
void udscs_server_write_all(struct udscs_server *server,
uint32_t type, uint32_t arg1, uint32_t arg2,
const uint8_t *data, uint32_t size);
/* Callback type for udscs_server_for_all_clients. Clients can be disconnected
* from this callback just like with a read callback.
*/
typedef int (*udscs_for_all_clients_callback)(UdscsConnection *conn,
void *priv);
/* Call func for all clients connected to the server, passing through
priv to all func calls. Returns the total of the return values from all
calls to func */
* priv to all func calls. Returns the total of the return values from all
* calls to func or 0 if server is NULL.
*/
int udscs_server_for_all_clients(struct udscs_server *server,
udscs_for_all_clients_callback func, void *priv);
udscs_for_all_clients_callback func, void *priv);
#endif
struct ucred udscs_get_peer_cred(struct udscs_connection *conn);
/* For server use, to associate per connection data with a connection */
void udscs_set_user_data(struct udscs_connection *conn, void *data);
void *udscs_get_user_data(struct udscs_connection *conn);
G_END_DECLS
#endif
+319
View File
@@ -0,0 +1,319 @@
/* vdagent-connection.c
Copyright 2019 Red Hat, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <syslog.h>
#include <fcntl.h>
#include <errno.h>
#include <glib/gstdio.h>
#include <gio/gunixinputstream.h>
#include <gio/gunixoutputstream.h>
#include <gio/gunixsocketaddress.h>
#include "vdagent-connection.h"
typedef struct {
GIOStream *io_stream;
gboolean opening;
VDAgentConnErrorCb error_cb;
GCancellable *cancellable;
GQueue *write_queue;
gsize bytes_written;
gsize header_size;
gpointer header_buf;
gpointer data_buf;
} VDAgentConnectionPrivate;
G_DEFINE_TYPE_WITH_PRIVATE(VDAgentConnection, vdagent_connection, G_TYPE_OBJECT)
static void read_next_message(VDAgentConnection *self);
GIOStream *vdagent_file_open(const gchar *path, GError **err)
{
gint fd, errsv;
fd = g_open(path, O_RDWR);
if (fd == -1) {
errsv = errno;
g_set_error_literal(err, G_FILE_ERROR,
g_file_error_from_errno(errsv),
g_strerror(errsv));
return NULL;
}
return g_simple_io_stream_new(g_unix_input_stream_new(fd, TRUE),
g_unix_output_stream_new(fd, TRUE));
}
GIOStream *vdagent_socket_connect(const gchar *path, GError **err)
{
GSocketConnection *conn;
GSocketAddress *addr;
GSocketClient *client;
addr = g_unix_socket_address_new(path);
client = g_object_new(G_TYPE_SOCKET_CLIENT,
"family", G_SOCKET_FAMILY_UNIX,
"type", G_SOCKET_TYPE_STREAM,
NULL);
conn = g_socket_client_connect(client, G_SOCKET_CONNECTABLE(addr), NULL, err);
g_object_unref(client);
g_object_unref(addr);
return G_IO_STREAM(conn);
}
static void vdagent_connection_init(VDAgentConnection *self)
{
VDAgentConnectionPrivate *priv = vdagent_connection_get_instance_private(self);
priv->cancellable = g_cancellable_new();
priv->write_queue = g_queue_new();
}
static void vdagent_connection_dispose(GObject *obj)
{
VDAgentConnection *self = VDAGENT_CONNECTION(obj);
VDAgentConnectionPrivate *priv = vdagent_connection_get_instance_private(self);
g_clear_object(&priv->cancellable);
g_clear_object(&priv->io_stream);
G_OBJECT_CLASS(vdagent_connection_parent_class)->dispose(obj);
}
static void vdagent_connection_finalize(GObject *obj)
{
VDAgentConnection *self = VDAGENT_CONNECTION(obj);
VDAgentConnectionPrivate *priv = vdagent_connection_get_instance_private(self);
g_queue_free_full(priv->write_queue, (GDestroyNotify)g_bytes_unref);
g_free(priv->header_buf);
g_free(priv->data_buf);
G_OBJECT_CLASS(vdagent_connection_parent_class)->finalize(obj);
}
static void vdagent_connection_class_init(VDAgentConnectionClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
gobject_class->dispose = vdagent_connection_dispose;
gobject_class->finalize = vdagent_connection_finalize;
}
void vdagent_connection_setup(VDAgentConnection *self,
GIOStream *io_stream,
gboolean wait_on_opening,
gsize header_size,
VDAgentConnErrorCb error_cb)
{
VDAgentConnectionPrivate *priv = vdagent_connection_get_instance_private(self);
priv->io_stream = io_stream;
priv->opening = wait_on_opening;
priv->header_size = header_size;
priv->header_buf = g_malloc(header_size);
priv->error_cb = error_cb;
read_next_message(self);
}
void vdagent_connection_destroy(gpointer p)
{
g_return_if_fail(VDAGENT_IS_CONNECTION(p));
VDAgentConnection *self = VDAGENT_CONNECTION(p);
VDAgentConnectionPrivate *priv = vdagent_connection_get_instance_private(self);
g_cancellable_cancel(priv->cancellable);
g_io_stream_close(priv->io_stream, NULL, NULL);
g_object_unref(self);
}
PidUid vdagent_connection_get_peer_pid_uid(VDAgentConnection *self,
GError **err)
{
VDAgentConnectionPrivate *priv = vdagent_connection_get_instance_private(self);
GSocket *sock;
GCredentials *cred;
PidUid pid_uid = { -1, -1 };
g_return_val_if_fail(G_IS_SOCKET_CONNECTION(priv->io_stream), pid_uid);
sock = g_socket_connection_get_socket(G_SOCKET_CONNECTION(priv->io_stream));
cred = g_socket_get_credentials(sock, err);
if (cred) {
pid_uid.pid = g_credentials_get_unix_pid(cred, err);
pid_uid.uid = g_credentials_get_unix_user(cred, err);
g_object_unref(cred);
}
return pid_uid;
}
/* Performs single write operation,
* returns TRUE if there's still data to be written, otherwise FALSE. */
static gboolean do_write(VDAgentConnection *self, gboolean block)
{
VDAgentConnectionPrivate *priv = vdagent_connection_get_instance_private(self);
GOutputStream *out;
GBytes *msg;
gssize res;
GError *err = NULL;
msg = g_queue_peek_head(priv->write_queue);
out = g_io_stream_get_output_stream(priv->io_stream);
if (!msg) {
return FALSE;
}
res = g_pollable_stream_write(out,
g_bytes_get_data(msg, NULL) + priv->bytes_written,
g_bytes_get_size(msg) - priv->bytes_written,
block, priv->cancellable, &err);
if (err) {
if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
g_error_free(err);
return TRUE;
} else if (g_error_matches(err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
g_error_free(err);
return FALSE;
} else {
priv->error_cb(self, err);
return FALSE;
}
}
priv->bytes_written += res;
if (priv->bytes_written == g_bytes_get_size(msg)) {
g_bytes_unref(g_queue_pop_head(priv->write_queue));
priv->bytes_written = 0;
}
return !g_queue_is_empty(priv->write_queue);
}
static gboolean out_stream_ready_cb(GObject *pollable_stream,
gpointer user_data)
{
return do_write(user_data, FALSE);
}
void vdagent_connection_write(VDAgentConnection *self,
gpointer data,
gsize size)
{
VDAgentConnectionPrivate *priv = vdagent_connection_get_instance_private(self);
GPollableOutputStream *out;
GSource *source;
g_queue_push_tail(priv->write_queue, g_bytes_new_take(data, size));
if (g_queue_get_length(priv->write_queue) == 1) {
out = G_POLLABLE_OUTPUT_STREAM(g_io_stream_get_output_stream(priv->io_stream));
source = g_pollable_output_stream_create_source(out, priv->cancellable);
g_source_set_callback(source, (GSourceFunc) out_stream_ready_cb,
g_object_ref(self), g_object_unref);
g_source_attach(source, NULL);
g_source_unref(source);
}
}
void vdagent_connection_flush(VDAgentConnection *self)
{
while (do_write(self, TRUE));
}
static void message_read_cb(GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
VDAgentConnection *self = user_data;
VDAgentConnectionPrivate *priv = vdagent_connection_get_instance_private(self);
GInputStream *in = G_INPUT_STREAM(source_object);
GError *err = NULL;
gsize bytes_read, data_size;
g_input_stream_read_all_finish(in, res, &bytes_read, &err);
if (err) {
if (g_error_matches(err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
g_error_free(err);
} else {
priv->error_cb(self, err);
}
goto unref;
}
if (bytes_read == 0) {
/* see virtio-port.c for the rationale behind this */
if (priv->opening) {
g_usleep(10000);
read_next_message(self);
} else {
priv->error_cb(self, NULL);
}
goto unref;
}
priv->opening = FALSE;
if (!priv->data_buf) {
/* we've read the message header, now let's read its body */
data_size = VDAGENT_CONNECTION_GET_CLASS(self)->handle_header(
self, priv->header_buf);
if (g_cancellable_is_cancelled(priv->cancellable)) {
goto unref;
}
if (data_size > 0) {
priv->data_buf = g_malloc(data_size);
g_input_stream_read_all_async(in,
priv->data_buf, data_size,
G_PRIORITY_DEFAULT, priv->cancellable,
message_read_cb, g_object_ref(self));
goto unref;
}
}
VDAGENT_CONNECTION_GET_CLASS(self)->handle_message(
self, priv->header_buf, priv->data_buf);
g_clear_pointer(&priv->data_buf, g_free);
read_next_message(self);
unref:
g_object_unref(self);
}
static void read_next_message(VDAgentConnection *self)
{
VDAgentConnectionPrivate *priv = vdagent_connection_get_instance_private(self);
GInputStream *in;
if (g_cancellable_is_cancelled(priv->cancellable)) {
return;
}
in = g_io_stream_get_input_stream(priv->io_stream);
g_input_stream_read_all_async(in,
priv->header_buf, priv->header_size,
G_PRIORITY_DEFAULT, priv->cancellable,
message_read_cb, g_object_ref(self));
}
+107
View File
@@ -0,0 +1,107 @@
/* vdagent-connection.h
Copyright 2019 Red Hat, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __VDAGENT_CONNECTION_H
#define __VDAGENT_CONNECTION_H
#include <glib.h>
#include <gio/gio.h>
#include <glib-object.h>
G_BEGIN_DECLS
#define VDAGENT_TYPE_CONNECTION vdagent_connection_get_type()
G_DECLARE_DERIVABLE_TYPE(VDAgentConnection, vdagent_connection, VDAGENT, CONNECTION, GObject)
/* Subclasses of VDAgentConnection must implement
* handle_header and handle_message. */
struct _VDAgentConnectionClass {
GObjectClass parent_class;
/* Called when a message header has been read.
*
* Handler must parse the @header_buf and
* return the size of message's body.
*
* @header_buf must not be freed. */
gsize (*handle_header) (VDAgentConnection *self,
gpointer header_buf);
/* Called when a full message has been read.
*
* @header, @data must not be freed. */
void (*handle_message) (VDAgentConnection *self,
gpointer header_buf,
gpointer data_buf);
};
/* Invoked when an error occurs during read or write.
*
* If @err is NULL, the connection was closed by the remote side,
* otherwise the handler must free @err using g_error_free().
*
* VDAgentConnection will not continue with the given I/O-op that failed. */
typedef void (*VDAgentConnErrorCb)(VDAgentConnection *self, GError *err);
/* Open a file in @path for read and write.
* Returns a new GIOStream to the given file or NULL when @err is set. */
GIOStream *vdagent_file_open(const gchar *path, GError **err);
/* Create a socket and initiate a new connection to the socket in @path.
* Returns a new GIOStream or NULL when @err is set. */
GIOStream *vdagent_socket_connect(const gchar *path, GError **err);
/* Set up @self to use @io_stream and start reading from it.
*
* If @wait_on_opening is set to TRUE, EOF won't be treated as an error
* until the first message is successfully read or written to the @io_stream. */
void vdagent_connection_setup(VDAgentConnection *self,
GIOStream *io_stream,
gboolean wait_on_opening,
gsize header_size,
VDAgentConnErrorCb error_cb);
/* Cancel running I/O-operations, close the underlying FD and
* unref the VDAgentConnection object. */
void vdagent_connection_destroy(gpointer p);
/* Append a message to the write queue.
*
* VDAgentConnection takes ownership of @data
* and frees it once the message is flushed. */
void vdagent_connection_write(VDAgentConnection *self,
gpointer data,
gsize size);
/* Synchronously write all queued messages to the output stream. */
void vdagent_connection_flush(VDAgentConnection *self);
typedef struct PidUid {
pid_t pid;
uid_t uid;
} PidUid;
/* Returns the PID and UID of the foreign process connected to the socket
* or fill @err set. */
PidUid vdagent_connection_get_peer_pid_uid(VDAgentConnection *self,
GError **err);
G_END_DECLS
#endif
-493
View File
@@ -1,493 +0,0 @@
/* vdagent-virtio-port.c virtio port communication code
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "vdagent-virtio-port.h"
#define VDP_LAST_PORT VDP_SERVER_PORT
struct vdagent_virtio_port_buf {
uint8_t *buf;
size_t pos;
size_t size;
size_t write_pos;
struct vdagent_virtio_port_buf *next;
};
/* Data to keep track of the assembling of vdagent messages per chunk port,
for de-multiplexing the messages */
struct vdagent_virtio_port_chunk_port_data {
int message_header_read;
int message_data_pos;
VDAgentMessage message_header;
uint8_t *message_data;
};
struct vdagent_virtio_port {
int fd;
int opening;
int is_uds;
/* Chunk read stuff, single buffer, separate header and data buffer */
int chunk_header_read;
int chunk_data_pos;
VDIChunkHeader chunk_header;
uint8_t chunk_data[VD_AGENT_MAX_DATA_SIZE];
/* Per chunk port data */
struct vdagent_virtio_port_chunk_port_data port_data[VDP_LAST_PORT + 1];
/* Writes are stored in a linked list of buffers, with both the header
+ data for a single message in 1 buffer. */
struct vdagent_virtio_port_buf *write_buf;
/* Callbacks */
vdagent_virtio_port_read_callback read_callback;
vdagent_virtio_port_disconnect_callback disconnect_callback;
};
static void vdagent_virtio_port_do_write(struct vdagent_virtio_port **vportp);
static void vdagent_virtio_port_do_read(struct vdagent_virtio_port **vportp);
struct vdagent_virtio_port *vdagent_virtio_port_create(const char *portname,
vdagent_virtio_port_read_callback read_callback,
vdagent_virtio_port_disconnect_callback disconnect_callback)
{
struct vdagent_virtio_port *vport;
struct sockaddr_un address;
int c;
vport = calloc(1, sizeof(*vport));
if (!vport)
return 0;
vport->fd = open(portname, O_RDWR);
if (vport->fd == -1) {
vport->fd = socket(PF_UNIX, SOCK_STREAM, 0);
if (vport->fd == -1) {
goto error;
}
address.sun_family = AF_UNIX;
snprintf(address.sun_path, sizeof(address.sun_path), "%s", portname);
c = connect(vport->fd, (struct sockaddr *)&address, sizeof(address));
if (c == 0) {
vport->is_uds = 1;
} else {
goto error;
}
} else {
vport->is_uds = 0;
}
vport->opening = 1;
vport->read_callback = read_callback;
vport->disconnect_callback = disconnect_callback;
return vport;
error:
syslog(LOG_ERR, "open %s: %m", portname);
if (vport->fd != -1) {
close(vport->fd);
}
free(vport);
return NULL;
}
void vdagent_virtio_port_destroy(struct vdagent_virtio_port **vportp)
{
struct vdagent_virtio_port_buf *wbuf, *next_wbuf;
struct vdagent_virtio_port *vport = *vportp;
int i;
if (!vport)
return;
if (vport->disconnect_callback)
vport->disconnect_callback(vport);
wbuf = vport->write_buf;
while (wbuf) {
next_wbuf = wbuf->next;
free(wbuf->buf);
free(wbuf);
wbuf = next_wbuf;
}
for (i = 0; i <= VDP_LAST_PORT; i++) {
free(vport->port_data[i].message_data);
}
close(vport->fd);
free(vport);
*vportp = NULL;
}
int vdagent_virtio_port_fill_fds(struct vdagent_virtio_port *vport,
fd_set *readfds, fd_set *writefds)
{
if (!vport)
return -1;
FD_SET(vport->fd, readfds);
if (vport->write_buf)
FD_SET(vport->fd, writefds);
return vport->fd + 1;
}
void vdagent_virtio_port_handle_fds(struct vdagent_virtio_port **vportp,
fd_set *readfds, fd_set *writefds)
{
if (!*vportp)
return;
if (FD_ISSET((*vportp)->fd, readfds))
vdagent_virtio_port_do_read(vportp);
if (*vportp && FD_ISSET((*vportp)->fd, writefds))
vdagent_virtio_port_do_write(vportp);
}
static struct vdagent_virtio_port_buf* vdagent_virtio_port_get_last_wbuf(
struct vdagent_virtio_port *vport)
{
struct vdagent_virtio_port_buf *wbuf;
wbuf = vport->write_buf;
if (!wbuf)
return NULL;
while (wbuf->next)
wbuf = wbuf->next;
return wbuf;
}
int vdagent_virtio_port_write_start(
struct vdagent_virtio_port *vport,
uint32_t port_nr,
uint32_t message_type,
uint32_t message_opaque,
uint32_t data_size)
{
struct vdagent_virtio_port_buf *wbuf, *new_wbuf;
VDIChunkHeader chunk_header;
VDAgentMessage message_header;
new_wbuf = malloc(sizeof(*new_wbuf));
if (!new_wbuf)
return -1;
new_wbuf->pos = 0;
new_wbuf->write_pos = 0;
new_wbuf->size = sizeof(chunk_header) + sizeof(message_header) + data_size;
new_wbuf->next = NULL;
new_wbuf->buf = malloc(new_wbuf->size);
if (!new_wbuf->buf) {
free(new_wbuf);
return -1;
}
chunk_header.port = port_nr;
chunk_header.size = sizeof(message_header) + data_size;
memcpy(new_wbuf->buf + new_wbuf->write_pos, &chunk_header,
sizeof(chunk_header));
new_wbuf->write_pos += sizeof(chunk_header);
message_header.protocol = VD_AGENT_PROTOCOL;
message_header.type = message_type;
message_header.opaque = message_opaque;
message_header.size = data_size;
memcpy(new_wbuf->buf + new_wbuf->write_pos, &message_header,
sizeof(message_header));
new_wbuf->write_pos += sizeof(message_header);
if (!vport->write_buf) {
vport->write_buf = new_wbuf;
return 0;
}
wbuf = vdagent_virtio_port_get_last_wbuf(vport);
wbuf->next = new_wbuf;
return 0;
}
int vdagent_virtio_port_write_append(struct vdagent_virtio_port *vport,
const uint8_t *data, uint32_t size)
{
struct vdagent_virtio_port_buf *wbuf;
wbuf = vdagent_virtio_port_get_last_wbuf(vport);
if (!wbuf) {
syslog(LOG_ERR, "can't append without a buffer");
return -1;
}
if (wbuf->size - wbuf->write_pos < size) {
syslog(LOG_ERR, "can't append to full buffer");
return -1;
}
memcpy(wbuf->buf + wbuf->write_pos, data, size);
wbuf->write_pos += size;
return 0;
}
int vdagent_virtio_port_write(
struct vdagent_virtio_port *vport,
uint32_t port_nr,
uint32_t message_type,
uint32_t message_opaque,
const uint8_t *data,
uint32_t data_size)
{
if (vdagent_virtio_port_write_start(vport, port_nr, message_type,
message_opaque, data_size)) {
return -1;
}
vdagent_virtio_port_write_append(vport, data, data_size);
return 0;
}
void vdagent_virtio_port_flush(struct vdagent_virtio_port **vportp)
{
while (*vportp && (*vportp)->write_buf)
vdagent_virtio_port_do_write(vportp);
}
void vdagent_virtio_port_reset(struct vdagent_virtio_port *vport, int port)
{
if (port > VDP_LAST_PORT) {
syslog(LOG_ERR, "vdagent_virtio_port_reset port out of range");
return;
}
free(vport->port_data[port].message_data);
memset(&vport->port_data[port], 0, sizeof(vport->port_data[0]));
}
static void vdagent_virtio_port_do_chunk(struct vdagent_virtio_port **vportp)
{
int avail, read, pos = 0;
struct vdagent_virtio_port *vport = *vportp;
struct vdagent_virtio_port_chunk_port_data *port =
&vport->port_data[vport->chunk_header.port];
if (port->message_header_read < sizeof(port->message_header)) {
read = sizeof(port->message_header) - port->message_header_read;
if (read > vport->chunk_header.size) {
read = vport->chunk_header.size;
}
memcpy((uint8_t *)&port->message_header + port->message_header_read,
vport->chunk_data, read);
port->message_header_read += read;
if (port->message_header_read == sizeof(port->message_header) &&
port->message_header.size) {
port->message_data = malloc(port->message_header.size);
if (!port->message_data) {
syslog(LOG_ERR, "out of memory, disconnecting virtio");
vdagent_virtio_port_destroy(vportp);
return;
}
}
pos = read;
}
if (port->message_header_read == sizeof(port->message_header)) {
read = port->message_header.size - port->message_data_pos;
avail = vport->chunk_header.size - pos;
if (avail > read) {
syslog(LOG_ERR, "chunk larger then message, lost sync?");
vdagent_virtio_port_destroy(vportp);
return;
}
if (avail < read)
read = avail;
if (read) {
memcpy(port->message_data + port->message_data_pos,
vport->chunk_data + pos, read);
port->message_data_pos += read;
}
if (port->message_data_pos == port->message_header.size) {
if (vport->read_callback) {
int r = vport->read_callback(vport, vport->chunk_header.port,
&port->message_header, port->message_data);
if (r == -1) {
vdagent_virtio_port_destroy(vportp);
return;
}
}
port->message_header_read = 0;
port->message_data_pos = 0;
free(port->message_data);
port->message_data = NULL;
}
}
}
static int vport_read(struct vdagent_virtio_port *vport, uint8_t *buf, int len)
{
if (vport->is_uds) {
return recv(vport->fd, buf, len, 0);
} else {
return read(vport->fd, buf, len);
}
}
static void vdagent_virtio_port_do_read(struct vdagent_virtio_port **vportp)
{
ssize_t n;
size_t to_read;
uint8_t *dest;
struct vdagent_virtio_port *vport = *vportp;
if (vport->chunk_header_read < sizeof(vport->chunk_header)) {
to_read = sizeof(vport->chunk_header) - vport->chunk_header_read;
dest = (uint8_t *)&vport->chunk_header + vport->chunk_header_read;
} else {
to_read = vport->chunk_header.size - vport->chunk_data_pos;
dest = vport->chunk_data + vport->chunk_data_pos;
}
n = vport_read(vport, dest, to_read);
if (n < 0) {
if (errno == EINTR)
return;
syslog(LOG_ERR, "reading from vdagent virtio port: %m");
}
if (n == 0 && vport->opening) {
/* When we open the virtio serial port, the following happens:
1) The linux kernel virtio_console driver sends a
VIRTIO_CONSOLE_PORT_OPEN message to qemu
2) qemu's spicevmc chardev driver calls qemu_spice_add_interface to
register the agent chardev with the spice-server
3) spice-server then calls the spicevmc chardev driver's state
callback to let it know it is ready to receive data
4) The state callback sends a CHR_EVENT_OPENED to the virtio-console
chardev backend
5) The virtio-console chardev backend sends VIRTIO_CONSOLE_PORT_OPEN
to the linux kernel virtio_console driver
Until steps 1 - 5 have completed the linux kernel virtio_console
driver sees the virtio serial port as being in a disconnected state
and read will return 0 ! So if we blindly assume that a read 0 means
that the channel is closed we will hit a race here.
Therefore we ignore read returning 0 until we've successfully read
or written some data. If we hit this race we also sleep a bit here
to avoid busy waiting until the above steps complete */
usleep(10000);
return;
}
if (n <= 0) {
vdagent_virtio_port_destroy(vportp);
return;
}
vport->opening = 0;
if (vport->chunk_header_read < sizeof(vport->chunk_header)) {
vport->chunk_header_read += n;
if (vport->chunk_header_read == sizeof(vport->chunk_header)) {
if (vport->chunk_header.size > VD_AGENT_MAX_DATA_SIZE) {
syslog(LOG_ERR, "chunk size %u too large",
vport->chunk_header.size);
vdagent_virtio_port_destroy(vportp);
return;
}
if (vport->chunk_header.port > VDP_LAST_PORT) {
syslog(LOG_ERR, "chunk port %u out of range",
vport->chunk_header.port);
vdagent_virtio_port_destroy(vportp);
return;
}
}
} else {
vport->chunk_data_pos += n;
if (vport->chunk_data_pos == vport->chunk_header.size) {
vdagent_virtio_port_do_chunk(vportp);
if (!*vportp)
return;
vport->chunk_header_read = 0;
vport->chunk_data_pos = 0;
}
}
}
static int vport_write(struct vdagent_virtio_port *vport, uint8_t *buf, int len)
{
if (vport->is_uds) {
return send(vport->fd, buf, len, 0);
} else {
return write(vport->fd, buf, len);
}
}
static void vdagent_virtio_port_do_write(struct vdagent_virtio_port **vportp)
{
ssize_t n;
size_t to_write;
struct vdagent_virtio_port *vport = *vportp;
struct vdagent_virtio_port_buf* wbuf = vport->write_buf;
if (!wbuf) {
syslog(LOG_ERR, "do_write called on a port without a write buf ?!");
return;
}
if (wbuf->write_pos != wbuf->size) {
syslog(LOG_ERR, "do_write: buffer is incomplete!!");
return;
}
to_write = wbuf->size - wbuf->pos;
n = vport_write(vport, wbuf->buf + wbuf->pos, to_write);
if (n < 0) {
if (errno == EINTR)
return;
syslog(LOG_ERR, "writing to vdagent virtio port: %m");
vdagent_virtio_port_destroy(vportp);
return;
}
if (n > 0)
vport->opening = 0;
wbuf->pos += n;
if (wbuf->pos == wbuf->size) {
vport->write_buf = wbuf->next;
free(wbuf->buf);
free(wbuf);
}
}
-104
View File
@@ -1,104 +0,0 @@
/* vdagent-virtio-port.h virtio port communication header
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __VIRTIO_PORT_H
#define __VIRTIO_PORT_H
#include <stdio.h>
#include <stdint.h>
#include <sys/select.h>
#include <spice/vd_agent.h>
struct vdagent_virtio_port;
/* Callbacks with this type will be called when a complete message has been
received. Sometimes the callback may want to close the port, in this
case do *not* call vdagent_virtio_port_destroy from the callback. The desire
to close the port can be indicated be returning -1 from the callback,
in other cases return 0. */
typedef int (*vdagent_virtio_port_read_callback)(
struct vdagent_virtio_port *vport,
int port_nr,
VDAgentMessage *message_header,
uint8_t *data);
/* Callbacks with this type will be called when the port is disconnected.
Note:
1) vdagent_virtio_port will destroy the port in question itself after
this callback has completed!
2) This callback is always called, even if the disconnect is initiated
by the vdagent_virtio_port user through returning -1 from a read
callback, or by explictly calling vdagent_virtio_port_destroy */
typedef void (*vdagent_virtio_port_disconnect_callback)(
struct vdagent_virtio_port *conn);
/* Create a vdagent virtio port object for port portname */
struct vdagent_virtio_port *vdagent_virtio_port_create(const char *portname,
vdagent_virtio_port_read_callback read_callback,
vdagent_virtio_port_disconnect_callback disconnect_callback);
/* The contents of portp will be made NULL */
void vdagent_virtio_port_destroy(struct vdagent_virtio_port **vportp);
/* Given a vdagent_virtio_port fill the fd_sets pointed to by readfds and
writefds for select() usage.
Return value: value of the highest fd + 1 */
int vdagent_virtio_port_fill_fds(struct vdagent_virtio_port *vport,
fd_set *readfds, fd_set *writefds);
/* Handle any events flagged by select for the given vdagent_virtio_port.
Note the port may be destroyed (when disconnected) by this call
in this case the disconnect calllback will get called before the
destruction and the contents of connp will be made NULL */
void vdagent_virtio_port_handle_fds(struct vdagent_virtio_port **vportp,
fd_set *readfds, fd_set *writefds);
/* Queue a message for delivery, either bit by bit, or all at once
Returns 0 on success -1 on error (only happens when malloc fails) */
int vdagent_virtio_port_write_start(
struct vdagent_virtio_port *vport,
uint32_t port_nr,
uint32_t message_type,
uint32_t message_opaque,
uint32_t data_size);
int vdagent_virtio_port_write_append(
struct vdagent_virtio_port *vport,
const uint8_t *data,
uint32_t size);
int vdagent_virtio_port_write(
struct vdagent_virtio_port *vport,
uint32_t port_nr,
uint32_t message_type,
uint32_t message_opaque,
const uint8_t *data,
uint32_t data_size);
void vdagent_virtio_port_flush(struct vdagent_virtio_port **vportp);
void vdagent_virtio_port_reset(struct vdagent_virtio_port *vport, int port);
#endif
-308
View File
@@ -1,308 +0,0 @@
/* vdagent.c xorg-client to vdagentd (daemon).
Copyright 2010-2013 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <spice/vd_agent.h>
#include <glib.h>
#include "udscs.h"
#include "vdagentd-proto.h"
#include "vdagentd-proto-strings.h"
#include "vdagent-x11.h"
#include "vdagent-file-xfers.h"
static const char *portdev = "/dev/virtio-ports/com.redhat.spice.0";
static const char *vdagentd_socket = VDAGENTD_SOCKET;
static int debug = 0;
static const char *fx_dir = NULL;
static int fx_open_dir = -1;
static struct vdagent_x11 *x11 = NULL;
static struct vdagent_file_xfers *vdagent_file_xfers = NULL;
static struct udscs_connection *client = NULL;
static int quit = 0;
static int version_mismatch = 0;
void daemon_read_complete(struct udscs_connection **connp,
struct udscs_message_header *header, uint8_t *data)
{
switch (header->type) {
case VDAGENTD_MONITORS_CONFIG:
vdagent_x11_set_monitor_config(x11, (VDAgentMonitorsConfig *)data, 0);
free(data);
break;
case VDAGENTD_CLIPBOARD_REQUEST:
vdagent_x11_clipboard_request(x11, header->arg1, header->arg2);
free(data);
break;
case VDAGENTD_CLIPBOARD_GRAB:
vdagent_x11_clipboard_grab(x11, header->arg1, (uint32_t *)data,
header->size / sizeof(uint32_t));
free(data);
break;
case VDAGENTD_CLIPBOARD_DATA:
vdagent_x11_clipboard_data(x11, header->arg1, header->arg2,
data, header->size);
/* vdagent_x11_clipboard_data takes ownership of the data (or frees
it immediately) */
break;
case VDAGENTD_CLIPBOARD_RELEASE:
vdagent_x11_clipboard_release(x11, header->arg1);
free(data);
break;
case VDAGENTD_VERSION:
if (strcmp((char *)data, VERSION) != 0) {
syslog(LOG_INFO, "vdagentd version mismatch: got %s expected %s",
data, VERSION);
udscs_destroy_connection(connp);
version_mismatch = 1;
}
break;
case VDAGENTD_FILE_XFER_START:
vdagent_file_xfers_start(vdagent_file_xfers,
(VDAgentFileXferStartMessage *)data);
free(data);
break;
case VDAGENTD_FILE_XFER_STATUS:
vdagent_file_xfers_status(vdagent_file_xfers,
(VDAgentFileXferStatusMessage *)data);
free(data);
break;
case VDAGENTD_FILE_XFER_DATA:
vdagent_file_xfers_data(vdagent_file_xfers,
(VDAgentFileXferDataMessage *)data);
free(data);
break;
case VDAGENTD_CLIENT_DISCONNECTED:
vdagent_x11_client_disconnected(x11);
vdagent_file_xfers_destroy(vdagent_file_xfers);
vdagent_file_xfers = vdagent_file_xfers_create(client, fx_dir,
fx_open_dir, debug);
break;
default:
syslog(LOG_ERR, "Unknown message from vdagentd type: %d, ignoring",
header->type);
free(data);
}
}
int client_setup(int reconnect)
{
while (!quit) {
client = udscs_connect(vdagentd_socket, daemon_read_complete, NULL,
vdagentd_messages, VDAGENTD_NO_MESSAGES,
debug);
if (client || !reconnect || quit) {
break;
}
sleep(1);
}
return client == NULL;
}
static void usage(FILE *fp)
{
fprintf(fp,
"Usage: spice-vdagent [OPTIONS]\n\n"
"Spice guest agent X11 session agent, version %s.\n\n"
"Options:\n"
" -h print this text\n"
" -d log debug messages\n"
" -s <port> set virtio serial port\n"
" -S <filename> set udcs socket\n"
" -x don't daemonize\n"
" -f <dir|xdg-desktop|xdg-download> file xfer save dir\n"
" -o <0|1> open dir on file xfer completion\n",
VERSION);
}
static void quit_handler(int sig)
{
quit = 1;
}
void daemonize(void)
{
int x, retval = 0;
/* detach from terminal */
switch (fork()) {
case 0:
close(0); close(1); close(2);
setsid();
x = open("/dev/null", O_RDWR); x = dup(x); x = dup(x);
break;
case -1:
syslog(LOG_ERR, "fork: %s", strerror(errno));
retval = 1;
default:
exit(retval);
}
}
static int file_test(const char *path)
{
struct stat buffer;
return stat(path, &buffer);
}
int main(int argc, char *argv[])
{
fd_set readfds, writefds;
int c, n, nfds, x11_fd;
int do_daemonize = 1;
int x11_sync = 0;
struct sigaction act;
for (;;) {
if (-1 == (c = getopt(argc, argv, "-dxhys:f:o:S:")))
break;
switch (c) {
case 'd':
debug++;
break;
case 's':
portdev = optarg;
break;
case 'x':
do_daemonize = 0;
break;
case 'y':
x11_sync = 1;
break;
case 'h':
usage(stdout);
return 0;
case 'f':
fx_dir = optarg;
break;
case 'o':
fx_open_dir = atoi(optarg);
break;
case 'S':
vdagentd_socket = optarg;
break;
default:
fputs("\n", stderr);
usage(stderr);
return 1;
}
}
memset(&act, 0, sizeof(act));
act.sa_flags = SA_RESTART;
act.sa_handler = quit_handler;
sigaction(SIGINT, &act, NULL);
sigaction(SIGHUP, &act, NULL);
sigaction(SIGTERM, &act, NULL);
sigaction(SIGQUIT, &act, NULL);
openlog("spice-vdagent", do_daemonize ? LOG_PID : (LOG_PID | LOG_PERROR),
LOG_USER);
if (file_test(portdev) != 0) {
return 0;
}
if (do_daemonize)
daemonize();
reconnect:
if (version_mismatch) {
syslog(LOG_INFO, "Version mismatch, restarting");
sleep(1);
execvp(argv[0], argv);
}
if (client_setup(do_daemonize)) {
return 1;
}
x11 = vdagent_x11_create(client, debug, x11_sync);
if (!x11) {
udscs_destroy_connection(&client);
return 1;
}
if (!fx_dir) {
if (vdagent_x11_has_icons_on_desktop(x11))
fx_dir = "xdg-desktop";
else
fx_dir = "xdg-download";
}
if (fx_open_dir == -1)
fx_open_dir = !vdagent_x11_has_icons_on_desktop(x11);
if (!strcmp(fx_dir, "xdg-desktop"))
fx_dir = g_get_user_special_dir(G_USER_DIRECTORY_DESKTOP);
else if (!strcmp(fx_dir, "xdg-download"))
fx_dir = g_get_user_special_dir(G_USER_DIRECTORY_DOWNLOAD);
if (!fx_dir) {
syslog(LOG_WARNING,
"warning could not get file xfer save dir, using cwd");
fx_dir = ".";
}
vdagent_file_xfers = vdagent_file_xfers_create(client, fx_dir,
fx_open_dir, debug);
while (client && !quit) {
FD_ZERO(&readfds);
FD_ZERO(&writefds);
nfds = udscs_client_fill_fds(client, &readfds, &writefds);
x11_fd = vdagent_x11_get_fd(x11);
FD_SET(x11_fd, &readfds);
if (x11_fd >= nfds)
nfds = x11_fd + 1;
n = select(nfds, &readfds, &writefds, NULL, NULL);
if (n == -1) {
if (errno == EINTR)
continue;
syslog(LOG_ERR, "Fatal error select: %s", strerror(errno));
break;
}
if (FD_ISSET(x11_fd, &readfds))
vdagent_x11_do_read(x11);
udscs_client_handle_fds(&client, &readfds, &writefds);
}
vdagent_file_xfers_destroy(vdagent_file_xfers);
vdagent_x11_destroy(x11, client == NULL);
udscs_destroy_connection(&client);
if (!quit && do_daemonize)
goto reconnect;
return 0;
}
+165
View File
@@ -0,0 +1,165 @@
/* vdagent-audio.c vdagentd audio handling code
Copyright 2015 Red Hat, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <glib.h>
#include <syslog.h>
#include <stdbool.h>
#include <alsa/asoundlib.h>
#include <alsa/mixer.h>
#include <alsa/error.h>
#include "audio.h"
#define ALSA_MUTE 0
#define ALSA_UNMUTE 1
static snd_mixer_elem_t *
get_alsa_default_mixer_by_name(snd_mixer_t **handle, const char *name)
{
snd_mixer_selem_id_t *sid;
int err = 0;
if ((err = snd_mixer_open(handle, 0)) < 0)
goto fail;
if ((err = snd_mixer_attach(*handle, "default")) < 0)
goto fail;
if ((err = snd_mixer_selem_register(*handle, NULL, NULL)) < 0)
goto fail;
if ((err = snd_mixer_load(*handle)) < 0)
goto fail;
snd_mixer_selem_id_alloca(&sid);
snd_mixer_selem_id_set_index(sid, 0);
snd_mixer_selem_id_set_name(sid, name);
return snd_mixer_find_selem(*handle, sid);
fail:
syslog(LOG_WARNING, "%s fail: %s", __func__, snd_strerror(err));
return NULL;
}
static bool set_alsa_capture(uint8_t mute, uint8_t nchannels, uint16_t *volume)
{
snd_mixer_t *handle = NULL;
snd_mixer_elem_t *e;
long vol;
bool ret = true;
int alsa_mute;
e = get_alsa_default_mixer_by_name (&handle, "Capture");
if (e == NULL) {
syslog(LOG_WARNING, "vdagent-audio: can't get default alsa mixer");
ret = false;
goto end;
}
alsa_mute = (mute) ? ALSA_MUTE : ALSA_UNMUTE;
snd_mixer_selem_set_capture_switch_all(e, alsa_mute);
snd_mixer_selem_set_capture_volume_range(e, 0, UINT16_MAX);
switch (nchannels) {
case 1: /* MONO */
vol = volume[0];
snd_mixer_selem_set_capture_volume(e, SND_MIXER_SCHN_MONO, vol);
syslog(LOG_DEBUG, "vdagent-audio: (capture-mono) %lu (%0.2f%%)",
vol, 100.0 * vol / UINT16_MAX);
break;
case 2: /* LEFT-RIGHT */
vol = volume[0];
snd_mixer_selem_set_capture_volume(e, SND_MIXER_SCHN_FRONT_LEFT, vol);
syslog(LOG_DEBUG, "vdagent-audio: (capture-left) %lu (%0.2f%%)",
vol, 100.0 * vol / UINT16_MAX);
vol = volume[1];
snd_mixer_selem_set_capture_volume(e, SND_MIXER_SCHN_FRONT_RIGHT, vol);
syslog(LOG_DEBUG, "vdagent-audio: (capture-right) %lu (%0.2f%%)",
vol, 100.0 * vol / UINT16_MAX);
break;
default:
syslog(LOG_WARNING, "vdagent-audio: number of channels not supported");
ret = false;
}
end:
if (handle != NULL)
snd_mixer_close(handle);
return ret;
}
static bool set_alsa_playback (uint8_t mute, uint8_t nchannels, uint16_t *volume)
{
snd_mixer_t *handle = NULL;
snd_mixer_elem_t* e;
long vol;
bool ret = true;
int alsa_mute;
e = get_alsa_default_mixer_by_name (&handle, "Master");
if (e == NULL) {
syslog(LOG_WARNING, "vdagent-audio: can't get default alsa mixer");
ret = false;
goto end;
}
alsa_mute = (mute) ? ALSA_MUTE : ALSA_UNMUTE;
snd_mixer_selem_set_playback_switch_all(e, alsa_mute);
snd_mixer_selem_set_playback_volume_range(e, 0, UINT16_MAX);
switch (nchannels) {
case 1: /* MONO */
vol = volume[0];
snd_mixer_selem_set_playback_volume(e, SND_MIXER_SCHN_MONO, vol);
syslog(LOG_DEBUG, "vdagent-audio: (playback-mono) %lu (%0.2f%%)",
vol, 100.0 * vol / UINT16_MAX);
break;
case 2: /* LEFT-RIGHT */
vol = volume[0];
snd_mixer_selem_set_playback_volume(e, SND_MIXER_SCHN_FRONT_LEFT, vol);
syslog(LOG_DEBUG, "vdagent-audio: (playback-left) %lu (%0.2f%%)",
vol, 100.0 * vol / UINT16_MAX);
vol = volume[1];
snd_mixer_selem_set_playback_volume(e, SND_MIXER_SCHN_FRONT_RIGHT, vol);
syslog(LOG_DEBUG, "vdagent-audio: (playback-right) %lu (%0.2f%%)",
vol, 100.0 * vol / UINT16_MAX);
break;
default:
syslog(LOG_WARNING, "vdagent-audio: number of channels not supported");
ret = false;
}
end:
if (handle != NULL)
snd_mixer_close(handle);
return ret;
}
void vdagent_audio_playback_sync(uint8_t mute, uint8_t nchannels, uint16_t *volume)
{
syslog(LOG_DEBUG, "%s mute=%s nchannels=%u",
__func__, (mute) ? "yes" : "no", nchannels);
if (set_alsa_playback (mute, nchannels, volume) == false)
syslog(LOG_WARNING, "Fail to sync playback volume");
}
void vdagent_audio_record_sync(uint8_t mute, uint8_t nchannels, uint16_t *volume)
{
syslog(LOG_DEBUG, "%s mute=%s nchannels=%u",
__func__, (mute) ? "yes" : "no", nchannels);
if (set_alsa_capture (mute, nchannels, volume) == false)
syslog(LOG_WARNING, "Fail to sync record volume");
}
+11 -27
View File
@@ -1,43 +1,27 @@
/* glib-compat.h
/* audio.h vdagentd audio handling header
Copyright 2013 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
Copyright 2015, 2016 Red Hat, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __GLIB_COMPAT_H
#define __GLIB_COMPAT_H
#ifndef __VDAGENT_AUDIO_H
#define __VDAGENT_AUDIO_H
#include <glib.h>
#include <stdio.h>
#include <stdint.h>
#if !GLIB_CHECK_VERSION(2,26,0)
static inline guint64 g_key_file_get_uint64(GKeyFile *file,
const gchar *group, const gchar *key, GError **error)
{
gchar *val_str;
guint64 val = 0;
val_str = g_key_file_get_value(file, group, key, error);
if (val_str) {
val = g_ascii_strtoull(val_str, NULL, 10);
g_free(val_str);
}
return val;
}
#endif
void vdagent_audio_playback_sync(uint8_t mute, uint8_t nchannels, uint16_t *volume);
void vdagent_audio_record_sync(uint8_t mute, uint8_t nchannels, uint16_t *volume);
#endif
+522
View File
@@ -0,0 +1,522 @@
/* clipboard.c - vdagent clipboard handling code
Copyright 2017 Red Hat, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#ifdef USE_GTK_FOR_CLIPBOARD
# include <gtk/gtk.h>
# include <syslog.h>
# include "vdagentd-proto.h"
# include "spice/vd_agent.h"
#endif
#include "clipboard.h"
#ifdef USE_GTK_FOR_CLIPBOARD
/* 2 selections supported - _SELECTION_CLIPBOARD = 0, _SELECTION_PRIMARY = 1 */
#define SELECTION_COUNT (VD_AGENT_CLIPBOARD_SELECTION_PRIMARY + 1)
#define TYPE_COUNT (VD_AGENT_CLIPBOARD_IMAGE_JPG + 1)
static const GdkAtom sel_atom[] = {
[VD_AGENT_CLIPBOARD_SELECTION_CLIPBOARD] = GDK_SELECTION_CLIPBOARD,
[VD_AGENT_CLIPBOARD_SELECTION_PRIMARY] = GDK_SELECTION_PRIMARY,
};
G_STATIC_ASSERT(G_N_ELEMENTS(sel_atom) == SELECTION_COUNT);
static gint sel_id_from_clip(GtkClipboard *clipboard)
{
GdkAtom sel = gtk_clipboard_get_selection(clipboard);
int i;
for (i = 0; i < G_N_ELEMENTS(sel_atom); i++) {
if (sel == sel_atom[i]) {
return i;
}
}
g_return_val_if_reached(0);
}
enum {
OWNER_NONE,
OWNER_GUEST,
OWNER_CLIENT
};
typedef struct {
GMainLoop *loop;
GtkSelectionData *sel_data;
} AppRequest;
typedef struct {
GtkClipboard *clipboard;
guint owner;
GList *requests_from_apps; /* VDAgent --> Client */
GList *requests_from_client; /* Client --> VDAgent */
gpointer *last_targets_req;
GdkAtom targets[TYPE_COUNT];
} Selection;
#endif
struct _VDAgentClipboards {
GObject parent;
#ifdef USE_GTK_FOR_CLIPBOARD
UdscsConnection *conn;
Selection selections[SELECTION_COUNT];
#else
struct vdagent_x11 *x11;
#endif
};
struct _VDAgentClipboardsClass
{
GObjectClass parent;
};
G_DEFINE_TYPE(VDAgentClipboards, vdagent_clipboards, G_TYPE_OBJECT)
#ifdef USE_GTK_FOR_CLIPBOARD
static const struct {
guint type;
const gchar *atom_name;
} atom2agent[] = {
{VD_AGENT_CLIPBOARD_UTF8_TEXT, "UTF8_STRING"},
{VD_AGENT_CLIPBOARD_UTF8_TEXT, "text/plain;charset=utf-8"},
{VD_AGENT_CLIPBOARD_UTF8_TEXT, "STRING"},
{VD_AGENT_CLIPBOARD_UTF8_TEXT, "TEXT"},
{VD_AGENT_CLIPBOARD_UTF8_TEXT, "text/plain"},
{VD_AGENT_CLIPBOARD_IMAGE_PNG, "image/png"},
{VD_AGENT_CLIPBOARD_IMAGE_BMP, "image/bmp"},
{VD_AGENT_CLIPBOARD_IMAGE_BMP, "image/x-bmp"},
{VD_AGENT_CLIPBOARD_IMAGE_BMP, "image/x-MS-bmp"},
{VD_AGENT_CLIPBOARD_IMAGE_BMP, "image/x-win-bitmap"},
{VD_AGENT_CLIPBOARD_IMAGE_TIFF,"image/tiff"},
{VD_AGENT_CLIPBOARD_IMAGE_JPG, "image/jpeg"},
};
static guint get_type_from_atom(GdkAtom atom)
{
gchar *name = gdk_atom_name(atom);
int i;
for (i = 0; i < G_N_ELEMENTS(atom2agent); i++) {
if (!g_ascii_strcasecmp(name, atom2agent[i].atom_name)) {
g_free(name);
return atom2agent[i].type;
}
}
g_free(name);
return VD_AGENT_CLIPBOARD_NONE;
}
/* gtk_clipboard_request_(, callback, user_data) cannot be cancelled.
Instead, gpointer *ref = request_ref_new() is passed to the callback.
Callback can check using request_ref_is_cancelled(ref)
whether request_ref_cancel(ref) was called.
This mechanism enables cancellation of the request
as well as passing VDAgentClipboards reference to the desired callback.
*/
static gpointer *request_ref_new(gpointer data)
{
gpointer *ref = g_new(gpointer, 1);
*ref = data;
return ref;
}
static gpointer request_ref_free(gpointer *ref)
{
gpointer data = *ref;
g_free(ref);
return data;
}
static void request_ref_cancel(gpointer *ref)
{
g_return_if_fail(ref != NULL);
*ref = NULL;
}
static gboolean request_ref_is_cancelled(gpointer *ref)
{
g_return_val_if_fail(ref != NULL, TRUE);
return *ref == NULL;
}
static void clipboard_new_owner(VDAgentClipboards *c, guint sel_id, guint new_owner)
{
Selection *sel = &c->selections[sel_id];
GList *l;
/* let the other apps know no data is coming */
for (l = sel->requests_from_apps; l != NULL; l= l->next) {
AppRequest *req = l->data;
g_main_loop_quit(req->loop);
}
g_clear_pointer(&sel->requests_from_apps, g_list_free);
/* respond to pending client's data requests */
for (l = sel->requests_from_client; l != NULL; l = l->next) {
request_ref_cancel(l->data);
if (c->conn)
udscs_write(c->conn, VDAGENTD_CLIPBOARD_DATA,
sel_id, VD_AGENT_CLIPBOARD_NONE, NULL, 0);
}
g_clear_pointer(&sel->requests_from_client, g_list_free);
sel->owner = new_owner;
}
static void clipboard_targets_received_cb(GtkClipboard *clipboard,
GdkAtom *atoms,
gint n_atoms,
gpointer user_data)
{
if (request_ref_is_cancelled(user_data))
return;
VDAgentClipboards *c = request_ref_free(user_data);
Selection *sel;
guint32 types[G_N_ELEMENTS(atom2agent)];
guint sel_id, type, n_types, a;
sel_id = sel_id_from_clip(clipboard);
sel = &c->selections[sel_id];
sel->last_targets_req = NULL;
if (atoms == NULL)
return;
for (type = 0; type < TYPE_COUNT; type++)
sel->targets[type] = GDK_NONE;
n_types = 0;
for (a = 0; a < n_atoms; a++) {
type = get_type_from_atom(atoms[a]);
if (type == VD_AGENT_CLIPBOARD_NONE || sel->targets[type] != GDK_NONE)
continue;
sel->targets[type] = atoms[a];
types[n_types] = type;
n_types++;
}
if (n_types == 0) {
syslog(LOG_WARNING, "%s: sel_id=%u: no target supported", __func__, sel_id);
return;
}
clipboard_new_owner(c, sel_id, OWNER_GUEST);
udscs_write(c->conn, VDAGENTD_CLIPBOARD_GRAB, sel_id, 0,
(guint8 *)types, n_types * sizeof(guint32));
}
static void clipboard_owner_change_cb(GtkClipboard *clipboard,
GdkEventOwnerChange *event,
gpointer user_data)
{
VDAgentClipboards *c = user_data;
guint sel_id = sel_id_from_clip(clipboard);
Selection *sel = &c->selections[sel_id];
/* if the event was caused by gtk_clipboard_set_with_data(), ignore it */
if (gtk_clipboard_get_owner(clipboard) == G_OBJECT(c)) {
return;
}
if (event->reason != GDK_OWNER_CHANGE_NEW_OWNER) {
if (sel->owner == OWNER_GUEST) {
clipboard_new_owner(c, sel_id, OWNER_NONE);
udscs_write(c->conn, VDAGENTD_CLIPBOARD_RELEASE, sel_id, 0, NULL, 0);
}
return;
}
/* if there's a pending request for clipboard targets, cancel it */
if (sel->last_targets_req)
request_ref_cancel(sel->last_targets_req);
sel->last_targets_req = request_ref_new(c);
gtk_clipboard_request_targets(clipboard, clipboard_targets_received_cb,
sel->last_targets_req);
}
static void clipboard_contents_received_cb(GtkClipboard *clipboard,
GtkSelectionData *sel_data,
gpointer user_data)
{
if (request_ref_is_cancelled(user_data))
return;
VDAgentClipboards *c = request_ref_free(user_data);
guint sel_id, type, target;
sel_id = sel_id_from_clip(clipboard);
c->selections[sel_id].requests_from_client =
g_list_remove(c->selections[sel_id].requests_from_client, user_data);
type = get_type_from_atom(gtk_selection_data_get_data_type(sel_data));
target = get_type_from_atom(gtk_selection_data_get_target(sel_data));
if (type == target) {
udscs_write(c->conn, VDAGENTD_CLIPBOARD_DATA, sel_id, type,
gtk_selection_data_get_data(sel_data),
gtk_selection_data_get_length(sel_data));
} else {
syslog(LOG_WARNING, "%s: sel_id=%u: expected type %u, received %u, "
"skipping", __func__, sel_id, target, type);
udscs_write(c->conn, VDAGENTD_CLIPBOARD_DATA, sel_id,
VD_AGENT_CLIPBOARD_NONE, NULL, 0);
}
}
static void clipboard_get_cb(GtkClipboard *clipboard,
GtkSelectionData *sel_data,
guint info,
gpointer user_data)
{
AppRequest req;
VDAgentClipboards *c = user_data;
guint sel_id, type;
sel_id = sel_id_from_clip(clipboard);
g_return_if_fail(c->selections[sel_id].owner == OWNER_CLIENT);
type = get_type_from_atom(gtk_selection_data_get_target(sel_data));
g_return_if_fail(type != VD_AGENT_CLIPBOARD_NONE);
req.sel_data = sel_data;
req.loop = g_main_loop_new(NULL, FALSE);
c->selections[sel_id].requests_from_apps =
g_list_prepend(c->selections[sel_id].requests_from_apps, &req);
udscs_write(c->conn, VDAGENTD_CLIPBOARD_REQUEST, sel_id, type, NULL, 0);
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
gdk_threads_leave();
g_main_loop_run(req.loop);
gdk_threads_enter();
G_GNUC_END_IGNORE_DEPRECATIONS
g_main_loop_unref(req.loop);
}
static void clipboard_clear_cb(GtkClipboard *clipboard, gpointer user_data)
{
VDAgentClipboards *c = user_data;
clipboard_new_owner(c, sel_id_from_clip(clipboard), OWNER_NONE);
}
#endif
void vdagent_clipboard_grab(VDAgentClipboards *c, guint sel_id,
guint32 *types, guint n_types)
{
#ifndef USE_GTK_FOR_CLIPBOARD
vdagent_x11_clipboard_grab(c->x11, sel_id, types, n_types);
#else
GtkTargetEntry targets[G_N_ELEMENTS(atom2agent)];
Selection *sel;
guint n_targets, i, t;
g_return_if_fail(sel_id < SELECTION_COUNT);
n_targets = 0;
for (i = 0; i < G_N_ELEMENTS(atom2agent); i++)
for (t = 0; t < n_types; t++)
if (atom2agent[i].type == types[t]) {
targets[n_targets].target = (gchar *)atom2agent[i].atom_name;
n_targets++;
break;
}
if (n_targets == 0) {
syslog(LOG_WARNING, "%s: sel_id=%u: no type supported", __func__, sel_id);
return;
}
sel = &c->selections[sel_id];
if (sel->last_targets_req) {
g_clear_pointer(&sel->last_targets_req, request_ref_cancel);
}
if (gtk_clipboard_set_with_owner(sel->clipboard,
targets, n_targets,
clipboard_get_cb, clipboard_clear_cb,
G_OBJECT(c)))
clipboard_new_owner(c, sel_id, OWNER_CLIENT);
else {
syslog(LOG_ERR, "%s: sel_id=%u: clipboard grab failed", __func__, sel_id);
clipboard_new_owner(c, sel_id, OWNER_NONE);
}
#endif
}
void vdagent_clipboard_data(VDAgentClipboards *c, guint sel_id,
guint type, guchar *data, guint size)
{
#ifndef USE_GTK_FOR_CLIPBOARD
vdagent_x11_clipboard_data(c->x11, sel_id, type, data, size);
#else
g_return_if_fail(sel_id < SELECTION_COUNT);
Selection *sel = &c->selections[sel_id];
AppRequest *req;
GList *l;
for (l = sel->requests_from_apps; l != NULL; l = l->next) {
req = l->data;
if (get_type_from_atom(gtk_selection_data_get_target(req->sel_data)) == type)
break;
}
if (l == NULL) {
syslog(LOG_WARNING, "%s: sel_id=%u: no corresponding request found for "
"type=%u, skipping", __func__, sel_id, type);
return;
}
sel->requests_from_apps = g_list_delete_link(sel->requests_from_apps, l);
gtk_selection_data_set(req->sel_data,
gtk_selection_data_get_target(req->sel_data),
8, data, size);
g_main_loop_quit(req->loop);
#endif
}
void vdagent_clipboard_release(VDAgentClipboards *c, guint sel_id)
{
#ifndef USE_GTK_FOR_CLIPBOARD
vdagent_x11_clipboard_release(c->x11, sel_id);
#else
g_return_if_fail(sel_id < SELECTION_COUNT);
if (c->selections[sel_id].owner != OWNER_CLIENT)
return;
clipboard_new_owner(c, sel_id, OWNER_NONE);
gtk_clipboard_clear(c->selections[sel_id].clipboard);
#endif
}
void vdagent_clipboards_release_all(VDAgentClipboards *c)
{
#ifndef USE_GTK_FOR_CLIPBOARD
vdagent_x11_client_disconnected(c->x11);
#else
guint sel_id, owner;
for (sel_id = 0; sel_id < SELECTION_COUNT; sel_id++) {
owner = c->selections[sel_id].owner;
clipboard_new_owner(c, sel_id, OWNER_NONE);
if (owner == OWNER_CLIENT)
gtk_clipboard_clear(c->selections[sel_id].clipboard);
else if (owner == OWNER_GUEST && c->conn)
udscs_write(c->conn, VDAGENTD_CLIPBOARD_RELEASE, sel_id, 0, NULL, 0);
}
#endif
}
void vdagent_clipboard_request(VDAgentClipboards *c, guint sel_id, guint type)
{
#ifndef USE_GTK_FOR_CLIPBOARD
vdagent_x11_clipboard_request(c->x11, sel_id, type);
#else
Selection *sel;
if (sel_id >= SELECTION_COUNT)
goto err;
sel = &c->selections[sel_id];
if (sel->owner != OWNER_GUEST) {
syslog(LOG_WARNING, "%s: sel_id=%d: received request "
"while not owning clipboard", __func__, sel_id);
goto err;
}
if (type >= TYPE_COUNT || sel->targets[type] == GDK_NONE) {
syslog(LOG_WARNING, "%s: sel_id=%d: unadvertised data type requested",
__func__, sel_id);
goto err;
}
gpointer *ref = request_ref_new(c);
sel->requests_from_client = g_list_prepend(sel->requests_from_client, ref);
gtk_clipboard_request_contents(sel->clipboard, sel->targets[type],
clipboard_contents_received_cb, ref);
return;
err:
udscs_write(c->conn, VDAGENTD_CLIPBOARD_DATA, sel_id,
VD_AGENT_CLIPBOARD_NONE, NULL, 0);
#endif
}
static void
vdagent_clipboards_init(VDAgentClipboards *self)
{
}
VDAgentClipboards *vdagent_clipboards_new(struct vdagent_x11 *x11)
{
VDAgentClipboards *self = g_object_new(VDAGENT_TYPE_CLIPBOARDS, NULL);
#ifndef USE_GTK_FOR_CLIPBOARD
self->x11 = x11;
#else
guint sel_id;
for (sel_id = 0; sel_id < SELECTION_COUNT; sel_id++) {
GtkClipboard *clipboard = gtk_clipboard_get(sel_atom[sel_id]);
self->selections[sel_id].clipboard = clipboard;
g_signal_connect(G_OBJECT(clipboard), "owner-change",
G_CALLBACK(clipboard_owner_change_cb), self);
}
#endif
return self;
}
void
vdagent_clipboards_set_conn(VDAgentClipboards *self, UdscsConnection *conn)
{
#ifdef USE_GTK_FOR_CLIPBOARD
self->conn = conn;
#endif
}
static void vdagent_clipboards_dispose(GObject *obj)
{
#ifdef USE_GTK_FOR_CLIPBOARD
VDAgentClipboards *self = VDAGENT_CLIPBOARDS(obj);
guint sel_id;
for (sel_id = 0; sel_id < SELECTION_COUNT; sel_id++)
g_signal_handlers_disconnect_by_func(self->selections[sel_id].clipboard,
G_CALLBACK(clipboard_owner_change_cb), self);
if (self->conn)
vdagent_clipboards_release_all(self);
#endif
}
static void
vdagent_clipboards_class_init(VDAgentClipboardsClass *klass)
{
GObjectClass *oclass = G_OBJECT_CLASS(klass);
oclass->dispose = vdagent_clipboards_dispose;
}
+46
View File
@@ -0,0 +1,46 @@
/* clipboard.h - vdagent clipboard handling header
Copyright 2017 Red Hat, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __VDAGENT_CLIPBOARD_H
#define __VDAGENT_CLIPBOARD_H
#include <glib-object.h>
#include "x11.h"
#include "udscs.h"
#define VDAGENT_TYPE_CLIPBOARDS vdagent_clipboards_get_type()
G_DECLARE_FINAL_TYPE(VDAgentClipboards, vdagent_clipboards, VDAGENT, CLIPBOARDS, GObject)
VDAgentClipboards *vdagent_clipboards_new(struct vdagent_x11 *x11);
void vdagent_clipboards_set_conn(VDAgentClipboards *self, UdscsConnection *conn);
void vdagent_clipboard_request(VDAgentClipboards *c, guint sel_id, guint type);
void vdagent_clipboard_release(VDAgentClipboards *c, guint sel_id);
void vdagent_clipboards_release_all(VDAgentClipboards *c);
void vdagent_clipboard_data(VDAgentClipboards *c, guint sel_id,
guint type, guchar *data, guint size);
void vdagent_clipboard_grab(VDAgentClipboards *c, guint sel_id,
guint32 *types, guint n_types);
#endif
+533
View File
@@ -0,0 +1,533 @@
/* device-info.c utility function for looking up the xrandr output id for a
* given device address and display id
*
* Copyright 2018 Red Hat, Inc.
*
* Red Hat Authors:
* Jonathon Jongsma <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <syslog.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <unistd.h>
#include <X11/extensions/Xrandr.h>
#include <glib.h>
#include "device-info.h"
#define PCI_VENDOR_ID_REDHAT 0x1b36
#define PCI_VENDOR_ID_REDHAT_QUMRANET 0x1af4 // virtio-gpu
#define PCI_VENDOR_ID_INTEL 0x8086
#define PCI_VENDOR_ID_NVIDIA 0x10de
#define PCI_DEVICE_ID_QXL 0x0100
#define PCI_DEVICE_ID_VIRTIO_GPU 0x1050
typedef struct PciDevice {
int domain;
uint8_t bus;
uint8_t slot;
uint8_t function;
} PciDevice;
typedef struct PciAddress {
int domain;
GList *devices; /* PciDevice */
} PciAddress;
static PciAddress* pci_address_new()
{
return g_new0(PciAddress, 1);
}
static void pci_address_free(PciAddress *addr)
{
g_list_free_full(addr->devices, g_free);
g_free(addr);
}
static int read_next_hex_number(const char *input, char delim, char **endptr)
{
assert(input != NULL);
assert(endptr != NULL);
const char *pos = strchr(input, delim);
int n;
if (!pos) {
*endptr = NULL;
return 0;
}
char *endpos;
n = strtol(input, &endpos, 16);
// check if we read all characters until the delimiter
if (endpos != pos) {
endpos = NULL;
}
*endptr = endpos;
return n;
}
// the device should be specified in BDF notation (e.g. 0000:00:02.0)
// see https://wiki.xen.org/wiki/Bus:Device.Function_(BDF)_Notation
static bool parse_pci_device(const char *bdf, const char *end, PciDevice *device)
{
if (!end) {
end = strchr(bdf, 0);
}
int endpos = -1;
int domain, bus, slot, function;
sscanf(bdf, "%x:%x:%x.%x%n", &domain, &bus, &slot, &function, &endpos);
if (!device || endpos < 0 || bdf + endpos != end) {
return false;
}
if (domain < 0 || bus < 0 || slot < 0 || function < 0) {
return false;
}
device->domain = domain;
device->bus = bus;
device->slot = slot;
device->function = function;
return true;
}
// We need to extract the pci address of the device from the sysfs entry for the device like so:
// $ readlink /sys/class/drm/card0
// This should give you a path such as this for cards on the root bus:
// /sys/devices/pci0000:00/0000:00:02.0/drm/card0
// or something like this if there is a pci bridge:
// /sys/devices/pci0000:00/0000:00:03.0/0000:01:01.0/0000:02:03.0/virtio2/drm/card0
static PciAddress* parse_pci_address_from_sysfs_path(const char* addr)
{
char *pos = strstr(addr, "/pci");
if (!pos) {
return NULL;
}
// advance to the numbers in pci0000:00
pos += 4;
int domain = read_next_hex_number(pos, ':', &pos);
if (!pos) {
return NULL;
}
// not used right now.
G_GNUC_UNUSED uint8_t bus = read_next_hex_number(pos + 1, '/', &pos);
if (!pos) {
return NULL;
}
PciAddress *address = pci_address_new();
address->domain = domain;
// now read all of the devices
while (pos) {
PciDevice *dev = g_new0(PciDevice, 1);
char *next = strchr(pos + 1, '/');
if (!parse_pci_device(pos + 1, next, dev)) {
g_free(dev);
break;
}
address->devices = g_list_append(address->devices, dev);
pos = next;
}
return address;
}
// format should be something like pci/$domain/$slot.$fn/$slot.$fn
static PciAddress* parse_pci_address_from_spice(char *input)
{
static const char prefix[] = "pci/";
if (strncmp(input, prefix, strlen(prefix)) != 0) {
return NULL;
}
char *pos = input + strlen(prefix);
int domain = read_next_hex_number(pos, '/', &pos);
if (!pos) {
return NULL;
}
PciAddress *address = pci_address_new();
address->domain = domain;
// now read all of the devices
for (int n = 0; ; n++) {
PciDevice *dev = g_new0(PciDevice, 1);
char *next = strchr(pos + 1, '/');
dev->slot = read_next_hex_number(pos + 1, '.', &pos);
if (!pos) {
g_free(dev);
break;
}
dev->function = strtol(pos + 1, &pos, 16);
if (!pos || (next != NULL && next != pos)) {
g_free(dev);
break;
}
address->devices = g_list_append(address->devices, dev);
pos = next;
if (!pos) {
break;
}
}
return address;
}
static bool compare_addresses(PciAddress *a, PciAddress *b)
{
// only check domain, slot, and function
if (a->domain != b->domain) {
return false;
}
const GList *la, *lb;
for (la = a->devices, lb = b->devices;
la != NULL && lb != NULL;
la = la->next, lb = lb->next) {
PciDevice *deva = la->data;
PciDevice *devb = lb->data;
if (deva->slot != devb->slot
|| deva->function != devb->function) {
return false;
}
}
/* True only if both have the same length */
return (la == NULL && lb == NULL);
}
// Connector type names from xorg modesetting driver
static const char * const modesetting_output_names[] = {
[DRM_MODE_CONNECTOR_Unknown] = "None" ,
[DRM_MODE_CONNECTOR_VGA] = "VGA" ,
[DRM_MODE_CONNECTOR_DVII] = "DVI-I" ,
[DRM_MODE_CONNECTOR_DVID] = "DVI-D" ,
[DRM_MODE_CONNECTOR_DVIA] = "DVI-A" ,
[DRM_MODE_CONNECTOR_Composite] = "Composite" ,
[DRM_MODE_CONNECTOR_SVIDEO] = "SVIDEO" ,
[DRM_MODE_CONNECTOR_LVDS] = "LVDS" ,
[DRM_MODE_CONNECTOR_Component] = "Component" ,
[DRM_MODE_CONNECTOR_9PinDIN] = "DIN" ,
[DRM_MODE_CONNECTOR_DisplayPort] = "DP" ,
[DRM_MODE_CONNECTOR_HDMIA] = "HDMI" ,
[DRM_MODE_CONNECTOR_HDMIB] = "HDMI-B" ,
[DRM_MODE_CONNECTOR_TV] = "TV" ,
[DRM_MODE_CONNECTOR_eDP] = "eDP" ,
[DRM_MODE_CONNECTOR_VIRTUAL] = "Virtual" ,
[DRM_MODE_CONNECTOR_DSI] = "DSI" ,
[DRM_MODE_CONNECTOR_DPI] = "DPI" ,
};
// Connector type names from qxl driver
static const char * const qxl_output_names[] = {
[DRM_MODE_CONNECTOR_Unknown] = "None" ,
[DRM_MODE_CONNECTOR_VGA] = "VGA" ,
[DRM_MODE_CONNECTOR_DVII] = "DVI" ,
[DRM_MODE_CONNECTOR_DVID] = "DVI" ,
[DRM_MODE_CONNECTOR_DVIA] = "DVI" ,
[DRM_MODE_CONNECTOR_Composite] = "Composite" ,
[DRM_MODE_CONNECTOR_SVIDEO] = "S-video" ,
[DRM_MODE_CONNECTOR_LVDS] = "LVDS" ,
[DRM_MODE_CONNECTOR_Component] = "CTV" ,
[DRM_MODE_CONNECTOR_9PinDIN] = "DIN" ,
[DRM_MODE_CONNECTOR_DisplayPort] = "DisplayPort" ,
[DRM_MODE_CONNECTOR_HDMIA] = "HDMI" ,
[DRM_MODE_CONNECTOR_HDMIB] = "HDMI" ,
[DRM_MODE_CONNECTOR_TV] = "TV" ,
[DRM_MODE_CONNECTOR_eDP] = "eDP" ,
[DRM_MODE_CONNECTOR_VIRTUAL] = "Virtual" ,
};
static void drm_conn_name_full(drmModeConnector *conn,
const char * const *names,
int nnames, char *dest,
size_t dlen, bool decrement_id)
{
const char *type;
if (conn->connector_type < nnames &&
names[conn->connector_type]) {
type = names[conn->connector_type];
} else {
type = "unknown";
}
uint8_t id = conn->connector_type_id;
if (decrement_id) {
id--;
}
snprintf(dest, dlen, "%s-%d", type, id);
}
static void drm_conn_name_qxl(drmModeConnector *conn, char *dest, size_t dlen, bool decrement_id)
{
return drm_conn_name_full(conn, qxl_output_names,
sizeof(qxl_output_names)/sizeof(qxl_output_names[0]),
dest, dlen, decrement_id);
}
// NOTE: there are some cases (for example, in a Lenovo T460p laptop with
// intel graphics when attached to a docking station) where the modesetting
// driver uses a name such as DP-3-1 instead of DP-4. These outputs are not
// likely to exist in virtual machines, so they shouldn't matter much
static void drm_conn_name_modesetting(drmModeConnector *conn, char *dest, size_t dlen)
{
return drm_conn_name_full(conn, modesetting_output_names,
sizeof(modesetting_output_names)/sizeof(modesetting_output_names[0]),
dest, dlen, false);
}
static bool read_hex_value_from_file(const char *path, int* value)
{
if (value == NULL || path == NULL) {
return false;
}
FILE *f = fopen(path, "r");
if (f == NULL) {
return false;
}
int endpos = -1;
bool result = (fscanf(f, "%x\n%n", value, &endpos) > 0 && endpos >= 0);
fclose(f);
return result;
}
// returns a path to a drm device found at the given PCI Address. Returned
// string must be freed by caller.
static char* find_device_at_pci_address(PciAddress *pci_addr, int *vendor_id, int *device_id)
{
g_return_val_if_fail(pci_addr != NULL, NULL);
g_return_val_if_fail(device_id != NULL, NULL);
g_return_val_if_fail(vendor_id != NULL, NULL);
// Look for a device that matches the PCI address parsed above. Loop
// through the list of cards reported by the DRM subsystem
for (int i = 0; i < 10; ++i) {
char dev_path[64];
struct stat buf;
// device node for the card is needed to access libdrm functionality
snprintf(dev_path, sizeof(dev_path), DRM_DEV_NAME, DRM_DIR_NAME, i);
if (stat(dev_path, &buf) != 0) {
// no card exists, exit loop
syslog(LOG_DEBUG, "card%i not found while listing DRM devices.", i);
break;
}
// the sysfs directory for the card will allow us to determine the
// pci address for the device
char sys_path[64];
snprintf(sys_path, sizeof(sys_path), "/sys/class/drm/card%d", i);
// the file /sys/class/drm/card0 is a symlink to a file that
// specifies the device's address. It usually points to something
// like /sys/devices/pci0000:00/0000:00:02.0/drm/card0
char device_link[PATH_MAX];
if (realpath(sys_path, device_link) == NULL) {
syslog(LOG_WARNING, "Failed to get the real path of %s", sys_path);
break;
}
syslog(LOG_DEBUG, "Device %s is at %s", dev_path, device_link);
PciAddress *drm_pci_addr = parse_pci_address_from_sysfs_path(device_link);
if (!drm_pci_addr) {
syslog(LOG_WARNING, "Can't determine pci address from '%s'", device_link);
continue;
}
if (!compare_addresses(pci_addr, drm_pci_addr)) {
pci_address_free(drm_pci_addr);
continue;
}
pci_address_free(drm_pci_addr);
char id_path[150];
snprintf(id_path, sizeof(id_path), "%s/device/vendor", sys_path);
if (!read_hex_value_from_file(id_path, vendor_id)) {
syslog(LOG_WARNING, "Unable to read vendor ID of card: %s", strerror(errno));
}
snprintf(id_path, sizeof(id_path), "%s/device/device", sys_path);
if (!read_hex_value_from_file(id_path, device_id)) {
syslog(LOG_WARNING, "Unable to read device ID of card: %s", strerror(errno));
}
syslog(LOG_DEBUG, "Found card '%s' with Vendor ID %#x, Device ID %#x",
device_link, *device_id, *vendor_id);
return g_strdup(dev_path);
}
return NULL;
}
/**
* Look up DRM info for the device, and retrieve the expected connector name.
* This name will later be compared to the monitor names found at the display manager level.
*/
int get_connector_name_for_device_info(VDAgentDeviceDisplayInfo *device_info,
char *expected_name, size_t name_size,
bool has_virtual_zero_display)
{
PciAddress *user_pci_addr = parse_pci_address_from_spice((char*)device_info->device_address);
if (!user_pci_addr) {
syslog(LOG_WARNING,
"Couldn't parse PCI address '%s'. "
"Address should be the form 'pci/$domain/$slot.$fn/$slot.fn...",
device_info->device_address);
return -1;
}
int vendor_id = 0;
int device_id = 0;
char *dev_path = find_device_at_pci_address(user_pci_addr, &vendor_id, &device_id);
pci_address_free(user_pci_addr);
int drm_fd = open(dev_path, O_RDWR);
if (drm_fd < 0) {
syslog(LOG_WARNING, "Unable to open file %s", dev_path);
g_free(dev_path);
return -1;
}
drmModeResPtr res = drmModeGetResources(drm_fd);
if (res == NULL) {
syslog(LOG_WARNING,
"Unable to get DRM resources for card %s. "
"Falling back to using xrandr output index.",
dev_path);
close(drm_fd);
g_free(dev_path);
return 1; // error out - actual handling is deferred to the caller
}
// no need for dev_path anymore
g_free(dev_path);
// find the drm output that is equal to device_display_id
if (device_info->device_display_id >= res->count_connectors) {
syslog(LOG_WARNING,
"Specified display id %i is higher than the maximum display id "
"provided by this device (%i)",
device_info->device_display_id, res->count_connectors - 1);
close(drm_fd);
return -1;
}
drmModeConnectorPtr conn =
drmModeGetConnector(drm_fd, res->connectors[device_info->device_display_id]);
drmModeFreeResources(res);
res = NULL;
close(drm_fd);
if (conn == NULL) {
syslog(LOG_WARNING, "Unable to get drm connector for display id %i",
device_info->device_display_id);
return -1;
}
bool decrement_name = false;
if (vendor_id == PCI_VENDOR_ID_REDHAT && device_id == PCI_DEVICE_ID_QXL
&& has_virtual_zero_display) {
decrement_name = true;
}
// Compare the name of the xrandr output against what we would
// expect based on the drm connection type. The xrandr names
// are driver-specific, so we need to special-case some
// drivers. Most hardware these days uses the 'modesetting'
// driver, but the QXL device uses its own driver which has
// different naming conventions
if (vendor_id == PCI_VENDOR_ID_REDHAT && device_id == PCI_DEVICE_ID_QXL) {
drm_conn_name_qxl(conn, expected_name, name_size, decrement_name);
} else {
drm_conn_name_modesetting(conn, expected_name, name_size);
}
drmModeFreeConnector(conn);
return 0;
}
// PCI address should be in the following format:
// pci/$domain/$slot.$fn/$slot.$fn
bool lookup_xrandr_output_for_device_info(VDAgentDeviceDisplayInfo *device_info,
Display *xdisplay,
XRRScreenResources *xres,
RROutput *output_id,
bool has_virtual_zero_display)
{
char expected_name[100];
int ret;
ret = get_connector_name_for_device_info(device_info, expected_name, sizeof(expected_name),
has_virtual_zero_display);
switch (ret) {
case -1: // generic error => exit
return false;
case 0:
// Loop through xrandr outputs and check whether the xrandr
// output name matches the drm connector name
for (int i = 0; i < xres->noutput; ++i) {
int oid = xres->outputs[i];
XRROutputInfo *oinfo = XRRGetOutputInfo(xdisplay, xres, oid);
if (!oinfo) {
syslog(LOG_WARNING, "Unable to lookup XRandr output info for output %i", oid);
return false;
}
if (strcmp(oinfo->name, expected_name) == 0) {
*output_id = oid;
syslog(LOG_DEBUG, "Found matching X Output: name=%s id=%i",
oinfo->name, (int)oid);
XRRFreeOutputInfo(oinfo);
return true;
}
XRRFreeOutputInfo(oinfo);
}
break;
case 1: // no DRM info found
// This is probably a proprietary driver (e.g. Nvidia) that does
// not provide outputs via drm, so the only thing we can do is just
// assume that it is the only device assigned to X, and use the
// xrandr output order to determine the proper display.
if (device_info->device_display_id >= xres->noutput) {
syslog(LOG_WARNING, "The device display id %i does not exist",
device_info->device_display_id);
return false;
}
*output_id = xres->outputs[device_info->device_display_id];
return true;
}
syslog(LOG_WARNING, "Couldn't find an XRandr output for the specified device");
return false;
}
+35
View File
@@ -0,0 +1,35 @@
/* device-info.c utility function for looking up the xrandr output id for a
* given device address and display id
*
* Copyright 2018 Red Hat, Inc.
*
* Red Hat Authors:
* Jonathon Jongsma <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <spice/vd_agent.h>
#include <X11/extensions/Xrandr.h>
#include <stdbool.h>
struct vdagent_x11;
bool lookup_xrandr_output_for_device_info(VDAgentDeviceDisplayInfo *device_info,
Display *xdisplay,
XRRScreenResources *xres,
RROutput *output_id,
bool has_virtual_zero_display);
int get_connector_name_for_device_info(VDAgentDeviceDisplayInfo *device_info,
char *expected_name, size_t name_size,
bool has_virtual_zero_display);
+491
View File
@@ -0,0 +1,491 @@
/* display.c vdagent display source code
Copyright 2020 Red Hat, Inc.
Red Hat Authors:
Julien Ropé <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <glib.h>
#ifdef WITH_GTK
#include <gdk/gdk.h>
#include <gtk/gtk.h> // for GTK_CHECK_VERSION
#if GTK_CHECK_VERSION(3, 98, 0)
#include <gdk/wayland/gdkwayland.h>
#include <gdk/x11/gdkx.h>
#else
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#endif
#endif
#include <syslog.h>
#include "x11.h"
#include "x11-priv.h"
#include "device-info.h"
#include "vdagentd-proto.h"
#include "mutter.h"
#include "display.h"
/**
* VDAgentDisplay and the vdagent_display_*() functions are used as wrappers for display-related
* operations.
* They allow vdagent code to call generic display functions that are independent from the underlying
* API (X11/GTK/etc).
*
* The display.c file contains the actual implementation and chooses what API will be called.
* The x11.c and x11-randr.c files contains the x11-specific functions.
*/
struct VDAgentDisplay {
// association between SPICE display ID and expected connector name
GHashTable *connector_mapping;
struct vdagent_x11 *x11;
UdscsConnection *vdagentd;
int debug;
GIOChannel *x11_channel;
guint io_watch_source_id;
VDAgentMutterDBus *mutter;
};
static gint vdagent_guest_xorg_resolution_compare(gconstpointer a, gconstpointer b)
{
struct vdagentd_guest_xorg_resolution *ptr_a, *ptr_b;
ptr_a = (struct vdagentd_guest_xorg_resolution *)a;
ptr_b = (struct vdagentd_guest_xorg_resolution *)b;
return ptr_a->display_id - ptr_b->display_id;
}
static GArray *vdagent_gtk_get_resolutions(VDAgentDisplay *display,
int *width, int *height, int *screen_count)
{
#ifdef USE_GTK_FOR_MONITORS
if (!GDK_IS_WAYLAND_DISPLAY(gdk_display_get_default())) {
return NULL;
}
GArray *res_array = g_array_new(FALSE, FALSE, sizeof(struct vdagentd_guest_xorg_resolution));
int i;
GListModel *monitors = NULL;
GdkDisplay *gdk_display = gdk_display_get_default();
// Make sure GDK is aware of the changes we want to send.
// TODO: This may be removed if we get a notification of change from GDK itself,
// but with X11 notification, we end up sending obsolete information.
gdk_display_sync(gdk_display);
monitors = gdk_display_get_monitors(gdk_display);
*screen_count = g_list_model_get_n_items(monitors);
for (i = 0; i < *screen_count; i++) {
struct vdagentd_guest_xorg_resolution curr;
GdkMonitor *monitor = (GdkMonitor*)g_list_model_get_item(monitors, i);
GdkRectangle geometry;
gdk_monitor_get_geometry(monitor, &geometry);
curr.x = geometry.x;
curr.y = geometry.y;
curr.height = geometry.height;
curr.width = geometry.width;
// compute the size of the desktop based on the dimension of the monitors
// TODO: check for a specific API giving us that information (not found in GTK ?)
if (curr.x + curr.width > *width) {
*width = curr.x + curr.width;
}
if (curr.y + curr.height > *height) {
*height = curr.y + curr.height;
}
// retrieve the Spice Display ID based on the connector name
const char *name = gdk_monitor_get_connector(monitor);
if (!name) {
syslog(LOG_WARNING, "Unknown connector for monitor %d", i);
continue;
}
gpointer value;
if (g_hash_table_lookup_extended(display->connector_mapping, name, NULL, &value)) {
curr.display_id = GPOINTER_TO_UINT(value);
syslog(LOG_DEBUG, "Found monitor %s with geometry %dx%d+%d-%d - associating it to SPICE display #%d",
name, curr.width, curr.height, curr.x, curr.y, curr.display_id);
g_array_append_val(res_array, curr);
} else {
syslog(LOG_DEBUG, "No SPICE display found for connector %s", name);
}
}
if (res_array->len == 0) {
syslog(LOG_DEBUG, "No Spice display ID matching - assuming display ID == Monitor index");
for (i = 0; i < *screen_count; i++) {
struct vdagentd_guest_xorg_resolution res;
GdkMonitor *monitor = (GdkMonitor*)g_list_model_get_item(monitors, i);
GdkRectangle geometry;
gdk_monitor_get_geometry(monitor, &geometry);
res.x = geometry.x;
res.y = geometry.y;
res.height = geometry.height;
res.width = geometry.width;
res.display_id = i;
g_array_append_val(res_array, res);
}
}
return res_array;
#else
return NULL;
#endif
}
void vdagent_display_send_daemon_guest_res(VDAgentDisplay *display, gboolean update)
{
GArray *res_array;
int width = 0, height = 0, screen_count = 0;
// Try various backends one after the other.
// We try Mutter first, because it has a bigger probability of being available.
// Second GTK, because if/when we build with GTK4, this is the one that will work best.
// Finally we try X11. This is the default, and should work OK in most circumstances.
res_array = vdagent_mutter_get_resolutions(display->mutter, &width, &height, &screen_count);
if (res_array == NULL) {
res_array = vdagent_gtk_get_resolutions(display, &width, &height, &screen_count);
}
if (res_array == NULL) {
res_array = vdagent_x11_get_resolutions(display->x11, update, &width, &height, &screen_count);
}
if (res_array == NULL) {
return;
}
if (res_array->len < g_hash_table_size(display->connector_mapping)) {
// Complete the array with disabled displays.
// We need to send 0x0 resolution to let the daemon know the display is not there anymore.
syslog(LOG_DEBUG, "%d/%d displays found - completing with disabled displays.",
res_array->len, g_hash_table_size(display->connector_mapping));
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, display->connector_mapping);
while (g_hash_table_iter_next(&iter, &key, &value)) {
bool found = false;
int display_id = GPOINTER_TO_INT(value);
for (int i = 0; i < res_array->len; i++) {
struct vdagentd_guest_xorg_resolution *res =
(struct vdagentd_guest_xorg_resolution*)res_array->data;
if (res[i].display_id == display_id) {
found = true;
break;
}
}
if (!found) {
struct vdagentd_guest_xorg_resolution res;
res.x = 0;
res.y = 0;
res.height = 0;
res.width = 0;
res.display_id = display_id;
g_array_append_val(res_array, res);
}
}
}
// sort the list to make sure we send them in the display_id order
g_array_sort(res_array, vdagent_guest_xorg_resolution_compare);
if (display->debug) {
syslog(LOG_DEBUG, "Sending guest screen resolutions to vdagentd:");
if (res_array->len > screen_count) {
syslog(LOG_DEBUG, "(NOTE: list may contain overlapping areas when "
"multiple spice displays show the same guest output)");
}
struct vdagentd_guest_xorg_resolution *res =
(struct vdagentd_guest_xorg_resolution*)res_array->data;
for (int i = 0; i < res_array->len; i++) {
syslog(LOG_DEBUG, " display_id=%d - %dx%d%+d%+d",
res[i].display_id, res[i].width, res[i].height, res[i].x, res[i].y);
}
}
udscs_write(display->vdagentd, VDAGENTD_GUEST_XORG_RESOLUTION, width, height,
(uint8_t *)res_array->data,
res_array->len * sizeof(struct vdagentd_guest_xorg_resolution));
g_array_free(res_array, TRUE);
}
static gchar *vdagent_display_get_wm_name(VDAgentDisplay *display)
{
#ifdef GDK_WINDOWING_X11
// With GTK4, screen have disappear, and with it the access to the window manager name
// Use the X11 call instead.
#if ! GTK_CHECK_VERSION(3, 98, 0)
GdkDisplay *gdk_display = gdk_display_get_default();
if (GDK_IS_X11_DISPLAY(gdk_display))
return g_strdup(gdk_x11_screen_get_window_manager_name(
gdk_display_get_default_screen(gdk_display)));
return g_strdup("unsupported");
#endif
#endif
return vdagent_x11_get_wm_name(display->x11);
}
struct vdagent_x11* vdagent_display_get_x11(VDAgentDisplay *display)
{
return display->x11;
}
static gboolean x11_io_channel_cb(GIOChannel *source, GIOCondition condition, gpointer data)
{
VDAgentDisplay *display = data;
vdagent_x11_do_read(display->x11);
return G_SOURCE_CONTINUE;
}
VDAgentDisplay* vdagent_display_create(UdscsConnection *vdagentd, int debug, int sync)
{
VDAgentDisplay *display;
gchar *net_wm_name = NULL;
display = g_new0(VDAgentDisplay, 1);
display->vdagentd = vdagentd;
display->debug = debug;
display->x11 = vdagent_x11_create(vdagentd, debug, sync);
if (display->x11 == NULL) {
g_free(display);
return NULL;
}
display->x11->vdagent_display = display;
display->connector_mapping = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
display->mutter = vdagent_mutter_create(display->connector_mapping);
display->x11_channel = g_io_channel_unix_new(vdagent_x11_get_fd(display->x11));
if (display->x11_channel == NULL) {
vdagent_x11_destroy(display->x11, TRUE);
g_free(display);
return NULL;
}
display->io_watch_source_id =
g_io_add_watch(display->x11_channel, G_IO_IN, x11_io_channel_cb, display);
/* Since we are started at the same time as the wm,
sometimes we need to wait a bit for the _NET_WM_NAME to show up. */
for (int i = 0; i < 9; i++) {
g_free(net_wm_name);
net_wm_name = vdagent_display_get_wm_name(display);
if (strcmp(net_wm_name, "unknown"))
break;
usleep(100000);
}
if (display->debug)
syslog(LOG_DEBUG, "%s: net_wm_name=\"%s\", has icons=%d",
__func__, net_wm_name, vdagent_display_has_icons_on_desktop(display));
g_free(net_wm_name);
vdagent_display_send_daemon_guest_res(display, TRUE);
return display;
}
void vdagent_display_destroy(VDAgentDisplay *display, int vdagentd_disconnected)
{
if (!display) {
return;
}
g_source_remove(display->io_watch_source_id);
g_clear_pointer(&display->x11_channel, g_io_channel_unref);
vdagent_x11_destroy(display->x11, vdagentd_disconnected);
vdagent_mutter_destroy(display->mutter);
g_hash_table_destroy(display->connector_mapping);
g_free(display);
}
/* Function used to determine the default location to save file-xfers,
xdg desktop dir or xdg download dir. We err on the safe side and use a
whitelist approach, so any unknown desktop will end up with saving
file-xfers to the xdg download dir, and opening the xdg download dir with
xdg-open when the file-xfer completes. */
gboolean vdagent_display_has_icons_on_desktop(VDAgentDisplay *display)
{
static const char * const wms_with_icons_on_desktop[] = {
"Metacity", /* GNOME-2 or GNOME-3 fallback */
"Xfwm4", /* Xfce */
"Marco", /* Mate */
"Metacity (Marco)", /* Mate, newer */
NULL
};
gchar *net_wm_name = vdagent_display_get_wm_name(display);
int i;
for (i = 0; wms_with_icons_on_desktop[i]; i++)
if (!strcmp(net_wm_name, wms_with_icons_on_desktop[i])) {
g_free(net_wm_name);
return TRUE;
}
g_free(net_wm_name);
return FALSE;
}
static bool has_zero_based_display_id(VDAgentDisplay *display)
{
// Older QXL drivers numbered their outputs starting with
// 0. This contrasts with most drivers who start numbering
// outputs with 1. In this case, the expected drm connector
// name will need to be decremented before comparing to the
// display manager output name
bool ret = false;
#ifdef USE_GTK_FOR_MONITORS
GdkDisplay *gdk_display = gdk_display_get_default();
if (GDK_IS_WAYLAND_DISPLAY(gdk_display)) {
gdk_display_sync(gdk_display);
GListModel *monitors = gdk_display_get_monitors(gdk_display);
int screen_count = g_list_model_get_n_items(monitors);
for (int i = 0; i < screen_count; i++) {
GdkMonitor *monitor = (GdkMonitor *)g_list_model_get_item(monitors, i);
const char *name = gdk_monitor_get_connector(monitor);
if (!name) {
continue;
}
if (strcmp(name, "Virtual-0") == 0) {
ret = true;
break;
}
}
}
else // otherwise, use the X11 code (below)
#endif
{
XRRScreenResources *xres = display->x11->randr.res;
Display *xdisplay = display->x11->display;
for (int i = 0; i < xres->noutput; ++i) {
XRROutputInfo *oinfo = XRRGetOutputInfo(xdisplay, xres, xres->outputs[i]);
if (!oinfo) {
syslog(LOG_WARNING, "Unable to lookup XRandr output info for output %li",
xres->outputs[i]);
return false;
}
if (strcmp(oinfo->name, "Virtual-0") == 0) {
ret = true;
XRRFreeOutputInfo(oinfo);
break;
}
XRRFreeOutputInfo(oinfo);
}
}
return ret;
}
// handle the device info message from the server. This will allow us to
// maintain a mapping from spice display id to xrandr output
void vdagent_display_handle_graphics_device_info(VDAgentDisplay *display, uint8_t *data,
size_t size)
{
VDAgentGraphicsDeviceInfo *graphics_device_info = (VDAgentGraphicsDeviceInfo *)data;
VDAgentDeviceDisplayInfo *device_display_info = graphics_device_info->display_info;
void *buffer_end = data + size;
bool decrement_id = has_zero_based_display_id(display);
syslog(LOG_INFO, "Received Graphics Device Info:");
for (size_t i = 0; i < graphics_device_info->count; ++i) {
if ((void*) device_display_info > buffer_end ||
(void*) (&device_display_info->device_address +
device_display_info->device_address_len) > buffer_end) {
syslog(LOG_ERR, "Malformed graphics_display_info message, "
"extends beyond the end of the buffer");
break;
}
// make sure the string is terminated:
if (device_display_info->device_address_len > 0) {
device_display_info->device_address[device_display_info->device_address_len - 1] = '\0';
} else {
syslog(LOG_WARNING, "Zero length device_address received for channel_id: %u, monitor_id: %u",
device_display_info->channel_id, device_display_info->monitor_id);
}
// Get the expected connector name from hardware info. Store it with the SPICE display ID.
char expected_name[100];
int ret = get_connector_name_for_device_info(device_display_info, expected_name,
sizeof(expected_name), decrement_id);
if (ret == 0) {
g_hash_table_insert(display->connector_mapping,
g_strdup(expected_name),
GUINT_TO_POINTER(device_display_info->channel_id + device_display_info->monitor_id));
syslog(LOG_DEBUG, "Mapping connector %s to display #%d", expected_name,
(device_display_info->channel_id + device_display_info->monitor_id));
}
// Also map the SPICE display ID to the corresponding X server object.
vdagent_x11_handle_device_display_info(display->x11, device_display_info, decrement_id);
device_display_info = (VDAgentDeviceDisplayInfo*) ((char*) device_display_info +
sizeof(VDAgentDeviceDisplayInfo) + device_display_info->device_address_len);
}
// make sure daemon is up-to-date with (possibly updated) device IDs
vdagent_display_send_daemon_guest_res(display, TRUE);
}
/*
* Set monitor configuration according to client request.
*
* On exit send current configuration to client, regardless of error.
*
* Errors:
* screen size too large for driver to handle. (we set the largest/smallest possible)
* no randr support in X server.
* invalid configuration request from client.
*/
void vdagent_display_set_monitor_config(VDAgentDisplay *display, VDAgentMonitorsConfig *mon_config,
int fallback)
{
#ifdef USE_GTK_FOR_MONITORS
if (GDK_IS_WAYLAND_DISPLAY(gdk_display_get_default())) {
// FIXME: there is no equivalent call to set the monitor config under wayland
// Send the configuration back - the client need to know the resolution was not taken into account.
vdagent_display_send_daemon_guest_res(display, TRUE);
return;
}
#endif
vdagent_x11_set_monitor_config(display->x11, mon_config, fallback);
}
+39
View File
@@ -0,0 +1,39 @@
/*
* display.h- vdagent display handling header
Copyright 2020 Red Hat, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SRC_VDAGENT_DISPLAY_H_
#define SRC_VDAGENT_DISPLAY_H_
typedef struct VDAgentDisplay VDAgentDisplay;
VDAgentDisplay *vdagent_display_create(UdscsConnection *vdagentd, int debug, int sync);
void vdagent_display_destroy(VDAgentDisplay *display, int vdagentd_disconnected);
gboolean vdagent_display_has_icons_on_desktop(VDAgentDisplay *display);
void vdagent_display_handle_graphics_device_info(VDAgentDisplay *display, uint8_t *data, size_t size);
void vdagent_display_set_monitor_config(VDAgentDisplay *display,
VDAgentMonitorsConfig *mon_config,
int fallback);
struct vdagent_x11 *vdagent_display_get_x11(VDAgentDisplay *display);
void vdagent_display_send_daemon_guest_res(VDAgentDisplay *display, gboolean update);
#endif /* SRC_VDAGENT_DISPLAY_H_ */
@@ -1,27 +1,24 @@
/* vdagent file xfers code
Copyright 2013 Red Hat, Inc.
Copyright 2013 - 2016 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
@@ -32,17 +29,17 @@
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/types.h>
#include <spice/vd_agent.h>
#include <glib.h>
#include "vdagentd-proto.h"
#include "vdagent-file-xfers.h"
#include "glib-compat.h"
#include "file-xfers.h"
struct vdagent_file_xfers {
GHashTable *xfers;
struct udscs_connection *vdagentd;
UdscsConnection *vdagentd;
char *save_dir;
int open_save_dir;
int debug;
@@ -79,7 +76,7 @@ static void vdagent_file_xfer_task_free(gpointer data)
}
struct vdagent_file_xfers *vdagent_file_xfers_create(
struct udscs_connection *vdagentd, const char *save_dir,
UdscsConnection *vdagentd, const char *save_dir,
int open_save_dir, int debug)
{
struct vdagent_file_xfers *xfers;
@@ -97,19 +94,23 @@ struct vdagent_file_xfers *vdagent_file_xfers_create(
void vdagent_file_xfers_destroy(struct vdagent_file_xfers *xfers)
{
g_return_if_fail(xfers != NULL);
g_hash_table_destroy(xfers->xfers);
g_free(xfers->save_dir);
g_free(xfers);
}
AgentFileXferTask *vdagent_file_xfers_get_task(
static AgentFileXferTask *vdagent_file_xfers_get_task(
struct vdagent_file_xfers *xfers, uint32_t id)
{
AgentFileXferTask *task;
g_return_val_if_fail(xfers != NULL, NULL);
task = g_hash_table_lookup(xfers->xfers, GUINT_TO_POINTER(id));
if (task == NULL)
syslog(LOG_ERR, "file-xfer: error can not find task %u", id);
syslog(LOG_ERR, "file-xfer: error cannot find task %u", id);
return task;
}
@@ -132,6 +133,7 @@ static AgentFileXferTask *vdagent_parse_start_msg(
goto error;
}
task = g_new0(AgentFileXferTask, 1);
task->file_fd = -1;
task->id = msg->id;
task->file_name = g_key_file_get_string(
keyfile, "vdagent-file-xfer", "name", &error);
@@ -165,13 +167,73 @@ error:
return NULL;
}
static uint64_t get_free_space_available(const char *path)
{
struct statvfs stat;
if (statvfs(path, &stat) != 0) {
syslog(LOG_WARNING, "file-xfer: failed to get free space, statvfs error: %s",
strerror(errno));
return G_MAXUINT64;
}
return stat.f_bsize * stat.f_bavail;
}
int
vdagent_file_xfers_create_file(const char *save_dir, char **file_name_p)
{
char *file_path = NULL;
char *dir = NULL;
char *path = NULL;
int file_fd = -1;
int i;
file_path = g_build_filename(save_dir, *file_name_p, NULL);
dir = g_path_get_dirname(file_path);
if (g_mkdir_with_parents(dir, S_IRWXU) == -1) {
syslog(LOG_ERR, "file-xfer: Failed to create dir %s", dir);
goto error;
}
path = g_strdup(file_path);
for (i = 0; i < 64; i++) {
file_fd = open(path, O_CREAT | O_WRONLY | O_EXCL, 0644);
if (file_fd >= 0) {
break;
}
if (errno != EEXIST) {
syslog(LOG_ERR, "file-xfer: failed to create file %s: %s",
path, strerror(errno));
goto error;
}
g_free(path);
char *extension = strrchr(file_path, '/');
extension = strrchr(extension != NULL ? extension + 1 : file_path, '.');
int basename_len = extension != NULL ? extension - file_path : strlen(file_path);
path = g_strdup_printf("%.*s (%i)%s", basename_len, file_path,
i + 1, extension ? extension : "");
}
if (file_fd < 0) {
syslog(LOG_ERR, "file-xfer: more than 63 copies of %s exist?", file_path);
goto error;
}
g_free(*file_name_p);
*file_name_p = path;
path = NULL;
error:
g_free(path);
g_free(file_path);
g_free(dir);
return file_fd;
}
void vdagent_file_xfers_start(struct vdagent_file_xfers *xfers,
VDAgentFileXferStartMessage *msg)
{
AgentFileXferTask *task;
char *dir = NULL, *path = NULL, *file_path = NULL;
struct stat st;
int i;
uint64_t free_space;
g_return_if_fail(xfers != NULL);
if (g_hash_table_lookup(xfers->xfers, GUINT_TO_POINTER(msg->id))) {
syslog(LOG_ERR, "file-xfer: error id %u already exists, ignoring!",
@@ -186,37 +248,33 @@ void vdagent_file_xfers_start(struct vdagent_file_xfers *xfers,
task->debug = xfers->debug;
file_path = g_build_filename(xfers->save_dir, task->file_name, NULL);
free_space = get_free_space_available(xfers->save_dir);
if (task->file_size > free_space) {
gchar *free_space_str, *file_size_str;
free_space_str = g_format_size(free_space);
file_size_str = g_format_size(task->file_size);
syslog(LOG_ERR, "file-xfer: not enough free space (%s to copy, %s free)",
file_size_str, free_space_str);
g_free(free_space_str);
g_free(file_size_str);
dir = g_path_get_dirname(file_path);
if (g_mkdir_with_parents(dir, S_IRWXU) == -1) {
syslog(LOG_ERR, "file-xfer: Failed to create dir %s", dir);
goto error;
udscs_write(xfers->vdagentd,
VDAGENTD_FILE_XFER_STATUS,
msg->id,
VD_AGENT_FILE_XFER_STATUS_NOT_ENOUGH_SPACE,
(uint8_t *)&free_space,
sizeof(free_space));
goto cleanup;
}
path = g_strdup(file_path);
for (i = 0; i < 64 && (stat(path, &st) == 0 || errno != ENOENT); i++) {
g_free(path);
path = g_strdup_printf("%s (%d)", file_path, i + 1);
}
g_free(task->file_name);
task->file_name = path;
if (i == 64) {
syslog(LOG_ERR, "file-xfer: more then 63 copies of %s exist?",
file_path);
goto error;
}
task->file_fd = open(path, O_CREAT | O_WRONLY, 0644);
if (task->file_fd == -1) {
syslog(LOG_ERR, "file-xfer: failed to create file %s: %s",
path, strerror(errno));
task->file_fd = vdagent_file_xfers_create_file(xfers->save_dir, &task->file_name);
if (task->file_fd < 0) {
goto error;
}
if (ftruncate(task->file_fd, task->file_size) < 0) {
syslog(LOG_ERR, "file-xfer: err reserving %"PRIu64" bytes for %s: %s",
task->file_size, path, strerror(errno));
task->file_size, task->file_name, strerror(errno));
goto error;
}
@@ -224,21 +282,18 @@ void vdagent_file_xfers_start(struct vdagent_file_xfers *xfers,
if (xfers->debug)
syslog(LOG_DEBUG, "file-xfer: Adding task %u %s %"PRIu64" bytes",
task->id, path, task->file_size);
task->id, task->file_name, task->file_size);
udscs_write(xfers->vdagentd, VDAGENTD_FILE_XFER_STATUS,
msg->id, VD_AGENT_FILE_XFER_STATUS_CAN_SEND_DATA, NULL, 0);
g_free(file_path);
g_free(dir);
return ;
error:
udscs_write(xfers->vdagentd, VDAGENTD_FILE_XFER_STATUS,
msg->id, VD_AGENT_FILE_XFER_STATUS_ERROR, NULL, 0);
cleanup:
if (task)
vdagent_file_xfer_task_free(task);
g_free(file_path);
g_free(dir);
}
void vdagent_file_xfers_status(struct vdagent_file_xfers *xfers,
@@ -246,6 +301,8 @@ void vdagent_file_xfers_status(struct vdagent_file_xfers *xfers,
{
AgentFileXferTask *task;
g_return_if_fail(xfers != NULL);
task = vdagent_file_xfers_get_task(xfers, msg->id);
if (!task)
return;
@@ -267,6 +324,8 @@ void vdagent_file_xfers_data(struct vdagent_file_xfers *xfers,
AgentFileXferTask *task;
int len, status = -1;
g_return_if_fail(xfers != NULL);
task = vdagent_file_xfers_get_task(xfers, msg->id);
if (!task)
return;
@@ -282,10 +341,18 @@ void vdagent_file_xfers_data(struct vdagent_file_xfers *xfers,
close(task->file_fd);
task->file_fd = -1;
if (xfers->open_save_dir &&
task->file_xfer_nr == task->file_xfer_total) {
char buf[PATH_MAX];
snprintf(buf, PATH_MAX, "xdg-open '%s'&", xfers->save_dir);
status = system(buf);
task->file_xfer_nr == task->file_xfer_total &&
g_hash_table_size(xfers->xfers) == 1) {
GError *error = NULL;
gchar *argv[] = { "xdg-open", xfers->save_dir, NULL };
if (!g_spawn_async(NULL, argv, NULL,
G_SPAWN_SEARCH_PATH,
NULL, NULL, NULL, &error)) {
syslog(LOG_WARNING,
"file-xfer: failed to open save directory: %s",
error->message);
g_error_free(error);
}
}
status = VD_AGENT_FILE_XFER_STATUS_SUCCESS;
} else {
@@ -305,3 +372,11 @@ void vdagent_file_xfers_data(struct vdagent_file_xfers *xfers,
g_hash_table_remove(xfers->xfers, GUINT_TO_POINTER(msg->id));
}
}
void vdagent_file_xfers_error_disabled(UdscsConnection *vdagentd, uint32_t msg_id)
{
g_return_if_fail(vdagentd != NULL);
udscs_write(vdagentd, VDAGENTD_FILE_XFER_STATUS,
msg_id, VD_AGENT_FILE_XFER_STATUS_DISABLED, NULL, 0);
}
@@ -7,12 +7,12 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
@@ -27,7 +27,7 @@
struct vdagent_file_xfers;
struct vdagent_file_xfers *vdagent_file_xfers_create(
struct udscs_connection *vdagentd, const char *save_dir,
UdscsConnection *vdagentd, const char *save_dir,
int open_save_dir, int debug);
void vdagent_file_xfers_destroy(struct vdagent_file_xfers *xfer);
@@ -37,5 +37,8 @@ void vdagent_file_xfers_status(struct vdagent_file_xfers *xfers,
VDAgentFileXferStatusMessage *msg);
void vdagent_file_xfers_data(struct vdagent_file_xfers *xfers,
VDAgentFileXferDataMessage *msg);
void vdagent_file_xfers_error_disabled(UdscsConnection *vdagentd,
uint32_t msg_id);
int vdagent_file_xfers_create_file(const char *save_dir, char **file_name_p);
#endif
+276
View File
@@ -0,0 +1,276 @@
/* mutter.c - implements the DBUS interface to mutter
Copyright 2020 Red Hat, Inc.
Red Hat Authors:
Julien Ropé <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <glib.h>
#include <gio/gio.h>
#include <syslog.h>
#include "vdagentd-proto.h"
#include "mutter.h"
// MUTTER DBUS FORMAT STRINGS
#define MODE_BASE_FORMAT "siiddad"
#define MODE_FORMAT "(" MODE_BASE_FORMAT "a{sv})"
#define MODES_FORMAT "a" MODE_FORMAT
#define MONITOR_SPEC_FORMAT "(ssss)"
#define MONITOR_FORMAT "(" MONITOR_SPEC_FORMAT MODES_FORMAT "a{sv})"
#define MONITORS_FORMAT "a" MONITOR_FORMAT
#define LOGICAL_MONITOR_MONITORS_FORMAT "a" MONITOR_SPEC_FORMAT
#define LOGICAL_MONITOR_FORMAT "(iidub" LOGICAL_MONITOR_MONITORS_FORMAT "a{sv})"
#define LOGICAL_MONITORS_FORMAT "a" LOGICAL_MONITOR_FORMAT
#define CURRENT_STATE_FORMAT "(u" MONITORS_FORMAT LOGICAL_MONITORS_FORMAT "a{sv})"
struct VDAgentMutterDBus {
GDBusProxy *dbus_proxy;
GHashTable *connector_mapping;
};
/**
* Initialise a communication to Mutter through its DBUS interface.
*
* Errors can indicate that another compositor is used. This is not a blocker, and we should default
* to use a different API then.
*
* Returns:
* An initialise VDAgentMutterDBus structure if successful.
* NULL if an error occurred.
*/
VDAgentMutterDBus *vdagent_mutter_create(GHashTable *connector_mapping)
{
GError *error = NULL;
VDAgentMutterDBus *mutter = g_new0(VDAgentMutterDBus, 1);
mutter->connector_mapping = g_hash_table_ref(connector_mapping);
GDBusProxyFlags flags = (G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START
| G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES
| G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS);
mutter->dbus_proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SESSION,
flags,
NULL,
"org.gnome.Mutter.DisplayConfig",
"/org/gnome/Mutter/DisplayConfig",
"org.gnome.Mutter.DisplayConfig",
NULL,
&error);
if (!mutter->dbus_proxy) {
syslog(LOG_WARNING, "display: failed to create dbus proxy: %s", error->message);
g_clear_error(&error);
vdagent_mutter_destroy(mutter);
return NULL;
}
return mutter;
}
void vdagent_mutter_destroy(VDAgentMutterDBus *mutter)
{
g_clear_object(&mutter->dbus_proxy);
g_hash_table_unref(mutter->connector_mapping);
g_free(mutter);
}
/** Look through a list of logical monitor to find the one provided.
* Returns the corresponding x and y position of the monitor on the desktop.
* This function is a helper to vdagent_mutter_get_resolution().
*
* Parameters:
* logical_monitor: initialized GVariant iterator. It will be copied to look through the items
* so that its original position is not modified.
* connector: name of the connector that must be found
* x and y: will received the found position
*
*/
static void vdagent_mutter_get_monitor_position(GVariantIter *logical_monitors,
const gchar *connector, int *x, int *y)
{
GVariant *logical_monitor = NULL;
GVariantIter *logical_monitor_iterator = g_variant_iter_copy(logical_monitors);
while (g_variant_iter_next(logical_monitor_iterator, "@"LOGICAL_MONITOR_FORMAT,
&logical_monitor)) {
GVariantIter *tmp_monitors = NULL;
g_variant_get_child(logical_monitor, 0, "i", x);
g_variant_get_child(logical_monitor, 1, "i", y);
g_variant_get_child(logical_monitor, 5, LOGICAL_MONITOR_MONITORS_FORMAT, &tmp_monitors);
g_variant_unref(logical_monitor);
GVariant *tmp_monitor = NULL;
gboolean found = FALSE;
while (!found && g_variant_iter_next(tmp_monitors, "@"MONITOR_SPEC_FORMAT, &tmp_monitor)) {
const gchar *tmp_connector;
g_variant_get_child(tmp_monitor, 0, "&s", &tmp_connector);
if (g_strcmp0(connector, tmp_connector) == 0) {
found = TRUE;
}
g_variant_unref(tmp_monitor);
}
g_variant_iter_free(tmp_monitors);
if (found) {
break;
}
*x = *y = 0;
}
g_variant_iter_free(logical_monitor_iterator);
}
GArray *vdagent_mutter_get_resolutions(VDAgentMutterDBus *mutter,
int *desktop_width, int *desktop_height, int *screen_count)
{
GError *error = NULL;
GArray *res_array = NULL;
// keep track of monitors we find and are not mapped to SPICE displays
// we will map them back later (assuming display ID == monitor index)
// this prevents the need from looping twice on all DBUS items
GArray *not_found_array = NULL;
if (!mutter) {
return res_array;
}
GVariant *values = g_dbus_proxy_call_sync(mutter->dbus_proxy,
"GetCurrentState",
NULL,
G_DBUS_CALL_FLAGS_NONE,
-1, // use proxy default timeout
NULL,
&error);
if (!values) {
syslog(LOG_WARNING, "display: failed to call GetCurrentState from mutter over DBUS");
if (error != NULL) {
syslog(LOG_WARNING, " error message: %s", error->message);
g_clear_error(&error);
}
return res_array;
}
res_array = g_array_new(FALSE, FALSE, sizeof(struct vdagentd_guest_xorg_resolution));
not_found_array = g_array_new(FALSE, FALSE, sizeof(struct vdagentd_guest_xorg_resolution));
GVariantIter *monitors = NULL;
GVariantIter *logical_monitors = NULL;
g_variant_get_child(values, 1, MONITORS_FORMAT, &monitors);
g_variant_get_child(values, 2, LOGICAL_MONITORS_FORMAT, &logical_monitors);
// list monitors
GVariant *monitor = NULL;
*screen_count = g_variant_iter_n_children(monitors);
while (g_variant_iter_next(monitors, "@"MONITOR_FORMAT, &monitor)) {
const gchar *connector = NULL;
GVariantIter *modes = NULL;
GVariant *monitor_specs = NULL;
g_variant_get_child(monitor, 0, "@"MONITOR_SPEC_FORMAT, &monitor_specs);
g_variant_get_child(monitor_specs, 0, "&s", &connector);
g_variant_get_child(monitor, 1, MODES_FORMAT, &modes);
g_variant_unref(monitor_specs);
g_variant_unref(monitor);
// list modes
GVariant *mode = NULL;
while (g_variant_iter_next(modes, "@"MODE_FORMAT, &mode)) {
GVariant *properties = NULL;
gboolean is_current;
g_variant_get_child(mode, 6, "@a{sv}", &properties);
if (!g_variant_lookup(properties, "is-current", "b", &is_current)) {
is_current = FALSE;
}
g_variant_unref(properties);
if (!is_current) {
g_variant_unref(mode);
continue;
}
struct vdagentd_guest_xorg_resolution curr;
vdagent_mutter_get_monitor_position(logical_monitors, connector, &curr.x, &curr.y);
g_variant_get_child(mode, 1, "i", &curr.width);
g_variant_get_child(mode, 2, "i", &curr.height);
g_variant_unref(mode);
// compute the size of the desktop based on the dimension of the monitors
if (curr.x + curr.width > *desktop_width) {
*desktop_width = curr.x + curr.width;
}
if (curr.y + curr.height > *desktop_height) {
*desktop_height = curr.y + curr.height;
}
gpointer value;
if (g_hash_table_lookup_extended(mutter->connector_mapping, connector, NULL, &value)) {
curr.display_id = GPOINTER_TO_UINT(value);
syslog(LOG_DEBUG,
"Found monitor %s with geometry %dx%d+%d-%d - associating it to SPICE display #%d",
connector, curr.width, curr.height, curr.x, curr.y, curr.display_id);
g_array_append_val(res_array, curr);
} else {
syslog(LOG_DEBUG, "No SPICE display found for connector %s", connector);
g_array_append_val(not_found_array, curr);
}
break;
}
g_variant_iter_free(modes);
}
g_variant_iter_free(logical_monitors);
g_variant_iter_free(monitors);
int i;
if (res_array->len == 0) {
syslog(LOG_DEBUG, "%s: No Spice display ID matching - assuming display ID == Monitor index",
__FUNCTION__);
g_array_free(res_array, TRUE);
res_array = not_found_array;
struct vdagentd_guest_xorg_resolution *res;
res = (struct vdagentd_guest_xorg_resolution*)res_array->data;
for (i = 0; i < res_array->len; i++) {
res[i].display_id = i;
}
}
else {
g_array_free(not_found_array, TRUE);
}
g_variant_unref(values);
return res_array;
}
+33
View File
@@ -0,0 +1,33 @@
/* mutter.h - implements the DBUS interface to mutter
Copyright 2020 Red Hat, Inc.
Red Hat Authors:
Julien Ropé <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SRC_VDAGENT_MUTTER_H_
#define SRC_VDAGENT_MUTTER_H_
typedef struct VDAgentMutterDBus VDAgentMutterDBus;
VDAgentMutterDBus *vdagent_mutter_create(GHashTable *connector_mapping);
void vdagent_mutter_destroy(VDAgentMutterDBus *mutter);
GArray *vdagent_mutter_get_resolutions(VDAgentMutterDBus *mutter, int *width, int *height, int *screen_count);
#endif /* SRC_VDAGENT_MUTTER_H_ */
+528
View File
@@ -0,0 +1,528 @@
/* vdagent.c xorg-client to vdagentd (daemon).
Copyright 2010-2013 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <spice/vd_agent.h>
#include <poll.h>
#include <glib-unix.h>
#ifdef WITH_GTK
# include <gtk/gtk.h>
#endif
#include "udscs.h"
#include "vdagentd-proto.h"
#include "audio.h"
#include "file-xfers.h"
#include "clipboard.h"
#include "display.h"
#define MAX_RETRY_CONNECT_SYSTEM_AGENT 60
typedef struct VDAgent {
VDAgentClipboards *clipboards;
VDAgentDisplay *display;
struct vdagent_file_xfers *xfers;
UdscsConnection *conn;
gint udscs_num_retry;
GMainLoop *loop;
} VDAgent;
static int quit = 0;
static int parent_socket = -1;
static int version_mismatch = 0;
/* Command line options */
static gboolean debug = FALSE;
static gboolean x11_sync = FALSE;
static gboolean do_daemonize = TRUE;
static gint fx_open_dir = -1;
static gchar *fx_dir = NULL;
static gchar *portdev = NULL;
static gchar *vdagentd_socket = NULL;
static GOptionEntry entries[] = {
{ "debug", 'd',
G_OPTION_FLAG_NONE,
G_OPTION_ARG_NONE, &debug,
"Enable debug", NULL },
{ "virtio-serial-port-path", 's',
G_OPTION_FLAG_NONE,
G_OPTION_ARG_STRING, &portdev,
"Set virtio-serial path (" DEFAULT_VIRTIO_PORT_PATH ")", NULL },
{ "vdagentd-socket", 'S',
G_OPTION_FLAG_NONE,
G_OPTION_ARG_STRING, &vdagentd_socket,
"Set spice-vdagentd socket (" VDAGENTD_SOCKET ")", NULL },
{ "foreground", 'x',
G_OPTION_FLAG_REVERSE,
G_OPTION_ARG_NONE, &do_daemonize,
"Do not daemonize the agent", NULL },
{ "file-xfer-save-dir", 'f',
G_OPTION_FLAG_NONE,
G_OPTION_ARG_STRING, &fx_dir,
"Set directory to file transfers files", "<dir|xdg-desktop|xdg-download>"},
{ "file-xfer-open-dir", 'o',
G_OPTION_FLAG_NONE,
G_OPTION_ARG_INT, &fx_open_dir,
"Open directory after completing file transfer", "<0|1>" },
{ "x11-abort-on-error", 'y',
G_OPTION_FLAG_HIDDEN,
G_OPTION_ARG_NONE, &x11_sync,
"Aborts on errors from X11", NULL },
{ NULL }
};
/**
* xfer_get_download_directory
*
* Return path where transferred files should be stored.
* Returned path should not be freed or modified.
**/
static const gchar *xfer_get_download_directory(VDAgent *agent)
{
if (fx_dir != NULL) {
if (!strcmp(fx_dir, "xdg-desktop"))
return g_get_user_special_dir(G_USER_DIRECTORY_DESKTOP);
if (!strcmp(fx_dir, "xdg-download"))
return g_get_user_special_dir(G_USER_DIRECTORY_DOWNLOAD);
return fx_dir;
}
return g_get_user_special_dir(vdagent_display_has_icons_on_desktop(agent->display) ?
G_USER_DIRECTORY_DESKTOP :
G_USER_DIRECTORY_DOWNLOAD);
}
/**
* vdagent_init_file_xfer
*
* Initialize handler for file xfer,
* return TRUE on success (agent->xfers is not NULL).
**/
static gboolean vdagent_init_file_xfer(VDAgent *agent)
{
const gchar *xfer_dir;
gboolean open_dir;
if (agent->xfers != NULL) {
syslog(LOG_DEBUG, "File-xfer already initialized");
return TRUE;
}
xfer_dir = xfer_get_download_directory(agent);
if (xfer_dir == NULL) {
syslog(LOG_WARNING,
"warning could not get file xfer save dir, "
"file transfers will be disabled");
return FALSE;
}
open_dir = fx_open_dir == -1 ?
!vdagent_display_has_icons_on_desktop(agent->display) :
fx_open_dir;
agent->xfers = vdagent_file_xfers_create(agent->conn, xfer_dir,
open_dir, debug);
return (agent->xfers != NULL);
}
static gboolean vdagent_finalize_file_xfer(VDAgent *agent)
{
if (agent->xfers == NULL)
return FALSE;
g_clear_pointer(&agent->xfers, vdagent_file_xfers_destroy);
return TRUE;
}
static void vdagent_quit_loop(VDAgent *agent)
{
/* other GMainLoop(s) might be running, quit them before agent->loop */
if (agent->clipboards) {
vdagent_clipboards_set_conn(agent->clipboards, agent->conn);
g_clear_object(&agent->clipboards);
}
if (agent->loop)
g_main_loop_quit(agent->loop);
}
static void daemon_read_complete(UdscsConnection *conn,
struct udscs_message_header *header, uint8_t *data)
{
VDAgent *agent = g_object_get_data(G_OBJECT(conn), "agent");
switch (header->type) {
case VDAGENTD_MONITORS_CONFIG:
vdagent_display_set_monitor_config(agent->display, (VDAgentMonitorsConfig *)data, 0);
break;
case VDAGENTD_CLIPBOARD_REQUEST:
vdagent_clipboard_request(agent->clipboards, header->arg1, header->arg2);
break;
case VDAGENTD_CLIPBOARD_GRAB:
vdagent_clipboard_grab(agent->clipboards, header->arg1,
(guint32 *)data, header->size / sizeof(guint32));
break;
case VDAGENTD_CLIPBOARD_DATA:
vdagent_clipboard_data(agent->clipboards, header->arg1, header->arg2,
data, header->size);
break;
case VDAGENTD_CLIPBOARD_RELEASE:
vdagent_clipboard_release(agent->clipboards, header->arg1);
break;
case VDAGENTD_VERSION:
if (strcmp((char *)data, VERSION) != 0) {
syslog(LOG_INFO, "vdagentd version mismatch: got %s expected %s",
data, VERSION);
vdagent_quit_loop(agent);
version_mismatch = 1;
}
break;
case VDAGENTD_FILE_XFER_START:
if (agent->xfers != NULL) {
vdagent_file_xfers_start(agent->xfers,
(VDAgentFileXferStartMessage *)data);
} else {
vdagent_file_xfers_error_disabled(conn,
((VDAgentFileXferStartMessage *)data)->id);
}
break;
case VDAGENTD_FILE_XFER_STATUS:
if (agent->xfers != NULL) {
vdagent_file_xfers_status(agent->xfers,
(VDAgentFileXferStatusMessage *)data);
} else {
vdagent_file_xfers_error_disabled(conn,
((VDAgentFileXferStatusMessage *)data)->id);
}
break;
case VDAGENTD_FILE_XFER_DISABLE:
if (debug)
syslog(LOG_DEBUG, "Disabling file-xfers");
vdagent_finalize_file_xfer(agent);
break;
case VDAGENTD_AUDIO_VOLUME_SYNC: {
VDAgentAudioVolumeSync *avs = (VDAgentAudioVolumeSync *)data;
uint16_t *volume = g_memdup2(avs->volume, sizeof(uint16_t) * avs->nchannels);
if (avs->is_playback) {
vdagent_audio_playback_sync(avs->mute, avs->nchannels, volume);
} else {
vdagent_audio_record_sync(avs->mute, avs->nchannels, volume);
}
g_free(volume);
break;
}
case VDAGENTD_FILE_XFER_DATA:
if (agent->xfers != NULL) {
vdagent_file_xfers_data(agent->xfers,
(VDAgentFileXferDataMessage *)data);
} else {
vdagent_file_xfers_error_disabled(conn,
((VDAgentFileXferDataMessage *)data)->id);
}
break;
case VDAGENTD_GRAPHICS_DEVICE_INFO:
vdagent_display_handle_graphics_device_info(agent->display, data, header->size);
break;
case VDAGENTD_CLIENT_DISCONNECTED:
vdagent_clipboards_release_all(agent->clipboards);
if (vdagent_finalize_file_xfer(agent)) {
vdagent_init_file_xfer(agent);
}
break;
default:
syslog(LOG_ERR, "Unknown message from vdagentd type: %d, ignoring",
header->type);
}
}
static void daemon_error_cb(VDAgentConnection *conn, GError *err)
{
VDAgent *agent = g_object_get_data(G_OBJECT(conn), "agent");
if (err) {
syslog(LOG_ERR, "%s", err->message);
g_error_free(err);
}
g_clear_pointer(&agent->conn, vdagent_connection_destroy);
vdagent_quit_loop(agent);
}
/* When we daemonize, it is useful to have the main process
wait to make sure the X connection worked. We wait up
to 10 seconds to get an 'all clear' from the child
before we exit. If we don't, we're able to exit with a
status that indicates an error occurred */
static void wait_and_exit(int s)
{
char buf[4];
struct pollfd p;
p.fd = s;
p.events = POLLIN;
if (poll(&p, 1, 10000) > 0)
if (read(s, buf, sizeof(buf)) > 0)
exit(0);
exit(1);
}
static int daemonize(void)
{
int fd[2];
if (socketpair(PF_LOCAL, SOCK_STREAM, 0, fd)) {
syslog(LOG_ERR, "socketpair : %s", strerror(errno));
exit(1);
}
/* detach from terminal */
switch (fork()) {
case 0:
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
setsid();
// coverity[leaked_handle] just opening standard file descriptors
if (open("/dev/null", O_RDWR) != STDIN_FILENO) {
exit(1);
}
// coverity[leaked_handle] just opening standard file descriptors
if (dup(STDIN_FILENO) != STDOUT_FILENO) {
exit(1);
}
// coverity[leaked_handle] just opening standard file descriptors
if (dup(STDOUT_FILENO) != STDERR_FILENO) {
exit(1);
}
close(fd[0]);
return fd[1];
case -1:
syslog(LOG_ERR, "fork: %s", strerror(errno));
exit(1);
default:
close(fd[1]);
wait_and_exit(fd[0]);
}
return 0;
}
gboolean vdagent_signal_handler(gpointer user_data)
{
VDAgent *agent = user_data;
quit = TRUE;
vdagent_quit_loop(agent);
return G_SOURCE_REMOVE;
}
static VDAgent *vdagent_new(void)
{
VDAgent *agent = g_new0(VDAgent, 1);
agent->loop = g_main_loop_new(NULL, FALSE);
g_unix_signal_add(SIGINT, vdagent_signal_handler, agent);
g_unix_signal_add(SIGHUP, vdagent_signal_handler, agent);
g_unix_signal_add(SIGTERM, vdagent_signal_handler, agent);
return agent;
}
static void vdagent_destroy(VDAgent *agent)
{
vdagent_finalize_file_xfer(agent);
vdagent_display_destroy(agent->display, agent->conn == NULL);
g_clear_pointer(&agent->conn, vdagent_connection_destroy);
while (g_source_remove_by_user_data(agent))
continue;
g_clear_pointer(&agent->loop, g_main_loop_unref);
g_free(agent);
}
static gboolean vdagent_init_async_cb(gpointer user_data)
{
VDAgent *agent = user_data;
GError *err = NULL;
agent->conn = udscs_connect(vdagentd_socket,
daemon_read_complete,
daemon_error_cb,
debug,
&err);
if (agent->conn == NULL) {
if (agent->udscs_num_retry == MAX_RETRY_CONNECT_SYSTEM_AGENT) {
syslog(LOG_WARNING,
"Failed to connect to spice-vdagentd at %s (tried %d times)",
vdagentd_socket, agent->udscs_num_retry);
g_error_free(err);
goto err_init;
}
if (agent->udscs_num_retry == 0) {
/* Log only when it fails and at the end */
syslog(LOG_DEBUG,
"Failed to connect with spice-vdagentd due '%s'. Trying again in 1s",
err->message);
}
g_error_free(err);
agent->udscs_num_retry++;
g_timeout_add_seconds(1, vdagent_init_async_cb, agent);
return G_SOURCE_REMOVE;
}
if (agent->udscs_num_retry != 0) {
syslog(LOG_DEBUG,
"Connected with spice-vdagentd after %d attempts",
agent->udscs_num_retry);
}
agent->udscs_num_retry = 0;
g_object_set_data(G_OBJECT(agent->conn), "agent", agent);
agent->display = vdagent_display_create(agent->conn, debug, x11_sync);
if (agent->display == NULL)
goto err_init;
if (!vdagent_init_file_xfer(agent))
syslog(LOG_WARNING, "File transfer is disabled");
agent->clipboards = vdagent_clipboards_new(vdagent_display_get_x11(agent->display));
vdagent_clipboards_set_conn(agent->clipboards, agent->conn);
if (parent_socket != -1) {
if (write(parent_socket, "OK", 2) != 2)
syslog(LOG_WARNING, "Parent already gone.");
close(parent_socket);
parent_socket = -1;
}
return G_SOURCE_REMOVE;
err_init:
vdagent_quit_loop(agent);
quit = TRUE;
return G_SOURCE_REMOVE;
}
int main(int argc, char *argv[])
{
GOptionContext *context;
GError *error = NULL;
VDAgent *agent;
char **orig_argv = g_memdup2(argv, sizeof(char*) * (argc+1));
orig_argv[argc] = NULL; /* To avoid clang analyzer false-positive */
context = g_option_context_new(NULL);
g_option_context_add_main_entries(context, entries, NULL);
g_option_context_set_summary(context,
"\tSpice session guest agent: X11\n"
"\tVersion: " VERSION);
#ifdef WITH_GTK
#if ! GTK_CHECK_VERSION(3, 98, 0) // not with GTK4 - option parsing is gone
g_option_context_add_group(context, gtk_get_option_group(FALSE));
#endif
#endif
g_option_context_parse(context, &argc, &argv, &error);
g_option_context_free(context);
if (error != NULL) {
g_printerr("Invalid arguments, %s\n", error->message);
g_clear_error(&error);
g_free(orig_argv);
return -1;
}
/* Set default path value if none was set */
if (portdev == NULL)
portdev = g_strdup(DEFAULT_VIRTIO_PORT_PATH);
if (vdagentd_socket == NULL)
vdagentd_socket = g_strdup(VDAGENTD_SOCKET);
openlog("spice-vdagent", do_daemonize ? LOG_PID : (LOG_PID | LOG_PERROR),
LOG_USER);
if (!g_file_test(portdev, G_FILE_TEST_EXISTS)) {
syslog(LOG_DEBUG, "vdagent virtio channel %s does not exist, exiting", portdev);
g_free(orig_argv);
return 0;
}
if (do_daemonize)
parent_socket = daemonize();
syslog(LOG_INFO, "vdagent started");
#ifdef WITH_GTK
#if GTK_CHECK_VERSION(3, 98, 0)
// GTK4: use Wayland if possible, otherwise use X11
gdk_set_allowed_backends("wayland,x11");
gtk_init();
#else
// GTK3: need to use X11 as talking to Wayland will cause bugs
gdk_set_allowed_backends("x11");
gtk_init(NULL, NULL);
#endif
#endif
reconnect:
if (version_mismatch) {
syslog(LOG_INFO, "Version mismatch, restarting");
sleep(1);
execvp(orig_argv[0], orig_argv);
}
agent = vdagent_new();
g_timeout_add(0, vdagent_init_async_cb, agent);
g_main_loop_run(agent->loop);
vdagent_destroy(agent);
agent = NULL;
/* allow the VDAgentConnection to finalize properly */
g_main_context_iteration(NULL, FALSE);
if (!quit && do_daemonize)
goto reconnect;
g_free(fx_dir);
g_free(portdev);
g_free(vdagentd_socket);
g_free(orig_argv);
return 0;
}
+292
View File
@@ -0,0 +1,292 @@
/* webdav-cb.c - common code for x11 and GTK+ backend handling webdav copy&paste
Copyright 2020 Red Hat, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <syslog.h>
#include "webdav-cb.h"
/* FIXME:
* From my testing, gvfs-dav with avahi doesn't seem stable enough,
* so let's simply use the usual port 9843 when mounting the shared folder for now.
*
* This is a bit unfortunate because the port can be customized with the -p option,
* while the service name "Spice client folder" is hardcoded.
*
* Issues with gvfs-dav and avahi:
* - https://bugzilla.redhat.com/show_bug.cgi?id=1843035
* - similar to https://bugzilla.redhat.com/show_bug.cgi?id=1773219
* - https://gitlab.gnome.org/GNOME/gvfs/-/issues/498
* - hence the %2520 in CLIPBOARD_WEBDAV_URI below
* - fixed recently
* - https://gitlab.gnome.org/GNOME/gvfs/-/issues/449
*/
// #define CLIPBOARD_WEBDAV_URI "dav+sd://Spice%2520client%2520folder._webdav._tcp.local"
#define CLIPBOARD_WEBDAV_URI "dav://localhost:9843"
typedef enum clipboard_action {
CLIPBOARD_ACTION_COPY,
CLIPBOARD_ACTION_CUT,
} clipboard_action;
static GMount *webdav_mount;
static GVolumeMonitor *monitor;
static GCancellable *cancellable;
static gchar *clipboard_data_to_uris(const gchar *target, const gchar *mount_uri,
const gchar *data, gsize size, GError **err)
{
if (!data || size < 1) {
/* this is valid input */
return NULL;
}
if (data[size-1]) {
g_set_error_literal(err, G_IO_ERROR, G_IO_ERROR_PARTIAL_INPUT,
"received list of uris that is not null-terminated");
return NULL;
}
clipboard_action action;
if (!g_strcmp0(data, "copy")) {
action = CLIPBOARD_ACTION_COPY;
} else if (!g_strcmp0(data, "cut")) {
action = CLIPBOARD_ACTION_CUT;
} else {
g_set_error_literal(err, G_IO_ERROR, G_IO_ERROR_INVALID_DATA,
"first line of uri list must specify clipboard action");
return NULL;
}
/* skip the action line, since we're only interested in
* the actual uris from this point forward */
gsize action_len = strlen(data) + 1;
data += action_len;
size -= action_len;
if (size < 1) {
return NULL;
}
GString *str = g_string_new(NULL);
const gchar *delimiter = "\n";
gboolean end_with_delimiter = FALSE;
/* TODO: add support for more file managers
* (and then update clipboard_format_tmpl in x11-priv.h) */
if (!g_strcmp0(target, "text/uri-list")) {
delimiter = "\r\n";
if (action == CLIPBOARD_ACTION_CUT) {
syslog(LOG_WARNING, "cutting is not supported with 'text/uri-list' target");
}
} else if (!g_strcmp0(target, "text/plain;charset=utf-8")) {
/* Nautilus uses text clipboard since
* https://gitlab.gnome.org/GNOME/nautilus/commit/1f77023b5769c773dd9261e5294c0738bf6a3115 */
end_with_delimiter = TRUE;
g_string_append(str, "x-special/nautilus-clipboard\n");
g_string_append (str, action == CLIPBOARD_ACTION_CUT ? "cut\n" : "copy\n");
} else if (!g_strcmp0(target, "application/x-kde-cutselection")) {
/* KDE Dolphin handles text/uri-list just fine,
* but this atom is needed to distinguish between copy and move */
g_string_append(str, action == CLIPBOARD_ACTION_CUT ? "1" : "0");
return g_string_free(str, FALSE);
} else if (!g_strcmp0(target, "x-special/gnome-copied-files") ||
!g_strcmp0(target, "x-special/mate-copied-files")) {
/* Nautilus moved away from this approach,
* but there's a bunch of other file managers that do use it, such as:
* Nemo (Cinnamon), Thunar (Xfce), Deepin File Manager (Deepin), Xfe; Caja (Mate) */
g_string_append(str, action == CLIPBOARD_ACTION_CUT ? "cut\n" : "copy\n");
} else {
g_set_error(err, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
"conversion to uri target %s is not supported", target);
return g_string_free(str, TRUE);
}
for (const gchar *item = data; item < data + size; item += strlen(item) + 1) {
gchar *escaped = g_uri_escape_string(item, G_URI_RESERVED_CHARS_ALLOWED_IN_PATH, TRUE);
gchar *uri = g_build_filename(mount_uri, escaped, NULL);
g_string_append(str, uri);
g_string_append(str, delimiter);
g_free(escaped);
g_free(uri);
}
if (!end_with_delimiter) {
g_string_truncate(str, str->len - strlen(delimiter));
}
return g_string_free(str, FALSE);
}
static gchar *clipboard_webdav_mount_get_uri(GMount *mount, GError **err)
{
GFile *root;
gchar *path, *uri;
root = g_mount_get_root(mount);
path = g_file_get_path(root);
if (path) {
/* gvfs-fuse is running, so we get path as follows:
* "/run/user/<UID>/gvfs/dav+sd:host=SpiceClipboard._webdav._tcp.local"
* but we still need to convert it to uri */
uri = g_filename_to_uri(path, NULL, err);
g_free(path);
} else {
/* gvfs-fuse is not running, let's return the CLIPBOARD_WEBDAV_URI ("dav+sd://..."),
* so that at least gio apps can access the shared files */
uri = g_file_get_uri(root);
syslog(LOG_WARNING, "gvfs-fuse doesn't seem to be running, "
"file copy functionality may be limited");
}
g_object_unref(root);
return uri;
}
static void resolve_task(GTask *task, const gchar *target, GBytes *data)
{
GError *err = NULL;
gchar *mount_uri, *uris;
mount_uri = clipboard_webdav_mount_get_uri(webdav_mount, &err);
if (!mount_uri) {
g_task_return_error(task, err);
g_object_unref(task);
return;
}
uris = clipboard_data_to_uris(target, mount_uri,
g_bytes_get_data(data, NULL), g_bytes_get_size(data), &err);
g_free(mount_uri);
if (err) {
g_task_return_error(task, err);
g_object_unref(task);
return;
}
g_task_return_pointer(task, uris, g_free);
g_object_unref(task);
}
static void unmounted_cb(GMount *mount, gpointer user_data)
{
syslog(LOG_DEBUG, "%s unmounted", CLIPBOARD_WEBDAV_URI);
g_clear_object(&webdav_mount);
}
static void mount_found_cb(GObject *source, GAsyncResult *res, gpointer user_data)
{
GTask *task = user_data;
GError *err = NULL;
webdav_mount = g_file_find_enclosing_mount_finish(G_FILE(source), res, &err);
if (err) {
g_task_return_error(task, err);
g_object_unref(task);
}
syslog(LOG_DEBUG, "mount %s found", CLIPBOARD_WEBDAV_URI);
g_signal_connect(webdav_mount, "unmounted", G_CALLBACK(unmounted_cb), NULL);
gchar *target = g_object_get_data(G_OBJECT(task), "target");
GBytes *data = g_task_get_task_data(task);
resolve_task(task, target, data);
}
static void mounted_cb(GObject *source, GAsyncResult *res, gpointer user_data)
{
GFile *f = G_FILE(source);
GTask *task = user_data;
GError *err = NULL;
g_file_mount_enclosing_volume_finish(f, res, &err);
if (g_error_matches(err, G_IO_ERROR, G_IO_ERROR_ALREADY_MOUNTED)) {
g_clear_error(&err);
} else if (err) {
g_task_return_error(task, err);
g_object_unref(task);
return;
}
syslog(LOG_DEBUG, "%s mounted successfully", CLIPBOARD_WEBDAV_URI);
g_file_find_enclosing_mount_async(f, G_PRIORITY_DEFAULT, cancellable, mount_found_cb, task);
}
static void clipboard_webdav_mount_async(GTask *task)
{
g_return_if_fail(webdav_mount == NULL);
syslog(LOG_DEBUG, "mounting %s", CLIPBOARD_WEBDAV_URI);
GFile *f = g_file_new_for_uri(CLIPBOARD_WEBDAV_URI);
g_file_mount_enclosing_volume(f,
G_MOUNT_MOUNT_NONE,
NULL, /* GMountOperation */
cancellable,
mounted_cb,
task);
g_object_unref(f);
}
gchar *clipboard_data_translate_to_uris_finish(GObject *source,
GAsyncResult *res, gsize *size, GError **err)
{
*size = 0;
g_return_val_if_fail(g_task_is_valid(res, source), NULL);
gchar *uris = g_task_propagate_pointer(G_TASK(res), err);
if (uris) {
*size = strlen(uris);
}
return uris;
}
void clipboard_data_translate_to_uris_async(const gchar *target, GBytes *data,
GCancellable *cancel, GAsyncReadyCallback callback, gpointer user_data)
{
GTask *task = g_task_new(NULL, cancel, callback, user_data);
if (!webdav_mount) {
g_task_set_task_data(task, g_bytes_ref(data), (GDestroyNotify)g_bytes_unref);
g_object_set_data_full(G_OBJECT(task), "target", g_strdup(target), g_free);
clipboard_webdav_mount_async(task);
return;
}
resolve_task(task, target, data);
}
void clipboard_webdav_init()
{
/* we listen to the "unmounted" signal,
* but without the GVolumeMonitor, the signal is not emitted,
* although the docs don't seem to mention it!
* https://gitlab.gnome.org/GNOME/gvfs/-/issues/494 */
monitor = g_volume_monitor_get();
webdav_mount = NULL;
cancellable = g_cancellable_new();
}
void clipboard_webdav_finalize()
{
g_cancellable_cancel(cancellable);
g_clear_object(&cancellable);
g_clear_object(&webdav_mount);
g_clear_object(&monitor);
}
+38
View File
@@ -0,0 +1,38 @@
/* webdav-cb.h
Copyright 2020 Red Hat, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <gio/gio.h>
void clipboard_webdav_init();
void clipboard_webdav_finalize();
/* converts the @data received from spice-gtk to the given @target;
* supported targets are:
* - "text/uri-list"
* - "text/plain;charset=utf-8"
* - "application/x-kde-cutselection"
* - "x-special/gnome-copied-files"
* - "x-special/mate-copied-files"
*/
void clipboard_data_translate_to_uris_async(const gchar *target, GBytes *data,
GCancellable *cancel, GAsyncReadyCallback callback, gpointer user_data);
gchar *clipboard_data_translate_to_uris_finish(GObject *source,
GAsyncResult *res, gsize *size, GError **err);
@@ -7,6 +7,11 @@
#include <spice/vd_agent.h>
#include <X11/extensions/Xrandr.h>
#include "display.h"
#ifndef USE_GTK_FOR_CLIPBOARD
#include "webdav-cb.h"
/* Macros to print a message to the logfile prefixed by the selection */
#define SELPRINTF(format, ...) \
@@ -21,10 +26,6 @@
} \
} while (0)
#define MAX_SCREENS 16
/* Same as qxl_dev.h client_monitors_config.heads count */
#define MONITOR_SIZE_COUNT 64
enum { owner_none, owner_guest, owner_client };
/* X11 terminology is confusing a selection request is a request from an
@@ -37,7 +38,7 @@ struct vdagent_x11_selection_request {
struct vdagent_x11_selection_request *next;
};
/* A conversion request is X11 speak for asking an other app to give its
/* A conversion request is X11 speak for asking another app to give its
clipboard data to us, we do these on behalf of the spice client to copy
data from the guest to the client. Like selection requests we process
these one at a time. */
@@ -58,47 +59,58 @@ struct clipboard_format_info {
int atom_count;
};
struct monitor_size {
int width;
int height;
};
static const struct clipboard_format_tmpl clipboard_format_templates[] = {
{ VD_AGENT_CLIPBOARD_UTF8_TEXT, { "UTF8_STRING",
"text/plain;charset=UTF-8", "text/plain;charset=utf-8", NULL }, },
{ VD_AGENT_CLIPBOARD_UTF8_TEXT, { "UTF8_STRING", "text/plain;charset=UTF-8",
"text/plain;charset=utf-8", "STRING", NULL }, },
{ VD_AGENT_CLIPBOARD_IMAGE_PNG, { "image/png", NULL }, },
{ VD_AGENT_CLIPBOARD_IMAGE_BMP, { "image/bmp", "image/x-bmp",
"image/x-MS-bmp", "image/x-win-bitmap", NULL }, },
{ VD_AGENT_CLIPBOARD_IMAGE_TIFF, { "image/tiff", NULL }, },
{ VD_AGENT_CLIPBOARD_IMAGE_JPG, { "image/jpeg", NULL }, },
{ VD_AGENT_CLIPBOARD_FILE_LIST, { "text/uri-list",
"text/plain;charset=utf-8", "application/x-kde-cutselection",
"x-special/gnome-copied-files", "x-special/mate-copied-files", NULL } },
};
#define clipboard_format_count (sizeof(clipboard_format_templates)/sizeof(clipboard_format_templates[0]))
#define ATOM_NAME_CACHE_SIZE 16
struct atom_name_cache_item {
Atom atom;
char *name;
};
#endif
#define MAX_SCREENS 16
/* Same as qxl_dev.h client_monitors_config.heads count */
#define MONITOR_SIZE_COUNT 64
struct monitor_size {
int width;
int height;
};
struct vdagent_x11 {
struct clipboard_format_info clipboard_formats[clipboard_format_count];
Display *display;
#ifndef USE_GTK_FOR_CLIPBOARD
struct clipboard_format_info clipboard_formats[clipboard_format_count];
Atom clipboard_atom;
Atom clipboard_primary_atom;
Atom targets_atom;
Atom incr_atom;
Atom multiple_atom;
Window root_window[MAX_SCREENS];
Atom timestamp_atom;
struct atom_name_cache_item atom_name_cache[ATOM_NAME_CACHE_SIZE];
int atom_name_cache_next;
Window selection_window;
struct udscs_connection *vdagentd;
char *net_wm_name;
int debug;
int fd;
int screen_count;
int width[MAX_SCREENS];
int height[MAX_SCREENS];
int has_xfixes;
int xfixes_event_base;
int max_prop_size;
int expected_targets_notifies[256];
int ignore_targets_notifies[256];
int clipboard_owner[256];
int clipboard_type_count[256];
uint32_t clipboard_agent_types[256][256];
Bool clipboard_has_files[256];
Atom clipboard_x11_targets[256][256];
/* Data for conversion_req which is currently being processed */
struct vdagent_x11_conversion_request *conversion_req;
@@ -111,12 +123,21 @@ struct vdagent_x11 {
uint8_t *selection_req_data;
uint32_t selection_req_data_pos;
uint32_t selection_req_data_size;
GBytes *file_list_data[256];
Atom selection_req_atom;
#endif
Window root_window[MAX_SCREENS];
UdscsConnection *vdagentd;
int debug;
int screen_count;
int width[MAX_SCREENS];
int height[MAX_SCREENS];
/* resolution change state */
struct {
XRRScreenResources *res;
XRROutputInfo **outputs;
XRRCrtcInfo **crtcs;
int event_base;
int min_width;
int max_width;
int min_height;
@@ -134,17 +155,23 @@ struct vdagent_x11 {
int xrandr_minor;
int has_xinerama;
int dont_send_guest_xorg_res;
GHashTable *guest_output_map;
VDAgentDisplay *vdagent_display;
};
extern int (*vdagent_x11_prev_error_handler)(Display *, XErrorEvent *);
extern int vdagent_x11_caught_error;
void vdagent_x11_randr_init(struct vdagent_x11 *x11);
void vdagent_x11_send_daemon_guest_xorg_res(struct vdagent_x11 *x11,
int update);
void vdagent_x11_randr_destroy(struct vdagent_x11 *x11);
GArray *vdagent_x11_get_resolutions(struct vdagent_x11 *x11, gboolean update,
int *width, int *height, int *system_screen_count);
void vdagent_x11_randr_handle_root_size_change(struct vdagent_x11 *x11,
int screen, int width, int height);
int vdagent_x11_randr_handle_event(struct vdagent_x11 *x11,
const XEvent *event);
void vdagent_x11_set_error_handler(struct vdagent_x11 *x11,
int (*handler)(Display *, XErrorEvent *));
int vdagent_x11_restore_error_handler(struct vdagent_x11 *x11);
@@ -9,18 +9,21 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <string.h>
#include <syslog.h>
#include <stdlib.h>
@@ -28,11 +31,14 @@
#include <X11/extensions/Xinerama.h>
#include "device-info.h"
#include "vdagentd-proto.h"
#include "vdagent-x11.h"
#include "vdagent-x11-priv.h"
#include "x11.h"
#include "x11-priv.h"
static int error_handler(Display *display, XErrorEvent *error)
#define MM_PER_INCH (25.4)
static int ignore_error_handler(Display *display, XErrorEvent *error)
{
vdagent_x11_caught_error = 1;
return 0;
@@ -54,6 +60,10 @@ static XRRCrtcInfo *crtc_from_id(struct vdagent_x11 *x11, int id)
{
int i;
if (id == 0) {
return NULL;
}
for (i = 0 ; i < x11->randr.res->ncrtc ; ++i) {
if (id == x11->randr.res->crtcs[i]) {
return x11->randr.crtcs[i];
@@ -73,18 +83,15 @@ static void free_randr_resources(struct vdagent_x11 *x11)
for (i = 0 ; i < x11->randr.res->noutput; ++i) {
XRRFreeOutputInfo(x11->randr.outputs[i]);
}
free(x11->randr.outputs);
g_clear_pointer(&x11->randr.outputs, g_free);
}
if (x11->randr.crtcs != NULL) {
for (i = 0 ; i < x11->randr.res->ncrtc; ++i) {
XRRFreeCrtcInfo(x11->randr.crtcs[i]);
}
free(x11->randr.crtcs);
g_clear_pointer(&x11->randr.crtcs, g_free);
}
XRRFreeScreenResources(x11->randr.res);
x11->randr.res = NULL;
x11->randr.outputs = NULL;
x11->randr.crtcs = NULL;
g_clear_pointer(&x11->randr.res, XRRFreeScreenResources);
x11->randr.num_monitors = 0;
}
@@ -97,8 +104,8 @@ static void update_randr_res(struct vdagent_x11 *x11, int poll)
x11->randr.res = XRRGetScreenResources(x11->display, x11->root_window[0]);
else
x11->randr.res = XRRGetScreenResourcesCurrent(x11->display, x11->root_window[0]);
x11->randr.outputs = malloc(x11->randr.res->noutput * sizeof(*x11->randr.outputs));
x11->randr.crtcs = malloc(x11->randr.res->ncrtc * sizeof(*x11->randr.crtcs));
x11->randr.outputs = g_new(XRROutputInfo *, x11->randr.res->noutput);
x11->randr.crtcs = g_new(XRRCrtcInfo *, x11->randr.res->ncrtc);
for (i = 0 ; i < x11->randr.res->noutput; ++i) {
x11->randr.outputs[i] = XRRGetOutputInfo(x11->display, x11->randr.res,
x11->randr.res->outputs[i]);
@@ -115,7 +122,7 @@ static void update_randr_res(struct vdagent_x11 *x11, int poll)
&x11->randr.min_height,
&x11->randr.max_width,
&x11->randr.max_height) != 1) {
syslog(LOG_ERR, "update_randr_res: RRGetScreenSizeRange failed");
syslog(LOG_ERR, "update_randr_res: XRRGetScreenSizeRange failed");
}
}
@@ -124,17 +131,20 @@ void vdagent_x11_randr_init(struct vdagent_x11 *x11)
int i;
if (x11->screen_count > 1) {
syslog(LOG_WARNING, "X-server has more then 1 screen, "
syslog(LOG_WARNING, "X-server has more than 1 screen, "
"disabling client -> guest resolution syncing");
return;
}
if (XRRQueryExtension(x11->display, &i, &i)) {
if (XRRQueryExtension(x11->display, &x11->randr.event_base, &i)) {
XRRQueryVersion(x11->display, &x11->xrandr_major, &x11->xrandr_minor);
if (x11->xrandr_major == 1 && x11->xrandr_minor >= 3)
x11->has_xrandr = 1;
}
XRRSelectInput(x11->display, x11->root_window[0],
RRScreenChangeNotifyMask | RRCrtcChangeNotifyMask);
if (x11->has_xrandr) {
update_randr_res(x11, 0);
} else {
@@ -161,6 +171,12 @@ void vdagent_x11_randr_init(struct vdagent_x11 *x11)
}
}
void vdagent_x11_randr_destroy(struct vdagent_x11 *x11)
{
free_randr_resources(x11);
g_free(x11->randr.failed_conf);
}
static XRRModeInfo *
find_mode_by_name (struct vdagent_x11 *x11, char *name)
{
@@ -178,14 +194,14 @@ find_mode_by_name (struct vdagent_x11 *x11, char *name)
}
static XRRModeInfo *
find_mode_by_size (struct vdagent_x11 *x11, int output, int width, int height)
find_mode_by_size (struct vdagent_x11 *x11, int output_index, int width, int height)
{
int m;
XRRModeInfo *ret = NULL;
for (m = 0; m < x11->randr.outputs[output]->nmode; m++) {
for (m = 0; m < x11->randr.outputs[output_index]->nmode; m++) {
XRRModeInfo *mode = mode_from_id(x11,
x11->randr.outputs[output]->modes[m]);
x11->randr.outputs[output_index]->modes[m]);
if (mode && mode->width == width && mode->height == height) {
ret = mode;
break;
@@ -221,7 +237,7 @@ static void delete_mode(struct vdagent_x11 *x11, int output_index,
break;
}
if (m < x11->randr.res->nmode) {
vdagent_x11_set_error_handler(x11, error_handler);
vdagent_x11_set_error_handler(x11, ignore_error_handler);
XRRDeleteOutputMode (x11->display, x11->randr.res->outputs[output_index],
mode->id);
XRRDestroyMode (x11->display, mode->id);
@@ -229,7 +245,7 @@ static void delete_mode(struct vdagent_x11 *x11, int output_index,
vdagent_x11_restore_error_handler(x11);
}
/* silly to update everytime for more then one monitor */
/* silly to update every time for more than one monitor */
update_randr_res(x11, 0);
}
@@ -321,54 +337,62 @@ static XRRModeInfo *create_new_mode(struct vdagent_x11 *x11, int output_index,
set_reduced_cvt_mode(&mode, width, height);
mode.modeFlags = 0;
mode.id = 0;
vdagent_x11_set_error_handler(x11, error_handler);
vdagent_x11_set_error_handler(x11, ignore_error_handler);
XRRCreateMode (x11->display, x11->root_window[0], &mode);
// ignore race error, if mode is created by others
vdagent_x11_restore_error_handler(x11);
/* silly to update everytime for more then one monitor */
/* silly to update every time for more than one monitor */
update_randr_res(x11, 0);
return find_mode_by_name(x11, modename);
}
static int xrandr_add_and_set(struct vdagent_x11 *x11, int output, int x, int y,
static int xrandr_add_and_set(struct vdagent_x11 *x11, int output_index, int x, int y,
int width, int height)
{
XRRModeInfo *mode;
int xid;
Status s;
RROutput outputs[1];
int old_width = x11->randr.monitor_sizes[output].width;
int old_height = x11->randr.monitor_sizes[output].height;
int old_width;
int old_height;
if (!x11->randr.res || output >= x11->randr.res->noutput || output < 0) {
syslog(LOG_ERR, "%s: program error: missing RANDR or bad output",
__FUNCTION__);
if (!x11->randr.res) {
syslog(LOG_ERR, "%s: program error: missing RANDR", __FUNCTION__);
return 0;
}
if (output_index < 0 || output_index >= x11->randr.res->noutput) {
syslog(LOG_ERR, "%s: program error: bad output", __FUNCTION__);
return 0;
}
old_width = x11->randr.monitor_sizes[output_index].width;
old_height = x11->randr.monitor_sizes[output_index].height;
if (x11->set_crtc_config_not_functional) {
/* fail, set_best_mode will find something close. */
return 0;
}
xid = x11->randr.res->outputs[output];
mode = find_mode_by_size(x11, output, width, height);
xid = x11->randr.res->outputs[output_index];
mode = find_mode_by_size(x11, output_index, width, height);
if (!mode) {
mode = create_new_mode(x11, output, width, height);
mode = create_new_mode(x11, output_index, width, height);
}
if (!mode) {
syslog(LOG_ERR, "failed to add a new mode");
return 0;
}
XRRAddOutputMode(x11->display, xid, mode->id);
x11->randr.monitor_sizes[output].width = width;
x11->randr.monitor_sizes[output].height = height;
x11->randr.monitor_sizes[output_index].width = width;
x11->randr.monitor_sizes[output_index].height = height;
outputs[0] = xid;
s = XRRSetCrtcConfig(x11->display, x11->randr.res, x11->randr.res->crtcs[output],
vdagent_x11_set_error_handler(x11, ignore_error_handler);
s = XRRSetCrtcConfig(x11->display, x11->randr.res, x11->randr.res->crtcs[output_index],
CurrentTime, x, y, mode->id, RR_Rotate_0, outputs,
1);
if (s != RRSetConfigSuccess) {
if (vdagent_x11_restore_error_handler(x11) || (s != RRSetConfigSuccess)) {
syslog(LOG_ERR, "failed to XRRSetCrtcConfig");
x11->set_crtc_config_not_functional = 1;
return 0;
@@ -376,33 +400,63 @@ static int xrandr_add_and_set(struct vdagent_x11 *x11, int output, int x, int y,
/* clean the previous name, if any */
if (width != old_width || height != old_height)
delete_mode(x11, output, old_width, old_height);
delete_mode(x11, output_index, old_width, old_height);
return 1;
}
static void xrandr_disable_output(struct vdagent_x11 *x11, int output)
// Looks up the xrandr output id associated with the given spice display id
static RROutput get_xrandr_output_for_display_id(struct vdagent_x11 *x11, int display_id)
{
guint map_size = g_hash_table_size(x11->guest_output_map);
if (map_size == 0) {
// we never got a device info message from the server, so just use old
// assumptions that the spice display id is equal to the index into the
// array of xrandr outputs
if (display_id < x11->randr.res->noutput) {
return x11->randr.res->outputs[display_id];
}
} else {
gpointer value;
if (g_hash_table_lookup_extended(x11->guest_output_map, GINT_TO_POINTER(display_id),
NULL, &value)) {
return (RROutput)value;
}
}
// unable to find a valid output id
return -1;
}
static void xrandr_disable_nth_output(struct vdagent_x11 *x11, int output_index)
{
Status s;
if (!x11->randr.res || output >= x11->randr.res->noutput || output < 0) {
if (!x11->randr.res || output_index >= x11->randr.res->noutput || output_index < 0) {
syslog(LOG_ERR, "%s: program error: missing RANDR or bad output",
__FUNCTION__);
return;
}
XRROutputInfo *oinfo = x11->randr.outputs[output_index];
if (oinfo->ncrtc == 0) {
syslog(LOG_WARNING, "Output index %i doesn't have any associated CRTCs", output_index);
return;
}
// assume output only has a single crtc
s = XRRSetCrtcConfig(x11->display, x11->randr.res,
x11->randr.res->crtcs[output],
oinfo->crtcs[0],
CurrentTime, 0, 0, None, RR_Rotate_0,
NULL, 0);
if (s != RRSetConfigSuccess)
syslog(LOG_ERR, "failed to disable monitor");
delete_mode(x11, output, x11->randr.monitor_sizes[output].width,
x11->randr.monitor_sizes[output].height);
x11->randr.monitor_sizes[output].width = 0;
x11->randr.monitor_sizes[output].height = 0;
delete_mode(x11, output_index, x11->randr.monitor_sizes[output_index].width,
x11->randr.monitor_sizes[output_index].height);
x11->randr.monitor_sizes[output_index].width = 0;
x11->randr.monitor_sizes[output_index].height = 0;
}
static int set_screen_to_best_size(struct vdagent_x11 *x11, int width, int height,
@@ -463,6 +517,9 @@ static int set_screen_to_best_size(struct vdagent_x11 *x11, int width, int heigh
void vdagent_x11_randr_handle_root_size_change(struct vdagent_x11 *x11,
int screen, int width, int height)
{
#ifndef USE_GTK_FOR_MONITORS
update_randr_res(x11, 0);
if (width == x11->width[screen] && height == x11->height[screen]) {
return;
}
@@ -473,19 +530,39 @@ void vdagent_x11_randr_handle_root_size_change(struct vdagent_x11 *x11,
x11->width[screen] = width;
x11->height[screen] = height;
#endif
if (!x11->dont_send_guest_xorg_res) {
vdagent_x11_send_daemon_guest_xorg_res(x11, 1);
vdagent_display_send_daemon_guest_res(x11->vdagent_display, TRUE);
}
}
static int min_int(int x, int y)
int vdagent_x11_randr_handle_event(struct vdagent_x11 *x11,
const XEvent *event)
{
return x > y ? y : x;
}
int handled = TRUE;
static int max_int(int x, int y)
{
return x > y ? x : y;
switch (event->type - x11->randr.event_base) {
case RRScreenChangeNotify: {
const XRRScreenChangeNotifyEvent *sce =
(const XRRScreenChangeNotifyEvent *) event;
vdagent_x11_randr_handle_root_size_change(x11, 0,
sce->width, sce->height);
break;
}
case RRNotify: {
#ifndef USE_GTK_FOR_MONITORS
update_randr_res(x11, 0);
#endif
if (!x11->dont_send_guest_xorg_res)
vdagent_display_send_daemon_guest_res(x11->vdagent_display, TRUE);
break;
}
default:
handled = FALSE;
break;
}
return handled;
}
static int constrain_to_range(int low, int *val, int high)
@@ -544,20 +621,24 @@ static void zero_base_monitors(struct vdagent_x11 *x11,
int *width, int *height)
{
int i, min_x = INT_MAX, min_y = INT_MAX, max_x = INT_MIN, max_y = INT_MIN;
int *mon_height, *mon_width;
for (i = 0; i < mon_config->num_of_monitors; i++) {
if (!monitor_enabled(&mon_config->monitors[i]))
int mon_height, mon_width;
if (!monitor_enabled(&mon_config->monitors[i])) {
continue;
}
mon_config->monitors[i].x &= ~7;
mon_config->monitors[i].width &= ~7;
mon_width = (int *)&mon_config->monitors[i].width;
mon_height = (int *)&mon_config->monitors[i].height;
constrain_to_screen(x11, mon_width, mon_height);
min_x = min_int(mon_config->monitors[i].x, min_x);
min_y = min_int(mon_config->monitors[i].y, min_y);
max_x = max_int(mon_config->monitors[i].x + *mon_width, max_x);
max_y = max_int(mon_config->monitors[i].y + *mon_height, max_y);
mon_width = mon_config->monitors[i].width;
mon_height = mon_config->monitors[i].height;
constrain_to_screen(x11, &mon_width, &mon_height);
min_x = MIN(mon_config->monitors[i].x, min_x);
min_y = MIN(mon_config->monitors[i].y, min_y);
max_x = MAX(mon_config->monitors[i].x + mon_width, max_x);
max_y = MAX(mon_config->monitors[i].y + mon_height, max_y);
mon_config->monitors[i].width = mon_width;
mon_config->monitors[i].height = mon_height;
}
if (min_x != 0 || min_y != 0) {
syslog(LOG_ERR, "%s: agent config %d,%d rooted, adjusting to 0,0.",
@@ -612,38 +693,69 @@ static int config_size(int num_of_monitors)
num_of_monitors * sizeof(VDAgentMonConfig);
}
// gets monitor information about the specified output index and returns true if there was no error
static bool get_monitor_info_for_output_index(struct vdagent_x11 *x11, int output_index,
int *x, int *y, int *width, int *height)
{
g_return_val_if_fail (output_index < x11->randr.res->noutput, false);
g_return_val_if_fail (x != NULL, false);
g_return_val_if_fail (y != NULL, false);
g_return_val_if_fail (width != NULL, false);
g_return_val_if_fail (height != NULL, false);
int j;
XRRCrtcInfo *crtc = NULL;
XRRModeInfo *mode;
if (x11->randr.outputs[output_index]->ncrtc == 0)
goto zeroed; /* Monitor disabled */
for (j = 0; crtc == NULL && j < x11->randr.outputs[output_index]->ncrtc; j++) {
crtc = crtc_from_id(x11, x11->randr.outputs[output_index]->crtcs[j]);
}
if (!crtc) {
// error. stale xrandr info?
return false;
}
mode = mode_from_id(x11, crtc->mode);
if (!mode)
goto zeroed; /* monitor disabled */
*x = crtc->x;
*y = crtc->y;
*width = mode->width;
*height = mode->height;
return true;
zeroed:
*x = 0;
*y = 0;
*width = 0;
*height = 0;
return true;
}
static VDAgentMonitorsConfig *get_current_mon_config(struct vdagent_x11 *x11)
{
int i, num_of_monitors = 0;
XRRModeInfo *mode;
XRRCrtcInfo *crtc;
XRRScreenResources *res = x11->randr.res;
VDAgentMonitorsConfig *mon_config;
mon_config = calloc(1, config_size(res->noutput));
if (!mon_config) {
syslog(LOG_ERR, "out of memory allocating current monitor config");
return NULL;
}
mon_config = g_malloc0(config_size(res->noutput));
for (i = 0 ; i < res->noutput; i++) {
if (x11->randr.outputs[i]->ncrtc == 0)
continue; /* Monitor disabled, already zero-ed by calloc */
if (x11->randr.outputs[i]->ncrtc != 1)
int x, y, width, height;
if (!get_monitor_info_for_output_index(x11, i, &x, &y, &width, &height)) {
syslog(LOG_WARNING, "Unable to get monitor info for output id %d", i);
goto error;
}
crtc = crtc_from_id(x11, x11->randr.outputs[i]->crtcs[0]);
if (!crtc)
goto error;
mode = mode_from_id(x11, crtc->mode);
if (!mode)
continue; /* Monitor disabled, already zero-ed by calloc */
mon_config->monitors[i].x = crtc->x;
mon_config->monitors[i].y = crtc->y;
mon_config->monitors[i].width = mode->width;
mon_config->monitors[i].height = mode->height;
VDAgentMonConfig *mon = &mon_config->monitors[i];
mon->x = x;
mon->y = y;
mon->width = width;
mon->height = height;
num_of_monitors = i + 1;
}
mon_config->num_of_monitors = num_of_monitors;
@@ -652,7 +764,7 @@ static VDAgentMonitorsConfig *get_current_mon_config(struct vdagent_x11 *x11)
error:
syslog(LOG_ERR, "error: inconsistent or stale data from X");
free(mon_config);
g_free(mon_config);
return NULL;
}
@@ -663,17 +775,58 @@ static void dump_monitors_config(struct vdagent_x11 *x11,
int i;
VDAgentMonConfig *m;
syslog(LOG_DEBUG, "%s: %d, %x", prefix, mon_config->num_of_monitors,
syslog(LOG_DEBUG, "Monitors config %s: %d, %x", prefix, mon_config->num_of_monitors,
mon_config->flags);
for (i = 0 ; i < mon_config->num_of_monitors; ++i) {
m = &mon_config->monitors[i];
if (!monitor_enabled(m))
continue;
syslog(LOG_DEBUG, "received monitor %d config %dx%d+%d+%d", i,
m->width, m->height, m->x, m->y);
syslog(LOG_DEBUG, " monitor %d, config %dx%d+%d+%d",
i, m->width, m->height, m->x, m->y);
}
}
// handle the device info message from the server. This will allow us to
// maintain a mapping from spice display id to xrandr output
void vdagent_x11_handle_device_display_info(struct vdagent_x11 *x11,
VDAgentDeviceDisplayInfo *device_display_info,
gboolean has_virtual_zero_display)
{
RROutput x_output;
if (lookup_xrandr_output_for_device_info(device_display_info, x11->display,
x11->randr.res, &x_output, has_virtual_zero_display)) {
syslog(LOG_INFO, "Adding graphics device info: channel_id: %u monitor_id: "
"%u device_address: %s, device_display_id: %u xrandr output ID: %lu",
device_display_info->channel_id,
device_display_info->monitor_id,
device_display_info->device_address,
device_display_info->device_display_id,
x_output);
g_hash_table_insert(x11->guest_output_map,
GUINT_TO_POINTER(device_display_info->channel_id + device_display_info->monitor_id),
(gpointer)x_output);
} else {
syslog(LOG_INFO, "channel_id: %u monitor_id: %u device_address: %s, "
"device_display_id: %u xrandr output ID NOT FOUND",
device_display_info->channel_id,
device_display_info->monitor_id,
device_display_info->device_address,
device_display_info->device_display_id);
}
}
static int get_output_index_for_display_id(struct vdagent_x11 *x11, int display_id)
{
RROutput oid = get_xrandr_output_for_display_id(x11, display_id);
for (int i = 0; i < x11->randr.res->noutput; i++) {
if (oid == x11->randr.res->outputs[i]) {
return i;
}
}
return -1;
}
/*
* Set monitor configuration according to client request.
*
@@ -688,8 +841,6 @@ void vdagent_x11_set_monitor_config(struct vdagent_x11 *x11,
VDAgentMonitorsConfig *mon_config,
int fallback)
{
int width, height;
int x, y;
int primary_w, primary_h;
int i, real_num_of_monitors = 0;
VDAgentMonitorsConfig *curr = NULL;
@@ -735,6 +886,8 @@ void vdagent_x11_set_monitor_config(struct vdagent_x11 *x11,
}
curr = get_current_mon_config(x11);
if (!curr)
goto exit;
if (same_monitor_configs(mon_config, curr) &&
x11->width[0] == primary_w && x11->height[0] == primary_h) {
goto exit;
@@ -745,12 +898,103 @@ void vdagent_x11_set_monitor_config(struct vdagent_x11 *x11,
goto exit;
}
for (i = mon_config->num_of_monitors; i < x11->randr.res->noutput; i++)
xrandr_disable_output(x11, i);
gchar *config = g_build_filename (g_get_user_config_dir (), "monitors.xml", NULL);
g_unlink(config);
g_free(config);
// disable all outputs that don't have associated entries in the MonitorConfig
for (i = 0; i < x11->randr.res->noutput; i++) {
bool disable = true;
// check if this xrandr output is represented by an item in mon_config
for (int j = 0; j < mon_config->num_of_monitors; j++) {
// j represents the display id of an enabled monitor. Check whether
// an enabled xrandr output is represented by this id.
RROutput oid = get_xrandr_output_for_display_id(x11, j);
if (oid == x11->randr.res->outputs[i]) {
disable = false;
}
}
if (disable) {
xrandr_disable_nth_output(x11, i);
}
}
/* disable CRTCs that are present but explicitly disabled in the
* MonitorConfig */
for (i = 0; i < mon_config->num_of_monitors; ++i) {
if (!monitor_enabled(&mon_config->monitors[i])) {
xrandr_disable_output(x11, i);
int output_index = get_output_index_for_display_id(x11, i);
if (output_index != -1) {
xrandr_disable_nth_output(x11, output_index);
} else {
syslog(LOG_WARNING, "Unable to find a guest output index for spice display %i", i);
}
}
}
/* ... and disable the ones that would be bigger than
* the new RandR screen once it is resized. If they are enabled the
* XRRSetScreenSize call will fail with BadMatch. They will be
* re-enabled after changing the screen size.
*/
for (i = 0; i < curr->num_of_monitors; ++i) {
int width, height;
int x, y;
width = curr->monitors[i].width;
height = curr->monitors[i].height;
x = curr->monitors[i].x;
y = curr->monitors[i].y;
if ((x + width > primary_w) || (y + height > primary_h)) {
if (x11->debug)
syslog(LOG_DEBUG, "Disabling monitor %d: %dx%d+%d+%d > (%d,%d)",
i, width, height, x, y, primary_w, primary_h);
int output_index = get_output_index_for_display_id(x11, i);
if (output_index != -1) {
xrandr_disable_nth_output(x11, output_index);
} else {
syslog(LOG_WARNING, "Unable to find a guest output index for spice display %i", i);
}
}
}
/* Then we can resize the RandR screen. */
if (primary_w != x11->width[0] || primary_h != x11->height[0]) {
const int dpi = 96; /* FIXME: read settings from desktop or get from client dpi? */
int width_mm = (MM_PER_INCH * primary_w) / dpi;
int height_mm = (MM_PER_INCH * primary_h) / dpi;
if (x11->debug)
syslog(LOG_DEBUG, "Changing screen size to %dx%d",
primary_w, primary_h);
vdagent_x11_set_error_handler(x11, ignore_error_handler);
XRRSetScreenSize(x11->display, x11->root_window[0], primary_w, primary_h,
width_mm, height_mm);
if (vdagent_x11_restore_error_handler(x11)) {
syslog(LOG_ERR, "XRRSetScreenSize failed, not enough mem?");
if (!fallback) {
syslog(LOG_WARNING, "Restoring previous config");
vdagent_x11_set_monitor_config(x11, curr, 1);
g_free(curr);
/* Remember this config failed, if the client is maximized or
fullscreen it will keep sending the failing config. */
g_free(x11->randr.failed_conf);
x11->randr.failed_conf =
g_memdup2(mon_config, config_size(mon_config->num_of_monitors));
return;
}
}
}
/* Finally, we set the new resolutions on RandR CRTCs now that the
* RandR screen is big enough to hold these. */
for (i = 0; i < mon_config->num_of_monitors; ++i) {
int width, height;
int x, y;
if (!monitor_enabled(&mon_config->monitors[i])) {
continue;
}
/* Try to create the requested resolution */
@@ -758,42 +1002,25 @@ void vdagent_x11_set_monitor_config(struct vdagent_x11 *x11,
height = mon_config->monitors[i].height;
x = mon_config->monitors[i].x;
y = mon_config->monitors[i].y;
if (!xrandr_add_and_set(x11, i, x, y, width, height) &&
if (x11->debug) {
syslog(LOG_DEBUG, "Setting resolution for monitor %d: %dx%d+%d+%d)",
i, width, height, x, y);
}
int output_index = get_output_index_for_display_id(x11, i);
if (output_index != -1) {
if (!xrandr_add_and_set(x11, output_index, x, y, width, height) &&
enabled_monitors(mon_config) == 1) {
set_screen_to_best_size(x11, width, height,
&primary_w, &primary_h);
goto update;
}
}
if (primary_w != x11->width[0] || primary_h != x11->height[0]) {
if (x11->debug)
syslog(LOG_DEBUG, "Changing screen size to %dx%d",
primary_w, primary_h);
vdagent_x11_set_error_handler(x11, error_handler);
XRRSetScreenSize(x11->display, x11->root_window[0], primary_w, primary_h,
DisplayWidthMM(x11->display, 0),
DisplayHeightMM(x11->display, 0));
if (vdagent_x11_restore_error_handler(x11)) {
syslog(LOG_ERR, "XRRSetScreenSize failed, not enough mem?");
if (!fallback && curr) {
syslog(LOG_WARNING, "Restoring previous config");
vdagent_x11_set_monitor_config(x11, curr, 1);
free(curr);
/* Remember this config failed, if the client is maximized or
fullscreen it will keep sending the failing config. */
free(x11->randr.failed_conf);
x11->randr.failed_conf =
malloc(config_size(mon_config->num_of_monitors));
if (x11->randr.failed_conf)
memcpy(x11->randr.failed_conf, mon_config,
config_size(mon_config->num_of_monitors));
return;
set_screen_to_best_size(x11, width, height,
&primary_w, &primary_h);
break;
}
} else {
syslog(LOG_WARNING, "Unable to find a guest output index for spice display %i", i);
}
}
update:
update_randr_res(x11,
x11->randr.num_monitors != enabled_monitors(mon_config));
x11->width[0] = primary_w;
@@ -805,99 +1032,133 @@ update:
x11->dont_send_guest_xorg_res = 0;
exit:
vdagent_x11_send_daemon_guest_xorg_res(x11, 0);
vdagent_display_send_daemon_guest_res(x11->vdagent_display, FALSE);
/* Flush output buffers and consume any pending events */
vdagent_x11_do_read(x11);
free(curr);
g_free(curr);
}
void vdagent_x11_send_daemon_guest_xorg_res(struct vdagent_x11 *x11, int update)
/**
* Builds a list of available monitors, associated with their resolutions.
*
* This function will use the x11->guest_output_map hashtable to map the SPICE display ID to the
* XRandr display ID, and make sure we get the right resolution for each SPICE display.
* See vdagent_x11_handle_device_display_info() for how this hashtable is populated.
*
* If the ID can't be matched (which happens when running under XWayland for instance), a default
* mapping is made, which assumes the list of X displays are in the same order as the SPICE displays.
* This will cause issues if some SPICE displays are not enabled (for instance: display 2 is
* enabled, but not display 1, causing a mismatch of IDs).
*
* Parameters:
* x11 - pointer to the X11 structure
* update - TRUE if the cached resolutions need to be updated before building the list
* width - full width of the desktop area (containing all the displays)
* height - full height of the desktop area (containing all the displays)
* system_screen_count - number of displays found on the system. In some situations, this may be
* different than the number of SPICE displays (for instance: multiple displays
* overlapping the same area of the desktop).
* Used for logging/troubleshooting purposes.
*
* Returns: a GArray of vdagentd_guest_xorg_resolution elements, to be sent to the vdagent daemon.
* NULL if an error occurs.
*/
GArray *vdagent_x11_get_resolutions(struct vdagent_x11 *x11, gboolean update,
int *width, int *height, int *system_screen_count)
{
struct vdagentd_guest_xorg_resolution *res = NULL;
int i, width = 0, height = 0, screen_count = 0;
GArray *res_array = g_array_new(FALSE, FALSE, sizeof(struct vdagentd_guest_xorg_resolution));
int i, screen_count = 0;
*width = *height = 0;
if (x11->has_xrandr) {
VDAgentMonitorsConfig *curr;
if (update)
update_randr_res(x11, 0);
curr = get_current_mon_config(x11);
if (!curr)
goto no_info;
screen_count = curr->num_of_monitors;
res = malloc(screen_count * sizeof(*res));
if (!res) {
free(curr);
goto no_mem;
}
screen_count = x11->randr.res->noutput;
for (i = 0; i < screen_count; i++) {
res[i].width = curr->monitors[i].width;
res[i].height = curr->monitors[i].height;
res[i].x = curr->monitors[i].x;
res[i].y = curr->monitors[i].y;
struct vdagentd_guest_xorg_resolution curr;
if (!get_monitor_info_for_output_index(x11, i, &curr.x, &curr.y,
&curr.width, &curr.height)) {
g_array_free(res_array, TRUE);
goto no_info;
}
if (g_hash_table_size(x11->guest_output_map) == 0) {
syslog(LOG_DEBUG, "No guest output map, using output index as display id");
curr.display_id = i;
g_array_append_val(res_array, curr);
} else {
// There may be multiple spice outputs representing a single guest output. Send them
// all down.
RROutput output_id = x11->randr.res->outputs[i];
GHashTableIter iter;
gpointer key, other_id;
g_hash_table_iter_init(&iter, x11->guest_output_map);
bool found = false;
while (g_hash_table_iter_next(&iter, &key, &other_id)) {
if ((RROutput)other_id == output_id) {
curr.display_id = GPOINTER_TO_INT(key);
g_array_append_val(res_array, curr);
found = true;
}
}
if (!found) {
syslog(LOG_WARNING, "Unable to find a display id for output index %d)", i);
}
}
}
free(curr);
width = x11->width[0];
height = x11->height[0];
*width = x11->width[0];
*height = x11->height[0];
} else if (x11->has_xinerama) {
XineramaScreenInfo *screen_info = NULL;
screen_info = XineramaQueryScreens(x11->display, &screen_count);
if (!screen_info)
goto no_info;
res = malloc(screen_count * sizeof(*res));
if (!res) {
XFree(screen_info);
goto no_mem;
}
g_array_set_size(res_array, screen_count);
for (i = 0; i < screen_count; i++) {
if (screen_info[i].screen_number >= screen_count) {
syslog(LOG_ERR, "Invalid screen number in xinerama screen info (%d >= %d)",
screen_info[i].screen_number, screen_count);
XFree(screen_info);
free(res);
return;
g_array_free(res_array, true);
return NULL;
}
res[screen_info[i].screen_number].width = screen_info[i].width;
res[screen_info[i].screen_number].height = screen_info[i].height;
res[screen_info[i].screen_number].x = screen_info[i].x_org;
res[screen_info[i].screen_number].y = screen_info[i].y_org;
struct vdagentd_guest_xorg_resolution *curr = &g_array_index(res_array,
struct vdagentd_guest_xorg_resolution,
screen_info[i].screen_number);
curr->width = screen_info[i].width;
curr->height = screen_info[i].height;
curr->x = screen_info[i].x_org;
curr->y = screen_info[i].y_org;
}
XFree(screen_info);
width = x11->width[0];
height = x11->height[0];
*width = x11->width[0];
*height = x11->height[0];
} else {
no_info:
screen_count = x11->screen_count;
res = malloc(screen_count * sizeof(*res));
if (!res)
goto no_mem;
for (i = 0; i < screen_count; i++) {
res[i].width = x11->width[i];
res[i].height = x11->height[i];
struct vdagentd_guest_xorg_resolution res;
res.width = x11->width[i];
res.height = x11->height[i];
/* No way to get screen coordinates, assume rtl order */
res[i].x = width;
res[i].y = 0;
width += x11->width[i];
if (x11->height[i] > height)
height = x11->height[i];
res.x = *width;
res.y = 0;
*width += x11->width[i];
if (x11->height[i] > *height) {
*height = x11->height[i];
}
g_array_append_val(res_array, res);
}
}
if (x11->debug) {
for (i = 0; i < screen_count; i++)
syslog(LOG_DEBUG, "Screen %d %dx%d%+d%+d", i, res[i].width,
res[i].height, res[i].x, res[i].y);
if (screen_count == 0) {
syslog(LOG_DEBUG, "Screen count is zero, are we on wayland?");
g_array_free(res_array, TRUE);
return NULL;
}
udscs_write(x11->vdagentd, VDAGENTD_GUEST_XORG_RESOLUTION, width, height,
(uint8_t *)res, screen_count * sizeof(*res));
free(res);
return;
no_mem:
syslog(LOG_ERR, "out of memory while trying to send resolutions, not sending resolutions.");
*system_screen_count = screen_count;
return res_array;
}
+296 -147
View File
@@ -23,15 +23,28 @@
X11 socket. If events have arrived and have already been read by libX11 from
the socket triggered by other libX11 calls from this file, the select for
read in the main loop, won't see these and our event loop won't get called!
Thus we must make sure that all queued events have been consumed, whenever
we return to the main loop. IOW all (externally callable) functions in this
file must end with calling XPending and consuming all queued events.
Calling XPending when-ever we return to the mainloop also ensures any
pending writes are flushed. */
#include <config.h>
#include <glib.h>
#ifdef WITH_GTK
#include <gdk/gdk.h>
#include <gtk/gtk.h> // for GTK_CHECK_VERSION
#ifdef GDK_WINDOWING_X11
#if GTK_CHECK_VERSION(3, 98, 0)
#include <gdk/x11/gdkx.h>
#else
#include <gdk/gdkx.h>
#endif
#endif
#endif
#include <stdlib.h>
#include <limits.h>
#include <string.h>
@@ -42,24 +55,26 @@
#include <X11/Xlib.h>
#include <X11/extensions/Xfixes.h>
#include "vdagentd-proto.h"
#include "vdagent-x11.h"
#include "vdagent-x11-priv.h"
#include "x11.h"
#include "x11-priv.h"
/* Stupid X11 API, there goes our encapsulate all data in a struct design */
int (*vdagent_x11_prev_error_handler)(Display *, XErrorEvent *);
int vdagent_x11_caught_error;
#ifndef USE_GTK_FOR_CLIPBOARD
static void vdagent_x11_handle_selection_notify(struct vdagent_x11 *x11,
XEvent *event, int incr);
const XEvent *event, int incr);
static void vdagent_x11_handle_selection_request(struct vdagent_x11 *x11);
static void vdagent_x11_handle_targets_notify(struct vdagent_x11 *x11,
XEvent *event);
const XEvent *event);
static void vdagent_x11_handle_property_delete_notify(struct vdagent_x11 *x11,
XEvent *del_event);
const XEvent *del_event);
static void vdagent_x11_send_selection_notify(struct vdagent_x11 *x11,
Atom prop, struct vdagent_x11_selection_request *request);
static void vdagent_x11_set_clipboard_owner(struct vdagent_x11 *x11,
uint8_t selection, int new_owner);
static void uris_ready_cb(GObject *source, GAsyncResult *res, gpointer user_data);
static const char *vdagent_x11_sel_to_str(uint8_t selection) {
switch (selection) {
@@ -73,6 +88,7 @@ static const char *vdagent_x11_sel_to_str(uint8_t selection) {
return "unknown";
}
}
#endif
static int vdagent_x11_debug_error_handler(
Display *display, XErrorEvent *error)
@@ -111,19 +127,20 @@ int vdagent_x11_restore_error_handler(struct vdagent_x11 *x11)
return error;
}
static void vdagent_x11_get_wm_name(struct vdagent_x11 *x11)
gchar *vdagent_x11_get_wm_name(struct vdagent_x11 *x11)
{
Atom type_ret;
int format_ret;
unsigned long len, remain;
unsigned char *data = NULL;
Window sup_window = None;
gchar *net_wm_name = NULL;
/* XGetWindowProperty can throw a BadWindow error. One way we can trigger
this is when the display-manager (ie gdm) has set, and not cleared the
_NET_SUPPORTING_WM_CHECK property, and the window manager running in
the user session has not yet updated it to point to its window, so its
pointing to a non existing window. */
pointing to a nonexistent window. */
vdagent_x11_set_error_handler(x11, vdagent_x11_ignore_bad_window_handler);
/* Get the window manager SUPPORTING_WM_CHECK window */
@@ -152,47 +169,54 @@ static void vdagent_x11_get_wm_name(struct vdagent_x11 *x11)
LONG_MAX, False, utf8, &type_ret, &format_ret, &len,
&remain, &data) == Success) {
if (type_ret == utf8) {
x11->net_wm_name =
g_strndup((char *)data, (format_ret / 8) * len);
net_wm_name = g_strndup((char *)data, (format_ret / 8) * len);
}
XFree(data);
}
if (x11->net_wm_name == NULL &&
if (net_wm_name == NULL &&
XGetWindowProperty(x11->display, sup_window,
XInternAtom(x11->display, "_NET_WM_NAME", False), 0,
LONG_MAX, False, XA_STRING, &type_ret, &format_ret, &len,
&remain, &data) == Success) {
if (type_ret == XA_STRING) {
x11->net_wm_name =
g_strndup((char *)data, (format_ret / 8) * len);
net_wm_name = g_strndup((char *)data, (format_ret / 8) * len);
}
XFree(data);
}
}
vdagent_x11_restore_error_handler(x11);
if (net_wm_name == NULL)
return g_strdup("unknown");
return net_wm_name;
}
struct vdagent_x11 *vdagent_x11_create(struct udscs_connection *vdagentd,
int debug, int sync)
struct vdagent_x11 *vdagent_x11_create(UdscsConnection *vdagentd,
int debug, int sync)
{
struct vdagent_x11 *x11;
XWindowAttributes attrib;
#ifdef USE_GTK_FOR_CLIPBOARD
int i;
#else
int i, j, major, minor;
#endif
x11 = calloc(1, sizeof(*x11));
if (!x11) {
syslog(LOG_ERR, "out of memory allocating vdagent_x11 struct");
return NULL;
}
x11 = g_new0(struct vdagent_x11, 1);
x11->vdagentd = vdagentd;
x11->debug = debug;
x11->guest_output_map = g_hash_table_new_full(&g_direct_hash,
&g_direct_equal,
NULL,
NULL);
x11->display = XOpenDisplay(NULL);
if (!x11->display) {
syslog(LOG_ERR, "could not connect to X-server");
free(x11);
g_free(x11);
return NULL;
}
@@ -201,7 +225,7 @@ struct vdagent_x11 *vdagent_x11_create(struct udscs_connection *vdagentd,
syslog(LOG_ERR, "Error too much screens: %d > %d",
x11->screen_count, MAX_SCREENS);
XCloseDisplay(x11->display);
free(x11);
g_free(x11);
return NULL;
}
@@ -212,12 +236,13 @@ struct vdagent_x11 *vdagent_x11_create(struct udscs_connection *vdagentd,
for (i = 0; i < x11->screen_count; i++)
x11->root_window[i] = RootWindow(x11->display, i);
x11->fd = ConnectionNumber(x11->display);
#ifndef USE_GTK_FOR_CLIPBOARD
x11->clipboard_atom = XInternAtom(x11->display, "CLIPBOARD", False);
x11->clipboard_primary_atom = XInternAtom(x11->display, "PRIMARY", False);
x11->targets_atom = XInternAtom(x11->display, "TARGETS", False);
x11->incr_atom = XInternAtom(x11->display, "INCR", False);
x11->multiple_atom = XInternAtom(x11->display, "MULTIPLE", False);
x11->timestamp_atom = XInternAtom(x11->display, "TIMESTAMP", False);
for(i = 0; i < clipboard_format_count; i++) {
x11->clipboard_formats[i].type = clipboard_format_templates[i].type;
for(j = 0; clipboard_format_templates[i].atom_names[j]; j++) {
@@ -234,12 +259,13 @@ struct vdagent_x11 *vdagent_x11_create(struct udscs_connection *vdagentd,
0, 0, 1, 1, 0, 0, 0);
if (x11->debug)
syslog(LOG_DEBUG, "Selection window: %u", (int)x11->selection_window);
#endif
vdagent_x11_randr_init(x11);
#ifndef USE_GTK_FOR_CLIPBOARD
if (XFixesQueryExtension(x11->display, &x11->xfixes_event_base, &i) &&
XFixesQueryVersion(x11->display, &major, &minor) && major >= 1) {
x11->has_xfixes = 1;
XFixesSelectSelectionInput(x11->display, x11->root_window[0],
x11->clipboard_atom,
XFixesSetSelectionOwnerNotifyMask|
@@ -263,6 +289,9 @@ struct vdagent_x11 *vdagent_x11_create(struct udscs_connection *vdagentd,
if (x11->max_prop_size > 262144)
x11->max_prop_size = 262144;
clipboard_webdav_init();
#endif
for (i = 0; i < x11->screen_count; i++) {
/* Catch resolution changes */
XSelectInput(x11->display, x11->root_window[i], StructureNotifyMask);
@@ -272,51 +301,45 @@ struct vdagent_x11 *vdagent_x11_create(struct udscs_connection *vdagentd,
x11->width[i] = attrib.width;
x11->height[i] = attrib.height;
}
vdagent_x11_send_daemon_guest_xorg_res(x11, 1);
/* Get net_wm_name, since we are started at the same time as the wm,
sometimes we need to wait a bit for it to show up. */
i = 10;
vdagent_x11_get_wm_name(x11);
while (x11->net_wm_name == NULL && --i > 0) {
usleep(100000);
vdagent_x11_get_wm_name(x11);
}
if (x11->debug && x11->net_wm_name)
syslog(LOG_DEBUG, "net_wm_name: \"%s\", has icons: %d",
x11->net_wm_name, vdagent_x11_has_icons_on_desktop(x11));
/* Flush output buffers and consume any pending events */
vdagent_x11_do_read(x11);
return x11;
}
void vdagent_x11_destroy(struct vdagent_x11 *x11, int vdagentd_disconnected)
{
uint8_t sel;
if (!x11)
return;
#ifndef USE_GTK_FOR_CLIPBOARD
if (vdagentd_disconnected)
x11->vdagentd = NULL;
uint8_t sel;
for (sel = 0; sel < VD_AGENT_CLIPBOARD_SELECTION_SECONDARY; ++sel) {
vdagent_x11_set_clipboard_owner(x11, sel, owner_none);
}
for (int i = 0; i < ATOM_NAME_CACHE_SIZE; i++) {
if (x11->atom_name_cache[i].name) {
XFree(x11->atom_name_cache[i].name);
}
}
clipboard_webdav_finalize();
#endif
g_hash_table_destroy(x11->guest_output_map);
XCloseDisplay(x11->display);
g_free(x11->net_wm_name);
free(x11->randr.failed_conf);
free(x11);
vdagent_x11_randr_destroy(x11);
g_free(x11);
}
int vdagent_x11_get_fd(struct vdagent_x11 *x11)
{
return x11->fd;
return ConnectionNumber(x11->display);
}
#ifndef USE_GTK_FOR_CLIPBOARD
static void vdagent_x11_next_selection_request(struct vdagent_x11 *x11)
{
struct vdagent_x11_selection_request *selection_request;
@@ -354,7 +377,7 @@ static void vdagent_x11_set_clipboard_owner(struct vdagent_x11 *x11,
once = 0;
}
vdagent_x11_send_selection_notify(x11, None, curr_sel);
if (curr_sel == x11->selection_req) {
if (prev_sel == NULL) {
x11->selection_req = next_sel;
free(x11->selection_req_data);
x11->selection_req_data = NULL;
@@ -385,7 +408,7 @@ static void vdagent_x11_set_clipboard_owner(struct vdagent_x11 *x11,
if (x11->vdagentd)
udscs_write(x11->vdagentd, VDAGENTD_CLIPBOARD_DATA, selection,
VD_AGENT_CLIPBOARD_NONE, NULL, 0);
if (curr_conv == x11->conversion_req) {
if (prev_conv == NULL) {
x11->conversion_req = next_conv;
x11->clipboard_data_size = 0;
x11->expect_property_notify = 0;
@@ -398,6 +421,9 @@ static void vdagent_x11_set_clipboard_owner(struct vdagent_x11 *x11,
}
}
x11->clipboard_has_files[selection] = False;
g_clear_pointer(&x11->file_list_data[selection], g_bytes_unref);
if (new_owner == owner_none) {
/* When going from owner_guest to owner_none we need to send a
clipboard release message to the client */
@@ -425,12 +451,13 @@ static int vdagent_x11_get_clipboard_atom(struct vdagent_x11 *x11, uint8_t selec
}
static int vdagent_x11_get_clipboard_selection(struct vdagent_x11 *x11,
XEvent *event, uint8_t *selection)
const XEvent *event, uint8_t *selection)
{
Atom atom;
if (event->type == x11->xfixes_event_base) {
XFixesSelectionNotifyEvent *xfev = (XFixesSelectionNotifyEvent *)event;
const XFixesSelectionNotifyEvent *xfev =
(const XFixesSelectionNotifyEvent *)event;
atom = xfev->selection;
} else if (event->type == SelectionNotify) {
atom = event->xselection.selection;
@@ -452,23 +479,25 @@ static int vdagent_x11_get_clipboard_selection(struct vdagent_x11 *x11,
return 0;
}
#endif
static void vdagent_x11_handle_event(struct vdagent_x11 *x11, XEvent event)
static void vdagent_x11_handle_event(struct vdagent_x11 *x11, const XEvent *event)
{
int i, handled = 0;
#ifndef USE_GTK_FOR_CLIPBOARD
uint8_t selection;
if (event.type == x11->xfixes_event_base) {
if (event->type == x11->xfixes_event_base) {
union {
XEvent ev;
XFixesSelectionNotifyEvent xfev;
} ev;
if (vdagent_x11_get_clipboard_selection(x11, &event, &selection)) {
if (vdagent_x11_get_clipboard_selection(x11, event, &selection)) {
return;
}
ev.ev = event;
ev.ev = *event;
switch (ev.xfev.subtype) {
case XFixesSetSelectionOwnerNotify:
break;
@@ -479,7 +508,7 @@ static void vdagent_x11_handle_event(struct vdagent_x11 *x11, XEvent event)
break;
default:
VSELPRINTF("unexpected xfix event subtype %d window %d",
(int)ev.xfev.subtype, (int)event.xany.window);
(int)ev.xfev.subtype, (int)event->xany.window);
return;
}
VSELPRINTF("New selection owner: %u", (unsigned int)ev.xfev.owner);
@@ -488,11 +517,10 @@ static void vdagent_x11_handle_event(struct vdagent_x11 *x11, XEvent event)
if (ev.xfev.owner == x11->selection_window)
return;
/* If the clipboard owner is changed we no longer own it */
vdagent_x11_set_clipboard_owner(x11, selection, owner_none);
if (ev.xfev.owner == None)
if (ev.xfev.owner == None) {
vdagent_x11_set_clipboard_owner(x11, selection, owner_none);
return;
}
/* Request the supported targets from the new owner */
XConvertSelection(x11->display, ev.xfev.selection, x11->targets_atom,
@@ -501,40 +529,44 @@ static void vdagent_x11_handle_event(struct vdagent_x11 *x11, XEvent event)
x11->expected_targets_notifies[selection]++;
return;
}
#endif
switch (event.type) {
if (vdagent_x11_randr_handle_event(x11, event))
return;
switch (event->type) {
case ConfigureNotify:
// TODO: handle CrtcConfigureNotify, OutputConfigureNotify can be ignored.
for (i = 0; i < x11->screen_count; i++)
if (event.xconfigure.window == x11->root_window[i])
if (event->xconfigure.window == x11->root_window[i])
break;
if (i == x11->screen_count)
break;
handled = 1;
vdagent_x11_randr_handle_root_size_change(x11, i,
event.xconfigure.width, event.xconfigure.height);
event->xconfigure.width, event->xconfigure.height);
break;
case MappingNotify:
/* These are uninteresting */
handled = 1;
break;
#ifndef USE_GTK_FOR_CLIPBOARD
case SelectionNotify:
if (event.xselection.target == x11->targets_atom)
vdagent_x11_handle_targets_notify(x11, &event);
if (event->xselection.target == x11->targets_atom)
vdagent_x11_handle_targets_notify(x11, event);
else
vdagent_x11_handle_selection_notify(x11, &event, 0);
vdagent_x11_handle_selection_notify(x11, event, 0);
handled = 1;
break;
case PropertyNotify:
if (x11->expect_property_notify &&
event.xproperty.state == PropertyNewValue) {
vdagent_x11_handle_selection_notify(x11, &event, 1);
event->xproperty.state == PropertyNewValue) {
vdagent_x11_handle_selection_notify(x11, event, 1);
}
if (x11->selection_req_data &&
event.xproperty.state == PropertyDelete) {
vdagent_x11_handle_property_delete_notify(x11, &event);
if (x11->selection_req_data &&
event->xproperty.state == PropertyDelete) {
vdagent_x11_handle_property_delete_notify(x11, event);
}
/* Always mark as handled, since we cannot unselect input for property
notifications once we are done with handling the incr transfer. */
@@ -548,7 +580,7 @@ static void vdagent_x11_handle_event(struct vdagent_x11 *x11, XEvent event)
case SelectionRequest: {
struct vdagent_x11_selection_request *req, *new_req;
if (vdagent_x11_get_clipboard_selection(x11, &event, &selection)) {
if (vdagent_x11_get_clipboard_selection(x11, event, &selection)) {
return;
}
@@ -560,7 +592,7 @@ static void vdagent_x11_handle_event(struct vdagent_x11 *x11, XEvent event)
handled = 1;
new_req->event = event;
new_req->event = *event;
new_req->selection = selection;
new_req->next = NULL;
@@ -578,10 +610,11 @@ static void vdagent_x11_handle_event(struct vdagent_x11 *x11, XEvent event)
req->next = new_req;
break;
}
#endif
}
if (!handled && x11->debug)
syslog(LOG_DEBUG, "unhandled x11 event, type %d, window %d",
(int)event.type, (int)event.xany.window);
(int)event->type, (int)event->xany.window);
}
void vdagent_x11_do_read(struct vdagent_x11 *x11)
@@ -590,19 +623,34 @@ void vdagent_x11_do_read(struct vdagent_x11 *x11)
while (XPending(x11->display)) {
XNextEvent(x11->display, &event);
vdagent_x11_handle_event(x11, event);
vdagent_x11_handle_event(x11, &event);
}
}
#ifndef USE_GTK_FOR_CLIPBOARD
static const char *vdagent_x11_get_atom_name(struct vdagent_x11 *x11, Atom a)
{
if (a == None)
return "None";
return XGetAtomName(x11->display, a);
for (int i = 0; i < ATOM_NAME_CACHE_SIZE; i++) {
if (x11->atom_name_cache[i].atom == a) {
return x11->atom_name_cache[i].name;
}
}
struct atom_name_cache_item *cch;
cch = &x11->atom_name_cache[x11->atom_name_cache_next];
if (cch->name) {
XFree(cch->name);
}
cch->atom = a;
cch->name = XGetAtomName(x11->display, a);
x11->atom_name_cache_next = (x11->atom_name_cache_next + 1) % ATOM_NAME_CACHE_SIZE;
return cch->name;
}
static int vdagent_x11_get_selection(struct vdagent_x11 *x11, XEvent *event,
static int vdagent_x11_get_selection(struct vdagent_x11 *x11, const XEvent *event,
uint8_t selection, Atom type, Atom prop, int format,
unsigned char **data_ret, int incr)
{
@@ -684,6 +732,7 @@ static int vdagent_x11_get_selection(struct vdagent_x11 *x11, XEvent *event,
len *= sizeof(short);
break;
case 32:
// on X11, a format of 32 is always a long
len *= sizeof(long);
break;
}
@@ -753,7 +802,18 @@ static uint32_t vdagent_x11_target_to_type(struct vdagent_x11 *x11,
int i, j;
for (i = 0; i < clipboard_format_count; i++) {
for (j = 0; j < x11->clipboard_formats[i].atom_count; i++) {
/* targets for VD_AGENT_CLIPBOARD_FILE_LIST overlap with the text targets */
if (x11->clipboard_has_files[selection]) {
if (x11->clipboard_formats[i].type == VD_AGENT_CLIPBOARD_UTF8_TEXT) {
continue;
}
} else {
if (x11->clipboard_formats[i].type == VD_AGENT_CLIPBOARD_FILE_LIST) {
continue;
}
}
for (j = 0; j < x11->clipboard_formats[i].atom_count; j++) {
if (x11->clipboard_formats[i].atoms[j] == target) {
return x11->clipboard_formats[i].type;
}
@@ -793,7 +853,7 @@ static void vdagent_x11_handle_conversion_request(struct vdagent_x11 *x11)
}
static void vdagent_x11_handle_selection_notify(struct vdagent_x11 *x11,
XEvent *event, int incr)
const XEvent *event, int incr)
{
int len = 0;
unsigned char *data = NULL;
@@ -878,7 +938,7 @@ static void vdagent_x11_print_targets(struct vdagent_x11 *x11,
}
static void vdagent_x11_handle_targets_notify(struct vdagent_x11 *x11,
XEvent *event)
const XEvent *event)
{
int i, len;
Atom atom, *atoms = NULL;
@@ -896,6 +956,12 @@ static void vdagent_x11_handle_targets_notify(struct vdagent_x11 *x11,
x11->expected_targets_notifies[selection]--;
if (x11->ignore_targets_notifies[selection] > 0) {
x11->ignore_targets_notifies[selection]--;
VSELPRINTF("ignoring selection notify TARGETS");
return;
}
/* If we have more targets_notifies pending, ignore this one, we
are only interested in the targets list of the current owner
(which is the last one we've requested a targets list from) */
@@ -916,6 +982,11 @@ static void vdagent_x11_handle_targets_notify(struct vdagent_x11 *x11,
type_count = &x11->clipboard_type_count[selection];
*type_count = 0;
for (i = 0; i < clipboard_format_count; i++) {
if (x11->clipboard_formats[i].type == VD_AGENT_CLIPBOARD_FILE_LIST) {
/* we don't support file copying in this direction yet */
continue;
}
atom = atom_lists_overlap(x11->clipboard_formats[i].atoms, atoms,
x11->clipboard_formats[i].atom_count, len);
if (atom) {
@@ -971,12 +1042,17 @@ static void vdagent_x11_send_selection_notify(struct vdagent_x11 *x11,
}
static void vdagent_x11_send_targets(struct vdagent_x11 *x11,
uint8_t selection, XEvent *event)
uint8_t selection, const XEvent *event)
{
Atom prop, targets[256] = { x11->targets_atom, };
int i, j, k, target_count = 1;
for (i = 0; i < x11->clipboard_type_count[selection]; i++) {
if (x11->clipboard_agent_types[selection][i] == VD_AGENT_CLIPBOARD_UTF8_TEXT &&
x11->clipboard_has_files[selection]) {
continue;
}
for (j = 0; j < clipboard_format_count; j++) {
if (x11->clipboard_formats[j].type !=
x11->clipboard_agent_types[selection][i])
@@ -1036,6 +1112,20 @@ static void vdagent_x11_handle_selection_request(struct vdagent_x11 *x11)
return;
}
if (event->xselectionrequest.target == x11->timestamp_atom) {
/* TODO: use more accurate selection time */
guint32 timestamp = event->xselectionrequest.time;
XChangeProperty(x11->display, event->xselectionrequest.requestor,
event->xselectionrequest.property,
event->xselectionrequest.target, 32, PropModeReplace,
(guint8*)&timestamp, 1);
vdagent_x11_send_selection_notify(x11,
event->xselectionrequest.property, NULL);
return;
}
if (event->xselectionrequest.target == x11->targets_atom) {
vdagent_x11_send_targets(x11, selection, event);
return;
@@ -1049,12 +1139,23 @@ static void vdagent_x11_handle_selection_request(struct vdagent_x11 *x11)
return;
}
if (type == VD_AGENT_CLIPBOARD_FILE_LIST && x11->file_list_data[selection]) {
VSELPRINTF("setting file list from cache");
clipboard_data_translate_to_uris_async(
vdagent_x11_get_atom_name(x11, event->xselectionrequest.target),
x11->file_list_data[selection],
NULL, uris_ready_cb, x11
);
return;
}
udscs_write(x11->vdagentd, VDAGENTD_CLIPBOARD_REQUEST, selection, type,
NULL, 0);
}
static void vdagent_x11_handle_property_delete_notify(struct vdagent_x11 *x11,
XEvent *del_event)
const XEvent *del_event)
{
XEvent *sel_event;
int len;
@@ -1094,7 +1195,7 @@ static void vdagent_x11_handle_property_delete_notify(struct vdagent_x11 *x11,
x11->selection_req_data_pos += len;
/* Note we must explictly send a 0 sized XChangeProperty to signal the
/* Note we must explicitly send a 0 sized XChangeProperty to signal the
incr transfer is done. Hence we do not check if we've send all data
but instead check we've send the final 0 sized XChangeProperty. */
if (len == 0) {
@@ -1183,6 +1284,104 @@ void vdagent_x11_clipboard_grab(struct vdagent_x11 *x11, uint8_t selection,
x11->selection_window, CurrentTime);
vdagent_x11_set_clipboard_owner(x11, selection, owner_client);
for (int i = 0; i < x11->clipboard_type_count[selection]; i++) {
if (x11->clipboard_agent_types[selection][i] == VD_AGENT_CLIPBOARD_FILE_LIST) {
x11->clipboard_has_files[selection] = True;
break;
}
}
/* If there're pending requests for targets, ignore the returned
* targets as the XSetSelectionOwner() call above made them invalid */
x11->ignore_targets_notifies[selection] =
x11->expected_targets_notifies[selection];
/* Flush output buffers and consume any pending events */
vdagent_x11_do_read(x11);
}
static void clipboard_data_send_to_requestor(struct vdagent_x11 *x11,
uint8_t selection, uint8_t *data, uint32_t size, Bool take_ownership)
{
XEvent *event;
Atom prop;
event = &x11->selection_req->event;
prop = event->xselectionrequest.property;
if (prop == None) {
prop = event->xselectionrequest.target;
}
if (size > x11->max_prop_size) {
unsigned long len = size;
VSELPRINTF("Starting incr send of clipboard data");
vdagent_x11_set_error_handler(x11, vdagent_x11_ignore_bad_window_handler);
XSelectInput(x11->display, event->xselectionrequest.requestor,
PropertyChangeMask);
XChangeProperty(x11->display, event->xselectionrequest.requestor, prop,
x11->incr_atom, 32, PropModeReplace,
(unsigned char*)&len, 1);
if (vdagent_x11_restore_error_handler(x11) == 0) {
if (take_ownership) {
x11->selection_req_data = data;
} else {
/* duplicate data */
x11->selection_req_data = malloc(size);
if (x11->selection_req_data == NULL) {
SELPRINTF("out of memory allocating selection buffer");
return;
}
memcpy(x11->selection_req_data, data, size);
}
x11->selection_req_data_pos = 0;
x11->selection_req_data_size = size;
x11->selection_req_atom = prop;
vdagent_x11_send_selection_notify(x11, prop, x11->selection_req);
} else {
SELPRINTF("clipboard data sent failed, requestor window gone");
}
} else {
vdagent_x11_set_error_handler(x11, vdagent_x11_ignore_bad_window_handler);
XChangeProperty(x11->display, event->xselectionrequest.requestor, prop,
event->xselectionrequest.target, 8, PropModeReplace,
data, size);
if (vdagent_x11_restore_error_handler(x11) == 0) {
vdagent_x11_send_selection_notify(x11, prop, NULL);
} else {
SELPRINTF("clipboard data sent failed, requestor window gone");
}
if (take_ownership) {
g_free(data);
}
}
}
static void uris_ready_cb(GObject *source, GAsyncResult *res, gpointer user_data)
{
struct vdagent_x11 *x11 = user_data;
GError *err = NULL;
size_t size;
char *uris = clipboard_data_translate_to_uris_finish(source, res, &size, &err);
if (g_error_matches(err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
g_error_free(err);
return;
}
if (!x11->selection_req) {
return;
}
uint8_t selection = x11->selection_req->selection;
if (err) {
SELPRINTF("failed to translate data to uris %s", err->message);
g_error_free(err);
}
clipboard_data_send_to_requestor(x11, selection, (uint8_t *)uris, size, True);
/* Flush output buffers and consume any pending events */
vdagent_x11_do_read(x11);
}
@@ -1190,7 +1389,6 @@ void vdagent_x11_clipboard_grab(struct vdagent_x11 *x11, uint8_t selection,
void vdagent_x11_clipboard_data(struct vdagent_x11 *x11, uint8_t selection,
uint32_t type, uint8_t *data, uint32_t size)
{
Atom prop;
XEvent *event;
uint32_t type_from_event;
@@ -1199,7 +1397,6 @@ void vdagent_x11_clipboard_data(struct vdagent_x11 *x11, uint8_t selection,
SELPRINTF("received clipboard data while still sending"
" data from previous request, ignoring");
}
free(data);
return;
}
@@ -1208,12 +1405,11 @@ void vdagent_x11_clipboard_data(struct vdagent_x11 *x11, uint8_t selection,
SELPRINTF("received clipboard data without an "
"outstanding selection request, ignoring");
}
free(data);
return;
}
event = &x11->selection_req->event;
type_from_event = vdagent_x11_target_to_type(x11,
type_from_event = vdagent_x11_target_to_type(x11,
x11->selection_req->selection,
event->xselectionrequest.target);
if (type_from_event != type ||
@@ -1227,48 +1423,23 @@ void vdagent_x11_clipboard_data(struct vdagent_x11 *x11, uint8_t selection,
type_from_event, type);
}
vdagent_x11_send_selection_notify(x11, None, NULL);
free(data);
/* Flush output buffers and consume any pending events */
vdagent_x11_do_read(x11);
return;
}
prop = event->xselectionrequest.property;
if (prop == None)
prop = event->xselectionrequest.target;
if (type == VD_AGENT_CLIPBOARD_FILE_LIST) {
g_clear_pointer(&x11->file_list_data[selection], g_bytes_unref);
x11->file_list_data[selection] = g_bytes_new(data, size);
if (size > x11->max_prop_size) {
unsigned long len = size;
VSELPRINTF("Starting incr send of clipboard data");
vdagent_x11_set_error_handler(x11, vdagent_x11_ignore_bad_window_handler);
XSelectInput(x11->display, event->xselectionrequest.requestor,
PropertyChangeMask);
XChangeProperty(x11->display, event->xselectionrequest.requestor, prop,
x11->incr_atom, 32, PropModeReplace,
(unsigned char*)&len, 1);
if (vdagent_x11_restore_error_handler(x11) == 0) {
x11->selection_req_data = data;
x11->selection_req_data_pos = 0;
x11->selection_req_data_size = size;
x11->selection_req_atom = prop;
vdagent_x11_send_selection_notify(x11, prop, x11->selection_req);
} else {
SELPRINTF("clipboard data sent failed, requestor window gone");
free(data);
}
clipboard_data_translate_to_uris_async(
vdagent_x11_get_atom_name(x11, event->xselectionrequest.target),
x11->file_list_data[selection], NULL, uris_ready_cb, x11
);
return;
} else {
vdagent_x11_set_error_handler(x11, vdagent_x11_ignore_bad_window_handler);
XChangeProperty(x11->display, event->xselectionrequest.requestor, prop,
event->xselectionrequest.target, 8, PropModeReplace,
data, size);
if (vdagent_x11_restore_error_handler(x11) == 0)
vdagent_x11_send_selection_notify(x11, prop, NULL);
else
SELPRINTF("clipboard data sent failed, requestor window gone");
free(data);
clipboard_data_send_to_requestor(x11, selection, data, size, False);
}
/* Flush output buffers and consume any pending events */
@@ -1296,7 +1467,7 @@ void vdagent_x11_clipboard_release(struct vdagent_x11 *x11, uint8_t selection)
XSync(x11->display, False);
while (XCheckTypedEvent(x11->display, x11->xfixes_event_base,
&event))
vdagent_x11_handle_event(x11, event);
vdagent_x11_handle_event(x11, &event);
/* Note no need to do a set_clipboard_owner(owner_none) here, as that is
already done by processing the XFixesSetSelectionOwnerNotify event. */
@@ -1314,26 +1485,4 @@ void vdagent_x11_client_disconnected(struct vdagent_x11 *x11)
vdagent_x11_clipboard_release(x11, sel);
}
}
/* Function used to determine the default location to save file-xfers,
xdg desktop dir or xdg download dir. We error on the save side and use a
whitelist approach, so any unknown desktops will end up with saving
file-xfers to the xdg download dir, and opening the xdg download dir with
xdg-open when the file-xfer completes. */
int vdagent_x11_has_icons_on_desktop(struct vdagent_x11 *x11)
{
const char * const wms_with_icons_on_desktop[] = {
"Metacity", /* GNOME-2 or GNOME-3 fallback */
"Xfwm4", /* XFCE */
"Marco", /* Mate */
NULL
};
int i;
if (x11->net_wm_name)
for (i = 0; wms_with_icons_on_desktop[i]; i++)
if (!strcmp(x11->net_wm_name, wms_with_icons_on_desktop[i]))
return 1;
return 0;
}
#endif
+13 -7
View File
@@ -1,18 +1,18 @@
/* vdagent-x11.h vdagent x11 code header file
/* x11.h vdagent x11 code header file
Copyright 2010 Red Hat, Inc.
Copyright 2010 - 2016 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
@@ -28,7 +28,7 @@
struct vdagent_x11;
struct vdagent_x11 *vdagent_x11_create(struct udscs_connection *vdagentd,
struct vdagent_x11 *vdagent_x11_create(UdscsConnection *vdagentd,
int debug, int sync);
void vdagent_x11_destroy(struct vdagent_x11 *x11, int vdagentd_disconnected);
@@ -38,6 +38,7 @@ void vdagent_x11_do_read(struct vdagent_x11 *x11);
void vdagent_x11_set_monitor_config(struct vdagent_x11 *x11,
VDAgentMonitorsConfig *mon_config, int fallback);
#ifndef USE_GTK_FOR_CLIPBOARD
void vdagent_x11_clipboard_grab(struct vdagent_x11 *x11, uint8_t selection,
uint32_t *types, uint32_t type_count);
void vdagent_x11_clipboard_request(struct vdagent_x11 *x11,
@@ -47,7 +48,12 @@ void vdagent_x11_clipboard_data(struct vdagent_x11 *x11, uint8_t selection,
void vdagent_x11_clipboard_release(struct vdagent_x11 *x11, uint8_t selection);
void vdagent_x11_client_disconnected(struct vdagent_x11 *x11);
#endif
int vdagent_x11_has_icons_on_desktop(struct vdagent_x11 *x11);
gchar *vdagent_x11_get_wm_name(struct vdagent_x11 *x11);
void vdagent_x11_handle_device_display_info(struct vdagent_x11 *x11,
VDAgentDeviceDisplayInfo *device_display_info,
gboolean has_virtual_zero_display);
#endif
+6 -3
View File
@@ -7,12 +7,12 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
@@ -30,10 +30,13 @@ static const char * const vdagentd_messages[] = {
"clipboard data",
"clipboard release",
"version",
"audio volume sync",
"file xfer start",
"file xfer status",
"file xfer data",
"file xfer disable",
"client disconnected",
"graphics device info",
};
#endif
+10 -4
View File
@@ -8,12 +8,12 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
@@ -23,7 +23,9 @@
#ifndef __VDAGENTD_PROTO_H
#define __VDAGENTD_PROTO_H
#define VDAGENTD_SOCKET "/var/run/spice-vdagentd/spice-vdagent-sock"
#define VDAGENTD_SOCKET "/run/spice-vdagentd/spice-vdagent-sock"
#define DEFAULT_VIRTIO_PORT_PATH "/dev/virtio-ports/com.redhat.spice.0"
enum {
VDAGENTD_GUEST_XORG_RESOLUTION, /* client -> daemon, arg1: overall width,
@@ -36,10 +38,13 @@ enum {
VDAGENTD_CLIPBOARD_DATA, /* arg1: sel, arg 2: type, data: data */
VDAGENTD_CLIPBOARD_RELEASE, /* arg1: selection */
VDAGENTD_VERSION, /* daemon -> client, data: version string */
VDAGENTD_AUDIO_VOLUME_SYNC,
VDAGENTD_FILE_XFER_START,
VDAGENTD_FILE_XFER_STATUS,
VDAGENTD_FILE_XFER_DATA,
VDAGENTD_FILE_XFER_DISABLE,
VDAGENTD_CLIENT_DISCONNECTED, /* daemon -> client */
VDAGENTD_GRAPHICS_DEVICE_INFO, /* daemon -> client */
VDAGENTD_NO_MESSAGES /* Must always be last */
};
@@ -48,6 +53,7 @@ struct vdagentd_guest_xorg_resolution {
int height;
int x;
int y;
int display_id;
};
#endif
-940
View File
@@ -1,940 +0,0 @@
/* vdagentd.c vdagentd (daemon) code
Copyright 2010-2013 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
Gerd Hoffmann <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <syslog.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <spice/vd_agent.h>
#include <glib.h>
#include "udscs.h"
#include "vdagentd-proto.h"
#include "vdagentd-proto-strings.h"
#include "vdagentd-uinput.h"
#include "vdagentd-xorg-conf.h"
#include "vdagent-virtio-port.h"
#include "session-info.h"
struct agent_data {
char *session;
int width;
int height;
struct vdagentd_guest_xorg_resolution *screen_info;
int screen_count;
};
/* variables */
static const char *pidfilename = "/var/run/spice-vdagentd/spice-vdagentd.pid";
static const char *portdev = "/dev/virtio-ports/com.redhat.spice.0";
static const char *vdagentd_socket = VDAGENTD_SOCKET;
static const char *uinput_device = "/dev/uinput";
static int debug = 0;
static int uinput_fake = 0;
static struct udscs_server *server = NULL;
static struct vdagent_virtio_port *virtio_port = NULL;
static GHashTable *active_xfers = NULL;
static struct session_info *session_info = NULL;
static struct vdagentd_uinput *uinput = NULL;
static VDAgentMonitorsConfig *mon_config = NULL;
static uint32_t *capabilities = NULL;
static int capabilities_size = 0;
static const char *active_session = NULL;
static unsigned int session_count = 0;
static struct udscs_connection *active_session_conn = NULL;
static int agent_owns_clipboard[256] = { 0, };
static int quit = 0;
static int retval = 0;
static int client_connected = 0;
/* utility functions */
/* vdagentd <-> spice-client communication handling */
static void send_capabilities(struct vdagent_virtio_port *vport,
uint32_t request)
{
VDAgentAnnounceCapabilities *caps;
uint32_t size;
size = sizeof(*caps) + VD_AGENT_CAPS_BYTES;
caps = calloc(1, size);
if (!caps) {
syslog(LOG_ERR, "out of memory allocating capabilities array (write)");
return;
}
caps->request = request;
VD_AGENT_SET_CAPABILITY(caps->caps, VD_AGENT_CAP_MOUSE_STATE);
VD_AGENT_SET_CAPABILITY(caps->caps, VD_AGENT_CAP_MONITORS_CONFIG);
VD_AGENT_SET_CAPABILITY(caps->caps, VD_AGENT_CAP_REPLY);
VD_AGENT_SET_CAPABILITY(caps->caps, VD_AGENT_CAP_CLIPBOARD_BY_DEMAND);
VD_AGENT_SET_CAPABILITY(caps->caps, VD_AGENT_CAP_CLIPBOARD_SELECTION);
VD_AGENT_SET_CAPABILITY(caps->caps, VD_AGENT_CAP_SPARSE_MONITORS_CONFIG);
VD_AGENT_SET_CAPABILITY(caps->caps, VD_AGENT_CAP_GUEST_LINEEND_LF);
vdagent_virtio_port_write(vport, VDP_CLIENT_PORT,
VD_AGENT_ANNOUNCE_CAPABILITIES, 0,
(uint8_t *)caps, size);
free(caps);
}
static void do_client_disconnect(void)
{
if (client_connected) {
udscs_server_write_all(server, VDAGENTD_CLIENT_DISCONNECTED, 0, 0,
NULL, 0);
client_connected = 0;
}
}
static void do_client_monitors(struct vdagent_virtio_port *vport, int port_nr,
VDAgentMessage *message_header, VDAgentMonitorsConfig *new_monitors)
{
VDAgentReply reply;
uint32_t size;
/* Store monitor config to send to agents when they connect */
size = sizeof(VDAgentMonitorsConfig) +
new_monitors->num_of_monitors * sizeof(VDAgentMonConfig);
if (message_header->size != size) {
syslog(LOG_ERR, "invalid message size for VDAgentMonitorsConfig");
return;
}
vdagentd_write_xorg_conf(new_monitors);
if (!mon_config ||
mon_config->num_of_monitors != new_monitors->num_of_monitors) {
free(mon_config);
mon_config = malloc(size);
if (!mon_config) {
syslog(LOG_ERR, "out of memory allocating monitors config");
return;
}
}
memcpy(mon_config, new_monitors, size);
/* Send monitor config to currently active agent */
if (active_session_conn)
udscs_write(active_session_conn, VDAGENTD_MONITORS_CONFIG, 0, 0,
(uint8_t *)mon_config, size);
/* Acknowledge reception of monitors config to spice server / client */
reply.type = VD_AGENT_MONITORS_CONFIG;
reply.error = VD_AGENT_SUCCESS;
vdagent_virtio_port_write(vport, port_nr, VD_AGENT_REPLY, 0,
(uint8_t *)&reply, sizeof(reply));
}
static void do_client_capabilities(struct vdagent_virtio_port *vport,
VDAgentMessage *message_header,
VDAgentAnnounceCapabilities *caps)
{
int new_size = VD_AGENT_CAPS_SIZE_FROM_MSG_SIZE(message_header->size);
if (capabilities_size != new_size) {
capabilities_size = new_size;
free(capabilities);
capabilities = malloc(capabilities_size * sizeof(uint32_t));
if (!capabilities) {
syslog(LOG_ERR, "oom allocating capabilities array (read)");
capabilities_size = 0;
return;
}
}
memcpy(capabilities, caps->caps, capabilities_size * sizeof(uint32_t));
if (caps->request) {
/* Report the previous client has disconneced. */
do_client_disconnect();
if (debug)
syslog(LOG_DEBUG, "New client connected");
client_connected = 1;
send_capabilities(vport, 0);
}
}
static void do_client_clipboard(struct vdagent_virtio_port *vport,
VDAgentMessage *message_header, uint8_t *data)
{
uint32_t msg_type = 0, data_type = 0, size = message_header->size;
uint8_t selection = VD_AGENT_CLIPBOARD_SELECTION_CLIPBOARD;
if (!active_session_conn) {
syslog(LOG_WARNING,
"Could not find an agent connection belonging to the "
"active session, ignoring client clipboard request");
return;
}
if (VD_AGENT_HAS_CAPABILITY(capabilities, capabilities_size,
VD_AGENT_CAP_CLIPBOARD_SELECTION)) {
selection = data[0];
data += 4;
size -= 4;
}
switch (message_header->type) {
case VD_AGENT_CLIPBOARD_GRAB:
msg_type = VDAGENTD_CLIPBOARD_GRAB;
agent_owns_clipboard[selection] = 0;
break;
case VD_AGENT_CLIPBOARD_REQUEST: {
VDAgentClipboardRequest *req = (VDAgentClipboardRequest *)data;
msg_type = VDAGENTD_CLIPBOARD_REQUEST;
data_type = req->type;
data = NULL;
size = 0;
break;
}
case VD_AGENT_CLIPBOARD: {
VDAgentClipboard *clipboard = (VDAgentClipboard *)data;
msg_type = VDAGENTD_CLIPBOARD_DATA;
data_type = clipboard->type;
size = size - sizeof(VDAgentClipboard);
data = clipboard->data;
break;
}
case VD_AGENT_CLIPBOARD_RELEASE:
msg_type = VDAGENTD_CLIPBOARD_RELEASE;
data = NULL;
size = 0;
break;
}
udscs_write(active_session_conn, msg_type, selection, data_type,
data, size);
}
static void cancel_file_xfer(struct vdagent_virtio_port *vport,
const char *msg, uint32_t id)
{
VDAgentFileXferStatusMessage status = {
.id = id,
.result = VD_AGENT_FILE_XFER_STATUS_CANCELLED,
};
syslog(LOG_WARNING, msg, id);
if (vport)
vdagent_virtio_port_write(vport, VDP_CLIENT_PORT,
VD_AGENT_FILE_XFER_STATUS, 0,
(uint8_t *)&status, sizeof(status));
}
static void do_client_file_xfer(struct vdagent_virtio_port *vport,
VDAgentMessage *message_header,
uint8_t *data)
{
uint32_t msg_type, id;
struct udscs_connection *conn;
switch (message_header->type) {
case VD_AGENT_FILE_XFER_START: {
VDAgentFileXferStartMessage *s = (VDAgentFileXferStartMessage *)data;
if (!active_session_conn) {
cancel_file_xfer(vport,
"Could not find an agent connnection belonging to the "
"active session, cancelling client file-xfer request %u",
s->id);
return;
}
udscs_write(active_session_conn, VDAGENTD_FILE_XFER_START, 0, 0,
data, message_header->size);
return;
}
case VD_AGENT_FILE_XFER_STATUS: {
VDAgentFileXferStatusMessage *s = (VDAgentFileXferStatusMessage *)data;
msg_type = VDAGENTD_FILE_XFER_STATUS;
id = s->id;
break;
}
case VD_AGENT_FILE_XFER_DATA: {
VDAgentFileXferDataMessage *d = (VDAgentFileXferDataMessage *)data;
msg_type = VDAGENTD_FILE_XFER_DATA;
id = d->id;
break;
}
}
conn = g_hash_table_lookup(active_xfers, GUINT_TO_POINTER(id));
if (!conn) {
if (debug)
syslog(LOG_DEBUG, "Could not find file-xfer %u (cancelled?)", id);
return;
}
udscs_write(conn, msg_type, 0, 0, data, message_header->size);
}
int virtio_port_read_complete(
struct vdagent_virtio_port *vport,
int port_nr,
VDAgentMessage *message_header,
uint8_t *data)
{
uint32_t min_size = 0;
if (message_header->protocol != VD_AGENT_PROTOCOL) {
syslog(LOG_ERR, "message with wrong protocol version ignoring");
return 0;
}
switch (message_header->type) {
case VD_AGENT_MOUSE_STATE:
if (message_header->size != sizeof(VDAgentMouseState))
goto size_error;
vdagentd_uinput_do_mouse(&uinput, (VDAgentMouseState *)data);
if (!uinput) {
/* Try to re-open the tablet */
struct agent_data *agent_data =
udscs_get_user_data(active_session_conn);
if (agent_data)
uinput = vdagentd_uinput_create(uinput_device,
agent_data->width,
agent_data->height,
agent_data->screen_info,
agent_data->screen_count,
debug > 1,
uinput_fake);
if (!uinput) {
syslog(LOG_CRIT, "Fatal uinput error");
retval = 1;
quit = 1;
}
}
break;
case VD_AGENT_MONITORS_CONFIG:
if (message_header->size < sizeof(VDAgentMonitorsConfig))
goto size_error;
do_client_monitors(vport, port_nr, message_header,
(VDAgentMonitorsConfig *)data);
break;
case VD_AGENT_ANNOUNCE_CAPABILITIES:
if (message_header->size < sizeof(VDAgentAnnounceCapabilities))
goto size_error;
do_client_capabilities(vport, message_header,
(VDAgentAnnounceCapabilities *)data);
break;
case VD_AGENT_CLIPBOARD_GRAB:
case VD_AGENT_CLIPBOARD_REQUEST:
case VD_AGENT_CLIPBOARD:
case VD_AGENT_CLIPBOARD_RELEASE:
switch (message_header->type) {
case VD_AGENT_CLIPBOARD_GRAB:
min_size = sizeof(VDAgentClipboardGrab); break;
case VD_AGENT_CLIPBOARD_REQUEST:
min_size = sizeof(VDAgentClipboardRequest); break;
case VD_AGENT_CLIPBOARD:
min_size = sizeof(VDAgentClipboard); break;
}
if (VD_AGENT_HAS_CAPABILITY(capabilities, capabilities_size,
VD_AGENT_CAP_CLIPBOARD_SELECTION)) {
min_size += 4;
}
if (message_header->size < min_size) {
goto size_error;
}
do_client_clipboard(vport, message_header, data);
break;
case VD_AGENT_FILE_XFER_START:
case VD_AGENT_FILE_XFER_STATUS:
case VD_AGENT_FILE_XFER_DATA:
do_client_file_xfer(vport, message_header, data);
break;
case VD_AGENT_CLIENT_DISCONNECTED:
vdagent_virtio_port_reset(vport, VDP_CLIENT_PORT);
do_client_disconnect();
break;
default:
syslog(LOG_WARNING, "unknown message type %d, ignoring",
message_header->type);
}
return 0;
size_error:
syslog(LOG_ERR, "read: invalid message size: %u for message type: %u",
message_header->size, message_header->type);
return 0;
}
/* vdagentd <-> vdagent communication handling */
int do_agent_clipboard(struct udscs_connection *conn,
struct udscs_message_header *header, const uint8_t *data)
{
uint8_t selection = header->arg1;
uint32_t msg_type = 0, data_type = -1, size = header->size;
if (!VD_AGENT_HAS_CAPABILITY(capabilities, capabilities_size,
VD_AGENT_CAP_CLIPBOARD_BY_DEMAND))
goto error;
/* Check that this agent is from the currently active session */
if (conn != active_session_conn) {
if (debug)
syslog(LOG_DEBUG, "%p clipboard req from agent which is not in "
"the active session?", conn);
goto error;
}
if (!virtio_port) {
syslog(LOG_ERR, "Clipboard req from agent but no client connection");
goto error;
}
if (!VD_AGENT_HAS_CAPABILITY(capabilities, capabilities_size,
VD_AGENT_CAP_CLIPBOARD_SELECTION) &&
selection != VD_AGENT_CLIPBOARD_SELECTION_CLIPBOARD) {
goto error;
}
switch (header->type) {
case VDAGENTD_CLIPBOARD_GRAB:
msg_type = VD_AGENT_CLIPBOARD_GRAB;
agent_owns_clipboard[selection] = 1;
break;
case VDAGENTD_CLIPBOARD_REQUEST:
msg_type = VD_AGENT_CLIPBOARD_REQUEST;
data_type = header->arg2;
size = 0;
break;
case VDAGENTD_CLIPBOARD_DATA:
msg_type = VD_AGENT_CLIPBOARD;
data_type = header->arg2;
break;
case VDAGENTD_CLIPBOARD_RELEASE:
msg_type = VD_AGENT_CLIPBOARD_RELEASE;
size = 0;
agent_owns_clipboard[selection] = 0;
break;
}
if (size != header->size) {
syslog(LOG_ERR,
"unexpected extra data in clipboard msg, disconnecting agent");
return -1;
}
if (VD_AGENT_HAS_CAPABILITY(capabilities, capabilities_size,
VD_AGENT_CAP_CLIPBOARD_SELECTION)) {
size += 4;
}
if (data_type != -1) {
size += 4;
}
vdagent_virtio_port_write_start(virtio_port, VDP_CLIENT_PORT, msg_type,
0, size);
if (VD_AGENT_HAS_CAPABILITY(capabilities, capabilities_size,
VD_AGENT_CAP_CLIPBOARD_SELECTION)) {
uint8_t sel[4] = { selection, 0, 0, 0 };
vdagent_virtio_port_write_append(virtio_port, sel, 4);
}
if (data_type != -1) {
vdagent_virtio_port_write_append(virtio_port, (uint8_t*)&data_type, 4);
}
vdagent_virtio_port_write_append(virtio_port, data, header->size);
return 0;
error:
if (header->type == VDAGENTD_CLIPBOARD_REQUEST) {
/* Let the agent know no answer is coming */
udscs_write(conn, VDAGENTD_CLIPBOARD_DATA,
selection, VD_AGENT_CLIPBOARD_NONE, NULL, 0);
}
return 0;
}
/* When we open the vdagent virtio channel, the server automatically goes into
client mouse mode, so we can only have the channel open when we know the
active session resolution. This function checks that we have an agent in the
active session, and that it has told us its resolution. If these conditions
are met it sets the uinput tablet device's resolution and opens the virtio
channel (if it is not already open). If these conditions are not met, it
closes both. */
static void check_xorg_resolution(void)
{
struct agent_data *agent_data = udscs_get_user_data(active_session_conn);
if (agent_data && agent_data->screen_info) {
if (!uinput)
uinput = vdagentd_uinput_create(uinput_device,
agent_data->width,
agent_data->height,
agent_data->screen_info,
agent_data->screen_count,
debug > 1,
uinput_fake);
else
vdagentd_uinput_update_size(&uinput,
agent_data->width,
agent_data->height,
agent_data->screen_info,
agent_data->screen_count);
if (!uinput) {
syslog(LOG_CRIT, "Fatal uinput error");
retval = 1;
quit = 1;
return;
}
if (!virtio_port) {
syslog(LOG_INFO, "opening vdagent virtio channel");
virtio_port = vdagent_virtio_port_create(portdev,
virtio_port_read_complete,
NULL);
if (!virtio_port) {
syslog(LOG_CRIT, "Fatal error opening vdagent virtio channel");
retval = 1;
quit = 1;
return;
}
send_capabilities(virtio_port, 1);
}
} else {
#ifndef WITH_STATIC_UINPUT
vdagentd_uinput_destroy(&uinput);
#endif
if (virtio_port) {
vdagent_virtio_port_flush(&virtio_port);
vdagent_virtio_port_destroy(&virtio_port);
syslog(LOG_INFO, "closed vdagent virtio channel");
}
}
}
static int connection_matches_active_session(struct udscs_connection **connp,
void *priv)
{
struct udscs_connection **conn_ret = (struct udscs_connection **)priv;
struct agent_data *agent_data = udscs_get_user_data(*connp);
/* Check if this connection matches the currently active session */
if (!agent_data->session || !active_session)
return 0;
if (strcmp(agent_data->session, active_session))
return 0;
*conn_ret = *connp;
return 1;
}
void release_clipboards(void)
{
uint8_t sel;
for (sel = 0; sel < VD_AGENT_CLIPBOARD_SELECTION_SECONDARY; ++sel) {
if (agent_owns_clipboard[sel] && virtio_port) {
vdagent_virtio_port_write(virtio_port, VDP_CLIENT_PORT,
VD_AGENT_CLIPBOARD_RELEASE, 0, &sel, 1);
}
agent_owns_clipboard[sel] = 0;
}
}
void update_active_session_connection(struct udscs_connection *new_conn)
{
if (session_info) {
new_conn = NULL;
if (!active_session)
active_session = session_info_get_active_session(session_info);
session_count = udscs_server_for_all_clients(server,
connection_matches_active_session,
(void*)&new_conn);
} else {
if (new_conn)
session_count++;
else
session_count--;
}
if (new_conn && session_count != 1) {
syslog(LOG_ERR, "multiple agents in one session, "
"disabling agent to avoid potential information leak");
new_conn = NULL;
}
if (new_conn == active_session_conn)
return;
active_session_conn = new_conn;
if (debug)
syslog(LOG_DEBUG, "%p is now the active session", new_conn);
if (active_session_conn && mon_config)
udscs_write(active_session_conn, VDAGENTD_MONITORS_CONFIG, 0, 0,
(uint8_t *)mon_config, sizeof(VDAgentMonitorsConfig) +
mon_config->num_of_monitors * sizeof(VDAgentMonConfig));
release_clipboards();
check_xorg_resolution();
}
gboolean remove_active_xfers(gpointer key, gpointer value, gpointer conn)
{
if (value == conn) {
cancel_file_xfer(virtio_port, "Agent disc; cancelling file-xfer %u",
GPOINTER_TO_UINT(key));
return 1;
} else
return 0;
}
void agent_connect(struct udscs_connection *conn)
{
struct agent_data *agent_data;
agent_data = calloc(1, sizeof(*agent_data));
if (!agent_data) {
syslog(LOG_ERR, "Out of memory allocating agent data, disconnecting");
udscs_destroy_connection(&conn);
return;
}
if (session_info) {
uint32_t pid = udscs_get_peer_cred(conn).pid;
agent_data->session = session_info_session_for_pid(session_info, pid);
}
udscs_set_user_data(conn, (void *)agent_data);
udscs_write(conn, VDAGENTD_VERSION, 0, 0,
(uint8_t *)VERSION, strlen(VERSION) + 1);
update_active_session_connection(conn);
}
void agent_disconnect(struct udscs_connection *conn)
{
struct agent_data *agent_data = udscs_get_user_data(conn);
g_hash_table_foreach_remove(active_xfers, remove_active_xfers, conn);
free(agent_data->session);
agent_data->session = NULL;
update_active_session_connection(NULL);
free(agent_data);
}
void agent_read_complete(struct udscs_connection **connp,
struct udscs_message_header *header, uint8_t *data)
{
struct agent_data *agent_data = udscs_get_user_data(*connp);
switch (header->type) {
case VDAGENTD_GUEST_XORG_RESOLUTION: {
struct vdagentd_guest_xorg_resolution *res;
int n = header->size / sizeof(*res);
/* Detect older version session agent, but don't disconnect, as
that stops it from getting the VDAGENTD_VERSION message, and then
it will never re-exec the new version... */
if (header->arg1 == 0 && header->arg2 == 0) {
syslog(LOG_INFO, "got old session agent xorg resolution message, "
"ignoring");
free(data);
return;
}
if (header->size != n * sizeof(*res)) {
syslog(LOG_ERR, "guest xorg resolution message has wrong size, "
"disconnecting agent");
udscs_destroy_connection(connp);
free(data);
return;
}
free(agent_data->screen_info);
res = malloc(n * sizeof(*res));
if (!res) {
syslog(LOG_ERR, "out of memory allocating screen info");
n = 0;
}
memcpy(res, data, n * sizeof(*res));
agent_data->width = header->arg1;
agent_data->height = header->arg2;
agent_data->screen_info = res;
agent_data->screen_count = n;
check_xorg_resolution();
break;
}
case VDAGENTD_CLIPBOARD_GRAB:
case VDAGENTD_CLIPBOARD_REQUEST:
case VDAGENTD_CLIPBOARD_DATA:
case VDAGENTD_CLIPBOARD_RELEASE:
if (do_agent_clipboard(*connp, header, data)) {
udscs_destroy_connection(connp);
free(data);
return;
}
break;
case VDAGENTD_FILE_XFER_STATUS:{
VDAgentFileXferStatusMessage status;
status.id = header->arg1;
status.result = header->arg2;
vdagent_virtio_port_write(virtio_port, VDP_CLIENT_PORT,
VD_AGENT_FILE_XFER_STATUS, 0,
(uint8_t *)&status, sizeof(status));
if (status.result == VD_AGENT_FILE_XFER_STATUS_CAN_SEND_DATA)
g_hash_table_insert(active_xfers, GUINT_TO_POINTER(status.id),
*connp);
else
g_hash_table_remove(active_xfers, GUINT_TO_POINTER(status.id));
break;
}
default:
syslog(LOG_ERR, "unknown message from vdagent: %u, ignoring",
header->type);
}
free(data);
}
/* main */
static void usage(FILE *fp)
{
fprintf(fp,
"Usage: spice-vdagentd [OPTIONS]\n\n"
"Spice guest agent daemon, version %s.\n\n"
"Options:\n"
" -h print this text\n"
" -d log debug messages (use twice for extra info)\n"
" -s <port> set virtio serial port [%s]\n"
" -S <filename> set udcs socket [%s]\n"
" -u <dev> set uinput device [%s]\n"
" -x don't daemonize\n"
#ifdef HAVE_CONSOLE_KIT
" -X Disable console kit integration\n"
#endif
#ifdef HAVE_LIBSYSTEMD_LOGIN
" -X Disable systemd-logind integration\n"
#endif
,VERSION, portdev, vdagentd_socket, uinput_device);
}
void daemonize(void)
{
int x;
FILE *pidfile;
/* detach from terminal */
switch (fork()) {
case 0:
close(0); close(1); close(2);
setsid();
x = open("/dev/null", O_RDWR); x = dup(x); x = dup(x);
pidfile = fopen(pidfilename, "w");
if (pidfile) {
fprintf(pidfile, "%d\n", (int)getpid());
fclose(pidfile);
}
break;
case -1:
syslog(LOG_ERR, "fork: %m");
retval = 1;
default:
udscs_destroy_server(server);
exit(retval);
}
}
void main_loop(void)
{
fd_set readfds, writefds;
int n, nfds;
int ck_fd = 0;
while (!quit) {
FD_ZERO(&readfds);
FD_ZERO(&writefds);
nfds = udscs_server_fill_fds(server, &readfds, &writefds);
n = vdagent_virtio_port_fill_fds(virtio_port, &readfds, &writefds);
if (n >= nfds)
nfds = n + 1;
if (session_info) {
ck_fd = session_info_get_fd(session_info);
FD_SET(ck_fd, &readfds);
if (ck_fd >= nfds)
nfds = ck_fd + 1;
}
n = select(nfds, &readfds, &writefds, NULL, NULL);
if (n == -1) {
if (errno == EINTR)
continue;
syslog(LOG_CRIT, "Fatal error select: %m");
retval = 1;
break;
}
udscs_server_handle_fds(server, &readfds, &writefds);
if (virtio_port) {
vdagent_virtio_port_handle_fds(&virtio_port, &readfds, &writefds);
if (!virtio_port) {
int old_client_connected = client_connected;
syslog(LOG_CRIT,
"AIIEEE lost spice client connection, reconnecting");
virtio_port = vdagent_virtio_port_create(portdev,
virtio_port_read_complete,
NULL);
if (!virtio_port) {
syslog(LOG_CRIT,
"Fatal error opening vdagent virtio channel");
retval = 1;
break;
}
do_client_disconnect();
client_connected = old_client_connected;
}
}
if (session_info && FD_ISSET(ck_fd, &readfds)) {
active_session = session_info_get_active_session(session_info);
update_active_session_connection(NULL);
}
}
}
static void quit_handler(int sig)
{
quit = 1;
}
int main(int argc, char *argv[])
{
int c;
int do_daemonize = 1;
int want_session_info = 1;
struct sigaction act;
for (;;) {
if (-1 == (c = getopt(argc, argv, "-dhxXs:u:S:")))
break;
switch (c) {
case 'd':
debug++;
break;
case 's':
portdev = optarg;
break;
case 'S':
vdagentd_socket = optarg;
break;
case 'u':
uinput_device = optarg;
break;
case 'x':
do_daemonize = 0;
break;
case 'X':
want_session_info = 0;
break;
case 'h':
usage(stdout);
return 0;
default:
fputs("\n", stderr);
usage(stderr);
return 1;
}
}
if (strncmp(uinput_device, "/dev", 4) != 0) {
syslog(LOG_INFO, "using fake uinput");
uinput_fake = 1;
}
memset(&act, 0, sizeof(act));
act.sa_flags = SA_RESTART;
act.sa_handler = quit_handler;
sigaction(SIGINT, &act, NULL);
sigaction(SIGHUP, &act, NULL);
sigaction(SIGTERM, &act, NULL);
sigaction(SIGQUIT, &act, NULL);
openlog("spice-vdagentd", do_daemonize ? 0 : LOG_PERROR, LOG_USER);
/* Setup communication with vdagent process(es) */
server = udscs_create_server(vdagentd_socket, agent_connect,
agent_read_complete, agent_disconnect,
vdagentd_messages, VDAGENTD_NO_MESSAGES,
debug);
if (!server) {
syslog(LOG_CRIT, "Fatal could not create server socket %s",
vdagentd_socket);
return 1;
}
if (chmod(vdagentd_socket, 0666)) {
syslog(LOG_CRIT, "Fatal could not change permissions on %s: %m",
vdagentd_socket);
udscs_destroy_server(server);
return 1;
}
if (do_daemonize)
daemonize();
#ifdef WITH_STATIC_UINPUT
uinput = vdagentd_uinput_create(uinput_device, 1024, 768, NULL, 0,
debug > 1, uinput_fake);
if (!uinput) {
udscs_destroy_server(server);
return 1;
}
#endif
if (want_session_info)
session_info = session_info_create(debug);
if (!session_info)
syslog(LOG_WARNING, "no session info, max 1 session agent allowed");
active_xfers = g_hash_table_new(g_direct_hash, g_direct_equal);
main_loop();
release_clipboards();
vdagentd_uinput_destroy(&uinput);
vdagent_virtio_port_flush(&virtio_port);
vdagent_virtio_port_destroy(&virtio_port);
session_info_destroy(session_info);
udscs_destroy_server(server);
if (unlink(vdagentd_socket) != 0)
syslog(LOG_ERR, "unlink %s: %s", vdagentd_socket, strerror(errno));
syslog(LOG_INFO, "vdagentd quiting, returning status %d", retval);
if (do_daemonize)
unlink(pidfilename);
return retval;
}
+637
View File
@@ -0,0 +1,637 @@
/* console-kit.c vdagentd ConsoleKit integration code
Copyright 2010-2012 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include "session-info.h"
#include <dbus/dbus.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <glib.h>
struct session_info {
DBusConnection *connection;
int fd;
char *seat;
char *active_session;
int verbose;
gchar *match_seat_signals;
gchar *match_session_signals;
gboolean session_is_locked;
gboolean session_idle_hint;
};
#define INTERFACE_CONSOLE_KIT "org.freedesktop.ConsoleKit"
#define OBJ_PATH_CONSOLE_KIT "/org/freedesktop/ConsoleKit"
#define INTERFACE_CONSOLE_KIT_MANAGER INTERFACE_CONSOLE_KIT ".Manager"
#define OBJ_PATH_CONSOLE_KIT_MANAGER OBJ_PATH_CONSOLE_KIT "/Manager"
#define INTERFACE_CONSOLE_KIT_SEAT INTERFACE_CONSOLE_KIT ".Seat"
#define INTERFACE_CONSOLE_KIT_SESSION INTERFACE_CONSOLE_KIT ".Session"
#define OBJ_PATH_CONSOLE_KIT_SESSION OBJ_PATH_CONSOLE_KIT "/Session"
#define SEAT_SIGNAL_ACTIVE_SESSION_CHANGED "ActiveSessionChanged"
#define SESSION_SIGNAL_LOCK "Lock"
#define SESSION_SIGNAL_UNLOCK "Unlock"
#define SESSION_SIGNAL_IDLE_HINT_CHANGED "IdleHintChanged"
static char *console_kit_get_first_seat(struct session_info *info);
static char *console_kit_check_active_session_change(struct session_info *info);
static void si_dbus_match_remove(struct session_info *info)
{
DBusError error;
if (info->match_seat_signals != NULL) {
dbus_error_init(&error);
dbus_bus_remove_match(info->connection,
info->match_seat_signals,
&error);
if (info->verbose)
syslog(LOG_DEBUG, "(console-kit) seat match removed: %s",
info->match_seat_signals);
g_clear_pointer(&info->match_seat_signals, g_free);
}
if (info->match_session_signals != NULL) {
dbus_error_init(&error);
dbus_bus_remove_match(info->connection,
info->match_session_signals,
&error);
if (info->verbose)
syslog(LOG_DEBUG, "(console-kit) session match removed: %s",
info->match_session_signals);
g_clear_pointer(&info->match_session_signals, g_free);
}
}
static void si_dbus_match_rule_update(struct session_info *info)
{
DBusError error;
if (info->connection == NULL)
return;
si_dbus_match_remove(info);
/* Seat signals */
if (info->seat != NULL) {
info->match_seat_signals =
g_strdup_printf ("type='signal',interface='%s',path='%s',"
"member='ActiveSessionChanged'",
INTERFACE_CONSOLE_KIT_SEAT,
info->seat);
if (info->verbose)
syslog(LOG_DEBUG, "(console-kit) seat match: %s",
info->match_seat_signals);
dbus_error_init(&error);
dbus_bus_add_match(info->connection,
info->match_seat_signals,
&error);
if (dbus_error_is_set(&error)) {
syslog(LOG_WARNING, "Unable to add dbus rule match: %s",
error.message);
dbus_error_free(&error);
g_clear_pointer(&info->match_seat_signals, g_free);
}
}
/* Session signals */
if (info->active_session != NULL) {
info->match_session_signals =
g_strdup_printf ("type='signal',interface='%s',path='%s'",
INTERFACE_CONSOLE_KIT_SESSION,
info->active_session);
if (info->verbose)
syslog(LOG_DEBUG, "(console-kit) session match: %s",
info->match_session_signals);
dbus_error_init(&error);
dbus_bus_add_match(info->connection,
info->match_session_signals,
&error);
if (dbus_error_is_set(&error)) {
syslog(LOG_WARNING, "Unable to add dbus rule match: %s",
error.message);
dbus_error_free(&error);
g_clear_pointer(&info->match_session_signals, g_free);
}
}
}
static void
si_dbus_read_signals(struct session_info *info)
{
DBusMessage *message = NULL;
dbus_connection_read_write(info->connection, 0);
message = dbus_connection_pop_message(info->connection);
while (message != NULL) {
const char *member;
member = dbus_message_get_member (message);
if (g_strcmp0(member, SEAT_SIGNAL_ACTIVE_SESSION_CHANGED) == 0) {
DBusMessageIter iter;
gint type;
gchar *session;
g_clear_pointer(&info->active_session, g_free);
dbus_message_iter_init(message, &iter);
type = dbus_message_iter_get_arg_type(&iter);
/* Session should be an object path, but there is a bug in
ConsoleKit where it sends a string rather than an object_path
accept object_path too in case the bug ever gets fixed */
if (type == DBUS_TYPE_STRING || type == DBUS_TYPE_OBJECT_PATH) {
dbus_message_iter_get_basic(&iter, &session);
if (session != NULL && session[0] != '\0') {
info->active_session = g_strdup(session);
si_dbus_match_rule_update(info);
} else {
syslog(LOG_WARNING, "(console-kit) received invalid session. "
"No active-session at the moment");
}
} else {
syslog(LOG_ERR,
"ActiveSessionChanged message has unexpected type: '%c'",
type);
}
} else if (g_strcmp0(member, SESSION_SIGNAL_LOCK) == 0) {
info->session_is_locked = TRUE;
} else if (g_strcmp0(member, SESSION_SIGNAL_UNLOCK) == 0) {
info->session_is_locked = FALSE;
} else if (g_strcmp0(member, SESSION_SIGNAL_IDLE_HINT_CHANGED) == 0) {
DBusMessageIter iter;
gint type;
dbus_bool_t idle_hint;
dbus_message_iter_init(message, &iter);
type = dbus_message_iter_get_arg_type(&iter);
if (type == DBUS_TYPE_BOOLEAN) {
dbus_message_iter_get_basic(&iter, &idle_hint);
info->session_idle_hint = (idle_hint);
} else {
syslog(LOG_ERR,
"(console-kit) IdleHintChanged has unexpected type: '%c'",
type);
}
} else {
if (dbus_message_get_type(message) != DBUS_MESSAGE_TYPE_SIGNAL) {
syslog(LOG_WARNING, "(console-kit) received non signal message");
} else if (info->verbose) {
syslog(LOG_DEBUG, "(console-kit) Signal not handled: %s", member);
}
}
dbus_message_unref(message);
dbus_connection_read_write(info->connection, 0);
message = dbus_connection_pop_message(info->connection);
}
}
struct session_info *session_info_create(int verbose)
{
struct session_info *info;
DBusError error;
info = g_new0(struct session_info, 1);
info->verbose = verbose;
info->session_is_locked = FALSE;
info->session_idle_hint = FALSE;
dbus_error_init(&error);
info->connection = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
if (info->connection == NULL || dbus_error_is_set(&error)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "Unable to connect to system bus: %s",
error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "Unable to connect to system bus");
g_free(info);
return NULL;
}
if (!dbus_connection_get_unix_fd(info->connection, &info->fd)) {
syslog(LOG_ERR, "Unable to get connection fd");
session_info_destroy(info);
return NULL;
}
if (!console_kit_get_first_seat(info)) {
session_info_destroy(info);
return NULL;
}
si_dbus_match_rule_update(info);
return info;
}
void session_info_destroy(struct session_info *info)
{
if (!info)
return;
si_dbus_match_remove(info);
dbus_connection_close(info->connection);
g_free(info->seat);
g_free(info->active_session);
g_free(info);
}
int session_info_get_fd(struct session_info *info)
{
return info->fd;
}
static char *console_kit_get_first_seat(struct session_info *info)
{
DBusError error;
DBusMessage *message = NULL;
DBusMessage *reply = NULL;
DBusMessageIter iter, subiter;
int type;
char *seat = NULL;
message = dbus_message_new_method_call(INTERFACE_CONSOLE_KIT,
OBJ_PATH_CONSOLE_KIT_MANAGER,
INTERFACE_CONSOLE_KIT_MANAGER,
"GetSeats");
if (message == NULL) {
syslog(LOG_ERR, "Unable to create dbus message");
goto exit;
}
dbus_error_init(&error);
reply = dbus_connection_send_with_reply_and_block(info->connection,
message,
-1,
&error);
if (reply == NULL || dbus_error_is_set(&error)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "GetSeats failed: %s", error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "GetSeats failed");
goto exit;
}
dbus_message_iter_init(reply, &iter);
type = dbus_message_iter_get_arg_type(&iter);
if (type != DBUS_TYPE_ARRAY) {
syslog(LOG_ERR,
"expected an array return value, got a '%c' instead", type);
goto exit;
}
dbus_message_iter_recurse(&iter, &subiter);
type = dbus_message_iter_get_arg_type(&subiter);
if (type != DBUS_TYPE_OBJECT_PATH) {
syslog(LOG_ERR,
"expected an object path element, got a '%c' instead", type);
goto exit;
}
dbus_message_iter_get_basic(&subiter, &seat);
info->seat = g_strdup(seat);
exit:
if (reply != NULL) {
dbus_message_unref(reply);
}
if (message != NULL) {
dbus_message_unref(message);
}
syslog(LOG_INFO, "(console-kit) seat: %s", info->seat);
return info->seat;
}
const char *session_info_get_active_session(struct session_info *info)
{
DBusError error;
DBusMessage *message = NULL;
DBusMessage *reply = NULL;
char *session = NULL;
if (!info)
return NULL;
if (info->active_session)
return console_kit_check_active_session_change(info);
message = dbus_message_new_method_call(INTERFACE_CONSOLE_KIT,
info->seat,
INTERFACE_CONSOLE_KIT_SEAT,
"GetActiveSession");
if (message == NULL) {
syslog(LOG_ERR, "Unable to create dbus message");
goto exit;
}
dbus_error_init(&error);
reply = dbus_connection_send_with_reply_and_block(info->connection,
message,
-1,
&error);
if (reply == NULL || dbus_error_is_set(&error)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "GetActiveSession failed: %s", error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "GetActiveSession failed");
goto exit;
}
dbus_error_init(&error);
if (!dbus_message_get_args(reply,
&error,
DBUS_TYPE_OBJECT_PATH, &session,
DBUS_TYPE_INVALID)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "error get ssid from reply: %s", error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "error getting ssid from reply");
session = NULL;
goto exit;
}
info->active_session = g_strdup(session);
si_dbus_match_rule_update(info);
exit:
if (reply != NULL) {
dbus_message_unref(reply);
}
if (message != NULL) {
dbus_message_unref(message);
}
/* In case the session was changed while we were running */
return console_kit_check_active_session_change(info);
}
char *session_info_session_for_pid(struct session_info *info, uint32_t pid)
{
DBusError error;
DBusMessage *message = NULL;
DBusMessage *reply = NULL;
DBusMessageIter args;
char *ssid = NULL;
if (!info)
return NULL;
message = dbus_message_new_method_call(INTERFACE_CONSOLE_KIT,
OBJ_PATH_CONSOLE_KIT_MANAGER,
INTERFACE_CONSOLE_KIT_MANAGER,
"GetSessionForUnixProcess");
if (message == NULL) {
syslog(LOG_ERR, "Unable to create dbus message");
goto exit;
}
dbus_message_iter_init_append(message, &args);
if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &pid)) {
syslog(LOG_ERR, "Unable to append dbus message args");
goto exit;
}
dbus_error_init(&error);
reply = dbus_connection_send_with_reply_and_block(info->connection,
message,
-1,
&error);
if (reply == NULL || dbus_error_is_set(&error)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "GetSessionForUnixProcess failed: %s",
error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "GetSessionForUnixProcess failed");
goto exit;
}
dbus_error_init(&error);
if (!dbus_message_get_args(reply,
&error,
DBUS_TYPE_OBJECT_PATH, &ssid,
DBUS_TYPE_INVALID)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "error get ssid from reply: %s", error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "error getting ssid from reply");
ssid = NULL;
goto exit;
}
ssid = strdup(ssid);
exit:
if (reply != NULL) {
dbus_message_unref(reply);
}
if (message != NULL) {
dbus_message_unref(message);
}
return ssid;
}
static char *console_kit_check_active_session_change(struct session_info *info)
{
si_dbus_read_signals(info);
if (info->verbose)
syslog(LOG_DEBUG, "(console-kit) active-session: '%s'",
(info->active_session ? info->active_session : "None"));
return info->active_session;
}
gboolean session_info_session_is_locked(struct session_info *info)
{
gboolean locked;
g_return_val_if_fail (info != NULL, FALSE);
/* Not every system does emit Lock and Unlock signals (for instance, such
* is the case for RHEL6) but most of the systems seems to emit the
* IdleHintChanged. So use the IdleHint value.
* systemd-login uses locked-hint which is not implemented in ConsoleKit,
* see https://github.com/ConsoleKit2/ConsoleKit2/issues/89 */
si_dbus_read_signals(info);
locked = info->session_idle_hint;
if (info->verbose) {
syslog(LOG_DEBUG, "(console-kit) session is locked: %s",
locked ? "yes" : "no");
}
return locked;
}
/* This function should only be called after session_info_get_active_session
* in order to verify if active session belongs to user (non greeter) */
gboolean session_info_is_user(struct session_info *info)
{
DBusError error;
DBusMessage *message = NULL;
DBusMessage *reply = NULL;
gchar *session_type = NULL;
gboolean ret = TRUE;
g_return_val_if_fail (info != NULL, TRUE);
g_return_val_if_fail (info->connection != NULL, TRUE);
g_return_val_if_fail (info->active_session != NULL, TRUE);
message = dbus_message_new_method_call(INTERFACE_CONSOLE_KIT,
info->active_session,
INTERFACE_CONSOLE_KIT_SESSION,
"GetSessionType");
if (message == NULL) {
syslog(LOG_ERR,
"(console-kit) Unable to create dbus message for GetSessionType");
return TRUE;
}
dbus_error_init(&error);
reply = dbus_connection_send_with_reply_and_block(info->connection,
message,
-1,
&error);
if (reply == NULL || dbus_error_is_set(&error)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "GetSessionType failed: %s", error.message);
dbus_error_free(&error);
} else
syslog(LOG_ERR, "GetSessionType failed");
goto exit;
}
dbus_error_init(&error);
if (!dbus_message_get_args(reply,
&error,
DBUS_TYPE_STRING, &session_type,
DBUS_TYPE_INVALID)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR,
"(console-kit) fail to get session-type from reply: %s",
error.message);
dbus_error_free(&error);
} else {
syslog(LOG_ERR, "(console-kit) fail to get session-type from reply");
}
session_type = NULL;
goto exit;
}
/* Empty session_type means user */
if (info->verbose)
syslog(LOG_DEBUG, "(console-kit) session-type is '%s'", session_type);
ret = (g_strcmp0 (session_type, "LoginWindow") != 0);
exit:
if (reply != NULL) {
dbus_message_unref(reply);
}
if (message != NULL) {
dbus_message_unref(message);
}
return ret;
}
uid_t session_info_uid_for_session(struct session_info *info, const char *session)
{
DBusError error;
DBusMessage *message = NULL;
DBusMessage *reply = NULL;
uint32_t uid;
uid_t ret = -1;
const char *err_msg;
g_return_val_if_fail(info != NULL, ret);
g_return_val_if_fail(info->connection != NULL, ret);
g_return_val_if_fail(info->active_session != NULL, ret);
dbus_error_init(&error);
err_msg = "(console-kit) Unable to create dbus message for GetUnixUser";
message = dbus_message_new_method_call(INTERFACE_CONSOLE_KIT,
session,
INTERFACE_CONSOLE_KIT_SESSION,
"GetUnixUser");
if (message == NULL) {
goto exit;
}
err_msg = "(console-kit) GetUnixUser failed";
reply = dbus_connection_send_with_reply_and_block(info->connection,
message,
-1,
&error);
if (reply == NULL || dbus_error_is_set(&error)) {
goto exit;
}
dbus_error_init(&error);
err_msg = "(console-kit) fail to get session-type from reply";
if (!dbus_message_get_args(reply,
&error,
DBUS_TYPE_UINT32, &uid,
DBUS_TYPE_INVALID)) {
goto exit;
}
if (info->verbose) {
syslog(LOG_DEBUG, "(console-kit) unix user is '%u'", (unsigned) uid);
}
err_msg = NULL;
ret = uid;
exit:
if (err_msg) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "%s: %s", err_msg, error.message);
dbus_error_free(&error);
} else {
syslog(LOG_ERR, "%s", err_msg);
}
}
if (reply != NULL) {
dbus_message_unref(reply);
}
if (message != NULL) {
dbus_message_unref(message);
}
return ret;
}
@@ -7,17 +7,18 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include "session-info.h"
@@ -44,3 +45,18 @@ char *session_info_session_for_pid(struct session_info *si, uint32_t pid)
{
return NULL;
}
gboolean session_info_is_user(struct session_info *si)
{
return TRUE;
}
gboolean session_info_session_is_locked(G_GNUC_UNUSED struct session_info *si)
{
return FALSE;
}
uid_t session_info_uid_for_session(struct session_info *si, const char *session)
{
return -1;
}
@@ -7,12 +7,12 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
@@ -24,6 +24,7 @@
#include <stdio.h>
#include <stdint.h>
#include <glib.h>
struct session_info;
@@ -36,4 +37,10 @@ const char *session_info_get_active_session(struct session_info *ck);
/* Note result must be free()-ed by caller */
char *session_info_session_for_pid(struct session_info *ck, uint32_t pid);
gboolean session_info_session_is_locked(struct session_info *si);
gboolean session_info_is_user(struct session_info *si);
/* get owner of a given session */
uid_t session_info_uid_for_session(struct session_info *si, const char *session);
#endif
+405
View File
@@ -0,0 +1,405 @@
/* systemd-login.c vdagentd libsystemd-login integration code
Copyright 2012 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include "session-info.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <systemd/sd-login.h>
#include <dbus/dbus.h>
struct session_info {
int verbose;
sd_login_monitor *mon;
char *session;
struct {
DBusConnection *system_connection;
char *match_session_signals;
} dbus;
gboolean session_is_locked;
gboolean session_locked_hint;
};
#define LOGIND_INTERFACE "org.freedesktop.login1"
#define LOGIND_SESSION_INTERFACE "org.freedesktop.login1.Session"
#define LOGIND_SESSION_OBJ_TEMPLATE "/org/freedesktop/login1/session/_3%s"
#define DBUS_PROPERTIES_INTERFACE "org.freedesktop.DBus.Properties"
#define SESSION_SIGNAL_LOCK "Lock"
#define SESSION_SIGNAL_UNLOCK "Unlock"
#define SESSION_PROP_LOCKED_HINT "LockedHint"
/* dbus related */
static DBusConnection *si_dbus_get_system_bus(void)
{
DBusConnection *connection;
DBusError error;
dbus_error_init(&error);
connection = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
if (connection == NULL || dbus_error_is_set(&error)) {
if (dbus_error_is_set(&error)) {
syslog(LOG_WARNING, "Unable to connect to system bus: %s",
error.message);
dbus_error_free(&error);
} else {
syslog(LOG_WARNING, "Unable to connect to system bus");
}
return NULL;
}
return connection;
}
static void si_dbus_match_remove(struct session_info *si)
{
DBusError error;
if (si->dbus.match_session_signals == NULL)
return;
dbus_error_init(&error);
dbus_bus_remove_match(si->dbus.system_connection,
si->dbus.match_session_signals,
&error);
g_clear_pointer(&si->dbus.match_session_signals, g_free);
}
static void si_dbus_match_rule_update(struct session_info *si)
{
DBusError error;
if (si->dbus.system_connection == NULL ||
si->session == NULL)
return;
si_dbus_match_remove(si);
si->dbus.match_session_signals =
g_strdup_printf ("type='signal',interface='%s',path='"
LOGIND_SESSION_OBJ_TEMPLATE"'",
LOGIND_SESSION_INTERFACE,
si->session);
if (si->verbose)
syslog(LOG_DEBUG, "logind match: %s", si->dbus.match_session_signals);
dbus_error_init(&error);
dbus_bus_add_match(si->dbus.system_connection,
si->dbus.match_session_signals,
&error);
if (dbus_error_is_set(&error)) {
syslog(LOG_WARNING, "Unable to add dbus rule match: %s",
error.message);
dbus_error_free(&error);
g_clear_pointer(&si->dbus.match_session_signals, g_free);
}
}
static void
si_dbus_read_properties(struct session_info *si)
{
dbus_bool_t locked_hint, ret;
DBusMessageIter iter, iter_variant;
gint type;
DBusError error;
DBusMessage *message = NULL;
DBusMessage *reply = NULL;
gchar *session_object;
const gchar *interface, *property;
if (si->session == NULL)
return;
session_object = g_strdup_printf(LOGIND_SESSION_OBJ_TEMPLATE, si->session);
message = dbus_message_new_method_call(LOGIND_INTERFACE,
session_object,
DBUS_PROPERTIES_INTERFACE,
"Get");
g_free (session_object);
if (message == NULL) {
syslog(LOG_ERR, "Unable to create dbus message");
goto exit;
}
interface = LOGIND_SESSION_INTERFACE;
property = SESSION_PROP_LOCKED_HINT;
ret = dbus_message_append_args(message,
DBUS_TYPE_STRING, &interface,
DBUS_TYPE_STRING, &property,
DBUS_TYPE_INVALID);
if (!ret) {
syslog(LOG_ERR, "Unable to request locked-hint");
goto exit;
}
dbus_error_init(&error);
reply = dbus_connection_send_with_reply_and_block(si->dbus.system_connection,
message,
-1,
&error);
if (reply == NULL) {
if (dbus_error_is_set(&error)) {
syslog(LOG_ERR, "Properties.Get failed (locked-hint) due %s", error.message);
dbus_error_free(&error);
} else {
syslog(LOG_ERR, "Properties.Get failed (locked-hint)");
}
goto exit;
}
dbus_message_iter_init(reply, &iter);
type = dbus_message_iter_get_arg_type(&iter);
if (type != DBUS_TYPE_VARIANT) {
syslog(LOG_ERR, "expected a variant, got a '%c' instead", type);
goto exit;
}
dbus_message_iter_recurse(&iter, &iter_variant);
type = dbus_message_iter_get_arg_type(&iter_variant);
if (type != DBUS_TYPE_BOOLEAN) {
syslog(LOG_ERR, "expected a boolean, got a '%c' instead", type);
goto exit;
}
dbus_message_iter_get_basic(&iter_variant, &locked_hint);
si->session_locked_hint = (locked_hint) ? TRUE : FALSE;
exit:
if (reply != NULL) {
dbus_message_unref(reply);
}
if (message != NULL) {
dbus_message_unref(message);
}
}
static void
si_dbus_read_signals(struct session_info *si)
{
DBusMessage *message = NULL;
dbus_connection_read_write(si->dbus.system_connection, 0);
message = dbus_connection_pop_message(si->dbus.system_connection);
while (message != NULL) {
const char *member;
member = dbus_message_get_member (message);
if (g_strcmp0(member, SESSION_SIGNAL_LOCK) == 0) {
si->session_is_locked = TRUE;
} else if (g_strcmp0(member, SESSION_SIGNAL_UNLOCK) == 0) {
si->session_is_locked = FALSE;
} else {
if (dbus_message_get_type(message) != DBUS_MESSAGE_TYPE_SIGNAL) {
syslog(LOG_WARNING, "(systemd-login) received non signal message");
} else if (si->verbose) {
syslog(LOG_DEBUG, "(systemd-login) Signal not handled: %s", member);
}
}
dbus_message_unref(message);
dbus_connection_read_write(si->dbus.system_connection, 0);
message = dbus_connection_pop_message(si->dbus.system_connection);
}
}
struct session_info *session_info_create(int verbose)
{
struct session_info *si;
int r;
si = g_new0(struct session_info, 1);
si->verbose = verbose;
si->session_is_locked = FALSE;
r = sd_login_monitor_new("session", &si->mon);
if (r < 0) {
syslog(LOG_ERR, "Error creating login monitor: %s", strerror(-r));
g_free(si);
return NULL;
}
si->dbus.system_connection = si_dbus_get_system_bus();
return si;
}
void session_info_destroy(struct session_info *si)
{
if (!si)
return;
si_dbus_match_remove(si);
if (si->dbus.system_connection) {
dbus_connection_close(si->dbus.system_connection);
}
sd_login_monitor_unref(si->mon);
g_free(si->session);
g_free(si);
}
int session_info_get_fd(struct session_info *si)
{
return sd_login_monitor_get_fd(si->mon);
}
const char *session_info_get_active_session(struct session_info *si)
{
int r;
char *old_session = si->session;
si->session = NULL;
r = sd_seat_get_active("seat0", &si->session, NULL);
/* ENOENT happens when a seat is switching from one session to another */
if (r < 0 && r != -ENOENT)
syslog(LOG_ERR, "Error getting active session: %s",
strerror(-r));
if (si->verbose && si->session &&
(!old_session || strcmp(old_session, si->session)))
syslog(LOG_INFO, "Active session: %s", si->session);
sd_login_monitor_flush(si->mon);
g_free(old_session);
si_dbus_match_rule_update(si);
return si->session;
}
char *session_info_session_for_pid(struct session_info *si, uint32_t pid)
{
int i;
int r;
GStrv sessions = NULL;
char *session = NULL;
uid_t uid;
r = sd_pid_get_session(pid, &session);
if (r >= 0) {
goto out;
}
/* If we could not get a session for the pid then the agent is probably
* running in a systemd managed session. In that case we simply assume
* it is actually part of the newest graphical session we can find. */
r = sd_pid_get_owner_uid(pid, &uid);
if (r < 0) {
syslog(LOG_ERR, "Error getting owner UID for pid %u: %s",
pid, strerror(-r));
goto out;
}
r = sd_uid_get_sessions(uid, 0, &sessions);
if (r < 0) {
syslog(LOG_ERR, "Error getting sessions for UID %d: %s",
(int) uid, strerror(-r));
goto out;
}
for (i = 0; sessions[i] != NULL; i++) {
char *session_type = NULL;
r = sd_session_get_type(sessions[i], &session_type);
if (r < 0) {
syslog(LOG_ERR, "Error getting session type for session %s: %s",
sessions[i], strerror(-r));
continue;
}
if (g_strcmp0(session_type, "wayland") == 0 ||
g_strcmp0(session_type, "x11") == 0 ||
g_strcmp0(session_type, "mir") == 0) {
/* We prefer the newest session (i.e. last entry) from the
* user, assuming that any old session that still exist has
* just not yet died properly. */
if (session != NULL)
free (session);
session = g_strdup(sessions[i]);
}
free(session_type);
}
g_strfreev(sessions);
out:
if (session != NULL && si->verbose) {
syslog(LOG_INFO, "Session for pid %u: %s", pid, session);
}
return session;
}
gboolean session_info_session_is_locked(struct session_info *si)
{
gboolean locked;
g_return_val_if_fail (si != NULL, FALSE);
si_dbus_read_signals(si);
si_dbus_read_properties(si);
locked = (si->session_is_locked || si->session_locked_hint);
if (si->verbose) {
syslog(LOG_DEBUG, "(systemd-login) session is locked: %s",
locked ? "yes" : "no");
}
return locked;
}
/* This function should only be called after session_info_get_active_session
* in order to verify if active session belongs to user (non greeter) */
gboolean session_info_is_user(struct session_info *si)
{
gchar *class = NULL;
gboolean ret;
g_return_val_if_fail (si != NULL, TRUE);
g_return_val_if_fail (si->session != NULL, TRUE);
if (sd_session_get_class(si->session, &class) != 0) {
syslog(LOG_WARNING, "Unable to get class from session: %s",
si->session);
return TRUE;
}
if (si->verbose)
syslog(LOG_DEBUG, "(systemd-login) class for %s is %s",
si->session, class);
ret = (g_strcmp0(class, "user") == 0);
g_free(class);
return ret;
}
uid_t session_info_uid_for_session(struct session_info *si, const char *session)
{
uid_t ret = -1;
if (sd_session_get_uid(session, &ret) < 0) {
return -1;
}
return ret;
}
+34 -22
View File
@@ -1,6 +1,6 @@
/* vdagentd-uinput.c vdagentd uinput handling code
Copyright 2010-2012 Red Hat, Inc.
Copyright 2010-2016 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
@@ -8,20 +8,18 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <syslog.h>
@@ -31,7 +29,8 @@
#include <linux/input.h>
#include <linux/uinput.h>
#include <spice/vd_agent.h>
#include "vdagentd-uinput.h"
#include <glib.h>
#include "uinput.h"
struct vdagentd_uinput {
const char *devname;
@@ -52,10 +51,7 @@ struct vdagentd_uinput *vdagentd_uinput_create(const char *devname,
{
struct vdagentd_uinput *uinput;
uinput = calloc(1, sizeof(*uinput));
if (!uinput)
return NULL;
uinput = g_new0(struct vdagentd_uinput, 1);
uinput->devname = devname;
uinput->fd = -1; /* Gets opened by vdagentd_uinput_update_size() */
uinput->debug = debug;
@@ -76,8 +72,7 @@ void vdagentd_uinput_destroy(struct vdagentd_uinput **uinputp)
if (uinput->fd != -1)
close(uinput->fd);
free(uinput);
*uinputp = NULL;
g_clear_pointer(uinputp, g_free);
}
void vdagentd_uinput_update_size(struct vdagentd_uinput **uinputp,
@@ -99,10 +94,10 @@ void vdagentd_uinput_update_size(struct vdagentd_uinput **uinputp,
int i, rc;
if (uinput->debug) {
syslog(LOG_DEBUG, "uinput-update-size: %dx%d", width, height);
for (i = 0; i < screen_count; i++)
syslog(LOG_DEBUG, "screen %d: +%d+%d", i, screen_info[i].x,
screen_info[i].y);
syslog(LOG_DEBUG, "updating uinput size to %dx%d, screen positions:", width, height);
for (i = 0; i < screen_count; i++) {
syslog(LOG_DEBUG, " screen %d: +%d+%d", i, screen_info[i].x, screen_info[i].y);
}
}
uinput->screen_info = screen_info;
@@ -145,6 +140,8 @@ void vdagentd_uinput_update_size(struct vdagentd_uinput **uinputp,
ioctl(uinput->fd, UI_SET_KEYBIT, BTN_LEFT);
ioctl(uinput->fd, UI_SET_KEYBIT, BTN_MIDDLE);
ioctl(uinput->fd, UI_SET_KEYBIT, BTN_RIGHT);
ioctl(uinput->fd, UI_SET_KEYBIT, BTN_SIDE);
ioctl(uinput->fd, UI_SET_KEYBIT, BTN_EXTRA);
/* wheel */
ioctl(uinput->fd, UI_SET_EVBIT, EV_REL);
@@ -180,6 +177,18 @@ static void uinput_send_event(struct vdagentd_uinput **uinputp,
}
}
static struct vdagentd_guest_xorg_resolution* lookup_screen_info(struct vdagentd_uinput *uinput, int display_id)
{
int i;
for (i = 0; i < uinput->screen_count; i++) {
if (uinput->screen_info[i].display_id == display_id) {
return &uinput->screen_info[i];
}
}
syslog(LOG_WARNING, "Unable to find output index for display id %d", display_id);
return NULL;
}
void vdagentd_uinput_do_mouse(struct vdagentd_uinput **uinputp,
VDAgentMouseState *mouse)
{
@@ -193,6 +202,8 @@ void vdagentd_uinput_do_mouse(struct vdagentd_uinput **uinputp,
{ .name = "left", .mask = VD_AGENT_LBUTTON_MASK, .btn = BTN_LEFT },
{ .name = "middle", .mask = VD_AGENT_MBUTTON_MASK, .btn = BTN_MIDDLE },
{ .name = "right", .mask = VD_AGENT_RBUTTON_MASK, .btn = BTN_RIGHT },
{ .name = "side" , .mask = VD_AGENT_SBUTTON_MASK, .btn = BTN_SIDE },
{ .name = "extra" , .mask = VD_AGENT_EBUTTON_MASK, .btn = BTN_EXTRA },
};
static const struct button_s wheel[] = {
{ .name = "up", .mask = VD_AGENT_UBUTTON_MASK, .btn = 1 },
@@ -201,16 +212,17 @@ void vdagentd_uinput_do_mouse(struct vdagentd_uinput **uinputp,
int i, down;
if (*uinputp) {
if (mouse->display_id >= uinput->screen_count) {
syslog(LOG_WARNING, "mouse event for unknown monitor (%d >= %d)",
mouse->display_id, uinput->screen_count);
struct vdagentd_guest_xorg_resolution *screen_info = lookup_screen_info(uinput, mouse->display_id);
if (screen_info == NULL) {
syslog(LOG_WARNING, "mouse event for unknown monitor %d",
mouse->display_id);
return;
}
if (uinput->debug)
syslog(LOG_DEBUG, "mouse-event: mon %d %dx%d", mouse->display_id,
mouse->x, mouse->y);
mouse->x += uinput->screen_info[mouse->display_id].x;
mouse->y += uinput->screen_info[mouse->display_id].y;
mouse->x += screen_info->x;
mouse->y += screen_info->y;
#ifdef WITH_STATIC_UINPUT
mouse->x = mouse->x * 32767 / (uinput->width - 1);
mouse->y = mouse->y * 32767 / (uinput->height - 1);
@@ -8,12 +8,12 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
File diff suppressed because it is too large. Load diff
+322
View File
@@ -0,0 +1,322 @@
/* vdagent-virtio-port.c virtio port communication code
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <gio/gio.h>
#include <glib-unix.h>
#include "vdagent-connection.h"
#include "virtio-port.h"
struct vdagent_virtio_port_buf {
uint8_t *buf;
size_t size;
size_t write_pos;
};
/* Data to keep track of the assembling of vdagent messages per chunk port,
for de-multiplexing the messages */
struct vdagent_virtio_port_chunk_port_data {
int message_header_read;
int message_data_pos;
VDAgentMessage message_header;
uint8_t *message_data;
};
struct _VirtioPort {
VDAgentConnection parent_instance;
/* Per chunk port data */
struct vdagent_virtio_port_chunk_port_data port_data[VDP_END_PORT];
struct vdagent_virtio_port_buf write_buf;
/* Callbacks */
vdagent_virtio_port_read_callback read_callback;
VDAgentConnErrorCb error_cb;
};
G_DEFINE_TYPE(VirtioPort, virtio_port, VDAGENT_TYPE_CONNECTION)
static void vdagent_virtio_port_do_chunk(VDAgentConnection *conn,
gpointer header_data,
gpointer chunk_data);
static gsize conn_handle_header(VDAgentConnection *conn,
gpointer header_buf)
{
VirtioPort *self = VIRTIO_PORT(conn);
VDIChunkHeader *header = header_buf;
GError *err;
header->size = GUINT32_FROM_LE(header->size);
header->port = GUINT32_FROM_LE(header->port);
if (header->size > VD_AGENT_MAX_DATA_SIZE) {
err = g_error_new(G_IO_ERROR, G_IO_ERROR_FAILED,
"chunk size %u too large", header->size);
self->error_cb(conn, err);
return 0;
}
if (header->port >= VDP_END_PORT) {
err = g_error_new(G_IO_ERROR, G_IO_ERROR_FAILED,
"chunk port %u out of range", header->port);
self->error_cb(conn, err);
return 0;
}
return header->size;
}
static void virtio_port_init(VirtioPort *self)
{
}
static void virtio_port_finalize(GObject *obj)
{
VirtioPort *self = VIRTIO_PORT(obj);
guint i;
g_free(self->write_buf.buf);
for (i = 0; i < VDP_END_PORT; i++) {
g_free(self->port_data[i].message_data);
}
G_OBJECT_CLASS(virtio_port_parent_class)->finalize(obj);
}
static void virtio_port_class_init(VirtioPortClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
VDAgentConnectionClass *conn_class = VDAGENT_CONNECTION_CLASS(klass);
gobject_class->finalize = virtio_port_finalize;
conn_class->handle_header = conn_handle_header;
conn_class->handle_message = vdagent_virtio_port_do_chunk;
}
VirtioPort *vdagent_virtio_port_create(const char *portname,
vdagent_virtio_port_read_callback read_callback,
VDAgentConnErrorCb error_cb)
{
VirtioPort *vport;
GIOStream *io_stream;
GError *err = NULL;
io_stream = vdagent_file_open(portname, &err);
if (err) {
syslog(LOG_ERR, "%s: %s", __func__, err->message);
g_clear_error(&err);
io_stream = vdagent_socket_connect(portname, &err);
if (err) {
syslog(LOG_ERR, "%s: %s", __func__, err->message);
g_error_free(err);
return NULL;
}
}
vport = g_object_new(VIRTIO_TYPE_PORT, NULL);
/* When calling vdagent_connection_new(),
* @wait_on_opening MUST be set to TRUE:
*
* When we open the virtio serial port, the following happens:
* 1) The linux kernel virtio_console driver sends a
* VIRTIO_CONSOLE_PORT_OPEN message to qemu
* 2) qemu's spicevmc chardev driver calls qemu_spice_add_interface to
* register the agent chardev with the spice-server
* 3) spice-server then calls the spicevmc chardev driver's state
* callback to let it know it is ready to receive data
* 4) The state callback sends a CHR_EVENT_OPENED to the virtio-console
* chardev backend
* 5) The virtio-console chardev backend sends VIRTIO_CONSOLE_PORT_OPEN
* to the linux kernel virtio_console driver
*
* Until steps 1 - 5 have completed the linux kernel virtio_console
* driver sees the virtio serial port as being in a disconnected state
* and read will return 0 ! So if we blindly assume that a read 0 means
* that the channel is closed we will hit a race here.
*/
vdagent_connection_setup(VDAGENT_CONNECTION(vport),
io_stream,
TRUE,
sizeof(VDIChunkHeader),
error_cb);
vport->read_callback = read_callback;
vport->error_cb = error_cb;
return vport;
}
void vdagent_virtio_port_write_start(
VirtioPort *vport,
uint32_t port_nr,
uint32_t message_type,
uint32_t message_opaque,
uint32_t data_size)
{
struct vdagent_virtio_port_buf *new_wbuf;
VDIChunkHeader *chunk_header;
VDAgentMessage *message_header;
g_return_if_fail(vport->write_buf.buf == NULL);
new_wbuf = &vport->write_buf;
new_wbuf->write_pos = 0;
new_wbuf->size = sizeof(*chunk_header) + sizeof(*message_header) + data_size;
new_wbuf->buf = g_malloc(new_wbuf->size);
chunk_header = (VDIChunkHeader *) (new_wbuf->buf + new_wbuf->write_pos);
chunk_header->port = GUINT32_TO_LE(port_nr);
chunk_header->size = GUINT32_TO_LE(sizeof(*message_header) + data_size);
new_wbuf->write_pos += sizeof(*chunk_header);
message_header = (VDAgentMessage *) (new_wbuf->buf + new_wbuf->write_pos);
message_header->protocol = GUINT32_TO_LE(VD_AGENT_PROTOCOL);
message_header->type = GUINT32_TO_LE(message_type);
message_header->opaque = GUINT64_TO_LE(message_opaque);
message_header->size = GUINT32_TO_LE(data_size);
new_wbuf->write_pos += sizeof(*message_header);
}
int vdagent_virtio_port_write_append(VirtioPort *vport,
const uint8_t *data, uint32_t size)
{
struct vdagent_virtio_port_buf *wbuf;
if (size == 0) {
return 0;
}
wbuf = &vport->write_buf;
if (!wbuf->buf) {
syslog(LOG_ERR, "can't append without a buffer");
return -1;
}
if (wbuf->size - wbuf->write_pos < size) {
syslog(LOG_ERR, "can't append to full buffer");
return -1;
}
memcpy(wbuf->buf + wbuf->write_pos, data, size);
wbuf->write_pos += size;
if (wbuf->write_pos == wbuf->size) {
vdagent_connection_write(VDAGENT_CONNECTION(vport), wbuf->buf, wbuf->size);
wbuf->buf = NULL;
}
return 0;
}
void vdagent_virtio_port_write(
VirtioPort *vport,
uint32_t port_nr,
uint32_t message_type,
uint32_t message_opaque,
const uint8_t *data,
uint32_t data_size)
{
vdagent_virtio_port_write_start(vport, port_nr, message_type,
message_opaque, data_size);
vdagent_virtio_port_write_append(vport, data, data_size);
}
void vdagent_virtio_port_reset(VirtioPort *vport, int port)
{
if (port >= VDP_END_PORT) {
syslog(LOG_ERR, "vdagent_virtio_port_reset port out of range");
return;
}
g_free(vport->port_data[port].message_data);
memset(&vport->port_data[port], 0, sizeof(vport->port_data[0]));
}
static void vdagent_virtio_port_do_chunk(VDAgentConnection *conn,
gpointer header_data,
gpointer chunk_data)
{
int avail, read, pos = 0;
VirtioPort *vport = VIRTIO_PORT(conn);
VDIChunkHeader *chunk_header = header_data;
struct vdagent_virtio_port_chunk_port_data *port =
&vport->port_data[chunk_header->port];
if (port->message_header_read < sizeof(port->message_header)) {
read = sizeof(port->message_header) - port->message_header_read;
if (read > chunk_header->size) {
read = chunk_header->size;
}
memcpy((uint8_t *)&port->message_header + port->message_header_read,
chunk_data, read);
port->message_header_read += read;
if (port->message_header_read == sizeof(port->message_header)) {
port->message_header.protocol = GUINT32_FROM_LE(port->message_header.protocol);
port->message_header.type = GUINT32_FROM_LE(port->message_header.type);
port->message_header.opaque = GUINT64_FROM_LE(port->message_header.opaque);
port->message_header.size = GUINT32_FROM_LE(port->message_header.size);
if (port->message_header.size) {
port->message_data = g_malloc(port->message_header.size);
}
}
pos = read;
}
if (port->message_header_read == sizeof(port->message_header)) {
read = port->message_header.size - port->message_data_pos;
avail = chunk_header->size - pos;
if (avail > read) {
GError *err = g_error_new(G_IO_ERROR, G_IO_ERROR_FAILED,
"chunk larger than message, lost sync?");
vport->error_cb(VDAGENT_CONNECTION(vport), err);
return;
}
if (avail < read)
read = avail;
if (read) {
memcpy(port->message_data + port->message_data_pos,
chunk_data + pos, read);
port->message_data_pos += read;
}
if (port->message_data_pos == port->message_header.size) {
if (vport->read_callback) {
vport->read_callback(vport, chunk_header->port,
&port->message_header, port->message_data);
}
port->message_header_read = 0;
port->message_data_pos = 0;
g_clear_pointer(&port->message_data, g_free);
}
}
}
+73
View File
@@ -0,0 +1,73 @@
/* virtio-port.h virtio port communication header
Copyright 2010 - 2016 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __VIRTIO_PORT_H
#define __VIRTIO_PORT_H
#include <stdint.h>
#include <spice/vd_agent.h>
#include <glib-object.h>
#include "vdagent-connection.h"
G_BEGIN_DECLS
#define VIRTIO_TYPE_PORT virtio_port_get_type()
G_DECLARE_FINAL_TYPE(VirtioPort, virtio_port, VIRTIO, PORT, VDAgentConnection)
/* Callbacks with this type will be called when a complete message has been
received. */
typedef void (*vdagent_virtio_port_read_callback)(
VirtioPort *vport,
int port_nr,
VDAgentMessage *message_header,
uint8_t *data);
/* Create a vdagent virtio port object for port portname */
VirtioPort *vdagent_virtio_port_create(const char *portname,
vdagent_virtio_port_read_callback read_callback,
VDAgentConnErrorCb error_cb);
/* Queue a message for delivery, either bit by bit, or all at once */
void vdagent_virtio_port_write_start(
VirtioPort *vport,
uint32_t port_nr,
uint32_t message_type,
uint32_t message_opaque,
uint32_t data_size);
int vdagent_virtio_port_write_append(
VirtioPort *vport,
const uint8_t *data,
uint32_t size);
void vdagent_virtio_port_write(
VirtioPort *vport,
uint32_t port_nr,
uint32_t message_type,
uint32_t message_opaque,
const uint8_t *data,
uint32_t data_size);
void vdagent_virtio_port_reset(VirtioPort *vport, int port);
G_END_DECLS
#endif
@@ -18,9 +18,7 @@
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_PCIACCESS
#include <pciaccess.h>
@@ -30,7 +28,7 @@
#include <errno.h>
#include <limits.h>
#include <syslog.h>
#include "vdagentd-xorg-conf.h"
#include "xorg-conf.h"
#define FPRINTF(...) \
do { \
@@ -56,8 +54,8 @@ void vdagentd_write_xorg_conf(VDAgentMonitorsConfig *monitor_conf)
.subvendor_id = PCI_MATCH_ANY,
.subdevice_id = PCI_MATCH_ANY,
};
const char *xorg_conf = "/var/run/spice-vdagentd/xorg.conf.spice";
const char *xorg_conf_old = "/var/run/spice-vdagentd/xorg.conf.spice.old";
const char *xorg_conf = "/run/spice-vdagentd/xorg.conf.spice";
const char *xorg_conf_old = "/run/spice-vdagentd/xorg.conf.spice.old";
r = rename(xorg_conf, xorg_conf_old);
if (r && errno != ENOENT) {
@@ -7,12 +7,12 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
+262
View File
@@ -0,0 +1,262 @@
/* test-device-info.c tests to see whether the functionality for converting a
* device address to a xrandr output are working properly
*
* Copyright 2018 Red Hat, Inc.
*
* Red Hat Authors:
* Jonathon Jongsma <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// just include the source file for testing
#include "vdagent/device-info.c"
#define assert_device(dev, domain_, bus_, slot_, function_) \
{ \
PciDevice* dev_ = (dev); \
assert(dev_ != NULL); \
assert(dev_->domain == domain_); \
assert(dev_->bus == bus_); \
assert(dev_->slot == slot_); \
assert(dev_->function == function_); \
}
static void test_compare_addresses()
{
{
PciDevice da1 = {1, 0, 3, 0};
PciDevice da2 = {1, 1, 1, 0};
PciDevice da3 = {1, 2, 3, 0};
PciAddress a1 = {1, NULL};
a1.domain = 0;
a1.devices = g_list_append(a1.devices, &da1);
a1.devices = g_list_append(a1.devices, &da2);
a1.devices = g_list_append(a1.devices, &da3);
PciDevice db1 = {1, 0, 3, 0};
PciDevice db2 = {1, 1, 1, 0};
PciDevice db3 = {1, 2, 3, 0};
PciAddress a2 = {1, NULL};
a2.domain = 0;
a2.devices = g_list_append(a2.devices, &db1);
a2.devices = g_list_append(a2.devices, &db2);
a2.devices = g_list_append(a2.devices, &db3);
assert(compare_addresses(&a1, &a2));
}
{
PciDevice da1 = {1, 0, 3, 0};
PciDevice da2 = {1, 1, 1, 0};
PciDevice da3 = {1, 2, 3, 0};
PciAddress a1 = {1, NULL};
a1.domain = 0;
a1.devices = g_list_append(a1.devices, &da1);
a1.devices = g_list_append(a1.devices, &da2);
a1.devices = g_list_append(a1.devices, &da3);
// a 'spice' format PCI address will not provide domain or bus for each
// device, only slot and function. So first two numbers for each device
// will always be set to 0
PciDevice db1 = {0, 0, 3, 0};
PciDevice db2 = {0, 0, 1, 0};
PciDevice db3 = {0, 0, 3, 0};
PciAddress a2 = {1, NULL};
a2.domain = 0;
a2.devices = g_list_append(a2.devices, &db1);
a2.devices = g_list_append(a2.devices, &db2);
a2.devices = g_list_append(a2.devices, &db3);
assert(compare_addresses(&a1, &a2));
}
// different number of devices
{
PciDevice da1 = {0, 0, 3, 0};
PciDevice da2 = {0, 1, 1, 0};
PciDevice da3 = {0, 2, 3, 0};
PciAddress a1 = {0, NULL};
a1.domain = 0;
a1.devices = g_list_append(a1.devices, &da1);
a1.devices = g_list_append(a1.devices, &da2);
a1.devices = g_list_append(a1.devices, &da3);
PciDevice db1 = {0, 0, 3, 0};
PciDevice db2 = {0, 1, 1, 0};
PciAddress a2 = {0, NULL};
a2.domain = 0;
a2.devices = g_list_append(a2.devices, &db1);
a2.devices = g_list_append(a2.devices, &db2);
assert(!compare_addresses(&a1, &a2));
}
// mismatched function
{
PciDevice da1 = {0, 0, 2, 0};
PciAddress a1 = {0, NULL};
a1.domain = 0;
a1.devices = g_list_append(a1.devices, &da1);
PciDevice db1 = {0, 0, 2, 1};
PciAddress a2 = {0, NULL};
a2.domain = 0;
a2.devices = g_list_append(a2.devices, &db1);
assert(!compare_addresses(&a1, &a2));
}
// mismatched slot
{
PciDevice da1 = {0, 0, 2, 0};
PciAddress a1 = {0, NULL};
a1.domain = 0;
a1.devices = g_list_append(a1.devices, &da1);
PciDevice db1 = {0, 0, 1, 0};
PciAddress a2 = {0, NULL};
a2.domain = 0;
a2.devices = g_list_append(a2.devices, &db1);
assert(!compare_addresses(&a1, &a2));
}
// mismatched domain
{
PciDevice da1 = {0, 0, 2, 0};
PciAddress a1 = {0, NULL};
a1.domain = 1;
a1.devices = g_list_append(a1.devices, &da1);
PciDevice db1 = {0, 0, 2, 0};
PciAddress a2 = {0, NULL};
a2.domain = 0;
a2.devices = g_list_append(a2.devices, &db1);
assert(!compare_addresses(&a1, &a2));
}
}
static void test_spice_parsing()
{
PciAddress *addr = parse_pci_address_from_spice("pci/0000/02.0");
assert(addr != NULL);
assert(addr->domain == 0);
assert(g_list_length(addr->devices) == 1);
assert_device(addr->devices->data, 0, 0, 2, 0);
pci_address_free(addr);
addr = parse_pci_address_from_spice("pci/ffff/ff.f");
assert(addr != NULL);
assert(addr->domain == 65535);
assert(g_list_length(addr->devices) == 1);
assert_device(addr->devices->data, 0, 0, 255, 15);
pci_address_free(addr);
addr = parse_pci_address_from_spice("pci/0000/02.1/03.0");
assert(addr != NULL);
assert(addr->domain == 0);
assert(g_list_length(addr->devices) == 2);
assert_device(addr->devices->data, 0, 0, 2, 1);
assert_device(addr->devices->next->data, 0, 0, 3, 0);
pci_address_free(addr);
addr = parse_pci_address_from_spice("pci/000a/01.0/02.1/03.0");
assert(addr != NULL);
assert(addr->domain == 10);
assert(g_list_length(addr->devices) == 3);
assert_device(addr->devices->data, 0, 0, 1, 0);
assert_device(addr->devices->next->data, 0, 0, 2, 1);
assert_device(addr->devices->next->next->data, 0, 0, 3, 0);
pci_address_free(addr);
addr = parse_pci_address_from_spice("pcx/0000/02.1/03.0");
assert(addr == NULL);
addr = parse_pci_address_from_spice("0000/02.0");
assert(addr == NULL);
addr = parse_pci_address_from_spice("0000/02.1/03.0");
assert(addr == NULL);
}
static void test_sysfs_parsing()
{
PciAddress *addr = parse_pci_address_from_sysfs_path("../../devices/pci0000:00/0000:00:02.0/drm/card0");
assert(addr != NULL);
assert(addr->domain == 0);
assert(g_list_length(addr->devices) == 1);
assert_device(addr->devices->data, 0, 0, 2, 0);
pci_address_free(addr);
addr = parse_pci_address_from_sysfs_path("../../devices/pciffff:ff/ffff:ff:ff.f/drm/card0");
assert(addr != NULL);
assert(addr->domain == 65535);
assert(g_list_length(addr->devices) == 1);
assert_device(addr->devices->data, 65535, 255, 255, 15);
pci_address_free(addr);
addr = parse_pci_address_from_sysfs_path("../../devices/pci0000:00/0000:00:03.0/0000:01:01.0/0000:02:03.0/virtio2/drm/card0");
assert(addr != NULL);
assert(addr->domain == 0);
assert(g_list_length(addr->devices) == 3);
assert_device(addr->devices->data, 0, 0, 3, 0);
assert_device(addr->devices->next->data, 0, 1, 1, 0);
assert_device(addr->devices->next->next->data, 0, 2, 3, 0);
pci_address_free(addr);
}
// verify that we parse the BDF notation correctly
static bool test_bdf(const char* string, int domain, uint8_t bus, uint8_t slot, uint8_t function)
{
PciDevice pci_dev;
return (parse_pci_device(string, NULL, &pci_dev)
&& (pci_dev.domain == domain)
&& (pci_dev.bus == bus)
&& (pci_dev.slot == slot)
&& (pci_dev.function == function));
}
static void test_bdf_parsing()
{
// valid input
assert(test_bdf("0000:00:02.1", 0, 0, 2, 1));
assert(test_bdf("00:00:02.1", 0, 0, 2, 1));
assert(test_bdf("0000:00:03.0", 0, 0, 3, 0));
assert(test_bdf("0000:00:1d.1", 0, 0, 29, 1));
assert(test_bdf("0000:09:02.1", 0, 9, 2, 1));
assert(test_bdf("0000:1d:02.1", 0, 29, 2, 1));
assert(test_bdf("0000:00:02.d", 0, 0, 2, 13));
assert(test_bdf("000f:00:02.d", 15, 0, 2, 13));
assert(test_bdf("000f:00:02.d", 15, 0, 2, 13));
assert(test_bdf("000f:00:02.d", 15, 0, 2, 13));
assert(test_bdf("000f:00:02.d", 15, 0, 2, 13));
assert(test_bdf("ffff:ff:ff.f", 65535, 255, 255, 15));
assert(test_bdf("0:0:2.1", 0, 0, 2, 1));
// invalid input
assert(!test_bdf("0000:00:02:0", 0, 0, 2, 0));
assert(!test_bdf("-0001:00:02.1", -1, 0, 2, 1));
assert(!test_bdf("0000.00.02.0", 0, 0, 2, 0));
assert(!test_bdf("000f:00:02", 15, 0, 2, 0));
assert(!test_bdf("000f:00", 15, 0, 0, 0));
assert(!test_bdf("000f", 15, 0, 0, 0));
assert(!test_bdf("random string", 0, 0, 0, 0));
assert(!test_bdf("12345", 12345, 0, 0, 0));
}
int main(int argc, char **argv)
{
test_bdf_parsing();
test_sysfs_parsing();
test_spice_parsing();
test_compare_addresses();
}
+83
View File
@@ -0,0 +1,83 @@
/* test-file-xfers.c - test file transfer
Copyright 2019 Red Hat, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#undef NDEBUG
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <glib.h>
#include <spice/vd_agent.h>
#include "file-xfers.h"
static void test_file(const char *file_name, const char *out)
{
char *fn = g_strdup(file_name);
int fd = vdagent_file_xfers_create_file("./test-dir", &fn);
if (out) {
g_assert_cmpint(fd, !=, -1);
g_assert_cmpstr(fn, ==, out);
close(fd);
g_assert_cmpint(access(out, W_OK), ==, 0);
} else {
g_assert_cmpint(fd, ==, -1);
}
g_free(fn);
}
int main(int argc, char *argv[])
{
assert(system("rm -rf test-dir && mkdir test-dir") == 0);
// create a file
test_file("test.txt", "./test-dir/test.txt");
// create a file with an existing name
for (int i = 1; i < 64; ++i) {
char out_name[64];
sprintf(out_name, "./test-dir/test (%d).txt", i);
test_file("test.txt", out_name);
}
// check too much files with the same name
test_file("test.txt", NULL);
// create a file in a subdirectory not existing
test_file("subdir/test.txt", "./test-dir/subdir/test.txt");
// create a file in a directory with no permissions
assert(system("ln -s /proc/1 test-dir/baddir") == 0);
test_file("baddir/test2.txt", NULL);
// try to create a file with a path where there's a file (should fail)
test_file("test.txt/out", NULL);
// create a file without extension in a directory with extension
test_file("sub.dir/test", "./test-dir/sub.dir/test");
// create a file with same name above, should not strip the filename
test_file("sub.dir/test", "./test-dir/sub.dir/test (1)");
assert(system("rm -rf test-dir") == 0);
return 0;
}
+59
View File
@@ -0,0 +1,59 @@
/* test-session-info.c - test session info
Copyright 2020 Red Hat, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#undef NDEBUG
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "session-info.h"
int main(int argc, char *argv[])
{
int pid, uid, uid_si;
pid = (int)getpid();
struct session_info *session_info = session_info_create(1);
if (session_info == NULL) {
return 1;
}
char *session = session_info_session_for_pid(session_info, pid);
if (session == NULL) {
session_info_destroy(session_info);
return 2;
}
uid_si = session_info_uid_for_session(session_info, session);
free(session);
session_info_destroy(session_info);
uid = getuid();
printf("MAIN: uid is %d, uid_si is %d\n", uid, uid_si);
if (uid != uid_si) {
fprintf(stderr, "MAIN: uid (%d) does not match the uid "
"obtained from session info (%d)\n", uid, uid_si);
return 3;
}
return 0;
}
+143
View File
@@ -0,0 +1,143 @@
/* test-termination.c tests program terminates correctly sending SIGTERM
*
* Copyright 2020 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
static pid_t child_pid;
static char socket_name[1024 + 64];
static void cleanup(void)
{
if (child_pid) {
kill(child_pid, SIGKILL);
}
if (socket_name[0]) {
unlink(socket_name);
}
}
static void handle_alarm(int sig)
{
fprintf(stderr, "Alarm reached!\n");
exit(1);
}
static void check(int line, const char *cond_str, int cond_value)
{
if (!cond_value) {
alarm(0);
fprintf(stderr, "%d: Check %s failed!\n", line, cond_str);
exit(1);
}
}
#define check(cond) check(__LINE__, #cond, cond)
static pid_t get_daemon_pid(void)
{
pid_t res = 0;
FILE *f = popen("ps -efww", "r");
check(f != NULL);
char line[1024];
while (fgets(line, sizeof(line), f)) {
if (strstr(line, socket_name) != NULL) {
int pid;
check(sscanf(line, "%*s %d", &pid) == 1);
res = pid;
}
}
pclose(f);
return res;
}
int main(int argc, char **argv)
{
atexit(cleanup);
// create new filename for the socket
char cwd[1024];
check(getcwd(cwd, sizeof(cwd)) != NULL);
snprintf(socket_name, sizeof(socket_name), "%s/sock-%u", cwd, (unsigned) getpid());
// daemon should not exist now
check(get_daemon_pid() == 0);
// launch daemon with -S
int pipes[2];
check(pipe(pipes) == 0);
child_pid = fork();
check(child_pid != -1);
if (child_pid == 0) {
close(pipes[0]);
execl("src/spice-vdagentd", "spice-vdagentd", "-S", socket_name, NULL);
fprintf(stderr, "Error launching agent\n");
return 1;
}
close(pipes[1]);
pipes[1] = -1;
// test child exits with success after a bit (wait timed)
int status;
signal(SIGALRM, handle_alarm);
alarm(1);
check(waitpid(child_pid, &status, 0) == child_pid);
alarm(0);
check(WIFEXITED(status) != 0);
check(WEXITSTATUS(status) == 0);
child_pid = 0;
// test child created the socket passed
struct stat sb;
check(stat(socket_name, &sb) == 0);
check((sb.st_mode & S_IFMT) == S_IFSOCK);
// child should have created the daemon
child_pid = get_daemon_pid();
check(child_pid != 0);
// wait a bit (1 second) and test daemon is still there, not failed some initialization
sleep(1);
check(get_daemon_pid() != 0);
// send a SIGTERM, process should close in a bit
kill(child_pid, SIGTERM);
// test daemon exits after a while, we use the pipe we created above to
// check if daemon closed
alarm(1);
check(read(pipes[0], cwd, sizeof(cwd)) == 0);
alarm(0);
check(get_daemon_pid() == 0);
// test the socket disappeared, so we know the program exited successful
check(stat(socket_name, &sb) == -1);
check(errno == ENOENT);
// don't send a SIGKILL to a not existing process
child_pid = 0;
return 0;
}
+779
View File
@@ -0,0 +1,779 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 55;
objects = {
/* Begin PBXAggregateTarget section */
CE03A11A2CEA8429006884EE /* vd_agent */ = {
isa = PBXAggregateTarget;
buildConfigurationList = CE03A11B2CEA8429006884EE /* Build configuration list for PBXAggregateTarget "vd_agent" */;
buildPhases = (
);
dependencies = (
CE03A11F2CEA8442006884EE /* PBXTargetDependency */,
CE03A1212CEA8442006884EE /* PBXTargetDependency */,
);
name = vd_agent;
packageProductDependencies = (
);
productName = vd_agent;
};
/* End PBXAggregateTarget section */
/* Begin PBXBuildFile section */
CE03A0BC2CE9012D006884EE /* udscs.c in Sources */ = {isa = PBXBuildFile; fileRef = CE03A0B62CE900A0006884EE /* udscs.c */; };
CE03A0BD2CE9012D006884EE /* vdagent-connection.c in Sources */ = {isa = PBXBuildFile; fileRef = CE03A0B82CE900A0006884EE /* vdagent-connection.c */; };
CE03A0C02CE9039B006884EE /* dummy-session-info.c in Sources */ = {isa = PBXBuildFile; fileRef = CE03A0A92CE900A0006884EE /* dummy-session-info.c */; };
CE03A0C22CE90428006884EE /* virtio-port.c in Sources */ = {isa = PBXBuildFile; fileRef = CE03A0B02CE900A0006884EE /* virtio-port.c */; };
CE03A0C32CE90428006884EE /* vdagentd.c in Sources */ = {isa = PBXBuildFile; fileRef = CE03A0AE2CE900A0006884EE /* vdagentd.c */; };
CE03A0C82CE904D3006884EE /* libgio-2.0.a in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A0C52CE904C4006884EE /* libgio-2.0.a */; };
CE03A0C92CE904D4006884EE /* libglib-2.0.a in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A0C62CE904C4006884EE /* libglib-2.0.a */; };
CE03A0CC2CE90506006884EE /* libgobject-2.0.a in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A0CB2CE904EA006884EE /* libgobject-2.0.a */; };
CE03A0E72CE90CFC006884EE /* Vdagent.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE03A0E62CE90CFC006884EE /* Vdagent.swift */; };
CE03A0E82CE90CFC006884EE /* vdagent.c in Sources */ = {isa = PBXBuildFile; fileRef = CE03A0E52CE90CFC006884EE /* vdagent.c */; };
CE03A0EA2CE90D38006884EE /* udscs.c in Sources */ = {isa = PBXBuildFile; fileRef = CE03A0B62CE900A0006884EE /* udscs.c */; };
CE03A0ED2CE90D55006884EE /* ArgumentParser in Frameworks */ = {isa = PBXBuildFile; productRef = CE03A0EC2CE90D55006884EE /* ArgumentParser */; };
CE03A0EE2CE97927006884EE /* vdagent-connection.c in Sources */ = {isa = PBXBuildFile; fileRef = CE03A0B82CE900A0006884EE /* vdagent-connection.c */; };
CE03A0EF2CE97931006884EE /* libgio-2.0.a in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A0C52CE904C4006884EE /* libgio-2.0.a */; };
CE03A0F02CE97933006884EE /* libglib-2.0.a in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A0C62CE904C4006884EE /* libglib-2.0.a */; };
CE03A0F12CE97936006884EE /* libgobject-2.0.a in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A0CB2CE904EA006884EE /* libgobject-2.0.a */; };
CE03A1172CEA83AF006884EE /* com.redhat.spice.vdagentd.plist in CopyFiles */ = {isa = PBXBuildFile; fileRef = CE03A10D2CEA838C006884EE /* com.redhat.spice.vdagentd.plist */; };
CE03A1192CEA83C6006884EE /* com.redhat.spice.vdagent.plist in CopyFiles */ = {isa = PBXBuildFile; fileRef = CE03A10C2CEA838C006884EE /* com.redhat.spice.vdagent.plist */; };
CE03A1262CEA8EF1006884EE /* libiconv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A1232CEA8EF1006884EE /* libiconv.tbd */; };
CE03A1272CEA8EF1006884EE /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A1242CEA8EF1006884EE /* libz.tbd */; };
CE03A1282CEA8EF1006884EE /* libpcre2-8.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A1252CEA8EF1006884EE /* libpcre2-8.tbd */; };
CE03A12A2CEA8F18006884EE /* libffi.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A1292CEA8F18006884EE /* libffi.tbd */; };
CE03A12C2CEA8F6A006884EE /* libgmodule-2.0.a in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A12B2CEA8F60006884EE /* libgmodule-2.0.a */; };
CE03A12E2CEA8F75006884EE /* libintl.a in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A12D2CEA8F75006884EE /* libintl.a */; };
CE03A1302CEA8FBA006884EE /* libresolv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A12F2CEA8FBA006884EE /* libresolv.tbd */; };
CE03A1322CEA8FCE006884EE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A1312CEA8FCE006884EE /* Foundation.framework */; };
CE03A1342CEA8FE4006884EE /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A1332CEA8FE4006884EE /* AppKit.framework */; };
CE77170B2EC0000000A1B2C3 /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CE77170A2EC0000000A1B2C3 /* IOKit.framework */; };
CE54BD8E2CEA90F200FE3930 /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A1332CEA8FE4006884EE /* AppKit.framework */; };
CE54BD8F2CEA90F400FE3930 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A1312CEA8FCE006884EE /* Foundation.framework */; };
CE54BD902CEA90F600FE3930 /* libgmodule-2.0.a in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A12B2CEA8F60006884EE /* libgmodule-2.0.a */; };
CE54BD912CEA90FD00FE3930 /* libintl.a in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A12D2CEA8F75006884EE /* libintl.a */; };
CE54BD922CEA910000FE3930 /* libresolv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A12F2CEA8FBA006884EE /* libresolv.tbd */; };
CE54BD932CEA910200FE3930 /* libffi.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A1292CEA8F18006884EE /* libffi.tbd */; };
CE54BD942CEA910600FE3930 /* libiconv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A1232CEA8EF1006884EE /* libiconv.tbd */; };
CE54BD952CEA910700FE3930 /* libpcre2-8.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A1252CEA8EF1006884EE /* libpcre2-8.tbd */; };
CE54BD962CEA910E00FE3930 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = CE03A1242CEA8EF1006884EE /* libz.tbd */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
CE03A0F22CE9ED98006884EE /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = CE03A0822CE90065006884EE /* Project object */;
proxyType = 1;
remoteGlobalIDString = CE03A0892CE90065006884EE;
remoteInfo = "spice-vdagentd";
};
CE03A11E2CEA8442006884EE /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = CE03A0822CE90065006884EE /* Project object */;
proxyType = 1;
remoteGlobalIDString = CE03A0DC2CE90CE8006884EE;
remoteInfo = "spice-vdagent";
};
CE03A1202CEA8442006884EE /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = CE03A0822CE90065006884EE /* Project object */;
proxyType = 1;
remoteGlobalIDString = CE03A0892CE90065006884EE;
remoteInfo = "spice-vdagentd";
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
CE03A0882CE90065006884EE /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = /Library/LaunchDaemons;
dstSubfolderSpec = 0;
files = (
CE03A1172CEA83AF006884EE /* com.redhat.spice.vdagentd.plist in CopyFiles */,
);
runOnlyForDeploymentPostprocessing = 1;
};
CE03A1182CEA83C0006884EE /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 8;
dstPath = /Library/LaunchAgents;
dstSubfolderSpec = 0;
files = (
CE03A1192CEA83C6006884EE /* com.redhat.spice.vdagent.plist in CopyFiles */,
);
runOnlyForDeploymentPostprocessing = 1;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
CE03A08A2CE90065006884EE /* spice-vdagentd */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "spice-vdagentd"; sourceTree = BUILT_PRODUCTS_DIR; };
CE03A0A92CE900A0006884EE /* dummy-session-info.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = "dummy-session-info.c"; sourceTree = "<group>"; };
CE03A0AA2CE900A0006884EE /* session-info.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "session-info.h"; sourceTree = "<group>"; };
CE03A0AE2CE900A0006884EE /* vdagentd.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = vdagentd.c; sourceTree = "<group>"; };
CE03A0AF2CE900A0006884EE /* virtio-port.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "virtio-port.h"; sourceTree = "<group>"; };
CE03A0B02CE900A0006884EE /* virtio-port.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = "virtio-port.c"; sourceTree = "<group>"; };
CE03A0B42CE900A0006884EE /* config.h.in */ = {isa = PBXFileReference; lastKnownFileType = text; path = config.h.in; sourceTree = "<group>"; };
CE03A0B52CE900A0006884EE /* udscs.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = udscs.h; sourceTree = "<group>"; };
CE03A0B62CE900A0006884EE /* udscs.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = udscs.c; sourceTree = "<group>"; };
CE03A0B72CE900A0006884EE /* vdagent-connection.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "vdagent-connection.h"; sourceTree = "<group>"; };
CE03A0B82CE900A0006884EE /* vdagent-connection.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = "vdagent-connection.c"; sourceTree = "<group>"; };
CE03A0B92CE900A0006884EE /* vdagentd-proto.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "vdagentd-proto.h"; sourceTree = "<group>"; };
CE03A0BA2CE900A0006884EE /* vdagentd-proto-strings.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "vdagentd-proto-strings.h"; sourceTree = "<group>"; };
CE03A0BE2CE9036C006884EE /* config.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = config.h; sourceTree = "<group>"; };
CE03A0C52CE904C4006884EE /* libgio-2.0.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libgio-2.0.a"; path = "$(DERIVED_FILE_DIR)/lib/libgio-2.0.a"; sourceTree = "<absolute>"; };
CE03A0C62CE904C4006884EE /* libglib-2.0.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libglib-2.0.a"; path = "$(DERIVED_FILE_DIR)/lib/libglib-2.0.a"; sourceTree = "<absolute>"; };
CE03A0CB2CE904EA006884EE /* libgobject-2.0.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libgobject-2.0.a"; path = "$(DERIVED_FILE_DIR)/lib/libgobject-2.0.a"; sourceTree = "<absolute>"; };
CE03A0DD2CE90CE8006884EE /* spice-vdagent */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "spice-vdagent"; sourceTree = BUILT_PRODUCTS_DIR; };
CE03A0E42CE90CFC006884EE /* vdagent.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = vdagent.h; sourceTree = "<group>"; };
CE03A0E52CE90CFC006884EE /* vdagent.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = vdagent.c; sourceTree = "<group>"; };
CE03A0E62CE90CFC006884EE /* Vdagent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Vdagent.swift; sourceTree = "<group>"; };
CE03A10C2CEA838C006884EE /* com.redhat.spice.vdagent.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = com.redhat.spice.vdagent.plist; sourceTree = "<group>"; };
CE03A10D2CEA838C006884EE /* com.redhat.spice.vdagentd.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = com.redhat.spice.vdagentd.plist; sourceTree = "<group>"; };
CE03A1232CEA8EF1006884EE /* libiconv.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libiconv.tbd; path = usr/lib/libiconv.tbd; sourceTree = SDKROOT; };
CE03A1242CEA8EF1006884EE /* libz.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libz.tbd; path = usr/lib/libz.tbd; sourceTree = SDKROOT; };
CE03A1252CEA8EF1006884EE /* libpcre2-8.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = "libpcre2-8.tbd"; path = "usr/lib/libpcre2-8.tbd"; sourceTree = SDKROOT; };
CE03A1292CEA8F18006884EE /* libffi.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libffi.tbd; path = usr/lib/libffi.tbd; sourceTree = SDKROOT; };
CE03A12B2CEA8F60006884EE /* libgmodule-2.0.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libgmodule-2.0.a"; path = "$(DERIVED_FILE_DIR)/lib/libgmodule-2.0.a"; sourceTree = "<group>"; };
CE03A12D2CEA8F75006884EE /* libintl.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libintl.a; path = "$(DERIVED_FILE_DIR)/lib/libintl.a"; sourceTree = "<group>"; };
CE03A12F2CEA8FBA006884EE /* libresolv.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libresolv.tbd; path = usr/lib/libresolv.tbd; sourceTree = SDKROOT; };
CE03A1312CEA8FCE006884EE /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
CE03A1332CEA8FE4006884EE /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = System/Library/Frameworks/AppKit.framework; sourceTree = SDKROOT; };
CE77170A2EC0000000A1B2C3 /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
CE03A0872CE90065006884EE /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
CE03A1342CEA8FE4006884EE /* AppKit.framework in Frameworks */,
CE03A1322CEA8FCE006884EE /* Foundation.framework in Frameworks */,
CE77170B2EC0000000A1B2C3 /* IOKit.framework in Frameworks */,
CE03A1302CEA8FBA006884EE /* libresolv.tbd in Frameworks */,
CE03A12E2CEA8F75006884EE /* libintl.a in Frameworks */,
CE03A12A2CEA8F18006884EE /* libffi.tbd in Frameworks */,
CE03A1262CEA8EF1006884EE /* libiconv.tbd in Frameworks */,
CE03A1272CEA8EF1006884EE /* libz.tbd in Frameworks */,
CE03A1282CEA8EF1006884EE /* libpcre2-8.tbd in Frameworks */,
CE03A0C82CE904D3006884EE /* libgio-2.0.a in Frameworks */,
CE03A0C92CE904D4006884EE /* libglib-2.0.a in Frameworks */,
CE03A0CC2CE90506006884EE /* libgobject-2.0.a in Frameworks */,
CE03A12C2CEA8F6A006884EE /* libgmodule-2.0.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
CE03A0DA2CE90CE8006884EE /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
CE03A0ED2CE90D55006884EE /* ArgumentParser in Frameworks */,
CE54BD8E2CEA90F200FE3930 /* AppKit.framework in Frameworks */,
CE54BD8F2CEA90F400FE3930 /* Foundation.framework in Frameworks */,
CE54BD912CEA90FD00FE3930 /* libintl.a in Frameworks */,
CE54BD922CEA910000FE3930 /* libresolv.tbd in Frameworks */,
CE54BD932CEA910200FE3930 /* libffi.tbd in Frameworks */,
CE54BD942CEA910600FE3930 /* libiconv.tbd in Frameworks */,
CE54BD952CEA910700FE3930 /* libpcre2-8.tbd in Frameworks */,
CE54BD962CEA910E00FE3930 /* libz.tbd in Frameworks */,
CE03A0EF2CE97931006884EE /* libgio-2.0.a in Frameworks */,
CE03A0F02CE97933006884EE /* libglib-2.0.a in Frameworks */,
CE54BD902CEA90F600FE3930 /* libgmodule-2.0.a in Frameworks */,
CE03A0F12CE97936006884EE /* libgobject-2.0.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
CE03A0812CE90065006884EE = {
isa = PBXGroup;
children = (
CE03A1162CEA838C006884EE /* data */,
CE03A0BB2CE900A0006884EE /* src */,
CE03A0C42CE904C4006884EE /* Frameworks */,
CE03A08B2CE90065006884EE /* Products */,
);
sourceTree = "<group>";
};
CE03A08B2CE90065006884EE /* Products */ = {
isa = PBXGroup;
children = (
CE03A08A2CE90065006884EE /* spice-vdagentd */,
CE03A0DD2CE90CE8006884EE /* spice-vdagent */,
);
name = Products;
sourceTree = "<group>";
};
CE03A0B32CE900A0006884EE /* vdagentd */ = {
isa = PBXGroup;
children = (
CE03A0A92CE900A0006884EE /* dummy-session-info.c */,
CE03A0AA2CE900A0006884EE /* session-info.h */,
CE03A0AE2CE900A0006884EE /* vdagentd.c */,
CE03A0AF2CE900A0006884EE /* virtio-port.h */,
CE03A0B02CE900A0006884EE /* virtio-port.c */,
);
path = vdagentd;
sourceTree = "<group>";
};
CE03A0BB2CE900A0006884EE /* src */ = {
isa = PBXGroup;
children = (
CE03A0BF2CE9036C006884EE /* darwin */,
CE03A0B32CE900A0006884EE /* vdagentd */,
CE03A0B42CE900A0006884EE /* config.h.in */,
CE03A0B52CE900A0006884EE /* udscs.h */,
CE03A0B62CE900A0006884EE /* udscs.c */,
CE03A0B72CE900A0006884EE /* vdagent-connection.h */,
CE03A0B82CE900A0006884EE /* vdagent-connection.c */,
CE03A0B92CE900A0006884EE /* vdagentd-proto.h */,
CE03A0BA2CE900A0006884EE /* vdagentd-proto-strings.h */,
);
path = src;
sourceTree = "<group>";
};
CE03A0BF2CE9036C006884EE /* darwin */ = {
isa = PBXGroup;
children = (
CE03A0E42CE90CFC006884EE /* vdagent.h */,
CE03A0E52CE90CFC006884EE /* vdagent.c */,
CE03A0E62CE90CFC006884EE /* Vdagent.swift */,
CE03A0C12CE903F0006884EE /* include */,
);
path = darwin;
sourceTree = "<group>";
};
CE03A0C12CE903F0006884EE /* include */ = {
isa = PBXGroup;
children = (
CE03A0BE2CE9036C006884EE /* config.h */,
);
path = include;
sourceTree = "<group>";
};
CE03A0C42CE904C4006884EE /* Frameworks */ = {
isa = PBXGroup;
children = (
CE03A1332CEA8FE4006884EE /* AppKit.framework */,
CE03A1312CEA8FCE006884EE /* Foundation.framework */,
CE77170A2EC0000000A1B2C3 /* IOKit.framework */,
CE03A12B2CEA8F60006884EE /* libgmodule-2.0.a */,
CE03A12D2CEA8F75006884EE /* libintl.a */,
CE03A12F2CEA8FBA006884EE /* libresolv.tbd */,
CE03A1292CEA8F18006884EE /* libffi.tbd */,
CE03A1232CEA8EF1006884EE /* libiconv.tbd */,
CE03A1252CEA8EF1006884EE /* libpcre2-8.tbd */,
CE03A1242CEA8EF1006884EE /* libz.tbd */,
CE03A0C52CE904C4006884EE /* libgio-2.0.a */,
CE03A0C62CE904C4006884EE /* libglib-2.0.a */,
CE03A0CB2CE904EA006884EE /* libgobject-2.0.a */,
);
name = Frameworks;
sourceTree = "<group>";
};
CE03A1162CEA838C006884EE /* data */ = {
isa = PBXGroup;
children = (
CE03A10C2CEA838C006884EE /* com.redhat.spice.vdagent.plist */,
CE03A10D2CEA838C006884EE /* com.redhat.spice.vdagentd.plist */,
);
path = data;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
CE03A0892CE90065006884EE /* spice-vdagentd */ = {
isa = PBXNativeTarget;
buildConfigurationList = CE03A0912CE90065006884EE /* Build configuration list for PBXNativeTarget "spice-vdagentd" */;
buildPhases = (
CE03A0F42CE9EDB0006884EE /* Fetch SPICE headers */,
CE03A1222CEA86DC006884EE /* Build universal GLib */,
CE03A0862CE90065006884EE /* Sources */,
CE03A0872CE90065006884EE /* Frameworks */,
CE03A0882CE90065006884EE /* CopyFiles */,
);
buildRules = (
);
dependencies = (
);
name = "spice-vdagentd";
packageProductDependencies = (
);
productName = vd_agent;
productReference = CE03A08A2CE90065006884EE /* spice-vdagentd */;
productType = "com.apple.product-type.tool";
};
CE03A0DC2CE90CE8006884EE /* spice-vdagent */ = {
isa = PBXNativeTarget;
buildConfigurationList = CE03A0E12CE90CE8006884EE /* Build configuration list for PBXNativeTarget "spice-vdagent" */;
buildPhases = (
CE54BD972CEA914E00FE3930 /* Build universal GLib */,
CE03A0D92CE90CE8006884EE /* Sources */,
CE03A0DA2CE90CE8006884EE /* Frameworks */,
CE03A1182CEA83C0006884EE /* CopyFiles */,
);
buildRules = (
);
dependencies = (
CE03A0F32CE9ED98006884EE /* PBXTargetDependency */,
);
name = "spice-vdagent";
packageProductDependencies = (
CE03A0EC2CE90D55006884EE /* ArgumentParser */,
);
productName = "spice-vdagent";
productReference = CE03A0DD2CE90CE8006884EE /* spice-vdagent */;
productType = "com.apple.product-type.tool";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
CE03A0822CE90065006884EE /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 1600;
TargetAttributes = {
CE03A0892CE90065006884EE = {
CreatedOnToolsVersion = 16.0;
};
CE03A0DC2CE90CE8006884EE = {
CreatedOnToolsVersion = 16.0;
LastSwiftMigration = 1600;
};
CE03A11A2CEA8429006884EE = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = CE03A0852CE90065006884EE /* Build configuration list for PBXProject "vd_agent" */;
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = CE03A0812CE90065006884EE;
minimizedProjectReferenceProxies = 1;
packageReferences = (
CE03A0EB2CE90D55006884EE /* XCRemoteSwiftPackageReference "swift-argument-parser" */,
);
preferredProjectObjectVersion = 77;
productRefGroup = CE03A08B2CE90065006884EE /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
CE03A11A2CEA8429006884EE /* vd_agent */,
CE03A0892CE90065006884EE /* spice-vdagentd */,
CE03A0DC2CE90CE8006884EE /* spice-vdagent */,
);
};
/* End PBXProject section */
/* Begin PBXShellScriptBuildPhase section */
CE03A0F42CE9EDB0006884EE /* Fetch SPICE headers */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = "Fetch SPICE headers";
outputFileListPaths = (
);
outputPaths = (
"$(PROJECT_DIR)/src/darwin/include/spice",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "set -e\nif [ ! -d \"$SCRIPT_OUTPUT_FILE_0\" ]; then\n URL=\"https://www.spice-space.org/download/releases/spice-protocol-0.14.4.tar.xz\"\n FILE=\"$(basename $URL)\"\n NAME=\"${FILE%.tar.*}\"\n cd /tmp\n curl -L -O \"$URL\"\n tar -xf \"$FILE\"\n mv \"$NAME/spice\" \"$SCRIPT_OUTPUT_FILE_0\"\n rm -rf \"$DIR\" \"$FILE\"\nfi\n";
showEnvVarsInLog = 0;
};
CE03A1222CEA86DC006884EE /* Build universal GLib */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"$(GLIB_X86_64_PREFIX)/lib/libgio-2.0.a",
"$(GLIB_X86_64_PREFIX)/lib/libglib-2.0.a",
"$(GLIB_X86_64_PREFIX)/lib/libgobject-2.0.a",
"$(GLIB_X86_64_PREFIX)/lib/libgmodule-2.0.a",
"$(GLIB_X86_64_PREFIX)/lib/libintl.a",
"$(GLIB_ARM64_PREFIX)/lib/libgio-2.0.a",
"$(GLIB_ARM64_PREFIX)/lib/libglib-2.0.a",
"$(GLIB_ARM64_PREFIX)/lib/libgobject-2.0.a",
"$(GLIB_ARM64_PREFIX)/lib/libgmodule-2.0.a",
"$(GLIB_ARM64_PREFIX)/lib/libintl.a",
);
name = "Build universal GLib";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/lib/libgio-2.0.a",
"$(DERIVED_FILE_DIR)/lib/libglib-2.0.a",
"$(DERIVED_FILE_DIR)/lib/libgobject-2.0.a",
"$(DERIVED_FILE_DIR)/lib/libgmodule-2.0.a",
"$(DERIVED_FILE_DIR)/lib/libintl.a",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "set -e\n\nfor ((i=0; i<$SCRIPT_OUTPUT_FILE_COUNT; i++)); do\n output_var=\"SCRIPT_OUTPUT_FILE_$i\"\n output_path=\"${!output_var}\"\n output_dir=\"$(dirname \"$output_path\")\"\n name=\"$(basename \"$output_path\")\"\n intel_input=\"$GLIB_X86_64_PREFIX/lib/$name\"\n arm64_input=\"$GLIB_ARM64_PREFIX/lib/$name\"\n tmp_output=\"/tmp/$name.$$\"\n \n echo \"Creating $output_path\"\n lipo -output \"$tmp_output\" -create \"$intel_input\" \"$arm64_input\"\n if [ ! -d \"$output_dir\" ]; then\n mkdir -p \"$output_dir\"\n fi\n mv \"$tmp_output\" \"$output_path\"\ndone\n";
showEnvVarsInLog = 0;
};
CE54BD972CEA914E00FE3930 /* Build universal GLib */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"$(GLIB_X86_64_PREFIX)/lib/libgio-2.0.a",
"$(GLIB_X86_64_PREFIX)/lib/libglib-2.0.a",
"$(GLIB_X86_64_PREFIX)/lib/libgobject-2.0.a",
"$(GLIB_X86_64_PREFIX)/lib/libgmodule-2.0.a",
"$(GLIB_X86_64_PREFIX)/lib/libintl.a",
"$(GLIB_ARM64_PREFIX)/lib/libgio-2.0.a",
"$(GLIB_ARM64_PREFIX)/lib/libglib-2.0.a",
"$(GLIB_ARM64_PREFIX)/lib/libgobject-2.0.a",
"$(GLIB_ARM64_PREFIX)/lib/libgmodule-2.0.a",
"$(GLIB_ARM64_PREFIX)/lib/libintl.a",
);
name = "Build universal GLib";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/lib/libgio-2.0.a",
"$(DERIVED_FILE_DIR)/lib/libglib-2.0.a",
"$(DERIVED_FILE_DIR)/lib/libgobject-2.0.a",
"$(DERIVED_FILE_DIR)/lib/libgmodule-2.0.a",
"$(DERIVED_FILE_DIR)/lib/libintl.a",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "set -e\n\nfor ((i=0; i<$SCRIPT_OUTPUT_FILE_COUNT; i++)); do\n output_var=\"SCRIPT_OUTPUT_FILE_$i\"\n output_path=\"${!output_var}\"\n output_dir=\"$(dirname \"$output_path\")\"\n name=\"$(basename \"$output_path\")\"\n intel_input=\"$GLIB_X86_64_PREFIX/lib/$name\"\n arm64_input=\"$GLIB_ARM64_PREFIX/lib/$name\"\n tmp_output=\"/tmp/$name.$$\"\n \n echo \"Creating $output_path\"\n lipo -output \"$tmp_output\" -create \"$intel_input\" \"$arm64_input\"\n if [ ! -d \"$output_dir\" ]; then\n mkdir -p \"$output_dir\"\n fi\n mv \"$tmp_output\" \"$output_path\"\ndone\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
CE03A0862CE90065006884EE /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
CE03A0BC2CE9012D006884EE /* udscs.c in Sources */,
CE03A0C22CE90428006884EE /* virtio-port.c in Sources */,
CE03A0C32CE90428006884EE /* vdagentd.c in Sources */,
CE03A0BD2CE9012D006884EE /* vdagent-connection.c in Sources */,
CE03A0C02CE9039B006884EE /* dummy-session-info.c in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
CE03A0D92CE90CE8006884EE /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
CE03A0EA2CE90D38006884EE /* udscs.c in Sources */,
CE03A0E72CE90CFC006884EE /* Vdagent.swift in Sources */,
CE03A0E82CE90CFC006884EE /* vdagent.c in Sources */,
CE03A0EE2CE97927006884EE /* vdagent-connection.c in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
CE03A0F32CE9ED98006884EE /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = CE03A0892CE90065006884EE /* spice-vdagentd */;
targetProxy = CE03A0F22CE9ED98006884EE /* PBXContainerItemProxy */;
};
CE03A11F2CEA8442006884EE /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = CE03A0DC2CE90CE8006884EE /* spice-vdagent */;
targetProxy = CE03A11E2CEA8442006884EE /* PBXContainerItemProxy */;
};
CE03A1212CEA8442006884EE /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = CE03A0892CE90065006884EE /* spice-vdagentd */;
targetProxy = CE03A1202CEA8442006884EE /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
CE03A08F2CE90065006884EE /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
GLIB_ARM64_PREFIX = /opt/homebrew;
GLIB_X86_64_PREFIX = /usr/local;
HEADER_SEARCH_PATHS = (
"$(PROJECT_DIR)/src/darwin/include",
"$(GLIB_ARM64_PREFIX)/include/glib-2.0",
"$(GLIB_ARM64_PREFIX)/include/gio-unix-2.0",
"$(GLIB_ARM64_PREFIX)/lib/glib-2.0/include",
);
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(DERIVED_FILE_DIR)/lib",
);
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 10.13;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
};
name = Debug;
};
CE03A0902CE90065006884EE /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
GLIB_ARM64_PREFIX = /opt/homebrew;
GLIB_X86_64_PREFIX = /usr/local;
HEADER_SEARCH_PATHS = (
"$(PROJECT_DIR)/src/darwin/include",
"$(GLIB_ARM64_PREFIX)/include/glib-2.0",
"$(GLIB_ARM64_PREFIX)/include/gio-unix-2.0",
"$(GLIB_ARM64_PREFIX)/lib/glib-2.0/include",
);
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(DERIVED_FILE_DIR)/lib",
);
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 10.13;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
};
name = Release;
};
CE03A0922CE90065006884EE /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
};
CE03A0932CE90065006884EE /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
CE03A0E22CE90CE8006884EE /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/$(DERIVED_FILE_DIR)/lib",
);
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_OBJC_BRIDGING_HEADER = src/darwin/vdagent.h;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
};
name = Debug;
};
CE03A0E32CE90CE8006884EE /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/$(DERIVED_FILE_DIR)/lib",
);
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OBJC_BRIDGING_HEADER = src/darwin/vdagent.h;
SWIFT_VERSION = 5.0;
};
name = Release;
};
CE03A11C2CEA8429006884EE /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
};
CE03A11D2CEA8429006884EE /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
CE03A0852CE90065006884EE /* Build configuration list for PBXProject "vd_agent" */ = {
isa = XCConfigurationList;
buildConfigurations = (
CE03A08F2CE90065006884EE /* Debug */,
CE03A0902CE90065006884EE /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
CE03A0912CE90065006884EE /* Build configuration list for PBXNativeTarget "spice-vdagentd" */ = {
isa = XCConfigurationList;
buildConfigurations = (
CE03A0922CE90065006884EE /* Debug */,
CE03A0932CE90065006884EE /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
CE03A0E12CE90CE8006884EE /* Build configuration list for PBXNativeTarget "spice-vdagent" */ = {
isa = XCConfigurationList;
buildConfigurations = (
CE03A0E22CE90CE8006884EE /* Debug */,
CE03A0E32CE90CE8006884EE /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
CE03A11B2CEA8429006884EE /* Build configuration list for PBXAggregateTarget "vd_agent" */ = {
isa = XCConfigurationList;
buildConfigurations = (
CE03A11C2CEA8429006884EE /* Debug */,
CE03A11D2CEA8429006884EE /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
CE03A0EB2CE90D55006884EE /* XCRemoteSwiftPackageReference "swift-argument-parser" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/apple/swift-argument-parser.git";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 1.5.0;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
CE03A0EC2CE90D55006884EE /* ArgumentParser */ = {
isa = XCSwiftPackageProductDependency;
package = CE03A0EB2CE90D55006884EE /* XCRemoteSwiftPackageReference "swift-argument-parser" */;
productName = ArgumentParser;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = CE03A0822CE90065006884EE /* Project object */;
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
@@ -0,0 +1,15 @@
{
"originHash" : "59ba1edda695b389d6c9ac1809891cd779e4024f505b0ce1a9d5202b6762e38a",
"pins" : [
{
"identity" : "swift-argument-parser",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-argument-parser.git",
"state" : {
"revision" : "41982a3656a71c768319979febd796c6fd111d5c",
"version" : "1.5.0"
}
}
],
"version" : 3
}
@@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1600"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CE03A0DC2CE90CE8006884EE"
BuildableName = "spice-vdagent"
BlueprintName = "spice-vdagent"
ReferencedContainer = "container:vd_agent.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES"
viewDebuggingEnabled = "No">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CE03A0DC2CE90CE8006884EE"
BuildableName = "spice-vdagent"
BlueprintName = "spice-vdagent"
ReferencedContainer = "container:vd_agent.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<CommandLineArguments>
<CommandLineArgument
argument = "-d"
isEnabled = "YES">
</CommandLineArgument>
<CommandLineArgument
argument = "-x"
isEnabled = "YES">
</CommandLineArgument>
<CommandLineArgument
argument = "-S /var/run/spice-vdagent-sock"
isEnabled = "YES">
</CommandLineArgument>
</CommandLineArguments>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CE03A0DC2CE90CE8006884EE"
BuildableName = "spice-vdagent"
BlueprintName = "spice-vdagent"
ReferencedContainer = "container:vd_agent.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,98 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1600"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CE03A0892CE90065006884EE"
BuildableName = "spice-vdagentd"
BlueprintName = "spice-vdagentd"
ReferencedContainer = "container:vd_agent.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
debugAsWhichUser = "root"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES"
viewDebuggingEnabled = "No">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CE03A0892CE90065006884EE"
BuildableName = "spice-vdagentd"
BlueprintName = "spice-vdagentd"
ReferencedContainer = "container:vd_agent.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<CommandLineArguments>
<CommandLineArgument
argument = "-d"
isEnabled = "YES">
</CommandLineArgument>
<CommandLineArgument
argument = "-s /dev/tty.com.redhat.spice.0"
isEnabled = "YES">
</CommandLineArgument>
<CommandLineArgument
argument = "-S /var/run/spice-vdagent-sock"
isEnabled = "YES">
</CommandLineArgument>
<CommandLineArgument
argument = "-x"
isEnabled = "YES">
</CommandLineArgument>
</CommandLineArguments>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CE03A0892CE90065006884EE"
BuildableName = "spice-vdagentd"
BlueprintName = "spice-vdagentd"
ReferencedContainer = "container:vd_agent.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>