<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>template  class Shandyba: public T { };</title>
	<atom:link href="http://blog.shandyba.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.shandyba.com</link>
	<description></description>
	<lastBuildDate>Sat, 24 Apr 2010 13:40:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Calling function via void* pointer with arguments contained in std::container in a C++03 way</title>
		<link>http://blog.shandyba.com/2010/04/24/calling-function-via-void-pointer-with-arguments-contained-in-stdcontainer-in-a-c03-way/</link>
		<comments>http://blog.shandyba.com/2010/04/24/calling-function-via-void-pointer-with-arguments-contained-in-stdcontainer-in-a-c03-way/#comments</comments>
		<pubDate>Sat, 24 Apr 2010 13:36:46 +0000</pubDate>
		<dc:creator>Dmitry Shandyba</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.shandyba.com/?p=112</guid>
		<description><![CDATA[Recently I posted a technique that can be used to call functions, passed as raw void* pointers with arguments contained in an std::vector, so that the arguments are correctly transformed from container to normal C/C++&#8211;style arguments list. The method proposed was quite generalized and pretty type&#8211;safe. But it had one limitation: it required C++0x compiler [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I posted a <a href="http://blog.shandyba.com/2010/04/22/calling-function-via-void-pointer-with-arguments-as-stdcontainer/">technique</a> that can be used to call functions, passed as raw void* pointers with arguments contained in an std::vector, so that the arguments are correctly transformed from container to normal C/C++&#8211;style arguments list. The method proposed was quite generalized and pretty type&#8211;safe. But it had one limitation: it required C++0x compiler supporting variadic templates.<br />
So I decided to solve the original problem using C++03 compiler (which are mostly used in production today).</p>
<p><span id="more-112"></span></p>
<p>The main idea behind this method was that in case if compiler uses stack to pass parameters to called functions and also in case caller is responsible for stack maintenance then, essentially, calling a function with N parameters of type T sized X each is basically the same as calling this function with 1 &#8220;big&#8221; parameter sized N * X and which memory footprint is corresponding to passed parameters. This can be achieved, using just regular templates, but it has some limitations:</p>
<ul>
<li>only arguments passed via stack pushing are supported;</li>
<li>caller maintains stack state, therefore target function can&#8217;t accept ellipsis (&#8230;.) as an argument, e.g. printf can&#8217;t be called using this method;</li>
<li>target function has to accept N arguments of exactly same type, or if arguments are POD entities, exactly same size, otherwise &#8212; additional infrastructure has to be developed to provide correct type handling, which I hasn&#8217;t addressed (and am not planning to at the moment:)).</li>
</ul>
<p>I think that&#8217;s all. Only working example is left to be published <img src='http://blog.shandyba.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
We again used compile&#8211;time recursion to generate required a set of &#8220;big&#8221; types for us, for all possible cases (1 parameter, 2 parameters etc).</p>
<pre class="brush: c++">
#include &lt;cstdlib&gt;
#include &lt;vector&gt;
#include &lt;string&gt;
#include &lt;stdio.h&gt;

// This is a &quot;big&quot; holder for function parameters
template &lt;class TElement, int nElements&gt;
struct ParamsHolder
{
    // Such layout ensures that copy constructors do get correctly called
    TElement m_Val[nElements];
};

template &lt;class TElement, int nInst&gt;
struct F
{
    typedef ParamsHolder&lt;TElement, nInst&gt; TParamsHolder;

    template &lt;class TIt&gt;
    static void f(void *pFunc, TIt itFirst, TIt itLast)
    {
        if (nInst == (itLast - itFirst))
        {
            // We&#039;re ready to call the function
            // Creating pseudo function signature
            void (*fun)(TParamsHolder) = reinterpret_cast&lt;void(*)(TParamsHolder)&gt;(pFunc);

            // Creating actual container for parameter values
            TParamsHolder paramsHolder;

            // Filling params holder from vector
            for (--itLast; itFirst &lt;= itLast; --itLast)
                paramsHolder.m_Val[itLast - itFirst] = *itLast;

            // Calling the function
            fun(paramsHolder);
        }
        else
        {
            // We have to find right instantiation matching the number of passed parameters
            F&lt;TElement, nInst + 1&gt;::f(pFunc, itFirst, itLast);
        }
    }
};

template &lt;class TElement&gt;
struct F&lt;TElement, 50&gt;
{
    template &lt;class TIt&gt;
    static void f(void *pFunc, TIt itFirst, TIt itLast)
    {
        // runtime_assert(!&quot;Please increase number of possible instantiations of F&quot;);
    }
};

template &lt;class TElement, class TIt&gt;
void call_fun(void *pFunc, TIt itFirst, TIt itLast)
{
    F&lt;TElement, 0&gt;::f(pFunc, itFirst, itLast);
}

// This is the target function that we&#039;ll pass as void*
void func(std::string p0, std::string p1)
{
    // parameters are correctly passed to here
}

int main(int argc, char** argv)
{
    // Container with parameters
    std::vector&lt;std::string&gt; strVec(2);

    strVec[0] = &quot;Param 0!&quot;;
    strVec[1] = &quot;Param 1!&quot;;

    // Getting raw function pointer
    void *pFunc = reinterpret_cast&lt;void*&gt;(&amp;func);

    call_fun&lt;std::string&gt;(pFunc, strVec.begin(), strVec.end());

    return (EXIT_SUCCESS);
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.shandyba.com/2010/04/24/calling-function-via-void-pointer-with-arguments-contained-in-stdcontainer-in-a-c03-way/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Calling function via void* pointer with arguments contained in std::container</title>
		<link>http://blog.shandyba.com/2010/04/22/calling-function-via-void-pointer-with-arguments-as-stdcontainer/</link>
		<comments>http://blog.shandyba.com/2010/04/22/calling-function-via-void-pointer-with-arguments-as-stdcontainer/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 20:40:55 +0000</pubDate>
		<dc:creator>Dmitry Shandyba</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.shandyba.com/?p=89</guid>
		<description><![CDATA[Today I passed by a question posted to accu-general mailing list of Accu organization, which raised my interest. The guy was asking if it is possible to call a function, previously casted to void* pointer, passing to it a number of homogeneous arguments, with their unknown exact quantity at compile&#8211;time, that are contained in a [...]]]></description>
			<content:encoded><![CDATA[<p>Today I passed by a question posted to accu-general mailing list of <a href="http://www.accu.org">Accu</a> organization, which raised my interest. The guy was asking if it is possible to call a function, previously casted to void* pointer, passing to it a number of homogeneous arguments, with their unknown exact quantity at compile&#8211;time, that are contained in a container, e.g. vector. Simply saying, expressed in pseudo-code, he wanted something like:</p>
<pre class="brush: c++">
    template &lt;class TParameterType&gt;
    void call_function(void *pFunction, std::vector&lt;TParameterType&gt; pars)
    {
        pFunction(pars.begin(), pars.end());
    }
</pre>
<p>Easy to imagine &#8212; tricky to implement! <img src='http://blog.shandyba.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><span id="more-89"></span></p>
<p>I felt like I remembered I couldn&#8217;t have achieved that some few years ago, in c++03, when I had similar problem for myself. Some discussion in the list made me feel that it&#8217;s really kinda tricky task. But what came to my mind were variadic templates from c++0x. Well, we already know, partially from my previous posts, how to manipulate parameters typed with variadic templates. So I decided to apply similar technique to accomplish this task as well, which I had success with!</p>
<p>Some few words on the above excerpt: it&#8217;s important that we don&#8217;t have the exact function pointer type inside call_function, we have clear void*. Otherwise the task would&#8217;ve been somehow simpler. But of course arity of the function actually pointed by pFunction should match the number of parameters contained in pars, otherwise we&#8217;ll end up calling function with wrong number of arguments, with all the consequences. </p>
<p>Typical usage of that would be to create a table of functions each accepting some specific number of args, keep it in some homogeneous way (like vector of void* pointers), and then, before calling call_function, to chose the right function pointer from the table based on the number of elements in pars vector. So that at runtime arbitrary number can be accepted and correctly passed.</p>
<p>So, there we go. Below is just the same example that I posted to the list, with some more comments. This is a completely working example, buildable at least with gcc-4.4.1 on Ubuntu 9.10, with -std=c++0x option.</p>
<pre class="brush: c++">
#include &lt;cstdlib&gt;
#include &lt;vector&gt;
#include &lt;stdio.h&gt;

// We need to wrap function in class to bypass impossibility to have partially specialized template functions
// nInst is the &quot;reverse&quot; number of instantiations. If first called with value X, then each instantiation of F&lt;Y&gt;
// would serve a target function call with arity (X-Y). In total we&#039;ll have X instantiations, meaning that we&#039;ll have
// functions with up to X arguments
template &lt;int nInst&gt;
struct F
{
    // Iterator type and &quot;collecting&quot; list of function parameters, with corresponding values:
    // function pointer, first argument to add, end of arguments list, actual parameters values
    template &lt;class TIt, class ...TParams&gt;
    static void f(void* pFunc, TIt curIt, TIt lastIt, TParams ...params)
    {
        if (curIt == lastIt)
        {
            // We reach the end of arguments list
            // Converting void* to function pointer with required arity.
            void (*fun)(TParams...) = reinterpret_cast&lt;void(*)(TParams...)&gt;(pFunc);
            // Finally calling the function
            fun(params...);
        }
        else
        {
            // Extracting next argument
            TIt nextIt = curIt + 1;
            // recursively calling ourselves, previously adding extracted parameter to variadic parameters list
            F&lt;nInst - 1&gt;::f(pFunc, nextIt, lastIt, params..., *curIt);
        }
    }
};

// This specialization is required for compiler to finish producing compile--time instantiations of F with, which
// would happen otherwise because of the line above:  F&lt;nInst - 1&gt;::f(pFunc, nextIt, lastIt, params..., *curIt);
template&lt;&gt;
struct F&lt;0&gt;
{
    template &lt;class TIt, class ...TParams&gt;
    static void f(void* pFunc, TIt curIt, TIt lastIt, TParams ...params)
    {
        // In case designed number of parameters is not enough
        //runtime_assert(!&quot;Please, increase number of instantiations of F&quot;);
    }
};

// This is the one that well use, the interface function,
// which actully introduces the syntactic sugar we want:
// func(v.begin(), v.end());
template &lt;class TIt&gt;
void call_fun(void* pFunc, TIt curIt, TIt lastIt)
{
    TIt nextIt = curIt + 1;
    // We default to max 50 arguments by now
    F&lt;50&gt;::f(pFunc, nextIt, lastIt, *curIt);
}

int main(int argc, char** argv)
{
    // Container with parameters
    std::vector&lt;const char*&gt; pCharVec(2);

    pCharVec[0] = &quot;There we go, par = %s!&quot;;
    pCharVec[1] = &quot;&#039;I&#039;m a parameter!&#039;&quot;;

    // Function pointer, should handle ok the number of paramters in container
    // The actual signature isn&#039;t required here! It&#039;ll be &quot;composed&quot; based on the
    // number of paratmers in container above.
    // We explicitly show this by casting &quot;something&quot; (printf) to void*.
    void *pFunc = reinterpret_cast&lt;void*&gt;(&amp;printf);

    call_fun(pFunc, pCharVec.begin(), pCharVec.end());

    return (EXIT_SUCCESS);
}
</pre>
<p>So what do we do?<br />
Using compile-time recursion we create 50 possible instantiations of F (and consequently F::f), that implement function calling with 1, 2 &#8230; 50 arguments. Then, using runtime recursion we extract arguments from vector, one by one, and using variadic templates transforming arguments vector to real arguments list. At the same time we chose the right arity to use with the function pointer. As soon as we reach last argument we simply cast function pointer to function accepting the number of arguments deduced from arguments vector size, with arguments types deduced from vector elements type and, finally, we call that function using the list of arguments that we prepared using variadic templates. Pretty simple and works.</p>
<p>C++0x is sweeeeeet! <img src='http://blog.shandyba.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>PS We can somehow more generalize it by passing function return value type as a template argument as well.<br />
PPS This technique can be used with heterogeneous  arguments containers as well. Of course, function pointers have to match types of arguments from container, and their quantity.<br />
PPPS This technique can be used to create dynamic&#8211;languages like behavior: by using single function with single argument &#8230;, and by for example preceeding each parameter in the list with object representing its type, we can create a function that can be called with apriori unknown number of arguments and their types. And arguments for the function can created / decided in run&#8211;time!. This almost implements function call reflection in C++, without any additional runtime support required. Isn&#8217;t that even more sweeeeeeeet? <img src='http://blog.shandyba.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ))   </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.shandyba.com/2010/04/22/calling-function-via-void-pointer-with-arguments-as-stdcontainer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RCF 1.2 + OpenSSL</title>
		<link>http://blog.shandyba.com/2010/03/27/rcf-1-2-openssl/</link>
		<comments>http://blog.shandyba.com/2010/03/27/rcf-1-2-openssl/#comments</comments>
		<pubDate>Sat, 27 Mar 2010 01:20:43 +0000</pubDate>
		<dc:creator>Dmitry Shandyba</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.shandyba.com/?p=78</guid>
		<description><![CDATA[Being asked about code snippet showing real working example of using RCF together with OpenSSL, I decided to create such a refined self&#8211;contained example. I tried to make it as close to available docs and samples as possible, still keeping it compilable and working. This example will show probably the most simple case: server holding [...]]]></description>
			<content:encoded><![CDATA[<p>Being asked about code snippet showing real <strong>working</strong> example of using RCF together with OpenSSL, I decided to create such a refined self&#8211;contained example.<br />
I tried to make it as close to available docs and samples as possible, still keeping it compilable and working.</p>
<p><span id="more-78"></span></p>
<p>This example will show probably the most simple case: server holding a certificate and client verifying that certificate. So before running you&#8217;ll need to generate both: Ca and Server certs. </p>
<p>Here goes server part:</p>
<pre class="brush: c++">
#include &lt;cstdlib&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;

#include &lt;RCF/Idl.hpp&gt;
#include &lt;RCF/RcfServer.hpp&gt;
#include &lt;RCF/TcpEndpoint.hpp&gt;
#include &lt;RCF/FilterService.hpp&gt;
#include &lt;RCF/OpenSslEncryptionFilter.hpp&gt;
#include &lt;RCF/SessionObjectFactoryService.hpp&gt;

RCF_BEGIN(I_X, &quot;I_X&quot;)
RCF_METHOD_R1(int, test, int)
RCF_END(I_X)

class X
{
public:
    int test(int x)
    {
        std::vector&lt;RCF::FilterPtr&gt; transportFilters;
        RCF::getCurrentRcfSession().getTransportFilters(transportFilters);

        if (transportFilters.size() == 1)
        {
            boost::shared_ptr&lt;RCF::OpenSslEncryptionFilter&gt; filterPtr =
                boost::dynamic_pointer_cast&lt;RCF::OpenSslEncryptionFilter&gt;(
                    transportFilters.front());

            if (filterPtr)
            {
                RCF::getCurrentRcfSession().lockTransportFilters();
                RCF::getCurrentRcfSession().unlockTransportFilters();

                return x*x;
            }
        }

        return -1;
    }
};

int main()
{
    RCF::RcfServer server(RCF::TcpEndpoint(50001));

    RCF::SessionObjectFactoryServicePtr sofsPtr(new RCF::SessionObjectFactoryService());
    server.addService(sofsPtr);

    sofsPtr-&gt;bind&lt;I_X, X&gt;();

    RCF::FilterServicePtr fsPtr(new RCF::FilterService());
    fsPtr-&gt;addFilterFactory(RCF::FilterFactoryPtr(
        new RCF::OpenSslEncryptionFilterFactory(&quot;/path.../server.pem&quot;, &quot;&quot;)));
    server.addService(fsPtr);

    server.start();

    std::cout &lt;&lt; &quot;Press Enter to exit...&quot; &lt;&lt; std::endl;
    std::cin.get();

    return (EXIT_SUCCESS);
}
</pre>
<p>and here goes client part:</p>
<pre class="brush: c++">
#include &lt;cstdlib&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;

#include &lt;RCF/Idl.hpp&gt;
#include &lt;RCF/RcfServer.hpp&gt;
#include &lt;RCF/TcpEndpoint.hpp&gt;
#include &lt;RCF/FilterService.hpp&gt;
#include &lt;RCF/OpenSslEncryptionFilter.hpp&gt;
#include &lt;RCF/SessionObjectFactoryService.hpp&gt;

RCF_BEGIN(I_X, &quot;I_X&quot;)
RCF_METHOD_R1(int, test, int)
RCF_END(I_X)

int main()
{
    RcfClient&lt;I_X&gt; client(RCF::TcpEndpoint(50001));

    client.getClientStub().createRemoteSessionObject();

    client.getClientStub().requestTransportFilters(
        RCF::FilterPtr(
            new RCF::OpenSslEncryptionFilter(&quot;&quot;, &quot;&quot;, &quot;/path.../ca.pem&quot;)));

    std::cout &lt;&lt; client.test(21) &lt;&lt; std::endl;

    return (EXIT_SUCCESS);
}
</pre>
<p>Very simple and very similar to example in RCF&#8217;s docs.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.shandyba.com/2010/03/27/rcf-1-2-openssl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SSL certificates as easy as 1,2,.. 3!</title>
		<link>http://blog.shandyba.com/2009/12/28/ssl-certificates-as-easy-as-12-3/</link>
		<comments>http://blog.shandyba.com/2009/12/28/ssl-certificates-as-easy-as-12-3/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 16:08:53 +0000</pubDate>
		<dc:creator>Dmitry Shandyba</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.shandyba.com/?p=50</guid>
		<description><![CDATA[These days I yet again faced the problem of establishing of secure connection between my client and server applications. Although this time the task by itself was quite small and simple and (so a hand&#8211;made solution would definitely suffice) I&#8217;d decided to go via standard approach, i.e. using something that has already been invented, tested [...]]]></description>
			<content:encoded><![CDATA[<p>These days I yet again faced the problem of establishing of secure connection between my client and server applications. Although this time the task by itself was quite small  and simple and (so a hand&#8211;made solution would definitely suffice) I&#8217;d decided to go via standard approach, i.e. using something that has already been invented, tested and proved to be useful.</p>
<p>When we&#8217;re talking about transport&#8211;level security that&#8217;s undisputidly what is called a <strong>S</strong>ecure <strong>S</strong>ockets <strong>L</strong>ayer, or SSL. There is a number of <em>free</em> libraries out there implementing SSL, like popular <a href="http://www.openssl.org">OpenSSL</a> or less popular <a href="http://www.randombit.net/code/ajisai/">Ajisai</a> (based on cryptographic C++ library <a href="http://www.randombit.net/code/botan/">Botan</a>).  In my case I had to stick to OpenSSL as I also was about to use <a href="http://code.google.com/p/rcf-cpp/">RCF</a> for my client&#8211;server communication and RCF had already got support for OpenSSL integration to secure it&#8217;s transport channels.</p>
<p>OpenSSL uses certificates to make secured interactions work. So we immediately face a problem of getting these certificates. Searching the Internet would not give immediate understanding of what kind of certificate to we need and where to get the required one. so I&#8217;ve put all the pieces of information together and am sharing that knowledge with you <img src='http://blog.shandyba.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><span id="more-50"></span></p>
<p>First of all let me point out that most of OpenSSL usage instructions here were extracted from <a href="http://it.toolbox.com/blogs/securitymonkey/howto-securing-a-website-with-client-ssl-certificates-11500">here</a> &#8212; a beautiful post regarding setting&#8211;up of a secured Apache web&#8211;server.</p>
<p>Let&#8217;s get away a bit from our original goal (securing a custom client&#8211;server communication channel with SSL) and will have a look at more common SSL usage scenario: securing a connection between some privately held web&#8211;server with client web&#8211;browsers. Using SSL here resolves 2 problems:</p>
<ol>
<li>It ensures client that the server he&#8217;s talking to is really the actual server matching the one client wants to talk to and not the forged one. I.e. client can be sure that someserver.com is <em>really</em> someserver.com and not badguysserver.com trying to look like (pretend he is) a someserver.com.</li>
<li>It ensures that information between server and client will not be stolen or modified by any 3&#8211;rd party in between.</li>
</ol>
<p>Both are achieved at first by ensuring server&#8217;s authenticity. Using asymmetrical cryptography server just proves that it does really hold the private key it wants client to believe it holds, i.e. server <em>signs</em> its message first. Then anyone having the public key (client) can ensure that the correct private key was used for signature. But when client receives a signature it has no idea if the signature comes really from <em>that</em> server: i.e. private key is proven, but not ensured that it is exactly the  one required. In order to solve that, the hierarchy of <strong>C</strong>ertificate <strong>A</strong>uthorities was invented &#8212; client queries Certificate Authority if the received signature is authentic, or, more precisely, client just checks who issued the certificate that server used to make the signature. If server&#8217;s certificate was issued by a trusted Certificate Authority that would automatically mean that the server is authentic. Certificate Authority, before it issues certificates to for servers, performs a lot of checks and procedures. That means that only true server owners would receive certificates from CA. Basically &#8220;receiving&#8221; a certificate from CA would just mean that CA itself signs the certificate the server provides. Anyway, the list of trusted CA&#8217;s in its place is well known and is usually placed on client&#8217;s computer. Such CA&#8217;s are generally added to client&#8217;s system automatically during initial installation or update. Later client can add additional CA&#8217;s to his system (for example some not well known CAs that client still would like to trust to).</p>
<p>Once authenticity of server is proved using the method above, client and server interchange symmetrical cryptographic keys (using asymmetrical data interchange), and that keys are used to protect the session.</p>
<p>That&#8217;s why using a server certificate not signed by a well known CA for a web server would generally cause problems &#8212; clients visiting the web page will be prompted that the authenticity of the server is not checked. This also answers the question how CA&#8217;s earn their living &#8212; they just take some money to sign certificates of servers, in order for latter ones to be recognized by every potential client (which of course would already trust that CAs).</p>
<p>How one can try avoiding the need to sign his certificate with a well known CA?<br />
Obviously, by using an unknown CA, for example even one&#8217;s own CA! Then just all clients have to be convinced to trust that home&#8211;made CA which won&#8217;t likely to happen <img src='http://blog.shandyba.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
That&#8217;s why everyone out there uses pretty good known CAs for certificates located on public web services.</p>
<p>But what about our original case? There is a big difference with what we have in a web&#8211;server area: for our case we control both: the server and the client. That means that we can setup the client to check against any CA that we want and not only against some narrow list of big known trusted CAs.</p>
<p>So for our scenario we need to, firstly, create our own CA&#8217;s private key and CA&#8217;s certificate, and, secondly, create an actual server certificate and sign it with our CA&#8217;s certificate. After that we can embed CA certificate to client&#8217;s code so that client will check server&#8217;s authenticity using our own CA. And this will immediately solve 3 problems for us:</p>
<ol>
<li>Our clients will check our server&#8217;s authenticity</li>
<li>Connection between our server and our client will be protected</li>
<li>We won&#8217;t spend money on getting signature / certificate from public recognized CA <img src='http://blog.shandyba.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
</ol>
<p>So how can we manage that?</p>
<p>As it was first noted, let&#8217;s deal with our own CA certificate. To create it we&#8217;ll need first to generate a private key for our CA.</p>
<pre class="brush: php">openssl genrsa -out ca.key 4096</pre>
<p>This will create a 4096 bit RSA private key for our CA, named <strong>ca.key</strong>.</p>
<p>Now we have to create a CA certificate request based on CA private key for our future signed CA certificate. We will then sign this certificate request using the same key we just generated (so we&#8217;ll have a <em>self&#8211;signed</em> CA certificate).</p>
<pre class="brush: php">openssl req -new -key ca.key -out ca.req</pre>
<p>This will crete a certificate request located in <strong>ca.req</strong> file.</p>
<p>Finally we have to sign our CA certificate request with <em>itself</em>, i.e. with it&#8217;s own private key:</p>
<pre class="brush: php">openssl x509 -req -days 3650 -in ca.req -signkey ca.key -out ca.crt</pre>
<p>This way we get our home&#8211;made CA certificate valid for 10 years, signed with our CA key. The certificate is located in <strong>ca.crt</strong> file. This certificate will be embedded into our client, to check authenticity of our server.</p>
<p>Later after initially publishing this article I discovered a single command that could substitute 2 commands from the above</p>
<pre class="brush: php">openssl req -new -x509 -days 3650 -key ca.key -out ca.crt</pre>
<p>This should create self-signed CA certificate without intermediate step of creation of CA certificate request.</p>
<p>Having CA private key and CA certificate we now would like to create server&#8217;s certificate.<br />
This is pretty similary to creation of CA&#8217;s certificate with the only exclusion: on step 3 we will sign our server certificate not with itself (its own private key), but with our CA&#8217;s private key.</p>
<pre class="brush: php">
// Creating server private key
openssl genrsa -out server.key 4096
// Generating server certificate request, based on server private key
openssl req -new -key server.key -out server.req
// Signing server&#039;s certificate request with our CA&#039;s certificate (using CA&#039;s private key to prove that we have rights to use it)
openssl x509 -req -days 3650 -set_serial 01 -in server.req -CA ca.crt -CAkey ca.key -out server.crt
</pre>
<p>Voila! Now you can make your server use <strong>server.crt</strong> to use for server-side SSL and ship your clients with <strong>ca.crt</strong>, to check server&#8217;s authenticity. Obviously you can create certificate(s) for your clients just in the same manner, if you require them. </p>
<p>Please note, that in order to use certificate on server you&#8217;ll need both: your server&#8217;s certificate and server&#8217;s private key used to produced that certificate. In some cases you&#8217;ll be able to provide both separately and in some others (like RCF library) you&#8217;ll need to combine them into one file:</p>
<pre class="brush: php">cat server.crt server.key &gt; server.pem</pre>
<p>That&#8217;s pretty all &#8212; what I need for my RCF + OpenSSL stuff.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.shandyba.com/2009/12/28/ssl-certificates-as-easy-as-12-3/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>C++ Delayed Constructor 2: multi&#8211;level approach</title>
		<link>http://blog.shandyba.com/2009/12/19/c-delayed-constructor-2-multi-level-approach/</link>
		<comments>http://blog.shandyba.com/2009/12/19/c-delayed-constructor-2-multi-level-approach/#comments</comments>
		<pubDate>Sat, 19 Dec 2009 00:41:24 +0000</pubDate>
		<dc:creator>Dmitry Shandyba</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.shandyba.com/?p=36</guid>
		<description><![CDATA[Few days ago I described a mechanism which allows bind&#8211;like operations for constructors. In other words it gives opportunity for us to define object construction details once (e.g. all parameters required for object construction) and later to create this object, but without the need to specify these parameters at the place of creation, i.e. we [...]]]></description>
			<content:encoded><![CDATA[<p>Few days ago I described a <a href="http://blog.shandyba.com/2009/12/15/c-delayed-constructor/">mechanism</a> which allows bind&#8211;like operations for constructors. In other words it gives opportunity for us to define object construction details once (e.g. all parameters required for object construction) and later to create this object, but without the need to specify these parameters at the place of creation, i.e. we first bind constructor&#8217;s parameters to some helper object and later we just ask this helper object to create our original object, whilst the helper cares about all construction parameters for our obj.</p>
<p>I decided to develop this idea a bit further to allow &#8220;multi&#8211;level&#8221; delayed construction of objects.</p>
<p><span id="more-36"></span></p>
<p>In other words to allow delayed construction of objects that by themselves parameters for other objects being delayed&#8211;constructed. This would allow one to create a chain of such delayed&#8211;constructed objects. Until main (root) object is requested to be constructed &#8212; the rest of objects, upon which the root one is dependent, will also remain unconstructed. But as soon as root obj is created &#8212; all the others will be created in a chain, in a depth&#8211;first manner.</p>
<p>The actual implementation idea behind that functionality is very simple: we&#8217;ll just add a type cast operator for our DelayedConstructor helper. This type cast operation will actually create the embedded object. Having this we can pass instances of DelayedConstructor in place of actual objects. When this would happen all appropriate objects will be created and passed as required.</p>
<p>By the way, all these things are done in a static manner, without using procedural code from the interface perspective &#8212; we just say &#8220;prepare to create Obj with parameters Args&#8230; when we ask you to&#8221;. &#8212; all in a single line.</p>
<p>Besides that I added creation policies for the objects being created, so we can use new, copy or move&#8211;like construction:</p>
<pre class="brush: php">
template &lt;class T&gt;
struct CreateNew
{
    typedef T* TCreated;

    template &lt;class ...Args&gt;
    TCreated Create(Args ...args)
    {
        return new T(args...);
    }
};

template &lt;class T&gt;
struct CreateCopy
{
public:
    typedef T TCreated;

    template &lt;class ...Args&gt;
    TCreated Create(Args ...args)
    {
        return TCreated(args...);
    }
};

template &lt;class T&gt;
struct CreateMove
{
public:
    typedef T&amp;&amp; TCreated;

    template &lt;class ...Args&gt;
    TCreated Create(Args ...args)
    {
        return T(args...);
    }
};
</pre>
<p>These are self&#8211;explanatory and don&#8217;t require much attention I believe.</p>
<p>Instead, let&#8217;s have a look at our modified <code>DelayedConstructor</code>: it has just an added creation policy handing in its inner worker class plus adds an appropriate type cast operator.</p>
<pre class="brush: php">
template &lt;class TObject, template &lt;class T&gt; class TCreationPolicy = CreateNew&gt;
class DelayedConstructor
{
public:
    typedef typename TCreationPolicy&lt;TObject&gt;::TCreated TCreated;

    template &lt;class ...Args&gt;
    DelayedConstructor(Args ...args)
    {
        class ConstructHelper
        {
        public:
            static TCreated DoConstruct(Args ...args)
            {
                return TCreationPolicy&lt;TObject&gt;().Create(args...);
            }
        };

        m_funHelper = boost::bind(ConstructHelper::DoConstruct, args...);
    }

    TCreated operator()()
    {
        return m_funHelper();
    }

    operator TCreated()
    {
        operator()();
    }

protected:
    boost::function&lt;TCreated(void)&gt; m_funHelper;
};
</pre>
<p>That&#8217;s pretty all.</p>
<p>Now we can happily do things like that:</p>
<pre class="brush: php">
//Creation via operator new
DelayedConstructor&lt;int&gt; dc(42);
int *pInt = dc();

//Creation via returning a copy from inner stack
int  vInt = DelayedConstructor&lt;int, CreateCopy&gt;(42);

//2--level delayed construction:
//First we create an int on stack via copying and the
//we create an std::string via new
//Int argument is created only _after_
//std::string has been requested to create an instance
delayedConstructor&lt;std::string&gt; strDc = DelayedConstructor&lt;std::string&gt;(DelayedConstructor&lt;int, CreateCopy&gt;(42));
std::string str = strDc();
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.shandyba.com/2009/12/19/c-delayed-constructor-2-multi-level-approach/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Converting Variadic Template Arguments Pack to Boost Mpl Sequence</title>
		<link>http://blog.shandyba.com/2009/12/17/converting-variadic-template-arguments-pack-to-boost-mpl-sequence/</link>
		<comments>http://blog.shandyba.com/2009/12/17/converting-variadic-template-arguments-pack-to-boost-mpl-sequence/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 22:42:32 +0000</pubDate>
		<dc:creator>Dmitry Shandyba</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.shandyba.com/?p=15</guid>
		<description><![CDATA[Most existing articles describing variadic templates today address just some basic things, giving few encouraging examples, starting with recursive implementation of count&#60;T...&#62; method and usually finishing with type&#8211;safe printf, which by the way is very nice! I&#8217;d like to add to these starter&#8211;oriented hints yet another one. The question risen usually when one first meets [...]]]></description>
			<content:encoded><![CDATA[<p>Most existing articles describing variadic templates today address just some basic things, giving few encouraging examples, starting with recursive implementation of <code>count&lt;T...&gt;</code> method and usually finishing with type&#8211;safe printf, which by the way is very nice! <img src='http://blog.shandyba.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I&#8217;d like to add to these starter&#8211;oriented hints yet another one. The question risen usually when one first meets variadic templates is &#8220;a&#8230; is it possible to find out which types exactly were passed, like enumerate them and all sorts of such things?&#8230;&#8221; Usual answer refers to mentioned above <code>count&lt;T...&gt;</code> implementation only, saying that there could be little done with regards to the rest of problems. While it is true to some extent it is not actually.</p>
<p><span id="more-15"></span></p>
<p>This is indeed true if to be armed with pure compiler support only and have no time to create the whole required infrastructure. But wait, there already exist a number of excellent libraries dealing with C++ type sequences in all the ways allowing to get every bit of information from them. One of these is Boost MPL. </p>
<p>I won&#8217;t get into details with it: <a href="http://www.boost.org/doc/libs/release/libs/mpl/doc/index.html">go on your own</a>. Instead I&#8217;ll present a simple way to turn an arbitrary argument pack from variadic template to such a sequence. That would automatically mean you can have any information on the passed types you just might think of. Yes, you can count types, iterate through them, compare them do <strong>anything</strong>. The example I&#8217;ll give will be based on mpl::vector sequence. It doesn&#8217;t really matter which one to use, but vector is indexable, bidirectionally accessible so it might feet your needs the best.</p>
<p>The approach uses the same know recursive technique as is usually used in examples how to count the number of variadic template arguments.</p>
<pre class="brush: php">
//General definition of the helper class
template &lt;typename ...Args&gt; struct FromVariadic;

//This specialization does the actual job: it splits the whole pack
//into 2 parts: one single type T and the rest of types Args...
//As soon as it is done T is added to an mpl::vector.
//&quot;bottom--up&quot; recursion is used to fetch all types
template &lt;class T, typename ...Args&gt;
struct FromVariadic&lt;T, Args...&gt;
{
    typedef typename mpl::push_front&lt;typename FromVariadic&lt;Args...&gt;::type, T&gt;::type type;
};

//This is a specialization for the case when only one type is passed
//and also finishes recursive descent
template &lt;class T&gt;
struct FromVariadic&lt;T&gt;
{
    typedef mpl::vector&lt;T&gt; type;
};

//This one handles the case when no types where passed at all
template &lt;&gt;
struct FromVariadic&lt;&gt;
{
    typedef mpl::vector&lt;&gt; type;
};
</pre>
<p>Having this defined you can use it in the following way:</p>
<pre class="brush: php">
template &lt;typename ...Args&gt;
class A
{
    typedef typename FromVariadic&lt;Args...&gt;::type MplVector;

    //Do whatever you might imagine with MplVector ---
    //this is really a boost::mpl::vector !
};
</pre>
<p>And yes, this is compilable by gcc-4.4.1, with c++0x enabled.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.shandyba.com/2009/12/17/converting-variadic-template-arguments-pack-to-boost-mpl-sequence/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C++ Delayed Constructor</title>
		<link>http://blog.shandyba.com/2009/12/15/c-delayed-constructor/</link>
		<comments>http://blog.shandyba.com/2009/12/15/c-delayed-constructor/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 21:42:21 +0000</pubDate>
		<dc:creator>Dmitry Shandyba</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.shandyba.com/?p=1</guid>
		<description><![CDATA[Messing recently with a multiple&#8211;dispatch solution in C++ / Boost / Loki environment I faced a number of challenges one of which was to implement a &#8220;delayed constructor&#8221; mechanism. Basically, this is a somehow known problem of binding values to constructors which isn&#8217;t solvable by boost::bind as there is no way to get an address [...]]]></description>
			<content:encoded><![CDATA[<p>Messing recently with a multiple&#8211;dispatch solution in C++ / Boost / Loki environment I faced a number of challenges one of which was to implement a &#8220;delayed constructor&#8221; mechanism. Basically, this is a somehow known problem of binding values to constructors which isn&#8217;t solvable by boost::bind as there is no way to get an address of the constructor, but for which a solutions exists in boost::lambda::bind. Honestly, I didn&#8217;t look into there in deep. Instead I went for a short [maybe elegant] solution, compilable by any compiler supporting variadic templates (spirit of c++0x is already within our codes):</p>
<p><span id="more-1"></span></p>
<pre class="brush: php">
template &lt;class TObject&gt;
class DelayedConstructor
{
public:
    template &lt;class ...Args&gt;
    DelayedConstructor(Args ...args)
    {
        class ConstructHelper
        {
        public:
            static TObject* DoConstruct(Args ...args)
            {
                return new TObject(args...);
            }
        };
        m_funHelper = boost::bind(ConstructHelper::DoConstruct, args...);
    }

    TObject* operator()()
    {
        return m_funHelper();
    }

protected:
    boost::function&lt;TObject*(void)&gt; m_funHelper;
};
</pre>
<p>And here we use it:</p>
<pre class="brush: php">
class A
{
public:
    A(int a, std::string str) { }
};

//Binding values to the constructor
DelayedConstructor&lt;A&gt; dc(21, &quot;Good stuff!&quot;);

//Actually creating an object
A *pA = dc();
</pre>
<p>To me it looks very simple and rational. And keep in mind that it would work with any number of constructor arguments, which you don&#8217;t have to worry about at all. Just Use it.</p>
<p>But what&#8217;s left for a homework? Okay, let&#8217;s teach it to accept binding of only specific args. As we are used to do with regular functions.</p>
<p>P.S. But what is even more exciting is that as soon as c++0x lambdas come to play the solution of this problem would become trivial by using lambda factory function for desired class, which will eliminate usage of boot::bind.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.shandyba.com/2009/12/15/c-delayed-constructor/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
