commit 1095734b484e5465113963b018c2957549029ad7 Author: Alexander Vdolainen Date: Mon Nov 24 13:46:57 2014 +0200 initial import 0.1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3df996e --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +*~ +*.o +*.a +*.lo +*.la +*.dvi +*.synctex.gz +.deps +.libs +autom4te.cache/ +Makefile +Makefile.in +aclocal.m4 +config.guess +config.h +config.h.in +config.log +config.status +config.sub +configure +depcomp +install-sh +intltool-extract.in +intltool-merge.in +intltool-update.in +lib/libtdata-0.2.pc +libtool +ltmain.sh +missing +mkinstalldirs +po/Makefile.in.in +po/POTFILES +po/stamp-it +stamp-h1 +include/version.h +.emacs.desktop +nbproject +config.guess.dh-orig +config.sub.dh-orig diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..8ac1c7e --- /dev/null +++ b/AUTHORS @@ -0,0 +1,5 @@ +This software was developed by Askele companies group. + * EU part: http://askele.com + * NW European part of Russia: http://askele-ingria.com +Team: + * General SW Architect and PM: Alexander Vdolainen diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..befd914 --- /dev/null +++ b/COPYING @@ -0,0 +1,3 @@ +Askele business software license. + +Libs and others might be under LGPLv3. \ No newline at end of file diff --git a/COPYING.LGPL3 b/COPYING.LGPL3 new file mode 100644 index 0000000..3f7b8b1 --- /dev/null +++ b/COPYING.LGPL3 @@ -0,0 +1,166 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. + diff --git a/ChangeLog b/ChangeLog new file mode 100644 index 0000000..93ca727 --- /dev/null +++ b/ChangeLog @@ -0,0 +1,10 @@ +2013-09-22 Alexander Vdolainen + * (a set of files): added autotools + +2014-11-23 Alexander Vdolainen + * Initial import of 0.2 version + + +Copyright 2013-2014 Askele, Inc. +Copying and distribution of this file, with or without modification, are +permitted provided the copyright notice and this notice are preserved. diff --git a/INSTALL b/INSTALL new file mode 100644 index 0000000..a1e89e1 --- /dev/null +++ b/INSTALL @@ -0,0 +1,370 @@ +Installation Instructions +************************* + +Copyright (C) 1994-1996, 1999-2002, 2004-2011 Free Software Foundation, +Inc. + + Copying and distribution of this file, with or without modification, +are permitted in any medium without royalty provided the copyright +notice and this notice are preserved. This file is offered as-is, +without warranty of any kind. + +Basic Installation +================== + + Briefly, the shell commands `./configure; make; make install' should +configure, build, and install this package. The following +more-detailed instructions are generic; see the `README' file for +instructions specific to this package. Some packages provide this +`INSTALL' file but do not implement all of the features documented +below. The lack of an optional feature in a given package is not +necessarily a bug. More recommendations for GNU packages can be found +in *note Makefile Conventions: (standards)Makefile Conventions. + + The `configure' shell script attempts to guess correct values for +various system-dependent variables used during compilation. It uses +those values to create a `Makefile' in each directory of the package. +It may also create one or more `.h' files containing system-dependent +definitions. Finally, it creates a shell script `config.status' that +you can run in the future to recreate the current configuration, and a +file `config.log' containing compiler output (useful mainly for +debugging `configure'). + + It can also use an optional file (typically called `config.cache' +and enabled with `--cache-file=config.cache' or simply `-C') that saves +the results of its tests to speed up reconfiguring. Caching is +disabled by default to prevent problems with accidental use of stale +cache files. + + If you need to do unusual things to compile the package, please try +to figure out how `configure' could check whether to do them, and mail +diffs or instructions to the address given in the `README' so they can +be considered for the next release. If you are using the cache, and at +some point `config.cache' contains results you don't want to keep, you +may remove or edit it. + + The file `configure.ac' (or `configure.in') is used to create +`configure' by a program called `autoconf'. You need `configure.ac' if +you want to change it or regenerate `configure' using a newer version +of `autoconf'. + + The simplest way to compile this package is: + + 1. `cd' to the directory containing the package's source code and type + `./configure' to configure the package for your system. + + Running `configure' might take a while. While running, it prints + some messages telling which features it is checking for. + + 2. Type `make' to compile the package. + + 3. Optionally, type `make check' to run any self-tests that come with + the package, generally using the just-built uninstalled binaries. + + 4. Type `make install' to install the programs and any data files and + documentation. When installing into a prefix owned by root, it is + recommended that the package be configured and built as a regular + user, and only the `make install' phase executed with root + privileges. + + 5. Optionally, type `make installcheck' to repeat any self-tests, but + this time using the binaries in their final installed location. + This target does not install anything. Running this target as a + regular user, particularly if the prior `make install' required + root privileges, verifies that the installation completed + correctly. + + 6. You can remove the program binaries and object files from the + source code directory by typing `make clean'. To also remove the + files that `configure' created (so you can compile the package for + a different kind of computer), type `make distclean'. There is + also a `make maintainer-clean' target, but that is intended mainly + for the package's developers. If you use it, you may have to get + all sorts of other programs in order to regenerate files that came + with the distribution. + + 7. Often, you can also type `make uninstall' to remove the installed + files again. In practice, not all packages have tested that + uninstallation works correctly, even though it is required by the + GNU Coding Standards. + + 8. Some packages, particularly those that use Automake, provide `make + distcheck', which can by used by developers to test that all other + targets like `make install' and `make uninstall' work correctly. + This target is generally not run by end users. + +Compilers and Options +===================== + + Some systems require unusual options for compilation or linking that +the `configure' script does not know about. Run `./configure --help' +for details on some of the pertinent environment variables. + + You can give `configure' initial values for configuration parameters +by setting variables in the command line or in the environment. Here +is an example: + + ./configure CC=c99 CFLAGS=-g LIBS=-lposix + + *Note Defining Variables::, for more details. + +Compiling For Multiple Architectures +==================================== + + You can compile the package for more than one kind of computer at the +same time, by placing the object files for each architecture in their +own directory. To do this, you can use GNU `make'. `cd' to the +directory where you want the object files and executables to go and run +the `configure' script. `configure' automatically checks for the +source code in the directory that `configure' is in and in `..'. This +is known as a "VPATH" build. + + With a non-GNU `make', it is safer to compile the package for one +architecture at a time in the source code directory. After you have +installed the package for one architecture, use `make distclean' before +reconfiguring for another architecture. + + On MacOS X 10.5 and later systems, you can create libraries and +executables that work on multiple system types--known as "fat" or +"universal" binaries--by specifying multiple `-arch' options to the +compiler but only a single `-arch' option to the preprocessor. Like +this: + + ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ + CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ + CPP="gcc -E" CXXCPP="g++ -E" + + This is not guaranteed to produce working output in all cases, you +may have to build one architecture at a time and combine the results +using the `lipo' tool if you have problems. + +Installation Names +================== + + By default, `make install' installs the package's commands under +`/usr/local/bin', include files under `/usr/local/include', etc. You +can specify an installation prefix other than `/usr/local' by giving +`configure' the option `--prefix=PREFIX', where PREFIX must be an +absolute file name. + + You can specify separate installation prefixes for +architecture-specific files and architecture-independent files. If you +pass the option `--exec-prefix=PREFIX' to `configure', the package uses +PREFIX as the prefix for installing programs and libraries. +Documentation and other data files still use the regular prefix. + + In addition, if you use an unusual directory layout you can give +options like `--bindir=DIR' to specify different values for particular +kinds of files. Run `configure --help' for a list of the directories +you can set and what kinds of files go in them. In general, the +default for these options is expressed in terms of `${prefix}', so that +specifying just `--prefix' will affect all of the other directory +specifications that were not explicitly provided. + + The most portable way to affect installation locations is to pass the +correct locations to `configure'; however, many packages provide one or +both of the following shortcuts of passing variable assignments to the +`make install' command line to change installation locations without +having to reconfigure or recompile. + + The first method involves providing an override variable for each +affected directory. For example, `make install +prefix=/alternate/directory' will choose an alternate location for all +directory configuration variables that were expressed in terms of +`${prefix}'. Any directories that were specified during `configure', +but not in terms of `${prefix}', must each be overridden at install +time for the entire installation to be relocated. The approach of +makefile variable overrides for each directory variable is required by +the GNU Coding Standards, and ideally causes no recompilation. +However, some platforms have known limitations with the semantics of +shared libraries that end up requiring recompilation when using this +method, particularly noticeable in packages that use GNU Libtool. + + The second method involves providing the `DESTDIR' variable. For +example, `make install DESTDIR=/alternate/directory' will prepend +`/alternate/directory' before all installation names. The approach of +`DESTDIR' overrides is not required by the GNU Coding Standards, and +does not work on platforms that have drive letters. On the other hand, +it does better at avoiding recompilation issues, and works well even +when some directory options were not specified in terms of `${prefix}' +at `configure' time. + +Optional Features +================= + + If the package supports it, you can cause programs to be installed +with an extra prefix or suffix on their names by giving `configure' the +option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. + + Some packages pay attention to `--enable-FEATURE' options to +`configure', where FEATURE indicates an optional part of the package. +They may also pay attention to `--with-PACKAGE' options, where PACKAGE +is something like `gnu-as' or `x' (for the X Window System). The +`README' should mention any `--enable-' and `--with-' options that the +package recognizes. + + For packages that use the X Window System, `configure' can usually +find the X include and library files automatically, but if it doesn't, +you can use the `configure' options `--x-includes=DIR' and +`--x-libraries=DIR' to specify their locations. + + Some packages offer the ability to configure how verbose the +execution of `make' will be. For these packages, running `./configure +--enable-silent-rules' sets the default to minimal output, which can be +overridden with `make V=1'; while running `./configure +--disable-silent-rules' sets the default to verbose, which can be +overridden with `make V=0'. + +Particular systems +================== + + On HP-UX, the default C compiler is not ANSI C compatible. If GNU +CC is not installed, it is recommended to use the following options in +order to use an ANSI C compiler: + + ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" + +and if that doesn't work, install pre-built binaries of GCC for HP-UX. + + HP-UX `make' updates targets which have the same time stamps as +their prerequisites, which makes it generally unusable when shipped +generated files such as `configure' are involved. Use GNU `make' +instead. + + On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot +parse its `' header file. The option `-nodtk' can be used as +a workaround. If GNU CC is not installed, it is therefore recommended +to try + + ./configure CC="cc" + +and if that doesn't work, try + + ./configure CC="cc -nodtk" + + On Solaris, don't put `/usr/ucb' early in your `PATH'. This +directory contains several dysfunctional programs; working variants of +these programs are available in `/usr/bin'. So, if you need `/usr/ucb' +in your `PATH', put it _after_ `/usr/bin'. + + On Haiku, software installed for all users goes in `/boot/common', +not `/usr/local'. It is recommended to use the following options: + + ./configure --prefix=/boot/common + +Specifying the System Type +========================== + + There may be some features `configure' cannot figure out +automatically, but needs to determine by the type of machine the package +will run on. Usually, assuming the package is built to be run on the +_same_ architectures, `configure' can figure that out, but if it prints +a message saying it cannot guess the machine type, give it the +`--build=TYPE' option. TYPE can either be a short name for the system +type, such as `sun4', or a canonical name which has the form: + + CPU-COMPANY-SYSTEM + +where SYSTEM can have one of these forms: + + OS + KERNEL-OS + + See the file `config.sub' for the possible values of each field. If +`config.sub' isn't included in this package, then this package doesn't +need to know the machine type. + + If you are _building_ compiler tools for cross-compiling, you should +use the option `--target=TYPE' to select the type of system they will +produce code for. + + If you want to _use_ a cross compiler, that generates code for a +platform different from the build platform, you should specify the +"host" platform (i.e., that on which the generated programs will +eventually be run) with `--host=TYPE'. + +Sharing Defaults +================ + + If you want to set default values for `configure' scripts to share, +you can create a site shell script called `config.site' that gives +default values for variables like `CC', `cache_file', and `prefix'. +`configure' looks for `PREFIX/share/config.site' if it exists, then +`PREFIX/etc/config.site' if it exists. Or, you can set the +`CONFIG_SITE' environment variable to the location of the site script. +A warning: not all `configure' scripts look for a site script. + +Defining Variables +================== + + Variables not defined in a site shell script can be set in the +environment passed to `configure'. However, some packages may run +configure again during the build, and the customized values of these +variables may be lost. In order to avoid this problem, you should set +them in the `configure' command line, using `VAR=value'. For example: + + ./configure CC=/usr/local2/bin/gcc + +causes the specified `gcc' to be used as the C compiler (unless it is +overridden in the site shell script). + +Unfortunately, this technique does not work for `CONFIG_SHELL' due to +an Autoconf bug. Until the bug is fixed you can use this workaround: + + CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash + +`configure' Invocation +====================== + + `configure' recognizes the following options to control how it +operates. + +`--help' +`-h' + Print a summary of all of the options to `configure', and exit. + +`--help=short' +`--help=recursive' + Print a summary of the options unique to this package's + `configure', and exit. The `short' variant lists options used + only in the top level, while the `recursive' variant lists options + also present in any nested packages. + +`--version' +`-V' + Print the version of Autoconf used to generate the `configure' + script, and exit. + +`--cache-file=FILE' + Enable the cache: use and save the results of the tests in FILE, + traditionally `config.cache'. FILE defaults to `/dev/null' to + disable caching. + +`--config-cache' +`-C' + Alias for `--cache-file=config.cache'. + +`--quiet' +`--silent' +`-q' + Do not print messages saying which checks are being made. To + suppress all normal output, redirect it to `/dev/null' (any error + messages will still be shown). + +`--srcdir=DIR' + Look for the package's source code in directory DIR. Usually + `configure' can determine that directory automatically. + +`--prefix=DIR' + Use DIR as the installation prefix. *note Installation Names:: + for more details, including other options available for fine-tuning + the installation locations. + +`--no-create' +`-n' + Run the configure checks, but stop before creating any output + files. + +`configure' also accepts some other, not widely useful, options. Run +`configure --help' for more details. + diff --git a/Makefile.am b/Makefile.am new file mode 100644 index 0000000..258d2c6 --- /dev/null +++ b/Makefile.am @@ -0,0 +1,32 @@ +## Process this file with automake to produce Makefile.in + +SUBDIRS = po include lib + +libsntldocdir = ${prefix}/doc/libsexpr +libsntldoc_DATA = \ + README\ + COPYING\ + AUTHORS\ + ChangeLog\ + INSTALL\ + NEWS + + +INTLTOOL_FILES = intltool-extract.in \ + intltool-merge.in \ + intltool-update.in + +EXTRA_DIST = $(libsntldoc_DATA) \ + $(INTLTOOL_FILES) + +DISTCLEANFILES = intltool-extract \ + intltool-merge \ + intltool-update \ + po/.intltool-merge-cache + +clean-local: + + +# Remove doc directory on uninstall +uninstall-local: + -rm -r $(libsntldocdir) diff --git a/NEWS b/NEWS new file mode 100644 index 0000000..195c730 --- /dev/null +++ b/NEWS @@ -0,0 +1 @@ +22.09.2013: Autotools choosen to be a build be. diff --git a/README b/README new file mode 100644 index 0000000..e69e2f7 --- /dev/null +++ b/README @@ -0,0 +1 @@ +1. Build the Debian package: debuild -i -us -uc -b diff --git a/autogen.sh b/autogen.sh new file mode 100755 index 0000000..a0ec5ee --- /dev/null +++ b/autogen.sh @@ -0,0 +1,157 @@ +#!/bin/sh +# Run this to generate all the initial makefiles, etc. + +srcdir=`dirname $0` +test -z "$srcdir" && srcdir=. + +DIE=0 + +if [ -n "$GNOME2_DIR" ]; then + ACLOCAL_FLAGS="-I $GNOME2_DIR/share/aclocal $ACLOCAL_FLAGS" + LD_LIBRARY_PATH="$GNOME2_DIR/lib:$LD_LIBRARY_PATH" + PATH="$GNOME2_DIR/bin:$PATH" + export PATH + export LD_LIBRARY_PATH +fi + +(test -f $srcdir/configure.ac) || { + echo -n "**Error**: Directory "\`$srcdir\'" does not look like the" + echo " top-level package directory" + exit 1 +} + +(autoconf --version) < /dev/null > /dev/null 2>&1 || { + echo + echo "**Error**: You must have \`autoconf' installed." + echo "Download the appropriate package for your distribution," + echo "or get the source tarball at ftp://ftp.gnu.org/pub/gnu/" + DIE=1 +} + +(grep "^IT_PROG_INTLTOOL" $srcdir/configure.ac >/dev/null) && { + (intltoolize --version) < /dev/null > /dev/null 2>&1 || { + echo + echo "**Error**: You must have \`intltool' installed." + echo "You can get it from:" + echo " ftp://ftp.gnome.org/pub/GNOME/" + DIE=1 + } +} + +(grep "^AM_PROG_XML_I18N_TOOLS" $srcdir/configure.ac >/dev/null) && { + (xml-i18n-toolize --version) < /dev/null > /dev/null 2>&1 || { + echo + echo "**Error**: You must have \`xml-i18n-toolize' installed." + echo "You can get it from:" + echo " ftp://ftp.gnome.org/pub/GNOME/" + DIE=1 + } +} + +(grep "^LT_INIT" $srcdir/configure.ac >/dev/null) && { + (libtool --version) < /dev/null > /dev/null 2>&1 || { + echo + echo "**Error**: You must have \`libtool' installed." + echo "You can get it from: ftp://ftp.gnu.org/pub/gnu/" + DIE=1 + } +} + +(grep "^AM_GLIB_GNU_GETTEXT" $srcdir/configure.ac >/dev/null) && { + (grep "sed.*POTFILES" $srcdir/configure.ac) > /dev/null || \ + (glib-gettextize --version) < /dev/null > /dev/null 2>&1 || { + echo + echo "**Error**: You must have \`glib' installed." + echo "You can get it from: ftp://ftp.gtk.org/pub/gtk" + DIE=1 + } +} + +(automake --version) < /dev/null > /dev/null 2>&1 || { + echo + echo "**Error**: You must have \`automake' installed." + echo "You can get it from: ftp://ftp.gnu.org/pub/gnu/" + DIE=1 + NO_AUTOMAKE=yes +} + + +# if no automake, don't bother testing for aclocal +test -n "$NO_AUTOMAKE" || (aclocal --version) < /dev/null > /dev/null 2>&1 || { + echo + echo "**Error**: Missing \`aclocal'. The version of \`automake'" + echo "installed doesn't appear recent enough." + echo "You can get automake from ftp://ftp.gnu.org/pub/gnu/" + DIE=1 +} + +if test "$DIE" -eq 1; then + exit 1 +fi + +if test -z "$*"; then + echo "**Warning**: I am going to run \`configure' with no arguments." + echo "If you wish to pass any to it, please specify them on the" + echo \`$0\'" command line." + echo +fi + +case $CC in +xlc ) + am_opt=--include-deps;; +esac + +for coin in `find $srcdir -path $srcdir/CVS -prune -o -name configure.ac -print` +do + dr=`dirname $coin` + if test -f $dr/NO-AUTO-GEN; then + echo skipping $dr -- flagged as no auto-gen + else + echo processing $dr + ( cd $dr + + aclocalinclude="$ACLOCAL_FLAGS" + + if grep "^AM_GLIB_GNU_GETTEXT" configure.ac >/dev/null; then + echo "Creating $dr/aclocal.m4 ..." + test -r $dr/aclocal.m4 || touch $dr/aclocal.m4 + echo "Running glib-gettextize... Ignore non-fatal messages." + echo "no" | glib-gettextize --force --copy + echo "Making $dr/aclocal.m4 writable ..." + test -r $dr/aclocal.m4 && chmod u+w $dr/aclocal.m4 + fi + if grep "^IT_PROG_INTLTOOL" configure.ac >/dev/null; then + echo "Running intltoolize..." + intltoolize --copy --force --automake + fi + if grep "^AM_PROG_XML_I18N_TOOLS" configure.ac >/dev/null; then + echo "Running xml-i18n-toolize..." + xml-i18n-toolize --copy --force --automake + fi + if grep "^LT_INIT" configure.ac >/dev/null; then + if test -z "$NO_LIBTOOLIZE" ; then + echo "Running libtoolize..." + libtoolize --force --copy + fi + fi + echo "Running aclocal $aclocalinclude ..." + aclocal $aclocalinclude + if grep "^A[CM]_CONFIG_HEADER" configure.ac >/dev/null; then + echo "Running autoheader..." + autoheader + fi + echo "Running automake --gnu $am_opt ..." + automake --add-missing --copy --gnu $am_opt + echo "Running autoconf ..." + autoconf + ) + fi +done + +if test x$NOCONFIGURE = x; then + echo Running $srcdir/configure "$@" ... + $srcdir/configure "$@" \ + && echo Now type \`make\' to compile. || exit 1 +else + echo Skipping configure process. +fi diff --git a/configure.ac b/configure.ac new file mode 100644 index 0000000..877a928 --- /dev/null +++ b/configure.ac @@ -0,0 +1,47 @@ +dnl Process this file with autoconf to produce a configure script. + +AC_INIT(libsntl, 0.1) + +AC_CONFIG_HEADERS([config.h]) + +AM_INIT_AUTOMAKE([1.11]) + +AM_SILENT_RULES([yes]) + +AC_PROG_CC + +dnl *************************************************************************** +dnl Internationalization +dnl *************************************************************************** +IT_PROG_INTLTOOL([0.35.0]) + +GETTEXT_PACKAGE=libsntl +AC_SUBST(GETTEXT_PACKAGE) +AC_DEFINE_UNQUOTED(GETTEXT_PACKAGE,"$GETTEXT_PACKAGE", [GETTEXT package name]) +AM_GLIB_GNU_GETTEXT + + +LT_INIT + +PKG_CHECK_MODULES(OPENSSL, [openssl]) +PKG_CHECK_MODULES(LIBUUID, [uuid]) +PKG_CHECK_MODULES(LIBTDATA, [libtdata-0.2]) +PKG_CHECK_MODULES(LIBSEXPR, [libsexpr-1.2]) + +dnl ***************** +dnl ***** options ***** +dnl ***************** + +AC_ARG_ENABLE([build_examples], + AS_HELP_STRING([--enable-build-examples], [Enable examples build])) + +AS_IF([test "x$enable_build_examples" = "xyes"], [ + AC_DEFINE([BUILD_EXAMPLES], 1, [build of examples enabled]) +]) + +AC_OUTPUT([ +Makefile +lib/libsntl-0.1.pc +lib/Makefile +include/Makefile +po/Makefile.in]) diff --git a/doc/TODO b/doc/TODO new file mode 100644 index 0000000..e69de29 diff --git a/examples/TODO b/examples/TODO new file mode 100644 index 0000000..e69de29 diff --git a/include/Makefile.am b/include/Makefile.am new file mode 100644 index 0000000..7af89e1 --- /dev/null +++ b/include/Makefile.am @@ -0,0 +1 @@ +nobase_include_HEADERS = sntl/pth_queue.h sntl/connection.h diff --git a/include/sntl/connection.h b/include/sntl/connection.h new file mode 100644 index 0000000..a877040 --- /dev/null +++ b/include/sntl/connection.h @@ -0,0 +1,213 @@ +/* + * File: connection.h + * Author: vdo + * + * Created on September 24, 2014, 2:36 AM + */ + +#ifndef __ESXC_CONNECTION_H_ +#define __ESXC_CONNECTION_H_ + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include + +/* sexp helpers */ +#define SEXP_IS_LIST(sx) \ + ((sx)->ty == SEXP_LIST) ? 1 : 0 + +#define SEXP_IS_TYPE(sx,type) \ + ((sx)->ty == SEXP_VALUE && (sx)->aty == (type)) ? 1 : 0 + +#define SEXP_ITERATE_LIST(lst, iter, ind) \ + for((ind) = 0, (iter) = (lst)->list; (ind) < sexp_list_length(lst); \ + (ind)++, (iter) = (iter)->next) + +int sexp_list_cdr(sexp_t *expr, sexp_t **sx); +int sexp_list_car(sexp_t *expr, sexp_t **sx); + +#define VERIFY_DEPTH 1 /* FIXME: */ + +#define MAX_CONNECTIONS 32768 +#define MAX_CHANNELS 4096 +#define MAX_RPC_LIST 2048 +#define MAX_MULTI 12 +#define MAX_PENDINGMSG 16384 +#define MAX_MSGINDEX ((MAX_PENDINGMSG) * (MAX_MULTI)) + +typedef struct __perm_context_type { + char *login; + char *passwd; + ulong_t certid; + ulong_t uid; + ulong_t gid; + ulong_t *gids; + int n_gids; + int p_attr; + void *priv; +} perm_ctx_t; + +#define CXCONN_MASTER (1 << 1) +#define CXCONN_SLAVE (1 << 2) +#define CXCONN_ESTABL (1 << 3) + +typedef struct __connection_t { + char *uuid; /** < uuid of the connection */ + idx_allocator_t *idx_ch; /** < index allocation for channels */ + usrtc_t *chnl_tree; /** < search tree of all channels */ + usrtc_t *rpc_list; /** < search tree of possible RPC typed lists */ + SSL_CTX *ctx; /** < SSL context */ + SSL *ssl; /** < SSL connection */ + int ssl_data_index; /** < SSL index for the custom data */ + perm_ctx_t *pctx; /** < higher layer authentification context */ + pthread_t cthread; /** < thread for listening the connection socket */ + pthread_mutex_t oplock; /** < mutex used to sync operations on connection */ + pthread_rwlock_t chnl_lock; /** < rwlock used to sync ops with channels */ + int flags; /** < flags of the connection */ + usrtc_node_t csnode; /** < node to store the connection within list */ +} conn_t; + +struct __connection_rpc_list_type; +struct __message_t; + +#define ESXCHAN_PENDING (1 << 1) +#define ESXCHAN_CLOSURE (1 << 2) + +typedef struct __channel_t { + ulong_t cid; /** < ID of the channel */ + char *uuid; /** < UUID of the channel, used in advanced implementation + * of the complex distributed systems */ + conn_t *connection; /** < pointer to the parent connection */ + idx_allocator_t *idx_msg; /** < index allocation for messages */ + usrtc_t *msgs_tree; /** < search tree of the existing messages */ + struct __message_t *sysmsg; /** < system message used to operate with channel */ + struct __connection_rpc_list_type *rpc_list; /** < rpc functions list */ + pthread_mutex_t oplock; /** < operation ops lock */ + pthread_rwlock_t msglock; /** < rwlock used to operate with messages */ + usrtc_node_t node; /** < node for connection search tree */ + int use_count; /** < use count */ + int flags; /** < flags of the channel */ +} chnl_t; + +typedef struct __sexp_payload_t { + char *cstr; + sexp_t *sx; +} sxpayload_t; + +#define ESX_SYSMSG_SIZE 512 + +#define ESXMSG_SYS (1 << 1) +#define ESXMSG_USR (1 << 2) +#define ESXMSG_PENDING (1 << 3) +#define ESXMSG_NOWAY (1 << 4) + +typedef struct __message_t { + chnl_t *pch; /** < channel of the message(if applicable) */ + ulong_t mid; /** < unique ID within connection context */ + char *uuid; /** < UUID of the message, used for special messages */ + usrtc_node_t chnl_node; /** < node for channel search tree */ + usrtc_node_t poll_node; /** < node for the poll of the messages */ + usrtc_node_t pendingq_node; /** < node for the pending queue */ + pthread_mutex_t wait; /** < special wait mutex, used for sync */ + void *payload; /** < payload */ + int opcode; /** < opcode for system and pulse messages */ + int flags; /** < flags of the message (type, state etc ...)*/ + int use_count; /** < use count */ +} sxmsg_t; + +typedef struct __connection_rpc_entry_type { + char *name; + int (*rpcf)(void *, sexp_t *); + usrtc_node_t node; +} cx_rpc_t; + +typedef struct __connection_rpc_list_type { + usrtc_t *rpc_tree; /** < search tree for the rpc lookup */ + char *opt_version; /** < reserved for future implementations */ +} cx_rpc_list_t; + +typedef struct __connections_subsys_type { + int ex_ssldata_index; /** < index used to work with additional data provided to the special call during SSL handshake */ + usrtc_t *connections; + pth_queue_t *ioq; /** < general messages queue */ + pth_queue_t *ioqueue; /** < system messages queue */ + /* system threads */ + pthread_t iog_thread; /** < general io queue */ + pthread_t ios_thread; /** < system io queue */ + pthread_rwlock_t rwlock; + char *rootca, *certpem, *certkey; /* path name to the certificates */ + cx_rpc_list_t *system_rpc; + /* special functions pointers */ + int (*validate_sslpem)(conn_t *); /** < this function used to validate SSL certificate while SSL handshake */ + int (*secure_check)(conn_t *); /** < this function authorize user to login, and also should check SSL cert and user, and already made sessions */ + usrtc_t* (*get_rpc_typed_list_tree)(conn_t *); /** < this function is used to set RPC list of the functions */ + int (*set_typed_list_callback)(conn_t *, int, char *); /** < this function is a callback during setting up a typed channel */ + void *priv; +} conn_sys_t; + +typedef struct __rpc_typed_list_type { + int type_id; + char *description; + cx_rpc_list_t *rpc_list; + usrtc_node_t lnode; +} rpc_typed_list_t; + +extern conn_sys_t *conn_sys; + +/* General API */ +/* subsystem */ +int connections_subsystem_init(void); + +int connections_subsystem_setsslserts(const char *rootca, const char *certpem, + const char *certkey); + +int connections_subsystem_setrpclist_function(usrtc_t* (*get_rpc_typed_list_tree)(conn_t *)); + +#define connections_subsystem_set_securecheck(c, fuu) (c)->secure_check = fuu +#define connections_subsystem_set_sslvalidator(c, fuu) (c)->validate_sslpem = fuu +#define connections_subsystem_set_rpctlist_call(c, fuu) (c)->set_typed_list_callback = fuu + +/* connection */ +int connection_initiate (conn_t *co, const char *host, int port, + const char *SSL_cert, perm_ctx_t *pctx); + +int connection_create(conn_t *co, int sck); + +int connection_close(conn_t *co); + +int connection_reinit(conn_t *co); + +/* channels */ +int channel_open(conn_t *co, chnl_t **ch, int type); + +int channel_close(conn_t *co); + +/* message passing */ +int msg_send(chnl_t *ch, sexp_t *sx, sxmsg_t **msg); + +int msg_send_timed(chnl_t *ch, sexp_t *sx, sxmsg_t **msg, struct timespec *tio); + +int msg_return(sxmsg_t *msg, int opcode); + +int msg_reply(sxmsg_t *msg, sexp_t *sx); + +int msg_reply_timed(sxmsg_t *msg, sexp_t *sx, struct timespec *tio); + +int msg_send_pulse(chnl_t *ch, sexp_t *sx); + +int msg_send_pulse_timed(chnl_t *ch, sexp_t *sx, struct timespec *tio); + +int msg_send_pulse_nowait(chnl_t *ch, sexp_t *sx); + +#endif /* __ESXC_CONNECTION_H_ */ + diff --git a/include/sntl/pth_queue.h b/include/sntl/pth_queue.h new file mode 100644 index 0000000..d29e7b3 --- /dev/null +++ b/include/sntl/pth_queue.h @@ -0,0 +1,57 @@ +/* + * This is a proprietary software. See COPYING for further details. + * + * (c) 2013 Copyright Askele, inc. + * (c) 2013 Copyright Askele Ingria, inc. + * (c) 2014 Copyright Confident, inc. (granted permission to use in commercial software) + */ + +/** + * @file pth_queue.h + * @author Alexander Vdolainen + * @date 4 Nov 2013 + * @brief queue implementation for threads intercommunication + * + */ + +#ifndef __PTH_QUEUE_H__ +#define __PTH_QUEUE_H__ + +#include + +#define SYS_MSG 0x0f0affee +#define USR_MSG 0x0afeeffe +#define NIL_MSG 0x0 + +typedef struct pth_msg_s { + void *data; /** < message payload */ + unsigned int msgtype; /** < message type ID */ + unsigned int qlength; /** < current queue length (actual on add moment), + * it makes no sense with few readers */ + usrtc_node_t node; +} pth_msg_t; + +typedef struct pth_queue_s { + unsigned int length; + /* sync */ + pthread_mutex_t mutex; + pthread_cond_t cond; + /* queue data */ + usrtc_t qtree; + /* cache */ + usrtc_t msgcache; +} pth_queue_t; + +int pth_queue_init(pth_queue_t *queue); + +int pth_queue_add(pth_queue_t *queue, void *data, unsigned int msgtype); + +int pth_queue_get(pth_queue_t *queue, const struct timespec *timeout, + pth_msg_t *msg); + +unsigned int pth_queue_length(pth_queue_t *queue); + +int pth_queue_destroy(pth_queue_t *queue, int freedata, + void (*free_msg)(void *)); + +#endif /* __PTH_QUEUE_H__ */ diff --git a/lib/Makefile.am b/lib/Makefile.am new file mode 100644 index 0000000..d68bba8 --- /dev/null +++ b/lib/Makefile.am @@ -0,0 +1,28 @@ +## Process this file with automake to produce Makefile.in + +AM_CPPFLAGS = \ + -DPACKAGE_LOCALE_DIR=\""$(localedir)"\" \ + -DPACKAGE_SRC_DIR=\""$(srcdir)"\" \ + -DPACKAGE_DATA_DIR=\""$(pkgdatadir)"\" \ + $(LIBSNTL_CFLAGS) -I../include + +AM_CFLAGS =\ + -Wall\ + -g + +lib_LTLIBRARIES = libsntl.la + + +libsntl_la_SOURCES = \ + queue.c connection.c + +libsntl_la_LDFLAGS = + +libsntl_la_LIBADD = + +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = libsntl-0.1.pc + +EXTRA_DIST = \ + libsntl-1.2.pc.in + diff --git a/lib/connection.c b/lib/connection.c new file mode 100644 index 0000000..92f2aef --- /dev/null +++ b/lib/connection.c @@ -0,0 +1,1507 @@ +/* + * zMaster daemon: a server for a zOffice verification. + * This is a proprietary software. See COPYING for further details. + * + * (c) 2013-2014 Copyright Askele, inc. + * (c) 2013-2014 Copyright Askele Ingria, inc. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include + +conn_sys_t *conn_sys = NULL; + +static long __cmp_ulong(const void *a, const void *b); + +int __alloc_channel(ulong_t cid, conn_t *co, rpc_typed_list_t *rlist, chnl_t **channel) +{ + int r = 0; + chnl_t *ch = malloc(sizeof(chnl_t)); + usrtc_t *msg_tree = malloc(sizeof(usrtc_t)); + idx_allocator_t *idx_msg = malloc(sizeof(idx_allocator_t)); + + if(!idx_msg) goto __fin_enomem; + else if(idx_allocator_init(idx_msg, MAX_MSGINDEX, 0)) goto __fin_enomem; + + if(!ch || !msg_tree) { + __fin_enomem: + r = ENOMEM; + goto __fin_up; + } else { + usrtc_init(msg_tree, USRTC_REDBLACK, MAX_PENDINGMSG, __cmp_ulong); + ch->cid = cid; + ch->flags = ch->use_count = 0; + usrtc_node_init(&ch->node, ch); + if(rlist) ch->rpc_list = rlist->rpc_list; + /* init locks */ + if(pthread_rwlock_init(&(ch->msglock), NULL)) { + r = ENOMEM; + goto __fin_up; + } + if(pthread_mutex_init(&(ch->oplock), NULL)) { + pthread_rwlock_destroy(&(ch->msglock)); + r = ENOMEM; + goto __fin_up; + } + /* assign all the stuff */ + ch->idx_msg = idx_msg; + ch->msgs_tree = msg_tree; + ch->connection = co; + } + + __fin_up: + if(r) { + if(idx_msg) free(idx_msg); + if(ch) free(ch); + if(msg_tree) free(msg_tree); + return ENOMEM; + } else { + *channel = ch; + return 0; + } +} + +static int __conn_read(conn_t *co, void *buf, size_t buf_len) +{ + int rfd = SSL_get_fd(co->ssl), r; + fd_set readset; + printf("__conn_read\n"); + + /* get prepare to select */ + FD_ZERO(&readset); + FD_SET(rfd, &readset); + + /* waits until something will be ready to read */ + r = select(FD_SETSIZE, &readset, NULL, NULL, NULL); + if(r < 0) { + printf("select (%d)\n", errno); + return -1; + } + if(!r) { + printf("Nothing to wait for\n"); + return 0; + } + + if(r && FD_ISSET(rfd, &readset)) { + do { + /* ok, now we're ready to perform SSL_read */ + r = SSL_read(co->ssl, buf, (int)buf_len); + + switch(SSL_get_error(co->ssl, r)) { + case SSL_ERROR_NONE: + printf("Read done (f:%d)\n", rfd); + /* this is means we're get ridden it all */ + return r; break; + case SSL_ERROR_ZERO_RETURN: + printf("No data to read\n"); + /* no data to read ... */ + return 0; break; + case SSL_ERROR_WANT_READ: + case SSL_ERROR_WANT_WRITE: + printf("Bypass until SSL buffer not ready.\n"); + return 0; + default: /* seems the connection lost */ + printf("Unknown error!\n"); + return -1; + } + } while(SSL_pending(co->ssl)); + } + + return 0; +} + +static int __conn_write(conn_t *co, void *buf, size_t buf_len) +{ + return 0; +} + +static long __cmp_cstr(const void *a, const void *b) +{ + return strcmp((char *)a, (char *)b); +} + +static long __cmp_int(const void *a, const void *b) +{ + return *(int *)a - *(int *)b; +} + +static long __cmp_ulong(const void *a, const void *b) +{ + printf("(??cmp_ulong)a = %ld b = %ld\n", *(ulong_t *)a , *(ulong_t *)b); + return *(ulong_t *)a - *(ulong_t *)b; +} + +static int __resolvehost(const char *hostname, char *buf, int buf_len, + struct hostent **rhp) +{ + struct hostent *hostbuf = malloc(sizeof(struct hostent)); + struct hostent *hp = *rhp = NULL; + int herr = 0, hres = 0; + + if(!hostbuf) return NO_ADDRESS; + + hres = gethostbyname_r(hostname, hostbuf, + buf, buf_len, &hp, &herr); + + if (!hp) return NO_ADDRESS; + + *rhp = hp; + + return NETDB_SUCCESS; +} + +static void __destroy_rpc_list_tree(usrtc_t *tree) +{ + usrtc_node_t *node; + cx_rpc_t *ent; + + for(node = usrtc_first(tree); node != NULL; node = usrtc_first(tree)) { + ent = (cx_rpc_t *)usrtc_node_getdata(node); + usrtc_delete(tree, node); + free(ent->name); + free(ent); + } + + return; +} + +static int __insert_rpc_function(usrtc_t *tree, const char *name, int (*rpcf)(void *, sexp_t *)) +{ + cx_rpc_t *ent = malloc(sizeof(cx_rpc_t)); + usrtc_node_t *node; + + if(!ent) return ENOMEM; + else node = &ent->node; + + if(!(ent->name = strdup(name))) { + free(ent); + return ENOMEM; + } else ent->rpcf = rpcf; + + usrtc_node_init(node, ent); + usrtc_insert(tree, node, ent->name); + + return 0; +} + +static int __default_auth_set_context(void *cctx, sexp_t *sx) +{ + conn_t *co = (conn_t *)cctx; + char *val, *var, *tbuf; + sexp_t *lsx, *sx_iter, *sx_in; + int llen, idx, err; + + //co->pctx = malloc(sizeof(perm_ctx_t)); + + /* skip keyword itself */ + lsx = sx->list->next; + /* now we expect a list of lists */ + if(lsx->ty != SEXP_LIST) { + /* TODO: return error code ! via rpc */ + return EINVAL; + } + /* take length of the list */ + llen = sexp_list_length(lsx); + if(!llen) return 0; /* other side will not set any security attributes */ + SEXP_ITERATE_LIST(lsx, sx_iter, idx) { + if(SEXP_IS_LIST(sx_iter)) { + sexp_list_car(sx_iter, &sx_in); + + if(!SEXP_IS_TYPE(sx_in, SEXP_BASIC)) { + return EINVAL; /* TODO: return correct error code, clean up*/ + } else val = sx_in->val; + + if(sexp_list_length(sx_iter) < 2) continue; /* we will ignore it */ + + sexp_list_cdr(sx_iter, &sx_in); + if(!SEXP_IS_TYPE(sx_in, SEXP_DQUOTE)) { + return EINVAL; /* TODO: return correct error code, clean up*/ + } else var = sx_in->val; + + /* ok, now we need to analyze parameters */ + if(!strcmp(val, ":user")) { + co->pctx->login = strdup(var); /* FIXME: check */ + } else if(!strcmp(val, ":passwd")) { + co->pctx->passwd = strdup(var); /* FIXME: check */ + } else { + /* just ignore in default implementation */ + } + } else continue; /* ignore */ + } + + /* ok, now we need to fill security context */ + tbuf = malloc(2048); + if(conn_sys->secure_check) + err = conn_sys->secure_check(co); + else { /* FIXME: remove this ! */ + /* just for tests */ + err = 0; + co->pctx->p_attr = 256; co->pctx->uid = 12; co->pctx->gid = 34; + /* end tests */ + } + if(err) { + snprintf(tbuf, 2048, "(auth-set-error (%d))", err); + } else { + snprintf(tbuf, 2048, "(auth-set-attr (:attr %d)(:uid %ld)(:gid %ld))", + co->pctx->p_attr, co->pctx->uid, co->pctx->gid); + } + /* we will send it */ + SSL_write(co->ssl, tbuf, strlen(tbuf)+1); /* FIXME: check it */ + + free(tbuf); + return err; +} + +static int __default_auth_set_attr(void *cctx, sexp_t *sx) +{ + conn_t *co = (conn_t *)cctx; + char *val, *var; + sexp_t *lsx, *sx_iter, *sx_in; + int llen, idx; + + /* skip keyword itself */ + lsx = sx->list->next; + /* now we expect a list of lists */ + if(lsx->ty != SEXP_LIST) { + printf("%s:%d\n", __FUNCTION__, __LINE__); + return EINVAL; + } + /* take length of the list */ + llen = sexp_list_length(lsx); + if(!llen) return 0; /* other side will not set any security attributes */ + SEXP_ITERATE_LIST(lsx, sx_iter, idx) { + if(SEXP_IS_LIST(sx_iter)) { + sexp_list_car(sx_iter, &sx_in); + + if(!SEXP_IS_TYPE(sx_in, SEXP_BASIC)) { + return EINVAL; /* TODO: return correct error code, clean up*/ + } else val = sx_in->val; + + if(sexp_list_length(sx_iter) < 2) continue; /* we will ignore it */ + + sexp_list_cdr(sx_iter, &sx_in); + + if(!SEXP_IS_TYPE(sx_in, SEXP_BASIC)) { + return EINVAL; /* TODO: return correct error code, clean up*/ + } else var = sx_in->val; + + /* ok, now we need to analyze parameters */ + if(!strcmp(val, ":attr")) { + co->pctx->p_attr = atoi(var); + } else if(!strcmp(val, ":uid")) { + co->pctx->uid = (ulong_t)atoll(var); + } else if(!strcmp(val, ":gid")) { + co->pctx->gid = (ulong_t)atoll(var); + } else { + /* just ignore in default implementation */ + } + } else continue; /* ignore */ + } + + return 0; +} + +static int __default_auth_set_error(void *cctx, sexp_t *sx) +{ + char *errstr = NULL; + int r; + + /* skip keyword itself */ + sx->list = sx->list->next; + /* be sure - this is a list */ + if(sx->ty != SEXP_LIST) return EINVAL; + else sx = sx->list; /* get it */ + errstr = sx->list->val; + r = atoi(errstr); + + return r; +} + +static int __default_ch_get_types(void *cctx, sexp_t *sx) +{ + conn_t *co = (conn_t *)cctx; + usrtc_node_t *node; + rpc_typed_list_t *list_ent; + char *tbuf = malloc(4096), *tt; + int err = 0; + + /* if we cannot allocate anything ... */ + if(!tbuf) return ENOMEM; + /* ok here we go */ + co->rpc_list = conn_sys->get_rpc_typed_list_tree(co); + /* ok, here we're don't need to parse anything */ + if(!usrtc_count(co->rpc_list)) { + err = ENXIO; + snprintf(tbuf, 4096, "(ch-gl-error (%d))", err); + } else { + tt = tbuf; + snprintf(tt, 4096, "(ch-set-types ("); + tt += strlen(tt); + for(node = usrtc_first(co->rpc_list); node != NULL; + node = usrtc_next(co->rpc_list, node), tt += strlen(tt)) { + list_ent = (rpc_typed_list_t *)usrtc_node_getdata(node); + snprintf(tt, 4096, "(:%d \"%s\")", list_ent->type_id, list_ent->description); + } + snprintf(tt, 4096, "))"); + } + + /* reply to this rpc */ + SSL_write(co->ssl, tbuf, strlen(tbuf)+sizeof(char)); /* FIXME: do checks */ + + free(tbuf); + + return err; +} + +static int __default_ch_set_types(void *cctx, sexp_t *sx) +{ + conn_t *co = (conn_t *)cctx; + printf("setting types\n"); + char buf[1024], *val, *var; + int r = 0, llen, typeid, idx; + sexp_t *lsx, *sx_iter, *sx_in; + + /* skip keyword itself */ + lsx = sx->list->next; + /* now we expect a list of lists */ + if(lsx->ty != SEXP_LIST) { + printf("%s:%d\n", __FUNCTION__, __LINE__); + return EINVAL; + } + /* take length of the list */ + llen = sexp_list_length(lsx); + if(!llen) return 0; /* other side will not set any security attributes */ + SEXP_ITERATE_LIST(lsx, sx_iter, idx) { + if(SEXP_IS_LIST(sx_iter)) { + sexp_list_car(sx_iter, &sx_in); + + if(!SEXP_IS_TYPE(sx_in, SEXP_BASIC)) { + return EINVAL; /* TODO: return correct error code, clean up*/ + } else val = sx_in->val; + + if(sexp_list_length(sx_iter) < 2) continue; /* we will ignore it */ + + sexp_list_cdr(sx_iter, &sx_in); + + if(!SEXP_IS_TYPE(sx_in, SEXP_DQUOTE)) { + return EINVAL; /* TODO: return correct error code, clean up*/ + } else var = sx_in->val; + + /* ok, now we need to analyze parameters */ + if(*val != ':') { + return EINVAL; /* TODO: clean up all the shit */ + } else { + if(conn_sys->set_typed_list_callback) { + typeid = atoi((char *)(val + sizeof(char))); + if(conn_sys->set_typed_list_callback(co, typeid, var)) { + return ENXIO; /* TODO: clean up all the stuff */ + } + } /* FIXME: if no function, accept or decline ? */ + } + } else continue; /* ignore */ + } + + snprintf(buf, 1024, "(ch-gl-error (%d))", r); + SSL_write(co->ssl, buf, strlen(buf) + 1); + + return r; +} + +static int __default_ch_gl_error(void *cctx, sexp_t *sx) +{ + int r; + char *errstr; + conn_t *co = (conn_t *)cctx; + + if(co->flags & CXCONN_ESTABL) return EINVAL; /* error, we're already have channels list */ + + /* skip keyword itself */ + sx->list = sx->list->next; + /* be sure - this is a list */ + if(sx->ty != SEXP_LIST) return EINVAL; + else sx = sx->list; /* get it */ + errstr = sx->list->val; + r = atoi(errstr); + + if(!r) co->flags |= CXCONN_ESTABL; + + return r; +} + +static int __default_ch_open(void *cctx, sexp_t *sx) +{ + conn_t *co = (conn_t *)cctx; + usrtc_node_t *node; + char *val, *var, *uuid = NULL, *buf; + int typ = -1, idx, llen, r; + ulong_t cid; + sexp_t *lsx, *sx_iter, *sx_in; + rpc_typed_list_t *rlist; + chnl_t *channel; + + /* skip keyword itself */ + lsx = sx->list->next; + /* now we expect a list of lists */ + if(lsx->ty != SEXP_LIST) { + printf("%s:%d\n", __FUNCTION__, __LINE__); + r = EINVAL; + goto __send_repl; + } + + /* take length of the list */ + llen = sexp_list_length(lsx); + if(!llen) return 0; /* other side will not set any security attributes */ + SEXP_ITERATE_LIST(lsx, sx_iter, idx) { + if(SEXP_IS_LIST(sx_iter)) { + sexp_list_car(sx_iter, &sx_in); + + if(!SEXP_IS_TYPE(sx_in, SEXP_BASIC)) { + printf("%s:%d\n", __FUNCTION__, __LINE__); + r = EINVAL; /* TODO: return correct error code, clean up*/ + goto __send_repl; + } else val = sx_in->val; + + if(sexp_list_length(sx_iter) < 2) continue; /* we will ignore it */ + + sexp_list_cdr(sx_iter, &sx_in); + + if(!SEXP_IS_TYPE(sx_in, SEXP_BASIC)) { + r = EINVAL; /* TODO: return correct error code, clean up*/ + printf("%s:%d\n", __FUNCTION__, __LINE__); + goto __send_repl; + } else var = sx_in->val; + + /* ok, now we need to analyze parameters */ + if(*val != ':') { + r = EINVAL; /* TODO: clean up all the shit */ + goto __send_repl; + } else { + if(!strcmp((char *)(val + sizeof(char)), "type")) + typ = atoi(var); + else if(!strcmp((char *)(val + sizeof(char)), "id")) + cid = atoll(var); + else if(!strcmp((char *)(val + sizeof(char)), "uuid")) + uuid = var; + } + } else continue; /* ignore */ + } + + /* additional check for type of the channel */ + node = usrtc_lookup(co->rpc_list, &typ); + if(!node) { + r = EINVAL; /* FIXME: should be ESXNOCHANSUP */ + /* printf("%s:%d (usrtc count: %d) (typ %d)\n", __FUNCTION__, __LINE__, + usrtc_count(co->rpc_list), typ);*/ + node = usrtc_first(co->rpc_list); + rlist = (rpc_typed_list_t *)usrtc_node_getdata(node); + printf("---- rlist->type_id = %d\n", rlist->type_id); + goto __send_repl; + } else rlist = (rpc_typed_list_t *)usrtc_node_getdata(node); + + /* now we need to check up the channel */ + pthread_mutex_lock(&(co->oplock)); + node = usrtc_lookup(co->chnl_tree, &cid); + if(node) { + pthread_mutex_unlock(&(co->oplock)); + r = EEXIST; + goto __send_repl; + } else { + idx_reserve(co->idx_ch, cid); + pthread_mutex_unlock(&(co->oplock)); /* now we should alloc channel */ + if((r = __alloc_channel(cid, co, rlist, &channel))) { + pthread_mutex_lock(&(co->oplock)); + idx_free(co->idx_ch, cid); + pthread_mutex_unlock(&(co->oplock)); + goto __send_repl; + } else { + /* now we ready to confirm channel creation */ + pthread_rwlock_wrlock(&(co->chnl_lock)); + usrtc_insert(co->chnl_tree, &(channel->node), &(channel->cid)); + pthread_rwlock_unlock(&(co->chnl_lock)); + r = 0; + } + } + + __send_repl: + buf = malloc(2048); + snprintf(buf, 2048, "(ch-open-ret ((:error %d)(:uuid %s)(:id %ld)))", r, + uuid, cid); + SSL_write(co->ssl, buf, strlen(buf)); + free(buf); + + return r; +} + +static int __default_ch_open_ret(void *cctx, sexp_t *sx) +{ + conn_t *co = (conn_t *)cctx; + chnl_t *chan; + usrtc_node_t *node; + int err = 0, r, llen, idx; + ulong_t id; + char *uuid = NULL, *val, *var; + sexp_t *lsx, *sx_iter, *sx_in; + sxmsg_t *sms = NULL; + + /* skip keyword itself */ + lsx = sx->list->next; + /* now we expect a list of lists */ + if(lsx->ty != SEXP_LIST) { + printf("%s:%d\n", __FUNCTION__, __LINE__); + r = EINVAL; /* TODO: right opcode */ + goto __mark_msg; + } + /* take length of the list */ + llen = sexp_list_length(lsx); + if(!llen) return EINVAL; /* TODO: !! other side will not set any security attributes */ + SEXP_ITERATE_LIST(lsx, sx_iter, idx) { + if(SEXP_IS_LIST(sx_iter)) { + sexp_list_car(sx_iter, &sx_in); + + if(!SEXP_IS_TYPE(sx_in, SEXP_BASIC)) { + r = EINVAL; /* TODO: return correct error code, clean up*/ + goto __mark_msg; + } else val = sx_in->val; + + if(sexp_list_length(sx_iter) < 2) continue; /* we will ignore it */ + + sexp_list_cdr(sx_iter, &sx_in); + + if(!SEXP_IS_TYPE(sx_in, SEXP_BASIC)) { + r = EINVAL; /* TODO: return correct error code, clean up*/ + goto __mark_msg; + } else var = sx_in->val; + + /* ok, now we need to analyze parameters */ + if(*val != ':') { + r = EINVAL; /* TODO: clean up all the shit */ + goto __mark_msg; + } else { + if(!strcmp((char *)(val + sizeof(char)), "error")) + err = atoi(var); + else if(!strcmp((char *)(val + sizeof(char)), "id")) + id = atoll(var); + else if(!strcmp((char *)(val + sizeof(char)), "uuid")) + uuid = var; + } + } else continue; /* ignore */ + } + + /* try to find desired channel to intercept message */ + pthread_rwlock_rdlock(&(co->chnl_lock)); + node = usrtc_lookup(co->chnl_tree, (void *)&id); + //printf("channels (%d)\n", usrtc_count(co->chnl_tree)); + pthread_rwlock_unlock(&(co->chnl_lock)); + if(node) { + printf("found channel!\n"); + chan = (chnl_t *)usrtc_node_getdata(node); + sms = chan->sysmsg; + } + + __mark_msg: + if(!sms) return r; + sms->flags &= ~ESXMSG_PENDING; /* the message is done */ + sms->opcode = err; + + /* unlock mutex to wake up the waiting thread */ + pthread_mutex_unlock(&(sms->wait)); + + return 0; +} + +static int __default_ch_close(void *cctx, sexp_t *sx) +{ + return 0; +} + +static int __default_msg_pulse(void *cctx, sexp_t *sx) +{ + return 0; +} + +static int __default_msg_pulse_ret(void *cctx, sexp_t *sx) +{ + return 0; +} + +static int __default_msg(void *cctx, sexp_t *sx) +{ + return 0; +} + +static int __default_msg_return(void *cctx, sexp_t *sx) +{ + return 0; +} + +static int __default_msg_reply(void *cctx, sexp_t *sx) +{ + return 0; +} + +static int __init_systemrpc_tree(usrtc_t *rtree) +{ + /* security context functions */ + if(__insert_rpc_function(rtree, "auth-set-context", __default_auth_set_context)) goto __fail; + if(__insert_rpc_function(rtree, "auth-set-attr", __default_auth_set_attr)) goto __fail; + if(__insert_rpc_function(rtree, "auth-set-error", __default_auth_set_error)) goto __fail; + /* channels negotiation ops */ + if(__insert_rpc_function(rtree, "ch-get-types", __default_ch_get_types)) goto __fail; + if(__insert_rpc_function(rtree, "ch-gl-error", __default_ch_gl_error)) goto __fail; + if(__insert_rpc_function(rtree, "ch-set-types", __default_ch_set_types)) goto __fail; + if(__insert_rpc_function(rtree, "ch-open", __default_ch_open)) goto __fail; + if(__insert_rpc_function(rtree, "ch-open-ret", __default_ch_open_ret)) goto __fail; + if(__insert_rpc_function(rtree, "ch-close", __default_ch_close)) goto __fail; + /* messaging functions */ + if(__insert_rpc_function(rtree, "ch-msg-pulse", __default_msg_pulse)) goto __fail; + if(__insert_rpc_function(rtree, "ch-msg-pulse-ret", __default_msg_pulse_ret)) goto __fail; + if(__insert_rpc_function(rtree, "ch-msg", __default_msg)) goto __fail; + if(__insert_rpc_function(rtree, "ch-msg-rete", __default_msg_return)) goto __fail; + if(__insert_rpc_function(rtree, "ch-msg-repl", __default_msg_reply)) goto __fail; + + return 0; + + __fail: + __destroy_rpc_list_tree(rtree); + return ENOMEM; +} + +static int __eval_cstr(char *cstr, cx_rpc_list_t *rpc_list, void *ctx) +{ + int r = ENOENT; + sexp_t *sx; + usrtc_node_t *node; + cx_rpc_t *rentry; + char *rpcf; + + if(!(sx = parse_sexp(cstr, strlen(cstr)))) return EBADE; + if(sx->ty == SEXP_LIST) + rpcf = sx->list->val; + else rpcf = sx->val; + + /* find an appropriate function */ + printf("rpcf = %s\n", rpcf); + node = usrtc_lookup(rpc_list->rpc_tree, rpcf); + if(!node) return ENOENT; + else rentry = (cx_rpc_t *)usrtc_node_getdata(node); + /* call it */ + printf("rentry->rpcf = %p\n", rentry->rpcf); + r = rentry->rpcf(ctx, sx); + /* free s-expression */ + destroy_sexp(sx); + + return r; +} + +static void *__cxslave_thread_listener(void *wctx) +{ + conn_t *co = (conn_t *)wctx; + char *buf = malloc(4096); + int r; + + printf("Slave listening thread\n"); + + while((r = __conn_read(co, buf, 4096)) != -1) { + if(r) printf("Got the message %s \n", buf); + r = __eval_cstr(buf, conn_sys->system_rpc, co); + } + + free(buf); + + return NULL; +} + +static void *__cxmaster_thread_listener(void *wctx) +{ + conn_t *co = (conn_t *)wctx; + char *buf = malloc(4096); + int r; + + printf("Master listening thread\n"); + + while((r = __conn_read(co, buf, 4096)) != -1) { + if(r) printf("Got the message %s \n", buf); + r = __eval_cstr(buf, conn_sys->system_rpc, co); + } + + free(buf); + + return NULL; +} + +/* this function is an ugly implementation to get C string with uuid */ +static char *__generate_uuid(void) +{ + char *uuidc = NULL; + uuid_t uuid; + int len, i = 0; + + len = sizeof(char)*(sizeof(uuid_t)*2) + sizeof(char); + if(!(uuidc = malloc(len))) return NULL; + + uuid_generate_time_safe(uuid); + + for(i = 0; i < sizeof(uuid_t); i++) + snprintf(uuidc+(2*i*sizeof(char)), len, "%02x", uuid[i]); + + return uuidc; +} + +/* this is a callback to perform a custom SSL certs chain validation, + * as I promised here the comments, a lot of ... + * The first shit: 0 means validation failed, 1 otherwise + * The second shit: X509 API, I guess u will love it ;-) + * openssl calls this function for each certificate in chain, + * since our case is a simple (depth of chain is one, since we're + * don't care for public certificates lists or I cannot find any reasons to + * do it ...), amount of calls reduced, and in this case we're interested + * only in top of chain i.e. actual certificate used on client side, + * the validity of signing for other certificates within chain is + * guaranteed by the ssl itself. + * u know, we need to lookup in database, or elsewhere... some information + * about client certificate, and decide - is it valid, or not?, if so + * yep I mean it's valid, we can assign it's long fucking number to + * security context, to use in ongoing full scaled connection handshaking. + */ +static int __verify_certcall(int preverify_ok, X509_STORE_CTX *ctx) +{ + X509 *cert = X509_STORE_CTX_get_current_cert(ctx); + int err = X509_STORE_CTX_get_error(ctx), depth = X509_STORE_CTX_get_error_depth(ctx); + SSL *ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); + conn_t *co = SSL_get_ex_data(ssl, conn_sys->ex_ssldata_index); /* this is a custom data we're set before */ + + /* now we need to check for certificates with a long chain, + * so since we have a short one, reject long ones */ + if(depth > VERIFY_DEPTH) { /* longer than we expect */ + preverify_ok = 0; /* yep, 0 means error for those function callback in openssl, fucking set */ + err = X509_V_ERR_CERT_CHAIN_TOO_LONG; + X509_STORE_CTX_set_error(ctx, err); + } + + /* ok, now we're on top of SSL (depth == 0) certs chain, + * and we can validate client certificate */ + if(!depth) { + /* TODO: check serial number and other stuff */ + co->pctx = malloc(sizeof(perm_ctx_t)); + co->pctx->certid = + ASN1_INTEGER_get((const ASN1_INTEGER *)X509_get_serialNumber(ctx->current_cert)); + printf("Certificate ID: %lu\n", co->pctx->certid); + /* now we're need to check the ssl cert */ + if(conn_sys->validate_sslpem) { + if(conn_sys->validate_sslpem(co)) return 0; + else return 1; + } else return 1; /* FIXME: return 0 instead of 1 in production */ + } + + return preverify_ok; +} + +/* subsystem: here u can told me about how it's ugly to use global pointers, + * yep, it's a business of fucking morons, btw it works (heh, openssl uses this + * ancient shit method too, many many and many others too, trust me ...). + * subsystem required to define varios RPC lists, control list for connections, + * general queues, certificates (all connections uses the same set of certificates + * within application), general calls such as ... calls to get info about client + * cert and ... many other things. + */ + +void *__system_queue_listener(void *data) +{ + int r; + pth_msg_t *tmp = malloc(sizeof(pth_msg_t)); + sxmsg_t *sysmsg; + sxpayload_t *payload; + chnl_t *chan; + conn_t *co; + + if(!tmp) return NULL; + + while(1) { + r = pth_queue_get(conn_sys->ioqueue, NULL, tmp); + if(r) { + free(tmp); + return NULL; + } + + /* ok message is delivered */ + sysmsg = tmp->data; + if(!sysmsg) continue; /* ignore dummy messages */ + + if(!(sysmsg->flags & ESXMSG_SYS)) { /* not a system message */ + sysmsg->flags |= ESXMSG_NOWAY; /* mark it's as undeliverable */ + sysmsg->flags &= ~ESXMSG_PENDING; + pthread_mutex_unlock(&(sysmsg->wait)); /* wake up the waitee */ + continue; + } else { + chan = sysmsg->pch; + co = chan->connection; + payload = (sxpayload_t *)sysmsg->payload; + /* lock the connection for ops */ + pthread_mutex_lock(&(co->oplock)); /* exclusive write */ + /* write the buf */ + SSL_write(co->ssl, (void *)payload->cstr, strlen(payload->cstr) + 1); /* TODO: SSL*/ + pthread_mutex_unlock(&(co->oplock)); + } + } + + return NULL; +} + +/* general initialization must be called within app uses connection layer */ +int connections_subsystem_init(void) +{ + int r = 0; + + if(!(conn_sys = malloc(sizeof(conn_sys_t)))) return ENOMEM; + else if(!(conn_sys->connections = malloc(sizeof(usrtc_t)))) { + r = ENOMEM; + goto __fail; + } + + /* zeroing */ + conn_sys->rootca = conn_sys->certkey = conn_sys->certpem = NULL; + conn_sys->validate_sslpem = NULL; + conn_sys->secure_check = NULL; + /* init connections list */ + usrtc_init(conn_sys->connections, USRTC_REDBLACK, MAX_CONNECTIONS, + __cmp_cstr); + if((r = pthread_rwlock_init(&(conn_sys->rwlock), NULL))) + goto __fail_1; + + /* init queues */ + if(!(conn_sys->ioq = malloc(sizeof(pth_queue_t)))) { /* general io queue */ + r = ENOMEM; + goto __fail_2; + } + if((r = pth_queue_init(conn_sys->ioq))) goto __fail_3; + if(!(conn_sys->ioqueue = malloc(sizeof(pth_queue_t)))) { /* system io queue */ + r = ENOMEM; + goto __fail_2; + } + if((r = pth_queue_init(conn_sys->ioqueue))) goto __fail_3_1; + + /* init SSL certificates checking functions */ + /* init RPC list related functions */ + if(!(conn_sys->system_rpc = malloc(sizeof(cx_rpc_list_t)))) { + r = ENOMEM; + goto __fail_3; + } else { + if(!(conn_sys->system_rpc->rpc_tree = malloc(sizeof(usrtc_t)))) { + r = ENOMEM; + __fail_rpc: + free(conn_sys->system_rpc); + goto __fail_3_1; + } + usrtc_init(conn_sys->system_rpc->rpc_tree, USRTC_SPLAY, 256, __cmp_cstr); + r = __init_systemrpc_tree(conn_sys->system_rpc->rpc_tree); + if(r) { + free(conn_sys->system_rpc->rpc_tree); + goto __fail_rpc; + } + } + + /* init SSL library */ + SSL_library_init(); + printf("here\n"); + + OpenSSL_add_all_algorithms(); + SSL_load_error_strings(); + + conn_sys->ex_ssldata_index = SSL_get_ex_new_index(0, "__ssldata index", NULL, NULL, NULL); + + /* create threads for queue */ + if((r = pthread_create(&conn_sys->ios_thread, NULL, __system_queue_listener, NULL))) { + goto __fail_rpc; + } + + return 0; + + __fail_3_1: + free(conn_sys->ioqueue); + __fail_3: + free(conn_sys->ioq); + __fail_2: + pthread_rwlock_destroy(&(conn_sys->rwlock)); + __fail_1: + free(conn_sys->connections); + __fail: + free(conn_sys); + + return r; +} + +/* load certificates */ +int connections_subsystem_setsslserts(const char *rootca, const char *certpem, + const char *certkey) +{ + int r = ENOMEM; + + if(!conn_sys) return EINVAL; + /* simply copying */ + if(!(conn_sys->rootca = strdup(rootca))) return ENOMEM; + if(!(conn_sys->certkey = strdup(certkey))) goto __fail; + if(!(conn_sys->certpem = strdup(certpem))) goto __fail; + + r = 0; + return 0; + __fail: + if(conn_sys->rootca) free(conn_sys->rootca); + if(conn_sys->certkey) free(conn_sys->certkey); + if(conn_sys->certpem) free(conn_sys->certpem); + + return r; +} + +int connections_subsystem_setrpclist_function(usrtc_t* (*get_rpc_typed_list_tree)(conn_t *)) +{ + conn_sys->get_rpc_typed_list_tree = get_rpc_typed_list_tree; + return 0; +} + +#define __TMPBUFLEN 2048 + +/* connection_initiate: perform a connection thru the socket to the + * host with master certificate, i.e. it's a slave one for client. + */ +int connection_initiate(conn_t *co, const char *host, int port, + const char *SSL_cert, perm_ctx_t *pctx) +{ + int r = 0, sd; + int bytes = 0; + char *uuid; + char *buf = NULL; + struct hostent *host_; + struct sockaddr_in addr; + usrtc_t *ch_tree, *rpc_tree; + idx_allocator_t *idx_ch = malloc(sizeof(idx_allocator_t)); + + if(!co) return EINVAL; + if(!host) return EINVAL; + if(!SSL_cert) return EINVAL; + if(!pctx) return EINVAL; + + memset(co, 0, sizeof(co)); + + if(!idx_ch) return ENOMEM; + else r = idx_allocator_init(idx_ch, MAX_CHANNELS*MAX_MULTI, 0); + if(r) return r; + + if(!(uuid = __generate_uuid())) return ENOMEM; + if(!(ch_tree = malloc(sizeof(usrtc_t)))) { + r = ENOMEM; + goto __fail; + } + if(!(rpc_tree = malloc(sizeof(usrtc_t)))) { + r = ENOMEM; + goto __fail_1; + } + if((r = pthread_mutex_init(&co->oplock, NULL))) goto __fail_2; + if((r = pthread_rwlock_init(&co->chnl_lock, NULL))) goto __fail_3; + + usrtc_init(rpc_tree, USRTC_REDBLACK, MAX_RPC_LIST, __cmp_int); + usrtc_init(ch_tree, USRTC_REDBLACK, MAX_CHANNELS, __cmp_ulong); + + co->idx_ch = idx_ch; + + /* init SSL certificates and context */ + co->ctx = SSL_CTX_new(SSLv3_client_method()); + if(!co->ctx) { ERR_print_errors_fp(stderr); + r = EINVAL; goto __fail_3; } + else SSL_CTX_set_verify_depth(co->ctx, 1); /* FIXME: use configuration */ + + /* load certificates */ + SSL_CTX_load_verify_locations(co->ctx, conn_sys->rootca, NULL); + /* set the local certificate from CertFile */ + if(SSL_CTX_use_certificate_file(co->ctx, SSL_cert, + SSL_FILETYPE_PEM)<=0) { + r = EINVAL; printf("%s:%d\n", __FUNCTION__, __LINE__); + goto __fail_3; + } + /* set the private key from KeyFile (may be the same as CertFile) */ + if(SSL_CTX_use_PrivateKey_file(co->ctx, SSL_cert, + SSL_FILETYPE_PEM)<=0) { + r = EINVAL; printf("%s:%d\n", __FUNCTION__, __LINE__); + goto __fail_3; + } + /* verify private key */ + if (!SSL_CTX_check_private_key(co->ctx)) { + r = EINVAL; + goto __fail_3; + } + + /* assign allocated memory */ + co->rpc_list = rpc_tree; + co->chnl_tree = ch_tree; + co->uuid = uuid; + + /* connect to the pointed server */ + /* resolve host */ + if(!(buf = malloc(__TMPBUFLEN))) { + r = ENOMEM; + goto __fail_3; + } + if(__resolvehost(host, buf, __TMPBUFLEN, &host_) != NETDB_SUCCESS) { + r = ENOENT; + free(buf); + goto __fail_3; + } + /* create a socket */ + sd = socket(PF_INET, SOCK_STREAM, 0); + bzero(&addr, sizeof(addr)); + /* try to connect it */ + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + //printf("addr.sin_addr.s_addr = %p, host_ = %p\n", &addr.sin_addr.s_addr, host_); + addr.sin_addr.s_addr = *(uint32_t*)(host_->h_addr); + free(host_); + if (connect(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0) { + close(sd); + free(buf); + r = ENOENT; /* couldn't connect to the desired host */ + goto __fail_3; + } + + /* now we will create an SSL connection */ + co->ssl = SSL_new(co->ctx); + SSL_set_fd(co->ssl, sd); /* attach connected socket */ + if(SSL_connect(co->ssl) == -1) { + r = EBADE; + free(buf); + /* shutdown connection */ + goto __fail_3; + } /* if success we're ready to use established SSL channel */ + /* auth and RPC contexts sync */ + co->pctx = pctx; + snprintf(buf, __TMPBUFLEN, "(auth-set-context ((:user \"%s\")(:passwd \"%s\")))", + pctx->login, pctx->passwd); + /* send an auth request */ + SSL_write(co->ssl, buf, strlen(buf) + sizeof(char)); + /* read the message reply */ + bytes = __conn_read(co, buf, __TMPBUFLEN); + buf[bytes] = 0; + /* perform an rpc call */ + r = __eval_cstr(buf, conn_sys->system_rpc, (void *)co); + if(!r) { /* all is fine security context is good */ + snprintf(buf, __TMPBUFLEN, "(ch-get-types)"); /* now we should receive possible channel types */ + SSL_write(co->ssl, buf, strlen(buf) + sizeof(char)); + /* read the message reply */ + bytes = __conn_read(co, buf, __TMPBUFLEN); + buf[bytes] = 0; + /* perform an rpc call */ + r = __eval_cstr(buf, conn_sys->system_rpc, (void *)co); + } + + free(buf); /* now we can free the temporary buffer */ + /* a listening thread creation (incoming messages) */ + printf("%s:%d r = %d\n", __FUNCTION__, __LINE__, r); + if(!r) { /* success let's start a listening thread */ + r = pthread_create(&co->cthread, NULL, __cxslave_thread_listener, (void *)co); + if(!r) { + /* add connection to the list */ + usrtc_node_init(&co->csnode, co); + co->flags = (CXCONN_SLAVE | CXCONN_ESTABL); /* set the right flags */ + pthread_rwlock_wrlock(&conn_sys->rwlock); + usrtc_insert(conn_sys->connections, &co->csnode, (void *)co->uuid); + pthread_rwlock_unlock(&conn_sys->rwlock); + return 0; + } + } + + __fail_3: + pthread_mutex_destroy(&co->oplock); + __fail_2: + free(rpc_tree); + __fail_1: + free(ch_tree); + __fail: + free(uuid); + return r; +} + +int connection_create(conn_t *co, int sck) +{ + int r = 0, sd; + int bytes = 0; + char *uuid; + char *buf = NULL; + usrtc_t *ch_tree, *rpc_tree; + idx_allocator_t *idx_ch = malloc(sizeof(idx_allocator_t)); + + if(!co) return EINVAL; + else memset(co, 0, sizeof(co)); + + if(!idx_ch) return ENOMEM; + else r = idx_allocator_init(idx_ch, MAX_CHANNELS*MAX_MULTI, 0); + if(r) return r; + + if(!(uuid = __generate_uuid())) return ENOMEM; + if(!(ch_tree = malloc(sizeof(usrtc_t)))) { + r = ENOMEM; + goto __fail; + } + if(!(rpc_tree = malloc(sizeof(usrtc_t)))) { + r = ENOMEM; + goto __fail_1; + } + if((r = pthread_mutex_init(&co->oplock, NULL))) goto __fail_2; + if((r = pthread_rwlock_init(&co->chnl_lock, NULL))) goto __fail_3; + + usrtc_init(rpc_tree, USRTC_REDBLACK, MAX_RPC_LIST, __cmp_int); + usrtc_init(ch_tree, USRTC_REDBLACK, MAX_CHANNELS, __cmp_ulong); + + co->idx_ch = idx_ch; + + /* init SSL certificates and context */ + co->ctx = SSL_CTX_new(SSLv3_server_method()); + if(!co->ctx) { r = EINVAL; printf("%s:%d\n", __FUNCTION__, __LINE__);goto __fail_3; } + else { + /* set verify context */ + SSL_CTX_set_verify(co->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, + __verify_certcall); + /* set verify depth */ + SSL_CTX_set_verify_depth(co->ctx, VERIFY_DEPTH); + } + + /* load certificates */ + SSL_CTX_load_verify_locations(co->ctx, conn_sys->rootca, NULL); + /* set the local certificate from CertFile */ + if(SSL_CTX_use_certificate_file(co->ctx, conn_sys->certpem, + SSL_FILETYPE_PEM)<=0) { + printf("certpem1 = %s\n", conn_sys->certpem); + ERR_print_errors_fp(stderr); + r = EINVAL; printf("%s:%d\n", __FUNCTION__, __LINE__); + goto __fail_3; + } + /* set the private key from KeyFile (may be the same as CertFile) */ + if(SSL_CTX_use_PrivateKey_file(co->ctx, conn_sys->certkey, + SSL_FILETYPE_PEM)<=0) { + r = EINVAL; printf("%s:%d\n", __FUNCTION__, __LINE__); + goto __fail_3; + } + /* verify private key */ + if (!SSL_CTX_check_private_key(co->ctx)) { + r = EINVAL; printf("%s:%d\n", __FUNCTION__, __LINE__); + goto __fail_3; + } + + /* assign allocated memory */ + co->rpc_list = rpc_tree; + co->chnl_tree = ch_tree; + co->uuid = uuid; + + if(!(buf = malloc(__TMPBUFLEN))) { + r = ENOMEM; + goto __fail_3; + } + + /* now we will create an SSL connection */ + co->ssl = SSL_new(co->ctx); + SSL_set_fd(co->ssl, sck); /* attach connected socket */ + /* set the context to verify ssl connection */ + SSL_set_ex_data(co->ssl, conn_sys->ex_ssldata_index, (void *)co); + if(SSL_accept(co->ssl) == -1) { + r = EBADE; + free(buf); + /* shutdown connection */ + goto __fail_3; + } /* if success we're ready to use established SSL channel */ + printf("%s:%d\n", __FUNCTION__, __LINE__); + BIO_set_nbio(SSL_get_rbio(co->ssl), 1); + /*******************************************/ + /*-=Protocol part of connection establish=-*/ + /*******************************************/ + while(!(co->flags & CXCONN_ESTABL)) { /* read the initiation stage connections */ + bytes = __conn_read(co, buf, __TMPBUFLEN); + if(bytes > 0) { + buf[bytes] = 0; + r = __eval_cstr(buf, conn_sys->system_rpc, (void *)co); + printf("%s return %d (bytes %d)\n", buf, r, bytes); + if(r) goto __fail_3; + } else { + printf("bytes = %d\n", bytes); + if(bytes < 0) { + printf("Terminate SSL connection, the other end is lost.\n"); + goto __fail_3; + } + } + } + + /* before it will be done assign rpc list */ + if(conn_sys->get_rpc_typed_list_tree) + co->rpc_list = conn_sys->get_rpc_typed_list_tree(co); + + free(buf); + r = pthread_create(&co->cthread, NULL, __cxmaster_thread_listener, (void *)co); + if(!r) { + /* add connection to the list */ + usrtc_node_init(&co->csnode, co); + co->flags |= CXCONN_MASTER; /* set the right flags */ + pthread_rwlock_wrlock(&conn_sys->rwlock); + usrtc_insert(conn_sys->connections, &co->csnode, (void *)co->uuid); + pthread_rwlock_unlock(&conn_sys->rwlock); + } + + return r; + + __fail_3: + pthread_mutex_destroy(&co->oplock); + __fail_2: + free(rpc_tree); + __fail_1: + free(ch_tree); + __fail: + free(uuid); + return r; +} + +int connection_close(conn_t *co) +{ + return 0; +} + +int connection_reinit(conn_t *co) +{ + return 0; +} + +static sxmsg_t *__allocate_msg(int *res) +{ + sxmsg_t *msg = malloc(sizeof(sxmsg_t)); + int r = 0; + + if(!msg) { + *res = ENOMEM; + return NULL; + } else { + memset(msg, 0, sizeof(sxmsg_t)); + if((r = pthread_mutex_init(&(msg->wait), NULL))) { + free(msg); + *res = r; + return NULL; + } + + usrtc_node_init(&(msg->chnl_node), msg); + usrtc_node_init(&(msg->poll_node), msg); + usrtc_node_init(&(msg->pendingq_node), msg); + } + + *res = 0; + + return msg; +} + +static int __create_sys_msg(sxmsg_t **msg, char *uuid, chnl_t *ch, sxpayload_t *data) +{ + int r = 0; + sxmsg_t *m = __allocate_msg(&r); + + if(r) return r; + else { + /* fill values */ + m->pch = ch; + m->uuid = uuid; + m->payload = data; + /* set the right flags */ + m->flags = (ESXMSG_SYS | ESXMSG_PENDING); + /* we need to lock the wait mutex */ + pthread_mutex_lock(&(m->wait)); + + *msg = m; + } + + return 0; +} + +/* channels */ +int channel_open(conn_t *co, chnl_t **ch, int type) +{ + chnl_t *nch = NULL; + int r = 0; + char *uuid_ = __generate_uuid(); + sxpayload_t *pl = malloc(sizeof(sxpayload_t)); + ulong_t cid; + rpc_typed_list_t *rpclist; + usrtc_node_t *node = usrtc_lookup(co->rpc_list, &type); + sxmsg_t *sms; + /* + if(!node) { + r = EINVAL; printf("fuck\n"); + goto __fini_op; + } else rpclist = (rpc_typed_list_t *)usrtc_node_getdata(node); + */ + if(!uuid_) { + if(pl) free(pl); + return ENOMEM; + } + + if(!pl) { + __ffail: + if(uuid_) free(uuid_); + return ENOMEM; + } else { + pl->sx = NULL; + if(!(pl->cstr = malloc(sizeof(char)*ESX_SYSMSG_SIZE))) { + free(pl); goto __ffail; + } else memset(pl->cstr, 0, sizeof(char)*ESX_SYSMSG_SIZE); + } + + pthread_rwlock_wrlock(&(co->chnl_lock)); + cid = idx_allocate(co->idx_ch); + pthread_rwlock_unlock(&(co->chnl_lock)); + if(cid == IDX_INVAL) { + r = ENOMEM; + goto __fini_op; + } + + if((r = __alloc_channel(cid, co, rpclist, &nch))) { + goto __fini_op; + } else nch->flags |= ESXCHAN_PENDING; + + nch->uuid = uuid_; + + /* ok now we're ready to create a message and push channel to the list */ + if((r = __create_sys_msg(&sms, uuid_, nch, pl))) { + __fail_chan: + /* TODO: destroy the channel*/ + goto __fini_op; + } else { + /* put the channel to the channels search tree */ + pthread_rwlock_wrlock(&(co->chnl_lock)); + printf("inserting cid = %d\n", nch->cid); + usrtc_insert(co->chnl_tree, &nch->node, &nch->cid); + pthread_rwlock_unlock(&(co->chnl_lock)); + + /* put system message to the run queue */ + /* first form the message */ + snprintf(pl->cstr, sizeof(char)*ESX_SYSMSG_SIZE, + "(ch-open ((:id %ld)(:uuid %s)(:type %d)))", nch->cid, nch->uuid, type); + nch->sysmsg = sms; /* assign system message to the channel */ + /* put it */ + if((r = zst_queue_add(conn_sys->ioqueue, (void *)sms, SYS_MSG))) { + __fail_chan_r: + /* remove it from the search tree */ + pthread_rwlock_wrlock(&(co->chnl_lock)); + usrtc_delete(co->chnl_tree, &nch->node); + pthread_rwlock_unlock(&(co->chnl_lock)); + goto __fail_chan; + } + if(!(sms->flags & ESXMSG_PENDING)) { + /* was processed too fast */ + goto __process_smsg; + } else pthread_mutex_lock(&(sms->wait)); /* will sleep until got a reply */ + __process_smsg: + if(sms->opcode) { + r = sms->opcode; + goto __fail_chan_r; + } else r = 0; + nch->flags &= ~ESXCHAN_PENDING; /* mark it as established */ + /* TODO: destroy system message in the channel */ + } + + __fini_op: + if(r) { /* TODO: destroy */ + if(uuid_) free(uuid_); + if(pl) { + //if(pl->cstr) free(pl->cstr); + free(pl); + } + pthread_rwlock_wrlock(&(co->chnl_lock)); + //idx_free(co->idx_ch, cid); + pthread_rwlock_unlock(&(co->chnl_lock)); + } else *ch = nch; + + return r; +} + +int channel_close(conn_t *co) +{ + return 0; +} + +/* message passing */ +static int __message_send(chnl_t *ch, sexp_t *sx, sxmsg_t **msg, struct timespec *tio) +{ + int r = 0; + sxmsg_t *m = NULL; + + return r; +} + +int msg_send(chnl_t *ch, sexp_t *sx, sxmsg_t **msg) +{ + return __message_send(ch, sx, msg, NULL); +} + +int msg_send_timed(chnl_t *ch, sexp_t *sx, sxmsg_t **msg, struct timespec *tio) +{ + return __message_send(ch, sx, msg, tio); +} + +int msg_return(sxmsg_t *msg, int opcode) +{ + return 0; +} + +int msg_reply(sxmsg_t *msg, sexp_t *sx) +{ + return 0; +} + +int msg_reply_timed(sxmsg_t *msg, sexp_t *sx, struct timespec *tio) +{ + return 0; +} + +int msg_send_pulse(chnl_t *ch, sexp_t *sx) +{ + return 0; +} + +int msg_send_pulse_timed(chnl_t *ch, sexp_t *sx, struct timespec *tio) +{ + return 0; +} + +int msg_send_pulse_nowait(chnl_t *ch, sexp_t *sx) +{ + return 0; +} + +/* sexp helpers */ +int sexp_list_car(sexp_t *expr, sexp_t **sx) +{ + if (!SEXP_IS_LIST(expr) || expr->list->ty != SEXP_VALUE) return 1; + + *sx = expr->list; + + return 0; +} + +int sexp_list_cdr(sexp_t *expr, sexp_t **sx) +{ + /* Dummy function. Can we do cdr properly? */ + if (!SEXP_IS_LIST(expr) || expr->list->ty != SEXP_VALUE) return 1; + + if (!expr->list->next) *sx = NULL; + else *sx = expr->list->next; + + return 0; +} diff --git a/lib/libsntl-0.1.pc.in b/lib/libsntl-0.1.pc.in new file mode 100644 index 0000000..0a8fdac --- /dev/null +++ b/lib/libsntl-0.1.pc.in @@ -0,0 +1,13 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +datarootdir=@datarootdir@ +datadir=@datadir@ +includedir=@includedir@ + +Name: liblibsntl +Description: Secure Network Transport Layer library implementation +Version: @VERSION@ +Requires: +Libs: -L${libdir} -llibsntl +Cflags: -I${includedir} diff --git a/lib/queue.c b/lib/queue.c new file mode 100644 index 0000000..48bac31 --- /dev/null +++ b/lib/queue.c @@ -0,0 +1,213 @@ +/* + * This is a proprietary software. See COPYING for further details. + * + * (c) 2013 Copyright Askele, inc. + * (c) 2013 Copyright Askele Ingria, inc. + * (c) 2014 Copyright Confident, inc. (granted permission to use in commercial software) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#define MAX_QUEUE_SIZE 4096 +#define MAX_QUEUE_POOL 256 + +static long __cmp_uint(const void *a, const void *b) +{ + return (long)(*(unsigned int *)a - *(unsigned int *)b); +} + +static inline pth_msg_t *__get_newmsg(pth_queue_t *queue) +{ + usrtc_t *tree = &queue->msgcache; + usrtc_node_t *node; + pth_msg_t *tmp; + + if(usrtc_count(tree)) { + node = usrtc_first(tree); + tmp = (pth_msg_t *)usrtc_node_getdata(node); + usrtc_delete(tree, node); + } else { + tmp = malloc(sizeof(pth_msg_t)); + tree = &queue->qtree; + node = &tmp->node; + usrtc_node_init(node, tmp); + } + /* insert it */ + tree = &queue->qtree; + tmp->qlength = usrtc_count(tree); + usrtc_insert(tree, node, (void *)(&tmp->qlength)); + + return tmp; +} + +static inline void __release_msg(pth_queue_t *queue, pth_msg_t *msg) +{ + usrtc_node_t *node = &msg->node; + usrtc_t *tree = &queue->qtree; + + tree = &queue->qtree; /* remove from queue */ + usrtc_delete(tree, node); + + tree = &queue->msgcache; + + if(usrtc_count(tree) >= MAX_QUEUE_POOL) + free(msg); + else { + msg->data = NULL; + msg->msgtype = NIL_MSG; + usrtc_insert(tree, node, (void *)&msg->qlength); + } + + return; +} + +int pth_queue_init(pth_queue_t *queue) +{ + int r = 0; + + memset(queue, 0, sizeof(pth_queue_t)); + if((r = pthread_cond_init(&queue->cond, NULL))) + return r; + + if((r = pthread_mutex_init(&queue->mutex, NULL))) { + pthread_cond_destroy(&queue->cond); + return r; + } + + usrtc_init(&queue->qtree, USRTC_AVL, MAX_QUEUE_SIZE, __cmp_uint); + usrtc_init(&queue->msgcache, USRTC_AVL, MAX_QUEUE_POOL, __cmp_uint); + + return r; +} + +int pth_queue_add(pth_queue_t *queue, void *data, unsigned int msgtype) +{ + pth_msg_t *newmsg; + + pthread_mutex_lock(&queue->mutex); + newmsg = __get_newmsg(queue); + if (newmsg == NULL) { + pthread_mutex_unlock(&queue->mutex); + return ENOMEM; + } + + newmsg->data = data; + newmsg->msgtype = msgtype; + + if(queue->length == 0) + pthread_cond_broadcast(&queue->cond); + queue->length++; + pthread_mutex_unlock(&queue->mutex); + + return 0; +} + +int pth_queue_get(pth_queue_t *queue, const struct timespec *timeout, pth_msg_t *msg) +{ + usrtc_t *tree; + usrtc_node_t *node = NULL; + pth_msg_t *tmp; + int r = 0; + struct timespec abstimeout; + + if (queue == NULL || msg == NULL) + return EINVAL; + else + tree = &queue->qtree; + + if (timeout) { /* setup timeout */ + struct timeval now; + + gettimeofday(&now, NULL); + abstimeout.tv_sec = now.tv_sec + timeout->tv_sec; + abstimeout.tv_nsec = (now.tv_usec * 1000) + timeout->tv_nsec; + if (abstimeout.tv_nsec >= 1000000000) { + abstimeout.tv_sec++; + abstimeout.tv_nsec -= 1000000000; + } + } + + pthread_mutex_lock(&queue->mutex); + + /* Will wait until awakened by a signal or broadcast */ + while ((node = usrtc_first(tree)) == NULL && r != ETIMEDOUT) { /* Need to loop to handle spurious wakeups */ + if (timeout) + r = pthread_cond_timedwait(&queue->cond, &queue->mutex, &abstimeout); + else + pthread_cond_wait(&queue->cond, &queue->mutex); + } + if (r == ETIMEDOUT) { + pthread_mutex_unlock(&queue->mutex); + return r; + } + + tmp = (pth_msg_t *)usrtc_node_getdata(node); + queue->length--; + + msg->data = tmp->data; + msg->msgtype = tmp->msgtype; + msg->qlength = tmp->qlength; /* we will hold the msg id instead of size here */ + + __release_msg(queue, tmp); + pthread_mutex_unlock(&queue->mutex); + + return 0; +} + +int pth_queue_destroy(pth_queue_t *queue, int freedata, void (*free_msg)(void *)) +{ + int r = 0; + usrtc_t *tree = &queue->qtree; + usrtc_node_t *node = NULL; + pth_msg_t *msg; + + if (queue == NULL) return EINVAL; + + pthread_mutex_lock(&queue->mutex); + + for (node = usrtc_first(tree); node != NULL; node = usrtc_first(tree)) { + usrtc_delete(tree, node); + msg = (pth_msg_t *)usrtc_node_getdata(node); + + if(freedata) free(msg->data); + else if(free_msg) free_msg(msg->data); + + free(msg); + } + /* free cache */ + tree = &queue->msgcache; + for (node = usrtc_first(tree); node != NULL; node = usrtc_first(tree)) { + usrtc_delete(tree, node); + free(usrtc_node_getdata(node)); + } + + pthread_mutex_unlock(&queue->mutex); + r = pthread_mutex_destroy(&queue->mutex); + pthread_cond_destroy(&queue->cond); + + return r; +} + +unsigned int pth_queue_length(pth_queue_t *queue) +{ + unsigned int c; + + pthread_mutex_lock(&queue->mutex); + c = queue->length; + pthread_mutex_unlock(&queue->mutex); + + return c; +} diff --git a/po/ChangeLog b/po/ChangeLog new file mode 100644 index 0000000..e69de29 diff --git a/po/LINGUAS b/po/LINGUAS new file mode 100644 index 0000000..bc8cbb0 --- /dev/null +++ b/po/LINGUAS @@ -0,0 +1,2 @@ +# please keep this list sorted alphabetically +# diff --git a/po/POTFILES.in b/po/POTFILES.in new file mode 100644 index 0000000..17fc5de --- /dev/null +++ b/po/POTFILES.in @@ -0,0 +1,3 @@ +# List of source files containing translatable strings. + +