diff options
author | 2012-01-28 22:55:07 -0500 | |
---|---|---|
committer | 2012-01-28 22:55:07 -0500 | |
commit | 42aed9373bcc42fc7d9766e35e5158685a57ebdf (patch) | |
tree | 832ddad4b687ed66be939a4e744def868c523082 | |
download | openrc-settingsd-42aed9373bcc42fc7d9766e35e5158685a57ebdf.tar.gz openrc-settingsd-42aed9373bcc42fc7d9766e35e5158685a57ebdf.tar.bz2 openrc-settingsd-42aed9373bcc42fc7d9766e35e5158685a57ebdf.zip |
Initial commit
-rw-r--r-- | AUTHORS | 1 | ||||
-rw-r--r-- | COPYING | 339 | ||||
-rw-r--r-- | Makefile.am | 45 | ||||
-rw-r--r-- | README | 28 | ||||
-rwxr-xr-x | autogen.sh | 14 | ||||
-rw-r--r-- | configure.ac | 47 | ||||
-rw-r--r-- | data/hostnamed.xml | 24 | ||||
-rw-r--r-- | m4/.keep | 0 | ||||
-rw-r--r-- | src/bus-utils.c | 63 | ||||
-rw-r--r-- | src/bus-utils.h | 30 | ||||
-rw-r--r-- | src/hostnamed.c | 388 | ||||
-rw-r--r-- | src/hostnamed.h | 47 | ||||
-rw-r--r-- | src/main.c | 44 | ||||
-rw-r--r-- | src/shell-utils.c | 468 | ||||
-rw-r--r-- | src/shell-utils.h | 60 |
15 files changed, 1598 insertions, 0 deletions
@@ -0,0 +1 @@ +Alexandre Rostovtsev <tetromino@gentoo.org>
\ No newline at end of file @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey 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 2 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, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This 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. diff --git a/Makefile.am b/Makefile.am new file mode 100644 index 0000000..58a1dea --- /dev/null +++ b/Makefile.am @@ -0,0 +1,45 @@ +ACLOCAL_AMFLAGS = -I m4 ${ACLOCAL_FLAGS} + +EXTRA_DIST = \ + data/hostnamed.xml \ + $(NULL) + +AM_CPPFLAGS = \ + -include $(top_builddir)/config.h \ + -DSYSCONFDIR=\""$(sysconfdir)"\" \ + -DLIBEXECDIR=\""$(libexecdir)"\" \ + $(OPENRC_SETTINGSD_CFLAGS) \ + -I$(top_srcdir)/src \ + -I$(top_builddir)/src \ + $(NULL) + +LDADD = $(OPENRC_SETTINGSD_LIBS) + +libexec_PROGRAMS = openrc-settingsd + +hostnamed_built_sources = \ + src/hostnamed-generated.c \ + src/hostnamed-generated.h \ + $(NULL) + +openrc_settingsd_SOURCES = \ + $(hostnamed_built_sources) \ + src/hostnamed.c \ + src/hostnamed.h \ + src/bus-utils.c \ + src/bus-utils.h \ + src/shell-utils.c \ + src/shell-utils.h \ + src/main.c \ + $(NULL) + +$(hostnamed_built_sources) : data/hostnamed.xml + ( $(GDBUS_CODEGEN) \ + --interface-prefix org.freedesktop. \ + --c-namespace OpenrcSettingsdHostnamed \ + --generate-c-code hostnamed-generated \ + $(srcdir)/data/hostnamed.xml; \ + mv hostnamed-generated.{c,h} $(top_srcdir)/src/ ) + +BUILT_SOURCES = $(hostnamed_built_sources) +CLEANFILES = $(hostnamed_built_sources) @@ -0,0 +1,28 @@ +openrc-settingsd provides an implementation of the the hostnamed, localed, +and timedated DBus services for OpenRC-based systems - in particular, for +typical installations of Gentoo Linux. + +Bugs should be reported (for the moment) to gnome@gentoo.org + +Hostnamed: + + See http://www.freedesktop.org/wiki/Software/systemd/hostnamed for the DBus + protocol description. + + The static hostname is stored in /etc/conf.d/hostname as + hostname="foo" + + The pretty hostname and icon name are stored in /etc/machine-info as + PRETTY_HOSTNAME="Foo !" + ICON_NAME="computer-desktop" + +Note that openrc-settingsd expects any shell-syntax settings files that it +modifies to be in UTF-8 encoding, and to consist only of comments and simple +scalar assignments, i.e. something like + +# a comment +foo="bar" +baz='Let'\''s go!' + +If openrc-settingsd fails to parse a settings file, it will refuse to modify +it.
\ No newline at end of file diff --git a/autogen.sh b/autogen.sh new file mode 100755 index 0000000..4f9c076 --- /dev/null +++ b/autogen.sh @@ -0,0 +1,14 @@ +#!/bin/sh + +autoreconf --install --symlink + +args="--prefix=/usr \ +--sysconfdir=/etc" + +echo +echo "----------------------------------------------------------------" +echo "Initialized build system. For a common configuration please run:" +echo "----------------------------------------------------------------" +echo +echo "./configure CFLAGS='-ggdb -O0' $args" +echo diff --git a/configure.ac b/configure.ac new file mode 100644 index 0000000..5abb61c --- /dev/null +++ b/configure.ac @@ -0,0 +1,47 @@ +AC_PREREQ([2.60]) +AC_INIT([openrc-settingsd], [0]) +AC_CONFIG_SRCDIR([src/main.c]) +AM_INIT_AUTOMAKE([check-news foreign 1.11 -Wall -Wno-portability silent-rules tar-pax no-dist-gzip dist-xz]) +AC_PROG_CC_STDC +AC_USE_SYSTEM_EXTENSIONS +AC_CONFIG_MACRO_DIR([m4]) +AM_SILENT_RULES([yes]) +LT_INIT([disable-static pic-only]) +AC_PREFIX_DEFAULT([/usr]) + +AC_PROG_MKDIR_P +PKG_CHECK_MODULES(OPENRC_SETTINGSD, [gio-unix-2.0 >= 2.30 gio-2.0 >= 2.30 glib-2.0 >= 2.30 dbus-1 polkit-gobject-1]) +AC_SUBST(OPENRC_SETTINGSD_CFLAGS) +AC_SUBST(OPENRC_SETTINGSD_LIBS) + +AC_PATH_PROG(GDBUS_CODEGEN, gdbus-codegen) +if test "x$GDBUS_CODEGEN" = x; then + AC_MSG_ERROR([Failed to find gdbus-codegen]) +fi + +AC_ARG_ENABLE([debug], + [AS_HELP_STRING([--enable-debug], + [enable extra debugging messages])], + [], [enable_debug=no]) +if test "x$enable_debug" = "xyes" ; then + AC_MSG_RESULT([enabling extra debugging messages]) + AC_DEFINE(OPENRC_SETTINGSD_DEBUG,1,[Enable extra debugging messages.]) +fi + +AC_CONFIG_HEADERS([config.h]) +AC_CONFIG_FILES([ + Makefile +]) + +AC_OUTPUT +AC_MSG_RESULT([ + $PACKAGE $VERSION + ===== + + prefix: ${prefix} + sysconfdir: ${sysconfdir} + + compiler: ${CC} + cflags: ${CFLAGS} + ldflags: ${LDFLAGS} +]) diff --git a/data/hostnamed.xml b/data/hostnamed.xml new file mode 100644 index 0000000..80c0216 --- /dev/null +++ b/data/hostnamed.xml @@ -0,0 +1,24 @@ +<node name="/org/freedesktop/hostname1"> + <interface name="org.freedesktop.hostname1"> + <method name="SetHostname"> + <arg direction="in" type="s" name="name"/> + <arg direction="in" type="b" name="user_interaction"/> + </method> + <method name="SetStaticHostname"> + <arg direction="in" type="s" name="name"/> + <arg direction="in" type="b" name="user_interaction"/> + </method> + <method name="SetPrettyHostname"> + <arg direction="in" type="s" name="name"/> + <arg direction="in" type="b" name="user_interaction"/> + </method> + <method name="SetIconName"> + <arg direction="in" type="s" name="name"/> + <arg direction="in" type="b" name="user_interaction"/> + </method> + <property name="Hostname" type="s" access="read"/> + <property name="StaticHostname" type="s" access="read"/> + <property name="PrettyHostname" type="s" access="read"/> + <property name="IconName" type="s" access="read"/> + </interface> +</node> diff --git a/m4/.keep b/m4/.keep new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/m4/.keep diff --git a/src/bus-utils.c b/src/bus-utils.c new file mode 100644 index 0000000..d3bc7b2 --- /dev/null +++ b/src/bus-utils.c @@ -0,0 +1,63 @@ +/* + Copyright 2012 Alexandre Rostovtsev + + 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 2 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, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include <glib.h> +#include <gio/gio.h> +#include <polkit/polkit.h> + +gboolean +check_polkit (const gchar *unique_name, + const gchar *action_id, + const gboolean user_interaction, + GError **error) +{ + gboolean ret = FALSE; + GDBusConnection *connection = NULL; + PolkitAuthority *authority = NULL; + PolkitSubject *subject = NULL; + PolkitAuthorizationResult *result = NULL; + + if ((authority = polkit_authority_get_sync (NULL, error)) == NULL) + goto end; + + if (unique_name == NULL || action_id == NULL || + (subject = polkit_system_bus_name_new (unique_name)) == NULL) { + g_propagate_error (error, + g_error_new (POLKIT_ERROR, POLKIT_ERROR_FAILED, + "Authorizing for '%s': failed sanity check", action_id)); + goto end; + } + + if ((result = polkit_authority_check_authorization_sync (authority, subject, action_id, NULL, (PolkitCheckAuthorizationFlags) user_interaction, NULL, error)) == NULL) + goto end; + + if ((ret = polkit_authorization_result_get_is_authorized (result)) == FALSE) { + g_propagate_error (error, + g_error_new (POLKIT_ERROR, POLKIT_ERROR_NOT_AUTHORIZED, + "Authorizing for '%s': not authorized", action_id)); + } + + end: + if (result != NULL) + g_object_unref (result); + if (subject != NULL) + g_object_unref (subject); + if (authority != NULL) + g_object_unref (authority); + return ret; +}
\ No newline at end of file diff --git a/src/bus-utils.h b/src/bus-utils.h new file mode 100644 index 0000000..31a2ef1 --- /dev/null +++ b/src/bus-utils.h @@ -0,0 +1,30 @@ +/* + Copyright 2012 Alexandre Rostovtsev + + 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 2 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, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef _BUS_UTILS_H_ +#define _BUS_UTILS_H_ + +#include <glib.h> + +gboolean +check_polkit (const gchar *unique_name, + const gchar *action_id, + const gboolean user_interaction, + GError **error); + +#endif
\ No newline at end of file diff --git a/src/hostnamed.c b/src/hostnamed.c new file mode 100644 index 0000000..f0c2357 --- /dev/null +++ b/src/hostnamed.c @@ -0,0 +1,388 @@ +/* + Copyright 2012 Alexandre Rostovtsev + + 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 2 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, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include <errno.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include <dbus/dbus-protocol.h> +#include <glib.h> +#include <gio/gio.h> +#include <polkit/polkit.h> + +#include "hostnamed.h" +#include "hostnamed-generated.h" +#include "bus-utils.h" +#include "shell-utils.h" + +#include "config.h" + +#define QUOTE(macro) #macro +#define STR(macro) QUOTE(macro) + +guint bus_id = 0; +gboolean read_only = FALSE; + +static OpenrcSettingsdHostnamedHostname1 *hostname1 = NULL; + +static gchar hostname[HOST_NAME_MAX + 1]; +static gchar *static_hostname = NULL; +static gchar *pretty_hostname = NULL; +static gchar *icon_name = NULL; + +static gboolean +hostname_is_valid (const gchar *name) +{ + if (name == NULL) + return FALSE; + + return g_regex_match_simple ("^[a-zA-Z0-9_.-]{1," STR(HOST_NAME_MAX) "}$", + name, G_REGEX_MULTILINE, 0); +} + +static void +guess_icon_name () +{ + /* TODO: detect virtualization by reading rc_sys */ + +#if defined(__i386__) || defined(__x86_64__) + /* + Taken with a few minor changes from systemd's hostnamed + + See the SMBIOS Specification 2.7.1 section 7.4.1 for + details about the values listed here: + + http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_2.7.1.pdf + */ + gchar *contents; + + if (g_file_get_contents ("/sys/class/dmi/id/chassis_type", &contents, NULL, NULL)) { + switch (g_ascii_strtoull (contents, NULL, 10)) { + case 0x3: + case 0x4: + case 0x5: + case 0x6: + case 0x7: + icon_name = g_strdup ("computer-desktop"); + return; + case 0x9: + case 0xA: + case 0xE: + icon_name = g_strdup ("computer-laptop"); + return; + case 0x11: + case 0x17: + case 0x1C: + case 0x1D: + icon_name = g_strdup ("computer-server"); + return; + } + } +#endif + icon_name = g_strdup ("computer"); +} + +static gboolean +on_handle_set_hostname (OpenrcSettingsdHostnamedHostname1 *hostname1, + GDBusMethodInvocation *invocation, + const gchar *name, + const gboolean user_interaction, + gpointer user_data) +{ + GError *err = NULL; + + if (read_only) { + g_dbus_method_invocation_return_dbus_error (invocation, + DBUS_ERROR_NOT_SUPPORTED, + "openrc-settingsd hostnamed is in read-only mode"); + goto end; + } + + if (!check_polkit (g_dbus_method_invocation_get_sender (invocation), "org.freedesktop.hostname1.set-hostname", user_interaction, &err)) { + g_dbus_method_invocation_return_gerror (invocation, err); + goto end; + } + + /* Don't allow an empty or invalid hostname */ + if (!hostname_is_valid (name)) { + name = hostname; + if (!hostname_is_valid (name)) + name = "localhost"; + } + if (sethostname (name, strlen(name))) { + int errsv = errno; + g_dbus_method_invocation_return_dbus_error (invocation, + DBUS_ERROR_FAILED, + strerror (errsv)); + } + g_strlcpy (hostname, name, HOST_NAME_MAX + 1); + openrc_settingsd_hostnamed_hostname1_complete_set_hostname (hostname1, invocation); + openrc_settingsd_hostnamed_hostname1_set_hostname (hostname1, hostname); + + end: + return TRUE; +} + +static gboolean +on_handle_set_static_hostname (OpenrcSettingsdHostnamedHostname1 *hostname1, + GDBusMethodInvocation *invocation, + const gchar *name, + const gboolean user_interaction, + gpointer user_data) +{ + ShellUtilsTrivial *confd_file = NULL; + GError *err = NULL; + + if (read_only) { + g_dbus_method_invocation_return_dbus_error (invocation, + DBUS_ERROR_NOT_SUPPORTED, + "openrc-settingsd hostnamed is in read-only mode"); + goto end; + } + + if (!check_polkit (g_dbus_method_invocation_get_sender (invocation), "org.freedesktop.hostname1.set-static-hostname", user_interaction, &err)) { + g_dbus_method_invocation_return_gerror (invocation, err); + goto end; + } + + /* Don't allow an empty or invalid hostname */ + if (!hostname_is_valid (name)) + name = "localhost"; + + confd_file = shell_utils_trivial_new (SYSCONFDIR "/conf.d/hostname", &err); + if (confd_file == NULL) { + g_dbus_method_invocation_return_gerror (invocation, err); + goto end; + } + + if (!shell_utils_trivial_set_variable (confd_file, "hostname", name, FALSE) && + !shell_utils_trivial_set_variable (confd_file, "HOSTNAME", name, FALSE) && + !shell_utils_trivial_set_variable (confd_file, "hostname", name, TRUE)) + { + g_dbus_method_invocation_return_dbus_error (invocation, + DBUS_ERROR_FAILED, + "Failed to set static hostname in " SYSCONFDIR "/conf.d/hostname"); + goto end; + } + + if (!shell_utils_trivial_save (confd_file, &err)) { + g_dbus_method_invocation_return_gerror (invocation, err); + goto end; + } + + g_free (static_hostname); + static_hostname = g_strdup (name); + openrc_settingsd_hostnamed_hostname1_complete_set_static_hostname (hostname1, invocation); + openrc_settingsd_hostnamed_hostname1_set_static_hostname (hostname1, static_hostname); + + end: + shell_utils_trivial_free (confd_file); + if (err != NULL) + g_error_free (err); + + return TRUE; /* Always return TRUE to indicate signal has been handled */ +} + +static gboolean +on_handle_set_machine_info (OpenrcSettingsdHostnamedHostname1 *hostname1, + GDBusMethodInvocation *invocation, + const gchar *name, + const gboolean user_interaction, + gpointer user_data) +{ + ShellUtilsTrivial *confd_file = NULL; + GError *err = NULL; + gboolean is_pretty_hostname = GPOINTER_TO_INT(user_data); + + if (read_only) { + g_dbus_method_invocation_return_dbus_error (invocation, + DBUS_ERROR_NOT_SUPPORTED, + "openrc-settingsd hostnamed is in read-only mode"); + goto end; + } + + if (!check_polkit (g_dbus_method_invocation_get_sender (invocation), "org.freedesktop.hostname1.set-machine-info", user_interaction, &err)) { + g_dbus_method_invocation_return_gerror (invocation, err); + goto end; + } + + /* Don't allow a null pretty hostname */ + if (name == NULL) + name = ""; + + confd_file = shell_utils_trivial_new (SYSCONFDIR "/machine-info", &err); + if (confd_file == NULL) { + g_dbus_method_invocation_return_gerror (invocation, err); + goto end; + } + + if ((is_pretty_hostname && !shell_utils_trivial_set_variable (confd_file, "PRETTY_HOSTNAME", name, TRUE)) || + (!is_pretty_hostname && !shell_utils_trivial_set_variable (confd_file, "ICON_NAME", name, TRUE))) + { + g_dbus_method_invocation_return_dbus_error (invocation, + DBUS_ERROR_FAILED, + "Failed to value in " SYSCONFDIR "/machine-info"); + goto end; + } + + if (!shell_utils_trivial_save (confd_file, &err)) { + g_dbus_method_invocation_return_gerror (invocation, err); + goto end; + } + + if (is_pretty_hostname) { + g_free (pretty_hostname); + pretty_hostname = g_strdup (name); + openrc_settingsd_hostnamed_hostname1_complete_set_pretty_hostname (hostname1, invocation); + openrc_settingsd_hostnamed_hostname1_set_pretty_hostname (hostname1, pretty_hostname); + } else { + g_free (icon_name); + icon_name = g_strdup (name); + openrc_settingsd_hostnamed_hostname1_complete_set_icon_name (hostname1, invocation); + openrc_settingsd_hostnamed_hostname1_set_icon_name (hostname1, icon_name); + } + + end: + shell_utils_trivial_free (confd_file); + if (err != NULL) + g_error_free (err); + + return TRUE; /* Always return TRUE to indicate signal has been handled */ +} + +static void +on_bus_acquired (GDBusConnection *connection, + const gchar *bus_name, + gpointer user_data) +{ + gchar *name; + GError *err = NULL; + +#ifdef OPENRC_SETTINGSD_DEBUG + g_debug ("Acquired a message bus connection"); +#endif + + hostname1 = openrc_settingsd_hostnamed_hostname1_skeleton_new (); + + openrc_settingsd_hostnamed_hostname1_set_hostname (hostname1, hostname); + openrc_settingsd_hostnamed_hostname1_set_static_hostname (hostname1, static_hostname); + openrc_settingsd_hostnamed_hostname1_set_pretty_hostname (hostname1, pretty_hostname); + openrc_settingsd_hostnamed_hostname1_set_icon_name (hostname1, icon_name); + + g_signal_connect (hostname1, "handle-set-hostname", G_CALLBACK (on_handle_set_hostname), NULL); + g_signal_connect (hostname1, "handle-set-static-hostname", G_CALLBACK (on_handle_set_static_hostname), NULL); + g_signal_connect (hostname1, "handle-set-pretty-hostname", G_CALLBACK (on_handle_set_machine_info), GINT_TO_POINTER(TRUE)); + g_signal_connect (hostname1, "handle-set-icon-name", G_CALLBACK (on_handle_set_machine_info), GINT_TO_POINTER(FALSE)); + + if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (hostname1), + connection, + "/org/freedesktop/hostname1", + &err)) { + if (err != NULL) { + g_printerr ("Failed to export interface on /org/freedesktop/hostname1: %s\n", err->message); + g_error_free (err); + } + } +} + +static void +on_name_acquired (GDBusConnection *connection, + const gchar *bus_name, + gpointer user_data) +{ +#ifdef OPENRC_SETTINGSD_DEBUG + g_debug ("Acquired the name %s", bus_name); +#endif +} + +static void +on_name_lost (GDBusConnection *connection, + const gchar *bus_name, + gpointer user_data) +{ + if (connection == NULL) + g_printerr ("Failed to acquire a dbus connection\n"); + else + g_printerr ("Failed to acquire dbus name %s\n", bus_name); + exit(-1); +} + +/* Public functions */ + +void +hostnamed_init (gboolean _read_only) +{ + GError *err = NULL; + + memset (hostname, 0, HOST_NAME_MAX + 1); + if (gethostname (hostname, HOST_NAME_MAX)) { + perror (NULL); + hostname[0] = 0; + } + + static_hostname = shell_utils_source_var (SYSCONFDIR "/conf.d/hostname", "${hostname-${HOSTNAME-localhost}}", &err); + if (err != NULL) { + g_debug ("%s", err->message); + g_error_free (err); + err = NULL; + } + pretty_hostname = shell_utils_source_var (SYSCONFDIR "/machine-info", "${PRETTY_HOSTNAME}", &err); + if (pretty_hostname == NULL) + pretty_hostname = g_strdup (""); + if (err != NULL) { + g_debug ("%s", err->message); + g_error_free (err); + err = NULL; + } + icon_name = shell_utils_source_var (SYSCONFDIR "/machine-info", "${ICON_NAME}", &err); + if (icon_name == NULL) + icon_name = g_strdup (""); + if (err != NULL) { + g_debug ("%s", err->message); + g_error_free (err); + err = NULL; + } + + if (icon_name == NULL || strlen (icon_name) == 0) + guess_icon_name (); + + read_only = _read_only; + + bus_id = g_bus_own_name (G_BUS_TYPE_SYSTEM, + "org.freedesktop.hostname1", + G_BUS_NAME_OWNER_FLAGS_NONE, + on_bus_acquired, + on_name_acquired, + on_name_lost, + NULL, + NULL); +} + +void +hostnamed_destroy (void) +{ + g_bus_unown_name (bus_id); + bus_id = 0; + read_only = FALSE; + memset (hostname, 0, HOST_NAME_MAX + 1); + g_free (static_hostname); + g_free (pretty_hostname); + g_free (icon_name); +}
\ No newline at end of file diff --git a/src/hostnamed.h b/src/hostnamed.h new file mode 100644 index 0000000..e3107a0 --- /dev/null +++ b/src/hostnamed.h @@ -0,0 +1,47 @@ +/* + Copyright 2012 Alexandre Rostovtsev + + 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 2 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, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef OPENRC_HOSTNAMED_H +#define OPENRC_HOSTNAMED_H + +#include <glib.h> +#include <gio/gio.h> +#include <polkit/polkit.h> + +void +hostnamed_on_bus_acquired (GDBusConnection *connection, + const gchar *bus_name, + gpointer user_data); + +void +hostnamed_on_name_acquired (GDBusConnection *connection, + const gchar *bus_name, + gpointer user_data); + +void +hostnamed_on_name_lost (GDBusConnection *connection, + const gchar *bus_name, + gpointer user_data); + +void +hostnamed_init (gboolean read_only); + +void +hostnamed_destroy (void); + +#endif diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..1756b90 --- /dev/null +++ b/src/main.c @@ -0,0 +1,44 @@ +/* + Copyright 2012 Alexandre Rostovtsev + + 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 2 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, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include <glib.h> +#include <gio/gio.h> + +#include "hostnamed.h" +#include "shell-utils.h" + +#include "config.h" + +gint +main (gint argc, gchar *argv[]) +{ + GMainLoop *loop = NULL; + + g_type_init (); + + shell_utils_init (); + hostnamed_init (FALSE); + + loop = g_main_loop_new (NULL, FALSE); + g_main_loop_run (loop); + + g_main_loop_unref (loop); + hostnamed_destroy (); + shell_utils_destroy (); + return 0; +}
\ No newline at end of file diff --git a/src/shell-utils.c b/src/shell-utils.c new file mode 100644 index 0000000..6371ef1 --- /dev/null +++ b/src/shell-utils.c @@ -0,0 +1,468 @@ +/* + Copyright 2012 Alexandre Rostovtsev + + 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 2 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, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <sys/stat.h> + +#include <glib.h> +#include <glib/gstdio.h> +#include <gio/gio.h> + +#include "shell-utils.h" + +#include "config.h" + +GRegex *indent_regex = NULL; +GRegex *comment_regex = NULL; +GRegex *separator_regex = NULL; +GRegex *var_equals_regex = NULL; +GRegex *single_quoted_regex = NULL; +GRegex *double_quoted_regex = NULL; +GRegex *unquoted_regex = NULL; + +enum ShellEntryType { + SHELL_ENTRY_TYPE_INDENT, + SHELL_ENTRY_TYPE_COMMENT, + SHELL_ENTRY_TYPE_SEPARATOR, + SHELL_ENTRY_TYPE_ASSIGNMENT, +}; + +struct ShellEntry { + enum ShellEntryType type; + gchar *string; + gchar *variable; /* only relevant for assignments */ +}; + +gchar * +shell_utils_source_var (const gchar *filename, + const gchar *variable, + GError **error) +{ + gchar *argv[4] = { "sh", "-c", NULL, NULL }; + gchar *quoted_filename = NULL; + gchar *output = NULL; + + quoted_filename = g_shell_quote (filename); + argv[2] = g_strdup_printf (". %s; echo -n %s", quoted_filename, variable); + g_free (quoted_filename); + + if (g_file_test (filename, G_FILE_TEST_IS_REGULAR)) + if (!g_spawn_sync (NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, &output, NULL, NULL, error)) { + g_prefix_error (error, "Unable to source '%s': ", filename); + } + g_free (argv[2]); + return output; +} + +static void +shell_entry_free (struct ShellEntry *entry) +{ + if (entry == NULL) + return; + + if (entry->string != NULL) + g_free (entry->string); + if (entry->variable != NULL) + g_free (entry->variable); + g_free (entry); +} + +void +shell_utils_trivial_free (ShellUtilsTrivial *trivial) +{ + if (trivial == NULL) + return; + + if (trivial->filename != NULL) + g_free (trivial->filename); + if (trivial->entry_list != NULL) + g_list_free_full (trivial->entry_list, (GDestroyNotify)shell_entry_free); + g_free (trivial); +} + +ShellUtilsTrivial * +shell_utils_trivial_new (const gchar *filename, + GError **error) +{ + gchar *filebuf = NULL; + ShellUtilsTrivial *ret = NULL; + GError *local_err; + gchar *s; + + g_assert (filename != NULL); + + ret = g_new0 (ShellUtilsTrivial, 1); + ret->filename = g_strdup (filename); + + if (!g_file_get_contents (filename, &filebuf, NULL, &local_err)) { + if (local_err != NULL) { + /* Inability to parse or open is a failure; file not existing at all is *not* a failure */ + if (local_err->code == G_FILE_ERROR_NOENT) { + g_error_free (local_err); + return ret; + } + + g_propagate_prefixed_error (error, local_err, "Unable to read '%s':", filename); + } + shell_utils_trivial_free (ret); + return NULL; + } + + gboolean want_separator = FALSE; /* Do we expect the next entry to be a separator or comment? */ + s = filebuf; + while (*s != 0) { +#ifdef OPENRC_SETTINGSD_DEBUG + g_debug ("Scanning string: ``%s''", s); +#endif + gboolean matched = FALSE; + GMatchInfo *match_info = NULL; + struct ShellEntry *entry = NULL; + + matched = g_regex_match (comment_regex, s, 0, &match_info); + if (matched) { + entry = g_new0 (struct ShellEntry, 1); + entry->type = SHELL_ENTRY_TYPE_COMMENT; + entry->string = g_match_info_fetch (match_info, 0); + ret->entry_list = g_list_prepend (ret->entry_list, entry); + s += strlen (entry->string); +#ifdef OPENRC_SETTINGSD_DEBUG + g_debug ("Scanned comment: ``%s''", entry->string); +#endif + g_match_info_free (match_info); + match_info = NULL; + want_separator = FALSE; + continue; + } + g_match_info_free (match_info); + match_info = NULL; + + matched = g_regex_match (separator_regex, s, 0, &match_info); + if (matched) { + entry = g_new0 (struct ShellEntry, 1); + entry->type = SHELL_ENTRY_TYPE_SEPARATOR; + entry->string = g_match_info_fetch (match_info, 0); + ret->entry_list = g_list_prepend (ret->entry_list, entry); + s += strlen (entry->string); +#ifdef OPENRC_SETTINGSD_DEBUG + g_debug ("Scanned separator: ``%s''", entry->string); +#endif + g_match_info_free (match_info); + match_info = NULL; + want_separator = FALSE; + continue; + } + g_match_info_free (match_info); + match_info = NULL; + + matched = g_regex_match (indent_regex, s, 0, &match_info); + if (matched) { + entry = g_new0 (struct ShellEntry, 1); + entry->type = SHELL_ENTRY_TYPE_INDENT; + entry->string = g_match_info_fetch (match_info, 0); + ret->entry_list = g_list_prepend (ret->entry_list, entry); + s += strlen (entry->string); +#ifdef OPENRC_SETTINGSD_DEBUG + g_debug ("Scanned indent: ``%s''", entry->string); +#endif + g_match_info_free (match_info); + match_info = NULL; + continue; + } + g_match_info_free (match_info); + match_info = NULL; + + matched = g_regex_match (var_equals_regex, s, 0, &match_info); + if (matched) { + /* If we expect a separator and get an assignment instead, fail */ + if (want_separator) + goto no_match; + + entry = g_new0 (struct ShellEntry, 1); + entry->type = SHELL_ENTRY_TYPE_ASSIGNMENT; + entry->string = g_match_info_fetch (match_info, 0); + entry->variable = g_match_info_fetch (match_info, 1); + s += strlen (entry->string); +#ifdef OPENRC_SETTINGSD_DEBUG + g_debug ("Scanned variable: ``%s''", entry->string); +#endif + g_match_info_free (match_info); + match_info = NULL; + want_separator = TRUE; + + while (*s != 0) { +#ifdef OPENRC_SETTINGSD_DEBUG + g_debug ("Scanning string for values: ``%s''", s); +#endif + gboolean matched2 = FALSE; + gchar *temp1 = NULL, *temp2 = NULL; + + matched2 = g_regex_match (single_quoted_regex, s, 0, &match_info); + if (matched2) + goto append_value; + + g_match_info_free (match_info); + match_info = NULL; + + matched2 = g_regex_match (double_quoted_regex, s, 0, &match_info); + if (matched2) + goto append_value; + + g_match_info_free (match_info); + match_info = NULL; + + matched2 = g_regex_match (unquoted_regex, s, 0, &match_info); + if (matched2) + goto append_value; + + g_match_info_free (match_info); + match_info = NULL; + + break; +append_value: + temp1 = entry->string; + temp2 = g_match_info_fetch (match_info, 0); + entry->string = g_strconcat (temp1, temp2, NULL); + s += strlen (temp2); +#ifdef OPENRC_SETTINGSD_DEBUG + g_debug ("Scanned value: ``%s''", temp2); +#endif + g_free (temp1); + g_free (temp2); + g_match_info_free (match_info); + match_info = NULL; + } + + ret->entry_list = g_list_prepend (ret->entry_list, entry); + continue; + } + +no_match: + /* Nothing matches, parsing has failed! */ + g_match_info_free (match_info); + match_info = NULL; + g_propagate_error (error, + g_error_new (G_FILE_ERROR, G_FILE_ERROR_FAILED, + "Unable to parse '%s'", filename)); + shell_utils_trivial_free (ret); + return NULL; + } + + ret->entry_list = g_list_reverse (ret->entry_list); + return ret; +} + +gboolean +shell_utils_trivial_set_variable (ShellUtilsTrivial *trivial, + const gchar *variable, + const gchar *value, + gboolean add_if_unset) +{ + GList *curr = NULL; + struct ShellEntry *found_entry = NULL; + gchar *quoted_value = NULL; + gboolean ret = FALSE; + + g_assert (trivial != NULL); + g_assert (variable != NULL); + + for (curr = trivial->entry_list; curr != NULL; curr = curr->next) { + struct ShellEntry *entry; + + entry = (struct ShellEntry *)(curr->data); + if (entry->type == SHELL_ENTRY_TYPE_ASSIGNMENT && g_strcmp0 (variable, entry->variable) == 0) + found_entry = entry; + } + + quoted_value = g_shell_quote (value); + + if (found_entry != NULL) { + g_free (found_entry->string); + found_entry->string = g_strdup_printf ("%s=%s", variable, quoted_value); + ret = TRUE; + } else { + if (add_if_unset) { + found_entry = g_new0 (struct ShellEntry, 1); + found_entry->type = SHELL_ENTRY_TYPE_ASSIGNMENT; + found_entry->variable = g_strdup (variable); + found_entry->string = g_strdup_printf ("%s=%s", variable, quoted_value); + trivial->entry_list = g_list_append (trivial->entry_list, found_entry); + ret = TRUE; + } + } + + g_free (quoted_value); + return ret; +} + +gboolean +shell_utils_trivial_save (ShellUtilsTrivial *trivial, + GError **error) +{ + GList *curr = NULL; + gchar *temp_filename = NULL; + gint fd; + gboolean retval = FALSE; + GStatBuf stat_buf; + gint mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; /* 644 by default */ + + g_assert (trivial != NULL); + g_assert (trivial->filename != NULL); + + /* If the file exists, preserve its mode */ + if (!g_lstat (trivial->filename, &stat_buf)) + mode = stat_buf.st_mode; + + temp_filename = g_strdup_printf ("%s.XXXXXX", trivial->filename); + + if ((fd = g_mkstemp_full (temp_filename, O_WRONLY, mode)) < 0) { + int errsv = errno; + GFileError file_err; + file_err = g_file_error_from_errno (errsv); + g_propagate_prefixed_error (error, + g_error_copy ((GError*)&file_err), + "Unable to write '%s': Unable to create temp file: ", + trivial->filename); + goto out; + } + + for (curr = trivial->entry_list; curr != NULL; curr = curr->next) { + struct ShellEntry *entry; + ssize_t written; + + entry = (struct ShellEntry *)(curr->data); + written = write (fd, entry->string, strlen (entry->string)); + int errsv = errno; + if (written < strlen (entry->string)) { + if (written < 0) { + int errsv = errno; + GFileError file_err; + file_err = g_file_error_from_errno (errsv); + g_propagate_prefixed_error (error, + g_error_copy ((GError*)&file_err), + "Unable to write temp file '%s': ", + temp_filename); + } else { + g_propagate_error (error, + g_error_new (G_FILE_ERROR, G_FILE_ERROR_FAILED, + "Unable to write temp file '%s'", temp_filename)); + } + close (fd); + goto out; + } + } + if (fsync (fd) || close (fd)) { + int errsv = errno; + GFileError file_err; + file_err = g_file_error_from_errno (errsv); + g_propagate_prefixed_error (error, + g_error_copy ((GError*)&file_err), + "Unable to sync or close temp file '%s': ", + temp_filename); + close (fd); + goto out; + } + + if (g_rename (temp_filename, trivial->filename) < 0) { + int errsv = errno; + GFileError file_err; + file_err = g_file_error_from_errno (errsv); + g_propagate_prefixed_error (error, + g_error_copy ((GError*)&file_err), + "Unable to copy '%s' to '%s': ", + temp_filename, trivial->filename); + goto out; + } + retval = TRUE; + + out: + g_free (temp_filename); + g_unlink (temp_filename); + return retval; +} + +void +shell_utils_destroy (void) +{ + if (indent_regex != NULL) { + g_regex_unref (indent_regex); + indent_regex = NULL; + } + if (comment_regex != NULL) { + g_regex_unref (comment_regex); + comment_regex = NULL; + } + if (separator_regex != NULL) { + g_regex_unref (separator_regex); + separator_regex = NULL; + } + if (var_equals_regex != NULL) { + g_regex_unref (var_equals_regex); + var_equals_regex = NULL; + } + if (single_quoted_regex != NULL) { + g_regex_unref (single_quoted_regex); + single_quoted_regex = NULL; + } + if (double_quoted_regex != NULL) { + g_regex_unref (double_quoted_regex); + double_quoted_regex = NULL; + } + if (unquoted_regex != NULL) { + g_regex_unref (unquoted_regex); + unquoted_regex = NULL; + } +} + +void +shell_utils_init (void) +{ + if (indent_regex == NULL) { + indent_regex = g_regex_new ("^[ \\t]+", G_REGEX_ANCHORED, 0, NULL); + g_assert (indent_regex != NULL); + } + if (comment_regex == NULL) { + comment_regex = g_regex_new ("^#[^\\n]*\\n", G_REGEX_ANCHORED|G_REGEX_MULTILINE, 0, NULL); + g_assert (comment_regex != NULL); + } + if (separator_regex == NULL) { + separator_regex = g_regex_new ("^[ \\t;\\n\\r]*[;\\n][ \\t;\\n\\r]*", G_REGEX_ANCHORED|G_REGEX_MULTILINE, 0, NULL); + g_assert (separator_regex != NULL); + } + if (var_equals_regex == NULL) { + var_equals_regex = g_regex_new ("^([a-zA-Z_][a-zA-Z0-9_]*)(?:(?:\\\\\\n)*)=(?:(?:\\\\\\n)*)", G_REGEX_ANCHORED|G_REGEX_MULTILINE, 0, NULL); + g_assert (var_equals_regex != NULL); + } + if (single_quoted_regex == NULL) { + single_quoted_regex = g_regex_new ("^'[^']*'", G_REGEX_ANCHORED|G_REGEX_MULTILINE, 0, NULL); + g_assert (single_quoted_regex != NULL); + } + /* We do not want to allow $(...) or `...` constructs in double-quoted + * strings because they might have side effects, but ${...} is OK */ + if (double_quoted_regex == NULL) { + double_quoted_regex = g_regex_new ("^\"(?:[^\"`\\$]|\\\\[\"`\\$]|\\$\\{)*\"", G_REGEX_ANCHORED|G_REGEX_MULTILINE, 0, NULL); + g_assert (double_quoted_regex != NULL); + } + if (unquoted_regex == NULL) { + unquoted_regex = g_regex_new ("^(?:[^\\s\"'`\\$\\|&<>;]|\\\\[\\s\"'`\\$\\|&<>;]|\\$\\{)+", G_REGEX_ANCHORED|G_REGEX_MULTILINE, 0, NULL); + g_assert (unquoted_regex != NULL); + } +}
\ No newline at end of file diff --git a/src/shell-utils.h b/src/shell-utils.h new file mode 100644 index 0000000..861cd87 --- /dev/null +++ b/src/shell-utils.h @@ -0,0 +1,60 @@ +/* + Copyright 2012 Alexandre Rostovtsev + + 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 2 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, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef _SHELL_UTILS_H_ +#define _SHELL_UTILS_H_ + +#include <glib.h> + +typedef struct _ShellUtilsTrivial ShellUtilsTrivial; + +struct _ShellUtilsTrivial +{ + gchar *filename; + GList *entry_list; +}; + +gchar * +shell_utils_source_var (const gchar *filename, + const gchar *variable, + GError **error); + +void +shell_utils_init (void); + +void +shell_utils_destroy (void); + +ShellUtilsTrivial * +shell_utils_trivial_new (const gchar *filename, + GError **error); + +void +shell_utils_trivial_free (ShellUtilsTrivial *trivial); + +gboolean +shell_utils_trivial_set_variable (ShellUtilsTrivial *trivial, + const gchar *variable, + const gchar *value, + gboolean add_if_unset); + +gboolean +shell_utils_trivial_save (ShellUtilsTrivial *trivial, + GError **error); + +#endif |