Skip to content
Snippets Groups Projects
Commit 1069e52a authored by Liang Guo's avatar Liang Guo
Browse files

Imported Upstream version 0.6.3

parents
No related branches found
No related tags found
No related merge requests found
spice-vdagent
spice-vdagentd
*.o
*~
COPYING 0 → 100644
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
spice-agent-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
Makefile 0 → 100644
VERSION = 0.6.3
DESTDIR ?=
sbindir ?= /sbin
bindir ?= /usr/bin
initdir ?= /etc/rc.d/init.d
xdgautostartdir ?= /etc/xdg/autostart
gdmautostartdir ?= /usr/share/gdm/autostart/LoginWindow
socketdir ?= /var/run/spice-vdagentd
CFLAGS ?= -O2 -g -Wall
CPPFLAGS = $(shell pkg-config --cflags spice-protocol)
CPPFLAGS += $(shell pkg-config --cflags dbus-1)
CPPFLAGS += -D_GNU_SOURCE
TARGETS := spice-vdagentd spice-vdagent
build: $(TARGETS)
install: build
install -d $(DESTDIR)$(bindir)
install -d $(DESTDIR)$(sbindir)
install -d $(DESTDIR)$(socketdir)
install -p -m 755 spice-vdagent $(DESTDIR)$(bindir)
install -p -m 755 spice-vdagentd $(DESTDIR)$(sbindir)
install -d $(DESTDIR)$(initdir)
install -p -m 755 spice-vdagentd.sh $(DESTDIR)$(initdir)/spice-vdagentd
install -d $(DESTDIR)$(xdgautostartdir)
install -d $(DESTDIR)$(gdmautostartdir)
desktop-file-install --dir=$(DESTDIR)$(xdgautostartdir) \
spice-vdagent.desktop
desktop-file-install --dir=$(DESTDIR)$(gdmautostartdir) \
spice-vdagent.desktop
clean:
rm -f $(TARGETS) *.o *~
spice-vdagentd: vdagentd.o vdagentd-uinput.o udscs.o vdagent-virtio-port.o console-kit.o
$(CC) -o $@ $^ $(shell pkg-config --libs dbus-1)
spice-vdagent: vdagent.o vdagent-x11.o udscs.o
$(CC) -o $@ $^ -lX11 -lXrandr -lXfixes
tag:
@git tag -a -m "Tag as spice-vdagent-$(VERSION)" spice-vdagent-$(VERSION)
@echo "Tagged as spice-vdagent-$(VERSION)"
archive-no-tag:
@git archive --format=tar --prefix=spice-vdagent-$(VERSION)/ spice-vdagent-$(VERSION) > spice-vdagent-$(VERSION).tar
@bzip2 -f spice-vdagent-$(VERSION).tar
archive: clean tag archive-no-tag
README 0 → 100644
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 automatically started
in Spice guests through a udev rule. 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 the currently
active X-session (think switch user functionality) for this console kit is
used. spice-vdagent will not work without console kit.
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
Not handled: multiple displays.
Enjoy,
Gerd & Hans
--
Gerd Hoffmann <kraxel@redhat.com>
Hans de Goede <hdegoede@redhat.com>
TODO 0 → 100644
-patch xorg driver to allow adding "random" resolutions
-make vdagent xorg client try to add "random" resolutions
Maybe:
-Add support for selections with a target of STRING, which are
ISO Latin-1 strings, which we could support through iconv
/* console-kit.h vdagentd ConsoleKit integration code
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <hdegoede@redhat.com>
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 "console-kit.h"
#include <dbus/dbus.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
struct console_kit {
DBusConnection *connection;
int fd;
char *seat;
char *active_session;
FILE *errfile;
};
static char *console_kit_get_first_seat(struct console_kit *ck);
static char *console_kit_check_active_session_change(struct console_kit *ck);
struct console_kit *console_kit_create(FILE *errfile)
{
struct console_kit *ck;
DBusError error;
char match[1024];
ck = calloc(1, sizeof(*ck));
if (!ck)
return NULL;
ck->errfile = errfile;
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)) {
fprintf(ck->errfile, "Unable to connect to system bus: %s\n",
error.message);
dbus_error_free(&error);
} else
fprintf(ck->errfile, "Unable to connect to system bus\n");
free(ck);
return NULL;
}
if (!dbus_connection_get_unix_fd(ck->connection, &ck->fd)) {
fprintf(ck->errfile, "Unable to get connection fd\n");
console_kit_destroy(ck);
return NULL;
}
if (!console_kit_get_first_seat(ck)) {
console_kit_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)) {
fprintf(ck->errfile, "Match Error (%s)\n", error.message);
console_kit_destroy(ck);
return NULL;
}
return ck;
}
void console_kit_destroy(struct console_kit *ck)
{
if (!ck)
return;
dbus_connection_close(ck->connection);
free(ck->seat);
free(ck->active_session);
free(ck);
}
int console_kit_get_fd(struct console_kit *ck)
{
return ck->fd;
}
static char *console_kit_get_first_seat(struct console_kit *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) {
fprintf(ck->errfile, "Unable to create dbus message\n");
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)) {
fprintf(ck->errfile, "GetSeats failed: %s\n",
error.message);
dbus_error_free(&error);
} else
fprintf(ck->errfile, "GetSeats failed\n");
goto exit;
}
dbus_message_iter_init(reply, &iter);
type = dbus_message_iter_get_arg_type(&iter);
if (type != DBUS_TYPE_ARRAY) {
fprintf(ck->errfile,
"expected an array return value, got a '%c' instead\n", type);
goto exit;
}
dbus_message_iter_recurse(&iter, &subiter);
type = dbus_message_iter_get_arg_type(&subiter);
if (type != DBUS_TYPE_OBJECT_PATH) {
fprintf(ck->errfile,
"expected an object path element, got a '%c' instead\n", 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 *console_kit_get_active_session(struct console_kit *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) {
fprintf(ck->errfile, "Unable to create dbus message\n");
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)) {
fprintf(ck->errfile, "GetActiveSession failed: %s\n",
error.message);
dbus_error_free(&error);
} else
fprintf(ck->errfile, "GetActiveSession failed\n");
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)) {
fprintf(ck->errfile, "error getting ssid from reply: %s\n",
error.message);
dbus_error_free(&error);
} else
fprintf(ck->errfile, "error getting ssid from reply\n");
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 *console_kit_session_for_pid(struct console_kit *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) {
fprintf(ck->errfile, "Unable to create dbus message\n");
goto exit;
}
dbus_message_iter_init_append(message, &args);
if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &pid)) {
fprintf(ck->errfile, "Unable to append dbus message args\n");
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)) {
fprintf(ck->errfile, "GetSessionForUnixProcess failed: %s\n",
error.message);
dbus_error_free(&error);
} else
fprintf(ck->errfile, "GetSessionForUnixProces failed\n");
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)) {
fprintf(ck->errfile, "error getting ssid from reply: %s\n",
error.message);
dbus_error_free(&error);
} else
fprintf(ck->errfile, "error getting ssid from reply\n");
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 console_kit *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")) {
fprintf(ck->errfile, "unexpected signal member: %s\n", member);
dbus_message_unref(message);
continue;
}
} else {
fprintf(ck->errfile, "received non signal message!\n");
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) {
fprintf(ck->errfile,
"ActiveSessionChanged message has unexpected type: '%c'\n",
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;
}
/* console-kit.h vdagentd ConsoleKit integration code - header
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <hdegoede@redhat.com>
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 __CONSOLE_KIT_H
#define __CONSOLE_KIT_H
#include <stdio.h>
#include <stdint.h>
struct console_kit;
struct console_kit *console_kit_create(FILE *errfile);
void console_kit_destroy(struct console_kit *ck);
int console_kit_get_fd(struct console_kit *ck);
const char *console_kit_get_active_session(struct console_kit *ck);
/* Note result must be free()-ed by caller */
char *console_kit_session_for_pid(struct console_kit *ck, uint32_t pid);
#endif
[Desktop Entry]
Name=Spice vdagent
Comment=Agent for Spice guests
Exec=/usr/bin/spice-vdagent
Terminal=false
Type=Application
Categories=
X-GNOME-Autostart-Phase=Initialization
X-GNOME-AutoRestart=true
#!/bin/sh
#
# spice-vdagentd Agent daemon for Spice guests
#
# chkconfig: 345 70 30
# description: Together with a per X-session agent process the spice agent \
# daemon enhances the spice guest user experience with client \
# mouse mode, guest <-> client copy and paste support and more.
### BEGIN INIT INFO
# Provides: spice-vdagentd
# Required-Start: $local_fs messagebus
# Required-Stop: $local_fs messagebus
# Should-Start: $local_fs messagebus
# Should-Stop: $local_fs messagebus
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Agent daemon for Spice guests
# Description: Together with a per X-session agent process the spice agent
# daemon enhances the spice guest user experience with client
# mouse mode, guest <-> client copy and paste support and more.
### END INIT INFO
# Source function library.
. /etc/rc.d/init.d/functions
exec="/sbin/spice-vdagentd"
prog="spice-vdagentd"
port="/dev/virtio-ports/com.redhat.spice.0"
[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog
lockfile=/var/lock/subsys/$prog
start() {
[ -x $exec ] || exit 5
[ -c $port ] || exit 6
# In case the previous running vdagentd crashed
rm -f /var/run/spice-vdagentd/spice-vdagent-sock
echo -n $"Starting $prog: "
daemon $exec $SPICE_VDAGENTD_EXTRA_ARGS
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $prog: "
killproc $prog
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
stop
start
}
reload() {
restart
}
force_reload() {
restart
}
rh_status() {
# run checks to determine if the service is running or use generic status
status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
restart
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
exit 2
esac
exit $?
udscs.c 0 → 100644
/* udscs.c Unix Domain Socket Client Server framework. A framework for quickly
creating select() based servers capable of handling multiple clients and
matching select() based clients using variable size messages.
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <hdegoede@redhat.com>
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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "udscs.h"
struct udscs_buf {
uint8_t *buf;
size_t pos;
size_t size;
struct udscs_buf *next;
};
struct udscs_connection {
int fd;
const char * const *type_to_string;
int no_types;
FILE *logfile;
FILE *errfile;
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;
FILE *logfile;
FILE *errfile;
struct udscs_connection connections_head;
udscs_connect_callback connect_callback;
udscs_read_callback read_callback;
udscs_disconnect_callback disconnect_callback;
};
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,
FILE *logfile, FILE *errfile)
{
int c;
struct sockaddr_un address;
struct udscs_server *server;
server = calloc(1, sizeof(*server));
if (!server)
return NULL;
server->logfile = logfile;
server->errfile = errfile;
server->type_to_string = type_to_string;
server->no_types = no_types;
server->fd = socket(PF_UNIX, SOCK_STREAM, 0);
if (server->fd == -1) {
fprintf(server->errfile, "creating unix domain socket: %s\n",
strerror(errno));
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) {
fprintf(server->errfile, "bind %s: %s\n", socketname, strerror(errno));
free(server);
return NULL;
}
c = listen(server->fd, 5);
if (c != 0) {
fprintf(server->errfile, "listen: %s\n", strerror(errno));
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)
return;
conn = server->connections_head.next;
while (conn) {
next_conn = conn->next;
udscs_destroy_connection(&conn);
conn = next_conn;
}
close(server->fd);
free(server);
}
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,
FILE *logfile, FILE *errfile)
{
int c;
struct sockaddr_un address;
struct udscs_connection *conn;
conn = calloc(1, sizeof(*conn));
if (!conn)
return NULL;
conn->logfile = logfile;
conn->errfile = errfile;
conn->type_to_string = type_to_string;
conn->no_types = no_types;
conn->fd = socket(PF_UNIX, SOCK_STREAM, 0);
if (conn->fd == -1) {
fprintf(conn->errfile, "creating unix domain socket: %s\n",
strerror(errno));
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) {
fprintf(conn->errfile, "connect %s: %s\n", socketname,
strerror(errno));
free(conn);
return NULL;
}
conn->read_callback = read_callback;
conn->disconnect_callback = disconnect_callback;
if (conn->logfile)
fprintf(conn->logfile, "%p connected to %s\n", 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->logfile)
fprintf(conn->logfile, "%p disconnected\n", 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;
fprintf(server->errfile, "accept: %s\n", strerror(errno));
return;
}
new_conn = calloc(1, sizeof(*conn));
if (!new_conn) {
fprintf(server->errfile, "out of memory, disconnecting new client\n");
close(fd);
return;
}
new_conn->fd = fd;
new_conn->logfile = server->logfile;
new_conn->errfile = server->errfile;
new_conn->type_to_string = server->type_to_string;
new_conn->no_types = server->no_types;
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) {
fprintf(server->errfile,
"Could not get peercred, disconnecting new client\n");
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->logfile)
fprintf(server->logfile, "new client accepted: %p, pid: %d\n",
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 opaque,
const uint8_t *data, uint32_t size)
{
struct udscs_buf *wbuf, *new_wbuf;
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;
}
header.type = type;
header.opaque = opaque;
header.size = size;
memcpy(new_wbuf->buf, &header, sizeof(header));
memcpy(new_wbuf->buf + sizeof(header), data, size);
if (conn->logfile) {
if (type < conn->no_types)
fprintf(conn->logfile, "%p sent %s, opaque: %u, size %u\n",
conn, conn->type_to_string[type], opaque, size);
else
fprintf(conn->logfile,
"%p sent invalid message %u, opaque: %u, size %u\n",
conn, type, opaque, size);
}
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;
}
int udscs_server_write_all(struct udscs_server *server,
uint32_t type, uint32_t opaque,
const uint8_t *data, uint32_t size)
{
struct udscs_connection *conn;
conn = server->connections_head.next;
while (conn) {
if (udscs_write(conn, type, opaque, data, size))
return -1;
conn = conn->next;
}
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;
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;
}
return r;
}
static void udscs_read_complete(struct udscs_connection **connp)
{
struct udscs_connection *conn = *connp;
if (conn->logfile) {
if (conn->header.type < conn->no_types)
fprintf(conn->logfile, "%p received %s, opaque: %u, size %u\n",
conn, conn->type_to_string[conn->header.type],
conn->header.opaque, conn->header.size);
else
fprintf(conn->logfile,
"%p received invalid message %u, opaque: %u, size %u\n",
conn, conn->header.type, conn->header.opaque,
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;
}
free(conn->data.buf);
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;
fprintf(conn->errfile,
"reading unix domain socket: %s, disconnecting %p\n",
strerror(errno), 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) {
fprintf(conn->errfile, "out of memory, disconnecting %p\n",
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) {
fprintf(conn->errfile,
"%p do_write called on a connection without a write buf ?!\n",
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;
fprintf(conn->errfile,
"writing to unix domain socket: %s, disconnecting %p\n",
strerror(errno), 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;
}
udscs.h 0 → 100644
/* udscs.h Unix Domain Socket Client Server framework header file
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <hdegoede@redhat.com>
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 __UDSCS_H
#define __UDSCS_H
#include <stdio.h>
#include <stdint.h>
#include <sys/select.h>
#include <sys/socket.h>
struct udscs_connection;
struct udscs_server;
struct udscs_message_header {
uint32_t type;
uint32_t opaque;
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,
struct udscs_message_header *header, const 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,
udscs_read_callback read_callback,
udscs_disconnect_callback disconnect_callback,
const char * const type_to_string[], int no_types,
FILE *logfile, FILE *errfile);
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,
FILE *logfile, FILE *errfile);
/* 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);
/* 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 opaque,
const uint8_t *data, uint32_t size);
/* 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 opaque,
const uint8_t *data, uint32_t size);
/* 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 */
int udscs_server_for_all_clients(struct udscs_server *server,
udscs_for_all_clients_callback func, void *priv);
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);
#endif
/* vdagent-virtio-port.c virtio port communication code
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <hdegoede@redhat.com>
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 <unistd.h>
#include <fcntl.h>
#include <sys/select.h>
#include "vdagent-virtio-port.h"
struct vdagent_virtio_port_buf {
uint8_t *buf;
size_t pos;
size_t size;
struct vdagent_virtio_port_buf *next;
};
struct vdagent_virtio_port {
int fd;
FILE *errfile;
/* Read stuff, single buffer, separate header and data buffer */
int chunk_header_read;
int chunk_data_pos;
int message_header_read;
int message_data_pos;
VDIChunkHeader chunk_header;
VDAgentMessage message_header;
uint8_t chunk_data[VD_AGENT_MAX_DATA_SIZE];
uint8_t *message_data;
/* 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 **portp);
static void vdagent_virtio_port_do_read(struct vdagent_virtio_port **portp);
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,
FILE *errfile)
{
struct vdagent_virtio_port *port;
port = calloc(1, sizeof(*port));
if (!port)
return 0;
port->errfile = errfile;
port->fd = open(portname, O_RDWR);
if (port->fd == -1) {
fprintf(port->errfile, "open %s: %s\n", portname, strerror(errno));
free(port);
return NULL;
}
port->read_callback = read_callback;
port->disconnect_callback = disconnect_callback;
return port;
}
void vdagent_virtio_port_destroy(struct vdagent_virtio_port **portp)
{
struct vdagent_virtio_port_buf *wbuf, *next_wbuf;
struct vdagent_virtio_port *port = *portp;
if (!port)
return;
if (port->disconnect_callback)
port->disconnect_callback(port);
wbuf = port->write_buf;
while (wbuf) {
next_wbuf = wbuf->next;
free(wbuf->buf);
free(wbuf);
wbuf = next_wbuf;
}
free(port->message_data);
close(port->fd);
free(port);
*portp = NULL;
}
int vdagent_virtio_port_fill_fds(struct vdagent_virtio_port *port,
fd_set *readfds, fd_set *writefds)
{
if (!port)
return -1;
FD_SET(port->fd, readfds);
if (port->write_buf)
FD_SET(port->fd, writefds);
return port->fd + 1;
}
void vdagent_virtio_port_handle_fds(struct vdagent_virtio_port **portp,
fd_set *readfds, fd_set *writefds)
{
if (!*portp)
return;
if (FD_ISSET((*portp)->fd, readfds))
vdagent_virtio_port_do_read(portp);
if (*portp && FD_ISSET((*portp)->fd, writefds))
vdagent_virtio_port_do_write(portp);
}
int vdagent_virtio_port_write(
struct vdagent_virtio_port *port,
uint32_t port_nr,
uint32_t message_type,
uint32_t message_opaque,
const uint8_t *data,
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->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;
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, &chunk_header, sizeof(chunk_header));
memcpy(new_wbuf->buf + sizeof(chunk_header), &message_header,
sizeof(message_header));
memcpy(new_wbuf->buf + sizeof(chunk_header) + sizeof(message_header),
data, data_size);
if (!port->write_buf) {
port->write_buf = new_wbuf;
return 0;
}
/* maybe we should limit the write_buf stack depth ? */
wbuf = port->write_buf;
while (wbuf->next)
wbuf = wbuf->next;
wbuf->next = new_wbuf;
return 0;
}
void vdagent_virtio_port_flush(struct vdagent_virtio_port **portp)
{
while (*portp && (*portp)->write_buf)
vdagent_virtio_port_do_write(portp);
}
static void vdagent_virtio_port_do_chunk(struct vdagent_virtio_port **portp)
{
int avail, read, pos = 0;
struct vdagent_virtio_port *port = *portp;
if (port->message_header_read < sizeof(port->message_header)) {
read = sizeof(port->message_header) - port->message_header_read;
memcpy((uint8_t *)&port->message_header + port->message_header_read,
port->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) {
fprintf(port->errfile, "out of memory, disconnecting virtio\n");
vdagent_virtio_port_destroy(portp);
return;
}
}
pos = read;
}
if (port->message_header_read == sizeof(port->message_header)) {
read = port->message_header.size - port->message_data_pos;
avail = port->chunk_header.size - pos;
if (avail > read) {
fprintf(port->errfile, "chunk larger then message, lost sync?\n");
vdagent_virtio_port_destroy(portp);
return;
}
if (avail < read)
read = avail;
if (read) {
memcpy(port->message_data + port->message_data_pos,
port->chunk_data + pos, read);
port->message_data_pos += read;
}
if (port->message_data_pos == port->message_header.size) {
if (port->read_callback) {
int r = port->read_callback(port, &port->chunk_header,
&port->message_header, port->message_data);
if (r == -1) {
vdagent_virtio_port_destroy(portp);
return;
}
}
port->message_header_read = 0;
port->message_data_pos = 0;
free(port->message_data);
port->message_data = NULL;
}
}
}
static void vdagent_virtio_port_do_read(struct vdagent_virtio_port **portp)
{
ssize_t n;
size_t to_read;
uint8_t *dest;
struct vdagent_virtio_port *port = *portp;
if (port->chunk_header_read < sizeof(port->chunk_header)) {
to_read = sizeof(port->chunk_header) - port->chunk_header_read;
dest = (uint8_t *)&port->chunk_header + port->chunk_header_read;
} else {
to_read = port->chunk_header.size - port->chunk_data_pos;
dest = port->chunk_data + port->chunk_data_pos;
}
n = read(port->fd, dest, to_read);
if (n < 0) {
if (errno == EINTR)
return;
fprintf(port->errfile, "reading from vdagent virtio port: %s\n",
strerror(errno));
}
if (n <= 0) {
vdagent_virtio_port_destroy(portp);
return;
}
if (port->chunk_header_read < sizeof(port->chunk_header)) {
port->chunk_header_read += n;
if (port->chunk_header_read == sizeof(port->chunk_header)) {
if (port->chunk_header.size > VD_AGENT_MAX_DATA_SIZE) {
fprintf(port->errfile, "chunk size too large\n");
vdagent_virtio_port_destroy(portp);
return;
}
}
} else {
port->chunk_data_pos += n;
if (port->chunk_data_pos == port->chunk_header.size) {
vdagent_virtio_port_do_chunk(portp);
port->chunk_header_read = 0;
port->chunk_data_pos = 0;
}
}
}
static void vdagent_virtio_port_do_write(struct vdagent_virtio_port **portp)
{
ssize_t n;
size_t to_write;
struct vdagent_virtio_port *port = *portp;
struct vdagent_virtio_port_buf* wbuf = port->write_buf;
if (!wbuf) {
fprintf(port->errfile,
"do_write called on a port without a write buf ?!\n");
return;
}
to_write = wbuf->size - wbuf->pos;
n = write(port->fd, wbuf->buf + wbuf->pos, to_write);
if (n < 0) {
if (errno == EINTR)
return;
fprintf(port->errfile, "writing to vdagent virtio port: %s\n",
strerror(errno));
vdagent_virtio_port_destroy(portp);
return;
}
wbuf->pos += n;
if (wbuf->pos == wbuf->size) {
port->write_buf = wbuf->next;
free(wbuf->buf);
free(wbuf);
}
}
/* vdagent-virtio-port.h virtio port communication header
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <hdegoede@redhat.com>
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 *port,
VDIChunkHeader *chunk_header,
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,
FILE *errfile);
/* The contents of portp will be made NULL */
void vdagent_virtio_port_destroy(struct vdagent_virtio_port **portp);
/* 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 *port,
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 **portp,
fd_set *readfds, fd_set *writefds);
/* Queue a message for delivery
Returns 0 on success -1 on error (only happens when malloc fails) */
int vdagent_virtio_port_write(
struct vdagent_virtio_port *port,
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 **portp);
#endif
/* vdagent-x11.c vdagent x11 code
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <hdegoede@redhat.com>
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/>.
*/
/* Note *all* X11 calls in this file which do not wait for a result must be
followed by an XFlush, given that the X11 code pumping the event loop
(and thus flushing queued writes) is only called when there is data to be
read from the X11 socket. */
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
#include <X11/extensions/Xfixes.h>
#include "vdagentd-proto.h"
#include "vdagent-x11.h"
enum { owner_none, owner_guest, owner_client };
struct vdagent_x11_selection_request {
XEvent event;
struct vdagent_x11_selection_request *next;
};
struct clipboard_format_tmpl {
uint32_t type;
const char *atom_names[16];
};
struct clipboard_format_info {
uint32_t type;
Atom atoms[16];
int atom_count;
};
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_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 }, },
};
#define clipboard_format_count (sizeof(clipboard_format_templates)/sizeof(clipboard_format_templates[0]))
struct vdagent_x11 {
struct clipboard_format_info clipboard_formats[clipboard_format_count];
Display *display;
Atom clipboard_atom;
Atom targets_atom;
Atom incr_atom;
Atom multiple_atom;
Window root_window;
Window selection_window;
struct udscs_connection *vdagentd;
FILE *errfile;
int verbose;
int fd;
int screen;
int width;
int height;
int has_xrandr;
int has_xfixes;
int xfixes_event_base;
int expected_targets_notifies;
int expect_property_notify;
int clipboard_owner;
Atom clipboard_request_target;
int clipboard_type_count;
uint32_t clipboard_agent_types[256];
Atom clipboard_x11_targets[256];
uint8_t *clipboard_data;
uint32_t clipboard_data_size;
uint32_t clipboard_data_space;
struct vdagent_x11_selection_request *selection_request;
};
static void vdagent_x11_send_daemon_guest_xorg_res(struct vdagent_x11 *x11);
static void vdagent_x11_handle_selection_notify(struct vdagent_x11 *x11,
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, int incr);
static void vdagent_x11_send_selection_notify(struct vdagent_x11 *x11,
Atom prop,
int process_next_req);
struct vdagent_x11 *vdagent_x11_create(struct udscs_connection *vdagentd,
FILE *errfile, int verbose)
{
struct vdagent_x11 *x11;
XWindowAttributes attrib;
int i, j, major, minor;
x11 = calloc(1, sizeof(*x11));
if (!x11) {
fprintf(errfile, "out of memory allocating vdagent_x11 struct\n");
return NULL;
}
x11->vdagentd = vdagentd;
x11->errfile = errfile;
x11->verbose = verbose;
x11->display = XOpenDisplay(NULL);
if (!x11->display) {
fprintf(x11->errfile, "could not connect to X-server\n");
free(x11);
return NULL;
}
x11->screen = DefaultScreen(x11->display);
x11->root_window = RootWindow(x11->display, x11->screen);
x11->fd = ConnectionNumber(x11->display);
x11->clipboard_atom = XInternAtom(x11->display, "CLIPBOARD", 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);
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++) {
x11->clipboard_formats[i].atoms[j] =
XInternAtom(x11->display,
clipboard_format_templates[i].atom_names[j],
False);
}
x11->clipboard_formats[i].atom_count = j;
}
/* We should not store properties (for selections) on the root window */
x11->selection_window = XCreateSimpleWindow(x11->display, x11->root_window,
0, 0, 1, 1, 0, 0, 0);
if (x11->verbose)
fprintf(x11->errfile, "Selection window: %u\n",
(unsigned int)x11->selection_window);
if (XRRQueryExtension(x11->display, &i, &i))
x11->has_xrandr = 1;
else
fprintf(x11->errfile, "no xrandr\n");
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,
x11->clipboard_atom,
XFixesSetSelectionOwnerNotifyMask|
XFixesSelectionWindowDestroyNotifyMask|
XFixesSelectionClientCloseNotifyMask);
} else
fprintf(x11->errfile,
"no xfixes, no guest -> client copy paste support\n");
/* Catch resolution changes */
XSelectInput(x11->display, x11->root_window, StructureNotifyMask);
/* Get the current resolution */
XGetWindowAttributes(x11->display, x11->root_window, &attrib);
x11->width = attrib.width;
x11->height = attrib.height;
vdagent_x11_send_daemon_guest_xorg_res(x11);
/* No need for XFlush as XGetWindowAttributes does an implicit Xflush */
return x11;
}
void vdagent_x11_destroy(struct vdagent_x11 *x11)
{
if (!x11)
return;
XCloseDisplay(x11->display);
free(x11);
}
int vdagent_x11_get_fd(struct vdagent_x11 *x11)
{
return x11->fd;
}
static void vdagent_x11_set_clipboard_owner(struct vdagent_x11 *x11,
int new_owner)
{
/* Clear pending requests and clipboard data */
if (x11->selection_request) {
fprintf(x11->errfile,
"selection requests pending on clipboard ownership change, "
"clearing");
while (x11->selection_request)
vdagent_x11_send_selection_notify(x11, None, 0);
}
if (x11->clipboard_request_target != None) {
fprintf(x11->errfile,
"client clipboard request pending on clipboard ownership "
"change, clearing");
udscs_write(x11->vdagentd, VDAGENTD_CLIPBOARD_DATA,
VD_AGENT_CLIPBOARD_NONE, NULL, 0);
x11->clipboard_request_target = None;
}
x11->clipboard_data_size = 0;
x11->expect_property_notify = 0;
if (new_owner == owner_none) {
/* When going from owner_guest to owner_none we need to send a
clipboard release message to the client */
if (x11->clipboard_owner == owner_guest)
udscs_write(x11->vdagentd, VDAGENTD_CLIPBOARD_RELEASE, 0, NULL, 0);
x11->clipboard_type_count = 0;
}
x11->clipboard_owner = new_owner;
}
static void vdagent_x11_handle_event(struct vdagent_x11 *x11, XEvent event)
{
int handled = 0;
if (event.type == x11->xfixes_event_base) {
union {
XEvent ev;
XFixesSelectionNotifyEvent xfev;
} ev;
ev.ev = event;
switch (ev.xfev.subtype) {
case XFixesSetSelectionOwnerNotify:
break;
/* Treat ... as a SelectionOwnerNotify None */
case XFixesSelectionWindowDestroyNotify:
case XFixesSelectionClientCloseNotify:
ev.xfev.owner = None;
break;
default:
if (x11->verbose)
fprintf(x11->errfile,
"unexpected xfix event subtype %d window %d\n",
(int)ev.xfev.subtype, (int)event.xany.window);
return;
}
if (x11->verbose)
fprintf(x11->errfile, "New selection owner: %u\n",
(unsigned int)ev.xfev.owner);
/* Ignore becoming the owner ourselves */
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, owner_none);
if (ev.xfev.owner == None)
return;
/* Request the supported targets from the new owner */
XConvertSelection(x11->display, x11->clipboard_atom, x11->targets_atom,
x11->targets_atom, x11->selection_window,
CurrentTime);
XFlush(x11->display);
x11->expected_targets_notifies++;
return;
}
switch (event.type) {
case ConfigureNotify:
if (event.xconfigure.window != x11->root_window)
break;
handled = 1;
if (event.xconfigure.width == x11->width &&
event.xconfigure.height == x11->height)
break;
x11->width = event.xconfigure.width;
x11->height = event.xconfigure.height;
vdagent_x11_send_daemon_guest_xorg_res(x11);
break;
case SelectionNotify:
if (event.xselection.target == x11->targets_atom)
vdagent_x11_handle_targets_notify(x11, &event, 0);
else
vdagent_x11_handle_selection_notify(x11, &event, 0);
handled = 1;
break;
case PropertyNotify:
handled = 1;
if (!x11->expect_property_notify ||
event.xproperty.state != PropertyNewValue)
break;
if (event.xproperty.atom == x11->targets_atom)
vdagent_x11_handle_targets_notify(x11, &event, 1);
else
vdagent_x11_handle_selection_notify(x11, &event, 1);
break;
case SelectionClear:
/* Do nothing the clipboard ownership will get updated through
the XFixesSetSelectionOwnerNotify event */
handled = 1;
break;
case SelectionRequest: {
struct vdagent_x11_selection_request *req, *new_req;
new_req = malloc(sizeof(*new_req));
if (!new_req) {
fprintf(x11->errfile,
"out of memory on SelectionRequest, ignoring.\n");
break;
}
handled = 1;
new_req->event = event;
new_req->next = NULL;
if (!x11->selection_request) {
x11->selection_request = new_req;
vdagent_x11_handle_selection_request(x11);
break;
}
/* maybe we should limit the selection_request stack depth ? */
req = x11->selection_request;
while (req->next)
req = req->next;
req->next = new_req;
break;
}
}
if (!handled && x11->verbose)
fprintf(x11->errfile, "unhandled x11 event, type %d, window %d\n",
(int)event.type, (int)event.xany.window);
}
void vdagent_x11_do_read(struct vdagent_x11 *x11)
{
XEvent event;
while (XPending(x11->display)) {
XNextEvent(x11->display, &event);
vdagent_x11_handle_event(x11, event);
}
}
static void vdagent_x11_send_daemon_guest_xorg_res(struct vdagent_x11 *x11)
{
struct vdagentd_guest_xorg_resolution res;
res.width = x11->width;
res.height = x11->height;
udscs_write(x11->vdagentd, VDAGENTD_GUEST_XORG_RESOLUTION, 0,
(uint8_t *)&res, sizeof(res));
}
static const char *vdagent_x11_get_atom_name(struct vdagent_x11 *x11, Atom a)
{
if (a == None)
return "None";
return XGetAtomName(x11->display, a);
}
static int vdagent_x11_get_selection(struct vdagent_x11 *x11, XEvent *event,
Atom type, Atom prop, int format,
unsigned char **data_ret, int incr)
{
Bool del = incr ? True: False;
Atom type_ret;
int format_ret, ret_val = -1;
unsigned long len, remain;
unsigned char *data = NULL;
*data_ret = NULL;
if (incr) {
if (event->xproperty.atom != prop) {
fprintf(x11->errfile, "PropertyNotify parameters mismatch\n");
goto exit;
}
} else {
if (event->xselection.property == None) {
if (x11->verbose)
fprintf(x11->errfile,
"XConvertSelection refused by clipboard owner\n");
goto exit;
}
if (event->xselection.requestor != x11->selection_window ||
event->xselection.selection != x11->clipboard_atom ||
event->xselection.property != prop) {
fprintf(x11->errfile, "SelectionNotify parameters mismatch\n");
goto exit;
}
}
if (XGetWindowProperty(x11->display, x11->selection_window, prop, 0,
LONG_MAX, del, type, &type_ret, &format_ret, &len,
&remain, &data) != Success) {
fprintf(x11->errfile, "XGetWindowProperty failed\n");
goto exit;
}
if (!incr) {
if (type_ret == x11->incr_atom) {
int prop_min_size = *(uint32_t*)data;
if (x11->expect_property_notify) {
fprintf(x11->errfile,
"received an incr SelectionNotify while "
"still reading another incr property\n");
goto exit;
}
if (x11->clipboard_data_space < prop_min_size) {
free(x11->clipboard_data);
x11->clipboard_data = malloc(prop_min_size);
if (!x11->clipboard_data) {
fprintf(x11->errfile,
"out of memory allocating clipboard buffer\n");
x11->clipboard_data_space = 0;
goto exit;
}
x11->clipboard_data_space = prop_min_size;
}
x11->expect_property_notify = 1;
XSelectInput(x11->display, x11->selection_window,
PropertyChangeMask);
XDeleteProperty(x11->display, x11->selection_window, prop);
XFlush(x11->display);
XFree(data);
return 0; /* Wait for more data */
}
XDeleteProperty(x11->display, x11->selection_window, prop);
XFlush(x11->display);
}
if (type_ret != type) {
fprintf(x11->errfile, "expected property type: %s, got: %s\n",
vdagent_x11_get_atom_name(x11, type),
vdagent_x11_get_atom_name(x11, type_ret));
goto exit;
}
if (format_ret != format) {
fprintf(x11->errfile, "expected %d bit format, got %d bits\n", format,
format_ret);
goto exit;
}
/* Convert len to bytes */
switch(format) {
case 8:
break;
case 16:
len *= sizeof(short);
break;
case 32:
len *= sizeof(long);
break;
}
if (incr) {
if (len) {
if (x11->clipboard_data_size + len > x11->clipboard_data_space) {
void *old_clipboard_data = x11->clipboard_data;
x11->clipboard_data_space = x11->clipboard_data_size + len;
x11->clipboard_data = realloc(x11->clipboard_data,
x11->clipboard_data_space);
if (!x11->clipboard_data) {
fprintf(x11->errfile,
"out of memory allocating clipboard buffer\n");
x11->clipboard_data_space = 0;
free(old_clipboard_data);
goto exit;
}
}
memcpy(x11->clipboard_data + x11->clipboard_data_size, data, len);
x11->clipboard_data_size += len;
if (x11->verbose)
fprintf(x11->errfile, "Appended %ld bytes to buffer\n", len);
XFree(data);
return 0; /* Wait for more data */
}
len = x11->clipboard_data_size;
*data_ret = x11->clipboard_data;
} else
*data_ret = data;
if (len > 0) {
ret_val = len;
} else {
fprintf(x11->errfile, "property contains no data (zero length)\n");
*data_ret = NULL;
}
exit:
if ((incr || ret_val == -1) && data)
XFree(data);
if (incr) {
x11->clipboard_data_size = 0;
x11->expect_property_notify = 0;
}
return ret_val;
}
static void vdagent_x11_get_selection_free(struct vdagent_x11 *x11,
unsigned char *data, int incr)
{
if (incr) {
/* If the clipboard has grown large return the memory to the system */
if (x11->clipboard_data_space > 512 * 1024) {
free(x11->clipboard_data);
x11->clipboard_data = NULL;
x11->clipboard_data_space = 0;
}
} else if (data)
XFree(data);
}
static uint32_t vdagent_x11_target_to_type(struct vdagent_x11 *x11,
Atom target)
{
int i, j;
for (i = 0; i < clipboard_format_count; i++) {
for (j = 0; j < x11->clipboard_formats[i].atom_count; i++) {
if (x11->clipboard_formats[i].atoms[j] == target) {
return x11->clipboard_formats[i].type;
}
}
}
fprintf(x11->errfile, "unexpected selection type %s\n",
vdagent_x11_get_atom_name(x11, target));
return VD_AGENT_CLIPBOARD_NONE;
}
static Atom vdagent_x11_type_to_target(struct vdagent_x11 *x11, uint32_t type)
{
int i;
for (i = 0; i < x11->clipboard_type_count; i++)
if (x11->clipboard_agent_types[i] == type)
return x11->clipboard_x11_targets[i];
fprintf(x11->errfile, "client requested unavailable type %u\n", type);
return None;
}
static void vdagent_x11_handle_selection_notify(struct vdagent_x11 *x11,
XEvent *event, int incr)
{
int len = -1;
unsigned char *data = NULL;
uint32_t type;
if (x11->clipboard_request_target == None) {
fprintf(x11->errfile, "SelectionNotify received without a target\n");
return;
}
type = vdagent_x11_target_to_type(x11, x11->clipboard_request_target);
if (!incr &&
event->xselection.target != x11->clipboard_request_target &&
event->xselection.target != x11->incr_atom)
fprintf(x11->errfile, "Requested %s target got %s\n",
vdagent_x11_get_atom_name(x11, x11->clipboard_request_target),
vdagent_x11_get_atom_name(x11, event->xselection.target));
else
len = vdagent_x11_get_selection(x11, event, x11->clipboard_request_target,
x11->clipboard_atom, 8, &data, incr);
if (len == 0) /* waiting for more data? */
return;
if (len == -1) {
type = VD_AGENT_CLIPBOARD_NONE;
len = 0;
}
udscs_write(x11->vdagentd, VDAGENTD_CLIPBOARD_DATA, type, data, len);
x11->clipboard_request_target = None;
vdagent_x11_get_selection_free(x11, data, incr);
}
static Atom atom_lists_overlap(Atom *atoms1, Atom *atoms2, int l1, int l2)
{
int i, j;
for (i = 0; i < l1; i++)
for (j = 0; j < l2; j++)
if (atoms1[i] == atoms2[j])
return atoms1[i];
return 0;
}
static void vdagent_x11_print_targets(struct vdagent_x11 *x11,
const char *action, Atom *atoms, int c)
{
int i;
if (!x11->verbose)
return;
fprintf(x11->errfile, "%s %d targets:\n", action, c);
for (i = 0; i < c; i++)
fprintf(x11->errfile, "%s\n",
vdagent_x11_get_atom_name(x11, atoms[i]));
}
static void vdagent_x11_handle_targets_notify(struct vdagent_x11 *x11,
XEvent *event, int incr)
{
int i, len;
Atom atom, *atoms = NULL;
if (!x11->expected_targets_notifies) {
fprintf(x11->errfile, "unexpected selection notify TARGETS\n");
return;
}
x11->expected_targets_notifies--;
/* 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) */
if (x11->expected_targets_notifies)
return;
len = vdagent_x11_get_selection(x11, event, XA_ATOM, x11->targets_atom, 32,
(unsigned char **)&atoms, incr);
if (len == 0 || len == -1) /* waiting for more data or error? */
return;
/* bytes -> atoms */
len /= sizeof(Atom);
vdagent_x11_print_targets(x11, "received", atoms, len);
x11->clipboard_type_count = 0;
for (i = 0; i < clipboard_format_count; i++) {
atom = atom_lists_overlap(x11->clipboard_formats[i].atoms, atoms,
x11->clipboard_formats[i].atom_count, len);
if (atom) {
x11->clipboard_agent_types[x11->clipboard_type_count] =
x11->clipboard_formats[i].type;
x11->clipboard_x11_targets[x11->clipboard_type_count] = atom;
x11->clipboard_type_count++;
if (x11->clipboard_type_count ==
sizeof(x11->clipboard_agent_types)/sizeof(uint32_t)) {
fprintf(x11->errfile,
"handle_targets_notify: too many types\n");
break;
}
}
}
if (x11->clipboard_type_count) {
udscs_write(x11->vdagentd, VDAGENTD_CLIPBOARD_GRAB, 0,
(uint8_t *)x11->clipboard_agent_types,
x11->clipboard_type_count * sizeof(uint32_t));
vdagent_x11_set_clipboard_owner(x11, owner_guest);
}
vdagent_x11_get_selection_free(x11, (unsigned char *)atoms, incr);
}
static void vdagent_x11_send_selection_notify(struct vdagent_x11 *x11,
Atom prop, int process_next_req)
{
XEvent res, *event = &x11->selection_request->event;
struct vdagent_x11_selection_request *selection_request;
res.xselection.property = prop;
res.xselection.type = SelectionNotify;
res.xselection.display = event->xselectionrequest.display;
res.xselection.requestor = event->xselectionrequest.requestor;
res.xselection.selection = event->xselectionrequest.selection;
res.xselection.target = event->xselectionrequest.target;
res.xselection.time = event->xselectionrequest.time;
XSendEvent(x11->display, event->xselectionrequest.requestor, 0, 0, &res);
XFlush(x11->display);
selection_request = x11->selection_request;
x11->selection_request = selection_request->next;
free(selection_request);
if (process_next_req)
vdagent_x11_handle_selection_request(x11);
}
static void vdagent_x11_send_targets(struct vdagent_x11 *x11, XEvent *event)
{
Atom prop, targets[256] = { x11->targets_atom, };
int i, j, k, target_count = 1;
for (i = 0; i < x11->clipboard_type_count; i++) {
for (j = 0; j < clipboard_format_count; j++) {
if (x11->clipboard_formats[j].type !=
x11->clipboard_agent_types[i])
continue;
for (k = 0; k < x11->clipboard_formats[j].atom_count; k++) {
targets[target_count] = x11->clipboard_formats[j].atoms[k];
target_count++;
if (target_count == sizeof(targets)/sizeof(Atom)) {
fprintf(x11->errfile, "send_targets: too many targets\n");
goto exit_loop;
}
}
}
}
exit_loop:
prop = event->xselectionrequest.property;
if (prop == None)
prop = event->xselectionrequest.target;
XChangeProperty(x11->display, event->xselectionrequest.requestor, prop,
XA_ATOM, 32, PropModeReplace, (unsigned char *)&targets,
target_count);
vdagent_x11_print_targets(x11, "sent", targets, target_count);
vdagent_x11_send_selection_notify(x11, prop, 1);
}
static void vdagent_x11_handle_selection_request(struct vdagent_x11 *x11)
{
XEvent *event;
uint32_t type = VD_AGENT_CLIPBOARD_NONE;
if (!x11->selection_request)
return;
event = &x11->selection_request->event;
if (x11->clipboard_owner != owner_client) {
fprintf(x11->errfile,
"received selection request event for target %s, "
"while not owning client clipboard\n",
vdagent_x11_get_atom_name(x11, event->xselectionrequest.target));
vdagent_x11_send_selection_notify(x11, None, 1);
return;
}
if (event->xselectionrequest.target == x11->multiple_atom) {
fprintf(x11->errfile, "multiple target not supported\n");
vdagent_x11_send_selection_notify(x11, None, 1);
return;
}
if (event->xselectionrequest.target == x11->targets_atom) {
vdagent_x11_send_targets(x11, event);
return;
}
type = vdagent_x11_target_to_type(x11, event->xselectionrequest.target);
if (type == VD_AGENT_CLIPBOARD_NONE) {
vdagent_x11_send_selection_notify(x11, None, 1);
return;
}
udscs_write(x11->vdagentd, VDAGENTD_CLIPBOARD_REQUEST, type, NULL, 0);
}
void vdagent_x11_set_monitor_config(struct vdagent_x11 *x11,
VDAgentMonitorsConfig *mon_config)
{
int i, num_sizes = 0;
int best = -1;
unsigned int closest_diff = -1;
XRRScreenSize* sizes;
XRRScreenConfiguration* config;
Rotation rotation;
if (!x11->has_xrandr)
return;
if (mon_config->num_of_monitors != 1) {
fprintf(x11->errfile,
"Only 1 monitor supported, ignoring monitor config\n");
return;
}
sizes = XRRSizes(x11->display, x11->screen, &num_sizes);
if (!sizes || !num_sizes) {
fprintf(x11->errfile, "XRRSizes failed\n");
return;
}
/* Find the closest size which will fit within the monitor */
for (i = 0; i < num_sizes; i++) {
if (sizes[i].width > mon_config->monitors[0].width ||
sizes[i].height > mon_config->monitors[0].height)
continue; /* Too large for the monitor */
unsigned int wdiff = mon_config->monitors[0].width - sizes[i].width;
unsigned int hdiff = mon_config->monitors[0].height - sizes[i].height;
unsigned int diff = wdiff * wdiff + hdiff * hdiff;
if (diff < closest_diff) {
closest_diff = diff;
best = i;
}
}
if (best == -1) {
fprintf(x11->errfile, "no suitable resolution found for monitor\n");
return;
}
config = XRRGetScreenInfo(x11->display, x11->root_window);
if(!config) {
fprintf(x11->errfile, "get screen info failed\n");
return;
}
XRRConfigCurrentConfiguration(config, &rotation);
XRRSetScreenConfig(x11->display, config, x11->root_window, best,
rotation, CurrentTime);
XRRFreeScreenConfigInfo(config);
XFlush(x11->display);
x11->width = sizes[best].width;
x11->height = sizes[best].height;
vdagent_x11_send_daemon_guest_xorg_res(x11);
}
void vdagent_x11_clipboard_request(struct vdagent_x11 *x11, uint32_t type)
{
Atom target;
if (x11->clipboard_owner != owner_guest) {
fprintf(x11->errfile,
"received clipboard req while not owning guest clipboard\n");
udscs_write(x11->vdagentd, VDAGENTD_CLIPBOARD_DATA,
VD_AGENT_CLIPBOARD_NONE, NULL, 0);
return;
}
target = vdagent_x11_type_to_target(x11, type);
if (target == None) {
udscs_write(x11->vdagentd, VDAGENTD_CLIPBOARD_DATA,
VD_AGENT_CLIPBOARD_NONE, NULL, 0);
return;
}
if (x11->clipboard_request_target) {
fprintf(x11->errfile,
"XConvertSelection request is already pending\n");
udscs_write(x11->vdagentd, VDAGENTD_CLIPBOARD_DATA,
VD_AGENT_CLIPBOARD_NONE, NULL, 0);
return;
}
x11->clipboard_request_target = target;
XConvertSelection(x11->display, x11->clipboard_atom, target,
x11->clipboard_atom, x11->selection_window, CurrentTime);
XFlush(x11->display);
}
void vdagent_x11_clipboard_grab(struct vdagent_x11 *x11, uint32_t *types,
uint32_t type_count)
{
if (type_count > sizeof(x11->clipboard_agent_types)/sizeof(uint32_t)) {
fprintf(x11->errfile, "x11_clipboard_grab: too many types\n");
type_count = sizeof(x11->clipboard_agent_types)/sizeof(uint32_t);
}
memcpy(x11->clipboard_agent_types, types, type_count * sizeof(uint32_t));
x11->clipboard_type_count = type_count;
XSetSelectionOwner(x11->display, x11->clipboard_atom,
x11->selection_window, CurrentTime);
XFlush(x11->display);
vdagent_x11_set_clipboard_owner(x11, owner_client);
}
void vdagent_x11_clipboard_data(struct vdagent_x11 *x11, uint32_t type,
const uint8_t *data, uint32_t size)
{
Atom prop;
XEvent *event;
uint32_t type_from_event;
if (!x11->selection_request) {
fprintf(x11->errfile, "received clipboard data without an outstanding"
"selection request, ignoring\n");
return;
}
event = &x11->selection_request->event;
type_from_event = vdagent_x11_target_to_type(x11,
event->xselectionrequest.target);
if (type_from_event != type) {
fprintf(x11->errfile, "expecting type %u clipboard data got %u\n",
type_from_event, type);
vdagent_x11_send_selection_notify(x11, None, 1);
return;
}
prop = event->xselectionrequest.property;
if (prop == None)
prop = event->xselectionrequest.target;
/* FIXME: use INCR for large data transfers */
XChangeProperty(x11->display, event->xselectionrequest.requestor, prop,
event->xselectionrequest.target, 8, PropModeReplace,
data, size);
vdagent_x11_send_selection_notify(x11, prop, 1);
}
void vdagent_x11_clipboard_release(struct vdagent_x11 *x11)
{
XEvent event;
if (x11->clipboard_owner != owner_client) {
fprintf(x11->errfile,
"received clipboard release while not owning client clipboard\n");
return;
}
XSetSelectionOwner(x11->display, x11->clipboard_atom, None, CurrentTime);
/* Make sure we process the XFixesSetSelectionOwnerNotify event caused
by this, so we don't end up changing the clipboard owner to none, after
it has already been re-owned because this event is still pending. */
XSync(x11->display, False);
while (XCheckTypedEvent(x11->display, x11->xfixes_event_base,
&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. */
}
/* vdagent-x11.h vdagent x11 code header file
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <hdegoede@redhat.com>
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_H
#define __VDAGENT_H
#include <stdio.h>
#include <spice/vd_agent.h>
#include "udscs.h"
struct vdagent_x11;
struct vdagent_x11 *vdagent_x11_create(struct udscs_connection *vdagentd,
FILE *errfile, int verbose);
void vdagent_x11_destroy(struct vdagent_x11 *x11);
int vdagent_x11_get_fd(struct vdagent_x11 *x11);
void vdagent_x11_do_read(struct vdagent_x11 *x11);
void vdagent_x11_set_monitor_config(struct vdagent_x11 *x11,
VDAgentMonitorsConfig *mon_config);
void vdagent_x11_clipboard_grab(struct vdagent_x11 *x11, uint32_t *types,
uint32_t type_count);
void vdagent_x11_clipboard_request(struct vdagent_x11 *x11, uint32_t type);
void vdagent_x11_clipboard_data(struct vdagent_x11 *x11, uint32_t type,
const uint8_t *data, uint32_t size);
void vdagent_x11_clipboard_release(struct vdagent_x11 *x11);
#endif
vdagent.c 0 → 100644
/* vdagent.c xorg-client to vdagentd (daemon).
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <hdegoede@redhat.com>
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 <stdio.h>
#include <stdlib.h>
#include <string.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 "udscs.h"
#include "vdagentd-proto.h"
#include "vdagentd-proto-strings.h"
#include "vdagent-x11.h"
static int verbose = 0;
static struct vdagent_x11 *x11 = NULL;
static FILE *logfile = NULL;
static int quit = 0;
void daemon_read_complete(struct udscs_connection **connp,
struct udscs_message_header *header, const uint8_t *data)
{
switch (header->type) {
case VDAGENTD_MONITORS_CONFIG:
vdagent_x11_set_monitor_config(x11, (VDAgentMonitorsConfig *)data);
break;
case VDAGENTD_CLIPBOARD_REQUEST:
vdagent_x11_clipboard_request(x11, header->opaque);
break;
case VDAGENTD_CLIPBOARD_GRAB:
vdagent_x11_clipboard_grab(x11, (uint32_t *)data,
header->size / sizeof(uint32_t));
break;
case VDAGENTD_CLIPBOARD_DATA:
vdagent_x11_clipboard_data(x11, header->opaque, data, header->size);
break;
case VDAGENTD_CLIPBOARD_RELEASE:
vdagent_x11_clipboard_release(x11);
break;
default:
if (verbose)
fprintf(logfile, "Unknown message from vdagentd type: %d\n",
header->type);
}
}
static void usage(FILE *fp)
{
fprintf(fp,
"vdagent -- spice agent xorg client\n"
"options:\n"
" -h print this text\n"
" -d log debug messages\n");
}
static void quit_handler(int sig)
{
quit = 1;
}
int main(int argc, char *argv[])
{
struct udscs_connection *client = NULL;
fd_set readfds, writefds;
int c, n, nfds, x11_fd, retval = 0;
char *home, filename[1024];
struct sigaction act;
for (;;) {
if (-1 == (c = getopt(argc, argv, "-dh")))
break;
switch (c) {
case 'd':
verbose++;
break;
case 'h':
usage(stdout);
return 0;
default:
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);
home = getenv("HOME");
if (home) {
snprintf(filename, sizeof(filename), "%s/.spice-vdagent", home);
n = mkdir(filename, 0755);
snprintf(filename, sizeof(filename), "%s/.spice-vdagent/log", home);
logfile = fopen(filename, "w");
if (!logfile) {
fprintf(stderr, "Error opening %s: %s\n", filename,
strerror(errno));
logfile = stderr;
}
} else {
fprintf(stderr, "Could not get home directory, logging to stderr\n");
logfile = stderr;
}
client = udscs_connect(VDAGENTD_SOCKET, daemon_read_complete, NULL,
vdagentd_messages, VDAGENTD_NO_MESSAGES,
verbose? logfile:NULL, logfile);
if (!client)
return 1;
x11 = vdagent_x11_create(client, logfile, verbose);
if (!x11) {
udscs_destroy_connection(&client);
return 1;
}
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;
fprintf(logfile, "Fatal error select: %s\n", strerror(errno));
retval = 1;
break;
}
if (FD_ISSET(x11_fd, &readfds))
vdagent_x11_do_read(x11);
udscs_client_handle_fds(&client, &readfds, &writefds);
fflush(logfile);
}
vdagent_x11_destroy(x11);
udscs_destroy_connection(&client);
fclose(logfile);
return retval;
}
/* vdagentd-proto-strings.h header file
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <hdegoede@redhat.com>
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 __VDAGENTD_PROTO_STRINGS_H
#define __VDAGENTD_PROTO_STRINGS_H
static const char * const vdagentd_messages[] = {
"guest xorg resolution",
"monitors config",
"clipboard grab",
"clipboard request",
"clipboard data",
"clipboard release",
};
#endif
/* vdagentd-proto.h header file for the protocol over the unix domain socket
between the vdagent process / xorg-client and the vdagentd (daemon).
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <hdegoede@redhat.com>
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 __VDAGENTD_PROTO_H
#define __VDAGENTD_PROTO_H
#define VDAGENTD_SOCKET "/var/run/spice-vdagentd/spice-vdagent-sock"
enum {
VDAGENTD_GUEST_XORG_RESOLUTION, /* client -> daemon */
VDAGENTD_MONITORS_CONFIG, /* daemon -> client, VDAgentMonitorsConfig
followed by num_monitors VDAgentMonConfig-s */
VDAGENTD_CLIPBOARD_GRAB, /* data is array of supported types */
VDAGENTD_CLIPBOARD_REQUEST, /* opaque = type */
VDAGENTD_CLIPBOARD_DATA, /* opaque = type, data = data */
VDAGENTD_CLIPBOARD_RELEASE, /* no data */
VDAGENTD_NO_MESSAGES /* Must always be last */
};
struct vdagentd_guest_xorg_resolution {
int width;
int height;
};
#endif
/* vdagentd-uinput.c vdagentd uinput handling code
Copyright 2010 Red Hat, Inc.
Red Hat Authors:
Hans de Goede <hdegoede@redhat.com>
Gerd Hoffmann <kraxel@redhat.com>
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 <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
#include <linux/uinput.h>
#include <spice/vd_agent.h>
#include "vdagentd-uinput.h"
struct vdagentd_uinput {
const char *devname;
int fd;
int width;
int height;
int verbose;
FILE *errfile;
VDAgentMouseState last;
};
struct vdagentd_uinput *vdagentd_uinput_create(const char *devname,
int width, int height, FILE *errfile, int verbose)
{
struct vdagentd_uinput *uinput;
uinput = calloc(1, sizeof(*uinput));
if (!uinput)
return NULL;
uinput->devname = devname;
uinput->fd = -1; /* Gets opened by vdagentd_uinput_update_size() */
uinput->verbose = verbose;
uinput->errfile = errfile;
vdagentd_uinput_update_size(&uinput, width, height);
return uinput;
}
void vdagentd_uinput_destroy(struct vdagentd_uinput **uinputp)
{
struct vdagentd_uinput *uinput = *uinputp;
if (!uinput)
return;
if (uinput->fd != -1)
close(uinput->fd);
free(uinput);
*uinputp = NULL;
}
void vdagentd_uinput_update_size(struct vdagentd_uinput **uinputp,
int width, int height)
{
struct vdagentd_uinput *uinput = *uinputp;
struct uinput_user_dev device = {
.name = "spice vdagent tablet",
.absmax [ ABS_X ] = width,
.absmax [ ABS_Y ] = height,
};
int rc;
if (uinput->width == width && uinput->height == height)
return;
uinput->width = width;
uinput->height = height;
if (uinput->fd != -1)
close(uinput->fd);
uinput->fd = open(uinput->devname, O_RDWR);
if (uinput->fd == -1) {
fprintf(uinput->errfile, "open %s: %s\n",
uinput->devname, strerror(errno));
vdagentd_uinput_destroy(uinputp);
return;
}
rc = write(uinput->fd, &device, sizeof(device));
if (rc != sizeof(device)) {
fprintf(uinput->errfile, "write %s: %s\n",
uinput->devname, strerror(errno));
vdagentd_uinput_destroy(uinputp);
return;
}
/* buttons */
ioctl(uinput->fd, UI_SET_EVBIT, EV_KEY);
ioctl(uinput->fd, UI_SET_KEYBIT, BTN_LEFT);
ioctl(uinput->fd, UI_SET_KEYBIT, BTN_MIDDLE);
ioctl(uinput->fd, UI_SET_KEYBIT, BTN_RIGHT);
/* wheel */
ioctl(uinput->fd, UI_SET_EVBIT, EV_REL);
ioctl(uinput->fd, UI_SET_RELBIT, REL_WHEEL);
/* abs ptr */
ioctl(uinput->fd, UI_SET_EVBIT, EV_ABS);
ioctl(uinput->fd, UI_SET_ABSBIT, ABS_X);
ioctl(uinput->fd, UI_SET_ABSBIT, ABS_Y);
rc = ioctl(uinput->fd, UI_DEV_CREATE);
if (rc < 0) {
fprintf(uinput->errfile, "create %s: %s\n",
uinput->devname, strerror(errno));
vdagentd_uinput_destroy(uinputp);
}
}
static void uinput_send_event(struct vdagentd_uinput **uinputp,
__u16 type, __u16 code, __s32 value)
{
struct vdagentd_uinput *uinput = *uinputp;
struct input_event event = {
.type = type,
.code = code,
.value = value,
};
int rc;
rc = write(uinput->fd, &event, sizeof(event));
if (rc != sizeof(event)) {
fprintf(uinput->errfile, "write %s: %s\n",
uinput->devname, strerror(errno));
vdagentd_uinput_destroy(uinputp);
}
}
void vdagentd_uinput_do_mouse(struct vdagentd_uinput **uinputp,
VDAgentMouseState *mouse)
{
struct vdagentd_uinput *uinput = *uinputp;
struct button_s {
const char *name;
int mask;
int btn;
};
static const struct button_s btns[] = {
{ .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 },
};
static const struct button_s wheel[] = {
{ .name = "up", .mask = VD_AGENT_UBUTTON_MASK, .btn = 1 },
{ .name = "down", .mask = VD_AGENT_DBUTTON_MASK, .btn = -1 },
};
int i, down;
if (*uinputp && uinput->last.x != mouse->x) {
if (uinput->verbose)
fprintf(uinput->errfile, "mouse: abs-x %d\n", mouse->x);
uinput_send_event(uinputp, EV_ABS, ABS_X, mouse->x);
}
if (*uinputp && uinput->last.y != mouse->y) {
if (uinput->verbose)
fprintf(uinput->errfile, "mouse: abs-y %d\n", mouse->y);
uinput_send_event(uinputp, EV_ABS, ABS_Y, mouse->y);
}
for (i = 0; i < sizeof(btns)/sizeof(btns[0]) && *uinputp; i++) {
if ((uinput->last.buttons & btns[i].mask) ==
(mouse->buttons & btns[i].mask))
continue;
down = !!(mouse->buttons & btns[i].mask);
if (uinput->verbose)
fprintf(uinput->errfile, "mouse: btn-%s %s\n",
btns[i].name, down ? "down" : "up");
uinput_send_event(uinputp, EV_KEY, btns[i].btn, down);
}
for (i = 0; i < sizeof(wheel)/sizeof(wheel[0]) && *uinputp; i++) {
if ((uinput->last.buttons & wheel[i].mask) ==
(mouse->buttons & wheel[i].mask))
continue;
if (mouse->buttons & wheel[i].mask) {
if (uinput->verbose)
fprintf(uinput->errfile, "mouse: wheel-%s\n", wheel[i].name);
uinput_send_event(uinputp, EV_REL, REL_WHEEL, wheel[i].btn);
}
}
if (*uinputp) {
if (uinput->verbose)
fprintf(uinput->errfile, "mouse: syn\n");
uinput_send_event(uinputp, EV_SYN, SYN_REPORT, 0);
}
if (*uinputp)
uinput->last = *mouse;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment