<?xml version="1.0" encoding="UTF-8"?>
<feed
  xmlns="http://www.w3.org/2005/Atom"
  xmlns:thr="http://purl.org/syndication/thread/1.0"
  xml:lang="en"
   >
  <title type="text">funcptr</title>
  <subtitle type="text">An engineers technical notebook</subtitle>

  <updated>2013-04-21T00:24:56Z</updated>

  <link rel="alternate" type="text/html" href="http://funcptr.net/" />
  <id>http://funcptr.net//feed/atom/</id>
  <link rel="self" type="application/atom+xml" href="http://funcptr.net//feed/atom/" />
  <entry>
    <author>
      <name></name>
      <uri>http://funcptr.net/</uri>
    </author>
    <title type="html"><![CDATA[Embedding ZeroMQ in the libev Event Loop]]></title>
    <link rel="alternate" type="text/html" href="http://funcptr.net/2013/04/20/embedding-zeromq-in-the-libev-event-loop" />
    <id>http://funcptr.net/2013/04/20/embedding-zeromq-in-the-libev-event-loop</id>
    <updated>2013-04-20T18:22:00Z</updated>
    <published>2013-04-20T18:22:00Z</published>
    <category scheme="http://funcptr.net/" term="ZeroMQ" />
    <category scheme="http://funcptr.net/" term="C" />
    <category scheme="http://funcptr.net/" term="C++" />
    <category scheme="http://funcptr.net/" term="libev" />
    <summary type="html"><![CDATA[Embedding ZeroMQ in the libev Event Loop]]></summary>
    <content type="html" xml:base="http://funcptr.net/2013/04/20/embedding-zeromq-in-the-libev-event-loop"><![CDATA[<p>In a <a href="http://funcptr.net/2012/09/10/zeromq---edge-triggered-notification">previous article on ZeroMQ</a> we went over how ZeroMQ is triggered when
you use the socket that ZeroMQ returns, in that article there was some
discussion of embedding ZeroMQ into another event loop. Let's do that.</p>
<p><a href="http://software.schmorp.de/pkg/libev.html">libev</a> is an absolutely fantastic library that helps make it easy to write
evented programs. Evented programs work by getting notified that an action has
happened, and acting upon it. Unlike threaded where multiple pieces of work are
being executed at the same time, in an evented system you move every item that
could block to an event loop, that then calls back into user code with a
notification to continue. If one event uses up more than its fair share of CPU
time because it is busy doing a long calculation, every single other event that
is waiting will never get notified.</p>
<p>Now, as previously discussed ZeroMQ is edge triggered, so embedding it into an
event loop that is level triggered doesn't do us much good, because we will miss
certain ZeroMQ notifications.</p>
<p>One way to solve this problem is by looping over ZeroMQ's event system until we
get back a notification that it no longer has anything else for us to process,
that would look something like this<sup id="fnref:20130420zeromqedge"><a href="#fn:20130420zeromqedge" rel="footnote">1</a></sup>:</p>
<div class="codehilite"><pre><span class="kt">int</span> <span class="n">zevents</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="n">size_t</span> <span class="n">zevents_len</span> <span class="o">=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">zevents</span><span class="p">);</span>
<span class="n">zmq_socket</span><span class="p">.</span><span class="n">getsockopt</span><span class="p">(</span><span class="n">ZMQ_EVENTS</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents_len</span><span class="p">);</span>

<span class="k">do</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">zevents</span> <span class="o">&amp;</span> <span class="n">ZMQ_POLLIN</span><span class="p">)</span> <span class="p">{</span>
        <span class="c1">// We can read from the ZeroMQ socket</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c1">// Check to see if there is more to read ...</span>
    <span class="n">zmq_socket</span><span class="p">.</span><span class="n">getsockopt</span><span class="p">(</span><span class="n">ZMQ_EVENTS</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents_len</span><span class="p">);</span>
<span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="n">zevents</span> <span class="o">&amp;</span> <span class="n">ZMQ_POLLIN</span><span class="p">);</span>

<span class="k">if</span> <span class="p">(</span><span class="n">zevents</span> <span class="o">&amp;</span> <span class="n">ZMQ_POLLOUT</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// We can write to the ZeroMQ socket</span>
<span class="p">}</span>

<span class="c1">// If neither of the above is true, then it was a false positive</span>
</pre></div>


<p>However if we are receiving information from ZeroMQ remote endpoints faster
than we can process them, we end up being stuck in that <code>do</code> ... <code>while</code> loop
forever. If we have other events we want to process, that isn't entirely fair
since they will never ever get called again. Especially in a server application
where it may be servicing thousands of clients this is simply not acceptable.</p>
<h2>libev</h2>
<p>libev provides various different event notifications, to be able to get around
edge triggered notifications, and still provide fair round-robin for all events
we are going to have to build on top of multiple different events.</p>
<p>The events used will be:</p>
<ul>
<li><a href="http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#code_ev_io_code_is_this_file_descrip"><code>ev::io</code></a>: This one is pretty self explanatory, this is for getting notified
   about input output changes. This is the one we are going to use on the
   <code>ZMQ_FD</code>.</li>
<li><a href="http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#code_ev_prepare_code_and_code_ev_che"><code>ev::prepare</code></a> and <a href="http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#code_ev_prepare_code_and_code_ev_che"><code>ev::check</code></a>: These two are generally used together, they
   can be used to change the event loop and or make modifications on the fly to
   events that have been registered with the event loop.</li>
<li><a href="http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#code_ev_idle_code_when_you_ve_got_no"><code>ev::idle</code></a>: This is an event that gets fired whenever the event loop has
   nothing else to do, so no other events fired, this will fire.</li>
</ul>
<h2>Plan of attack</h2>
<p>Since the <code>prepare</code> and <code>check</code> run before and after the loop, we are going to
be using those to do most of the work. We use an <code>io</code> so that we can turn off
the <code>idle</code> when we can actually wait for a result from ZeroMQ's file
descriptor, otherwise we use <code>idle</code> so that we will always get called once
every loop.</p>
<p>In the <code>prepare</code> watcher callback we do the following:</p>
<ol>
<li>Check to see what events ZeroMQ has for us, and check what events the user
    has requested.</li>
<li>If the ZeroMQ has an event for us that we want, and the user has requested
    that event, we start the idle watcher.</li>
<li>If ZeroMQ has no events, we start the io watcher.</li>
</ol>
<p>In the <code>check</code> watcher callback we do the following:</p>
<ol>
<li>Stop both the <code>io</code> and <code>idle</code> watchers, they were only there to make sure
    that our <code>check</code> watcher was called.</li>
<li>See what event ZeroMQ has for us, and check that against what the user
    wants. Depending on the event, call user defined function write() or user
    defined function read().</li>
<li>If this was a spurious wake-up on the part of ZeroMQ we simply ignore it
    and let libev go on to other events.</li>
</ol>
<p>We could make all of this work by simply using the <code>prepare</code>, <code>check</code> and
<code>idle</code> watchers, but that would mean libev would be busy-waiting for something
to happen on the ZeroMQ socket. The <code>io</code> watcher is required simply so in times
of nothing happening libev in its library can call into the kernels event
handling mechanism and go to sleep. We can't use just the <code>io</code> watcher due to
the edge-triggered notification, because we'd miss all kinds of ZeroMQ
messages. So all four watchers are required, and play crucial parts in making
this work.</p>
<h2>Let's get down to code</h2>
<p>Below you will find example code, it is not complete. Do note that I am using
some C++11isms, error checking code may not be complete/correct and in general
I don't suggest you copy and paste this without reading and understanding what
it does.</p>
<p>The <code>zmq_event</code> class is meant to be used as a base class, inherit from it, and
create the <code>write()</code> and <code>read()</code> functions. These functions will be called
when you are able to read from the ZeroMQ socket, or when you are able to write
to the ZeroMQ socket. You are guaranteed to be able to read one whole ZeroMQ
message, so if it is a multi-part message, do make sure to loop on
<code>ZMQ_SNDMORE</code> as required.</p>
<p>Upon instantiation it will automatically start being notified about events, we
start off with <code>ev::READ</code>. When your sub-class wants to write to ZeroMQ it
should put the messages to be written into a list somewhere, and set 
<code>ev::READ | ev::WRITE</code> on <code>watcher_io</code>, by calling 
<code>watcher_io.set(socket_fd, ev::READ | ev::WRITE)</code>. <code>write()</code> will then be
called, write a single message to ZeroMQ, and if necessary when finished
writing, unset <code>ev::WRITE</code> using <code>watcher_io.set(socket_fd, ev::READ)</code>. If you
are not finished writing, after writing that singular message you may return
and <code>write()</code> will be called again the next loop iteration. This way if you
have a lot of data to write you don't starve the other events from receiving
their notifications.</p>
<h4><code>zmq_event.h</code></h4>
<div class="codehilite"><pre><span class="cp">#include &lt;string&gt;</span>

<span class="cp">#include &lt;ev++.h&gt;</span>
<span class="cp">#include &lt;zmq.hpp&gt;</span>

<span class="k">class</span> <span class="nc">zmq_event</span> <span class="p">{</span>
    <span class="k">public</span><span class="o">:</span>
        <span class="n">zmq_event</span><span class="p">(</span><span class="n">zmq</span><span class="o">::</span><span class="n">context_t</span><span class="o">&amp;</span> <span class="n">context</span><span class="p">,</span> <span class="kt">int</span> <span class="n">type</span><span class="p">,</span> <span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&amp;</span> <span class="n">connect</span><span class="p">);</span>
        <span class="k">virtual</span> <span class="o">~</span><span class="n">zmq_event</span><span class="p">();</span>

    <span class="k">protected</span><span class="o">:</span>
        <span class="c1">// This gets fired before the event loop, to prepare</span>
        <span class="kt">void</span> <span class="n">before</span><span class="p">(</span><span class="n">ev</span><span class="o">::</span><span class="n">prepare</span><span class="o">&amp;</span> <span class="n">prep</span><span class="p">,</span> <span class="kt">int</span> <span class="n">revents</span><span class="p">);</span>

        <span class="c1">// This is fired after the event loop, but before any other type of events</span>
        <span class="kt">void</span> <span class="n">after</span><span class="p">(</span><span class="n">ev</span><span class="o">::</span><span class="n">check</span><span class="o">&amp;</span> <span class="n">check</span><span class="p">,</span> <span class="kt">int</span> <span class="n">revents</span><span class="p">);</span>

        <span class="c1">// We need to have a no-op function available for those events that we</span>
        <span class="c1">// want to add to the list, but should never fire an actual event</span>
        <span class="k">template</span> <span class="o">&lt;</span><span class="k">typename</span> <span class="n">T</span><span class="o">&gt;</span>
            <span class="kr">inline</span> <span class="kt">void</span> <span class="n">noop</span><span class="p">(</span><span class="n">T</span><span class="o">&amp;</span> <span class="n">w</span><span class="p">,</span> <span class="kt">int</span> <span class="n">revents</span><span class="p">)</span> <span class="p">{};</span>

        <span class="c1">// Function we are going to call to write to the ZeroMQ socket</span>
        <span class="k">virtual</span> <span class="kt">void</span> <span class="n">write</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

        <span class="c1">// Function we are going to call to read from the ZeroMQ socket</span>
        <span class="k">virtual</span> <span class="kt">void</span> <span class="n">read</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

        <span class="c1">// Some helper function, one to start notifications</span>
        <span class="kt">void</span> <span class="n">start_notify</span><span class="p">();</span>

        <span class="c1">// And one to stop notifications.</span>
        <span class="kt">void</span> <span class="n">stop_notify</span><span class="p">();</span>

        <span class="c1">// Our event types</span>
        <span class="n">ev</span><span class="o">::</span><span class="n">io</span>      <span class="n">watcher_io</span><span class="p">;</span>
        <span class="n">ev</span><span class="o">::</span><span class="n">prepare</span> <span class="n">watcher_prepare</span><span class="p">;</span>
        <span class="n">ev</span><span class="o">::</span><span class="n">check</span>   <span class="n">watcher_check</span><span class="p">;</span>
        <span class="n">ev</span><span class="o">::</span><span class="n">idle</span>    <span class="n">watcher_idle</span><span class="p">;</span>

        <span class="c1">// Our ZeroMQ socket</span>
        <span class="n">zmq</span><span class="o">::</span><span class="n">socket_t</span> <span class="n">socket</span><span class="p">;</span>
        <span class="kt">int</span>           <span class="n">socket_fd</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>


<h4><code>zmq_event.cc</code></h4>
<div class="codehilite"><pre><span class="cp">#include &lt;stdexcept&gt;</span>

<span class="cp">#include &quot;zmq_event.h&quot;</span>

<span class="n">zmq_event</span><span class="o">::</span><span class="n">zmq_event</span><span class="p">(</span><span class="n">zmq</span><span class="o">::</span><span class="n">context_t</span><span class="o">&amp;</span> <span class="n">context</span><span class="p">,</span> <span class="kt">int</span> <span class="n">type</span><span class="p">,</span> <span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&amp;</span> <span class="n">connect</span><span class="p">)</span> <span class="o">:</span> <span class="n">socket</span><span class="p">(</span><span class="n">context</span><span class="p">,</span> <span class="n">type</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Get the file descriptor for the socket</span>
    <span class="n">size_t</span> <span class="n">fd_len</span> <span class="o">=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">_socket_fd</span><span class="p">);</span>
    <span class="n">socket</span><span class="p">.</span><span class="n">getsockopt</span><span class="p">(</span><span class="n">ZMQ_FD</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">socket_fd</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">fd_len</span><span class="p">);</span>

    <span class="c1">// Actually connect to the ZeroMQ endpoint, could replace this with a bind as well ...</span>
    <span class="n">socket</span><span class="p">.</span><span class="n">bind</span><span class="p">(</span><span class="n">connect</span><span class="p">.</span><span class="n">c_str</span><span class="p">());</span>

    <span class="c1">// Set up all of our watchers</span>

    <span class="c1">// Have our IO watcher check for READ on the ZeroMQ socket</span>
    <span class="n">watcher_io</span><span class="p">.</span><span class="n">set</span><span class="p">(</span><span class="n">socket_fd</span><span class="p">,</span> <span class="n">ev</span><span class="o">::</span><span class="n">READ</span><span class="p">);</span>

    <span class="c1">// This watcher has a no-op callback</span>
    <span class="n">watcher_io</span><span class="p">.</span><span class="n">set</span><span class="o">&lt;</span><span class="n">zmq_event</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zmq_event</span><span class="o">::</span><span class="n">noop</span><span class="o">&gt;</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>

    <span class="c1">// Set up our prepare watcher to call the before() function</span>
    <span class="n">watcher_prepare</span><span class="p">.</span><span class="n">set</span><span class="o">&lt;</span><span class="n">zmq_event</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zmq_event</span><span class="o">::</span><span class="n">before</span><span class="o">&gt;</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>

    <span class="c1">// Set up the check watcher to call the after() function</span>
    <span class="n">watcher_check</span><span class="p">.</span><span class="n">set</span><span class="o">&lt;</span><span class="n">zmq_event</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zmq_event</span><span class="o">::</span><span class="n">after</span><span class="o">&gt;</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>

    <span class="c1">// Set up our idle watcher, once again a no-op</span>
    <span class="n">watcher_idle</span><span class="p">.</span><span class="n">set</span><span class="o">&lt;</span><span class="n">zmq_event</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zmq_event</span><span class="o">::</span><span class="n">noop</span><span class="o">&gt;</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>

    <span class="c1">// Tell libev to start notifying us!</span>
    <span class="n">start_notify</span><span class="p">();</span>
<span class="p">}</span>

<span class="n">zmq_event</span><span class="o">::~</span><span class="n">zmq_event</span><span class="p">()</span> <span class="p">{}</span>

<span class="n">zmq_event</span><span class="o">::</span><span class="n">before</span><span class="p">(</span><span class="n">ev</span><span class="o">::</span><span class="n">prepare</span><span class="o">&amp;</span><span class="p">,</span> <span class="kt">int</span> <span class="n">revents</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">EV_ERROR</span> <span class="o">&amp;</span> <span class="n">revents</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="n">std</span><span class="o">::</span><span class="n">runtime_error</span><span class="p">(</span><span class="s">&quot;libev error&quot;</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="c1">// Get any events that may be waiting</span>
    <span class="n">uint32_t</span> <span class="n">zevents</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">size_t</span> <span class="n">zevents_len</span> <span class="o">=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">zevents</span><span class="p">);</span>

    <span class="c1">// Lucky for us, getting the events available doesn&#39;t invalidate the</span>
    <span class="c1">// events, so that calling this in `before()` and in `after()` will</span>
    <span class="c1">// give us the same results.</span>
    <span class="n">socket</span><span class="p">.</span><span class="n">getsockopt</span><span class="p">(</span><span class="n">ZMQ_EVENTS</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents_len</span><span class="p">);</span>

    <span class="c1">// Check what events exists, and check it against what event we want. We</span>
    <span class="c1">// &quot;abuse&quot; our watcher_io.events for this information.</span>
    <span class="k">if</span> <span class="p">((</span><span class="n">zevents</span> <span class="o">&amp;</span> <span class="n">ZMQ_POLLOUT</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">watcher_io</span><span class="p">.</span><span class="n">events</span> <span class="o">&amp;</span> <span class="n">ev</span><span class="o">::</span><span class="n">WRITE</span><span class="p">))</span> <span class="p">{</span>
        <span class="n">watcher_idle</span><span class="p">.</span><span class="n">start</span><span class="p">();</span>
        <span class="k">return</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">((</span><span class="n">zevents</span> <span class="o">&amp;</span> <span class="n">ZMQ_POLLIN</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">watcher_io</span><span class="p">.</span><span class="n">events</span> <span class="o">&amp;</span> <span class="n">ev</span><span class="o">::</span><span class="n">READ</span><span class="p">))</span> <span class="p">{</span>
        <span class="n">watcher_idle</span><span class="p">.</span><span class="n">start</span><span class="p">();</span>
        <span class="k">return</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c1">// No events ready to be processed, we&#39;ll just go watch some io</span>
    <span class="n">watcher_io</span><span class="p">.</span><span class="n">start</span><span class="p">();</span>
<span class="p">}</span>

<span class="n">zmq_event</span><span class="o">::</span><span class="n">after</span><span class="p">(</span><span class="n">ev</span><span class="o">::</span><span class="n">check</span><span class="o">&amp;</span><span class="p">,</span> <span class="kt">int</span> <span class="n">revents</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">EV_ERROR</span> <span class="o">&amp;</span> <span class="n">revents</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="n">std</span><span class="o">::</span><span class="n">runtime_error</span><span class="p">(</span><span class="s">&quot;libev error&quot;</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="c1">// Stop both the idle and the io watcher, no point in calling the no-op callback</span>
    <span class="c1">// One of them will be reactived by before() on the next loop</span>
    <span class="n">watcher_idle</span><span class="p">.</span><span class="n">stop</span><span class="p">();</span>
    <span class="n">watcher_io</span><span class="p">.</span><span class="n">stop</span><span class="p">();</span>

    <span class="c1">// Get the events</span>
    <span class="n">uint32_t</span> <span class="n">zevents</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">size_t</span> <span class="n">zevents_len</span> <span class="o">=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">zevents</span><span class="p">);</span>
    <span class="n">socket</span><span class="p">.</span><span class="n">getsockopt</span><span class="p">(</span><span class="n">ZMQ_EVENTS</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents_len</span><span class="p">);</span>

    <span class="c1">// Check the events and call the users read/write function</span>
    <span class="k">if</span> <span class="p">((</span><span class="n">zevents</span> <span class="o">&amp;</span> <span class="n">ZMQ_POLLIN</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">watcher_io</span><span class="p">.</span><span class="n">events</span> <span class="o">&amp;</span> <span class="n">ev</span><span class="o">::</span><span class="n">READ</span><span class="p">))</span> <span class="p">{</span>
        <span class="k">this</span><span class="o">-&gt;</span><span class="n">read</span><span class="p">();</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">((</span><span class="n">zevents</span> <span class="o">&amp;</span> <span class="n">ZMQ_POLLOUT</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">watcher_io</span><span class="p">.</span><span class="n">events</span> <span class="o">&amp;</span> <span class="n">ev</span><span class="o">::</span><span class="n">WRITE</span><span class="p">))</span> <span class="p">{</span>
        <span class="k">this</span><span class="o">-&gt;</span><span class="n">write</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="n">zmq_event</span><span class="o">::</span><span class="n">start_notify</span><span class="p">()</span> <span class="p">{</span>
    <span class="n">watcher_check</span><span class="p">.</span><span class="n">start</span><span class="p">();</span>
    <span class="n">watcher_prepare</span><span class="p">.</span><span class="n">start</span><span class="p">();</span>
<span class="p">}</span>

<span class="n">zmq_event</span><span class="o">::</span><span class="n">stop_notify</span><span class="p">()</span> <span class="p">{</span>
    <span class="n">watcher_check</span><span class="p">.</span><span class="n">stop</span><span class="p">();</span>
    <span class="n">watcher_prepare</span><span class="p">.</span><span class="n">stop</span><span class="p">();</span>
<span class="p">}</span>
</pre></div>


<h2>Other event loops</h2>
<p>libev is but just one of many event loops that exist out there, hopefully
this shows how it is possible to embed ZeroMQ into an event loop, thereby
making it easier to embed ZeroMQ into any other event loops.</p>
<div class="footnote">
<hr />
<ol>
<li id="fn:20130420zeromqedge">
<p>This snippet was from my older article regarding
<a href="http://funcptr.net/2012/09/10/zeromq---edge-triggered-notification">ZeroMQ edge triggered notifications</a>. I would highly suggest reading that
article for more information and even more background on what is going on.&#160;<a href="#fnref:20130420zeromqedge" rev="footnote" title="Jump back to footnote 1 in the text">&#8617;</a></p>
</li>
</ol>
</div>]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://funcptr.net/</uri>
    </author>
    <title type="html"><![CDATA[ZeroMQ - Edge Triggered Notification]]></title>
    <link rel="alternate" type="text/html" href="http://funcptr.net/2012/09/10/zeromq---edge-triggered-notification" />
    <id>http://funcptr.net/2012/09/10/zeromq---edge-triggered-notification</id>
    <updated>2012-09-10T19:01:50Z</updated>
    <published>2012-09-10T19:01:50Z</published>
    <category scheme="http://funcptr.net/" term="ZeroMQ" />
    <category scheme="http://funcptr.net/" term="C" />
    <category scheme="http://funcptr.net/" term="C++" />
    <summary type="html"><![CDATA[ZeroMQ - Edge Triggered Notification]]></summary>
    <content type="html" xml:base="http://funcptr.net/2012/09/10/zeromq---edge-triggered-notification"><![CDATA[<p><a href="http://www.zeromq.org">ZeroMQ</a> is an absolutely fantastic communications library that has allowed
me to very easily create networks/connections between multiple different
applications to communicate in an extremely fast yet directed manner and allow
scaling of the connected entities with almost no second thought.</p>
<p>I have used ZeroMQ within Python and C++, and it has been fantastic leaving
that part of the communication layer to a library rather than writing something
similar myself. However, embedding ZeroMQ into an another event loop has proven
to have some quirks. They are documented in the API, but not so much by other
users/examples found around the web, and caught me by surprise.</p>
<p>This post mainly goes over the issue, the difference between edge and level
triggered and how ZeroMQ works. I am hoping to spend some time documenting how
to embed ZeroMQ correctly inside <a href="http://software.schmorp.de/pkg/libev.html">libev</a> at a later date.</p>
<h2>The quirk</h2>
<p>ZeroMQ allows you to get an underlying file descriptor (<code>ZMQ_FD</code>) for a ZeroMQ
socket using <a href="http://api.zeromq.org/2-2:zmq-getsockopt#toc21"><code>getsockopt()</code></a>, this is not the actual ZeroMQ file descriptor
but a stand-in:</p>
<div class="codehilite"><pre><span class="kt">int</span> <span class="n">fd</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="n">size_t</span> <span class="n">fd_len</span> <span class="o">=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">fd</span><span class="p">);</span>
<span class="n">zmq_socket</span><span class="p">.</span><span class="n">getsockopt</span><span class="p">(</span><span class="n">ZMQ_FD</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">fd</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">fd_len</span><span class="p">);</span>
</pre></div>


<p>This file descriptor can then be passed on to <code>poll()</code>, <code>select()</code>, <code>kqueue()</code>
or whatever your event notification library of choice may be, the idea being
that if the file descriptor is notified to be available for reading then you
check the sockets <a href="http://api.zeromq.org/2-2:zmq-getsockopt#toc22"><code>ZMQ_EVENTS</code></a> and find out if you are allowed to read or
write to the ZeroMQ socket, or even possibly neither (false positive). The same
file descriptor is also used internally within the ZeroMQ library for
notification and thus we may receive an event notification that we can't do
anything with.</p>
<p>As stated in the <a href="http://api.zeromq.org/2-2:zmq-getsockopt#toc21">ZeroMQ API guide for <code>getsockopt()</code> under <code>ZMQ_FD</code></a>:</p>
<blockquote>
<p>the ØMQ library shall signal any pending events on the socket in an
<em>edge-triggered</em> fashion by making the file descriptor become ready for
reading.</p>
</blockquote>
<p>and further it states:</p>
<blockquote>
<p>The ability to read from the returned file descriptor does not necessarily
indicate that messages are available to be read from, or can be written to,
the underlying socket; applications must retrieve the actual event state with
a subsequent retrieval of the <code>ZMQ_EVENTS</code> option.</p>
</blockquote>
<p>So far so good, so after we return from our event notification on the file
descriptor we simply ask ZeroMQ whether or not we can read or write (or
possibly both):</p>
<div class="codehilite"><pre><span class="kt">int</span> <span class="n">zevents</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="n">size_t</span> <span class="n">zevents_len</span> <span class="o">=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">zevents</span><span class="p">);</span>
<span class="n">zmq_socket</span><span class="p">.</span><span class="n">getsockopt</span><span class="p">(</span><span class="n">ZMQ_EVENTS</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents_len</span><span class="p">);</span>

<span class="k">if</span> <span class="p">(</span><span class="n">zevents</span> <span class="o">&amp;</span> <span class="n">ZMQ_POLLIN</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// We can read from the ZeroMQ socket</span>
<span class="p">}</span>

<span class="k">if</span> <span class="p">(</span><span class="n">zevents</span> <span class="o">&amp;</span> <span class="n">ZMQ_POLLOUT</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// We can write to the ZeroMQ socket</span>
<span class="p">}</span>

<span class="c1">// If neither of the above is true, then it was a false positive</span>
</pre></div>


<p>So now you are happily reading from ZeroMQ and using the data as you wish,
except you start to notice that sometimes it can take a little while for data
to show up, or that if the end-point you are connected to on ZeroMQ sends a lot
of data it is not delivered in a timely fashion. This is where the
documentation for edge triggered comes into play, and that is something that is
different about ZeroMQ compared to for example BSD sockets.</p>
<h2>Edge triggered versus level triggered</h2>
<p>Edge and level triggered refer to what kind of signal a device will output in
an attempt to gain the attention of another device. Edge and level triggered
have their history in electronics and hardware, where they play a very crucial
role.</p>
<p>For both level and edge triggered assume the data is represented by this simple string:</p>
<div class="codehilite"><pre>00000000000111111111111111111111100000000011111111111000000000
</pre></div>


<p>The zeroes (0) are where no data is available, and the ones (1) are where data
is available for processing.</p>
<h3>Level triggered</h3>
<p>Level triggered devices when they require attention, and until they no longer
require attention will signal with a high voltage (going back to early
electronics), and when they no longer require attention signal with a low
voltage.</p>
<div class="codehilite"><pre><span class="n">Data</span><span class="o">:</span>  <span class="mi">00000000001111111111111111111111000000000011111111111000000000</span>
<span class="n">Block</span><span class="o">:</span>      <span class="n">A</span>               <span class="n">B</span>              <span class="n">C</span>         <span class="n">D</span>
<span class="o">+</span> <span class="mi">5</span><span class="n">v</span>              <span class="n">____________________</span>           <span class="n">_________</span>
  <span class="o">-</span>    <span class="n">__________</span><span class="o">|</span>                    <span class="o">|</span><span class="n">_________</span><span class="o">|</span>         <span class="o">|</span><span class="n">__________</span>
  <span class="mi">0</span><span class="n">v</span>
<span class="n">State</span><span class="o">:</span> <span class="mi">0</span>          <span class="mi">1</span>                    <span class="mi">0</span>          <span class="mi">1</span>        <span class="mi">0</span>
</pre></div>


<p>At this point, once the signal turns to 1 in block B we can start processing
data, and until we are done processing data the signal will stay 1. Once we are
done processing the device will signal that we are done by setting the state to
0 in block C, and the process can repeat itself with block D.</p>
<h3>Edge triggered</h3>
<p>Edge triggered devices when they require attention will simply turn on the
signal for a short period of time and then turn it back off until all of the
requireding processing is complete at which point they will once again signal
that they need processing.</p>
<div class="codehilite"><pre><span class="n">Data</span><span class="o">:</span>  <span class="mi">00000000001111111111111111111111100000000011111111111000000000</span>
<span class="n">Block</span><span class="o">:</span>      <span class="n">A</span>     <span class="n">B</span>              <span class="n">C</span>                 <span class="n">D</span>
<span class="o">+</span> <span class="mi">5</span><span class="n">v</span>              <span class="n">__</span>                              <span class="n">__</span>
  <span class="o">-</span>    <span class="n">__________</span><span class="o">|</span>  <span class="o">|</span><span class="n">____________________________</span><span class="o">|</span>  <span class="o">|</span><span class="n">________________</span>
  <span class="mi">0</span><span class="n">v</span>
<span class="n">State</span><span class="o">:</span> <span class="mi">0</span>          <span class="mi">1</span>              <span class="mi">0</span>                <span class="mi">1</span>        <span class="mi">0</span>
</pre></div>


<p>In this case when the trigger arrives you have to process all of the data
available. When block B arrives and we get 1 as our signal, we have to process
all of the data, we won't know when we are done other than some other
notification scheme by the device. (Such as a special message that says we are
done). Then when we are done we can go back to listening to waiting for a
trigger.</p>
<p>If however in the time that we are processing the data from the trigger at B
receive more data to process we won't get notified because we weren't
officially done processing data from the device, and thus the device will not
notify us of the new data again until we have processed all of the data.</p>
<p>There are some devices that as soon as you start processing their data, you
re-enable the trigger, so if you receive new data while still processing the
old you will get a new notification.</p>
<h2>ZeroMQ uses edge triggered</h2>
<p>When multiple message arrive for the ZeroMQ socket, one notification is sent.
You check to see if the <code>ZMQ_EVENTS</code> actually contains <code>ZMQ_POLLIN</code> and then
read a single message from ZeroMQ. Content that you have processed the data
ZeroMQ has for you, you add the file descriptor back to the event notification
library and wait. However, you know you sent two messages, but all you got was
one. The next time you send data to the socket, it returns the second message,
and you have now send three but the third doesn't seem to arrive.</p>
<p>This is where the edge triggered comes in. ZeroMQ only notifies you once, and
after it has notified you it won't notify you again until it receives new
messages, <em>EVEN</em> if you have messages waiting for you. In BSD sockets when you
<code>recv()</code> data from the socket, if it is not all of the data it will simply tell
you, and until all of the data has been read that the socket has to offer it is
going to tell you (level triggered).</p>
<p>This means that when you get a notification from ZeroMQ you have to use a loop
to process all of the messages that are coming your way:</p>
<div class="codehilite"><pre><span class="kt">int</span> <span class="n">zevents</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="n">size_t</span> <span class="n">zevents_len</span> <span class="o">=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">zevents</span><span class="p">);</span>
<span class="n">zmq_socket</span><span class="p">.</span><span class="n">getsockopt</span><span class="p">(</span><span class="n">ZMQ_EVENTS</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents_len</span><span class="p">);</span>

<span class="k">do</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">zevents</span> <span class="o">&amp;</span> <span class="n">ZMQ_POLLIN</span><span class="p">)</span> <span class="p">{</span>
        <span class="c1">// We can read from the ZeroMQ socket</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c1">// Check to see if there is more to read ...</span>
    <span class="n">zmq_socket</span><span class="p">.</span><span class="n">getsockopt</span><span class="p">(</span><span class="n">ZMQ_EVENTS</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">zevents_len</span><span class="p">);</span>
<span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="n">zevents</span> <span class="o">&amp;</span> <span class="n">ZMQ_POLLIN</span><span class="p">);</span>

<span class="k">if</span> <span class="p">(</span><span class="n">zevents</span> <span class="o">&amp;</span> <span class="n">ZMQ_POLLOUT</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// We can write to the ZeroMQ socket</span>
<span class="p">}</span>

<span class="c1">// If neither of the above is true, then it was a false positive</span>
</pre></div>


<p>The same is true if you need to send multiple messages, you will need to check
<code>ZMQ_EVENTS</code> for <code>ZMQ_POLLOUT</code> and send messages so long as that holds true, as
soon as it is no longer true you will need to wait until you get triggered
again by using the file descriptor in your event notification library.</p>
<h2>Embedding or co-existing with another event loop</h2>
<p>Embedding ZeroMQ into a different event loop becomes more difficult when you
realise that it is edge triggered versus level triggered. If you want to allow
fair processing of data between events it becomes harder to accomplish with
ZeroMQ because you are required to process all of the data before going back to
your event loop or requires the setting up of different types of events
depending on the state that the ZeroMQ socket is in to make sure you process
all of the data and don't forget any.</p>
<p>Edge triggered for the ZeroMQ file descriptor was a design decision which
unfortunately made the use of ZeroMQ sockets more difficult and different from
BSD sockets which makes it harder for application programmers to do the right
thing. There are plenty of questions on the internet regarding the proper usage
of <code>ZMQ_FD</code> with various different event notification schemes/implementations.</p>]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://funcptr.net/</uri>
    </author>
    <title type="html"><![CDATA[IPv6 -- getaddrinfo() and bind() ordering with V6ONLY]]></title>
    <link rel="alternate" type="text/html" href="http://funcptr.net/2012/08/07/ipv6----getaddrinfo()-and-bind()-ordering-with-v6only" />
    <id>http://funcptr.net/2012/08/07/ipv6----getaddrinfo()-and-bind()-ordering-with-v6only</id>
    <updated>2012-08-07T22:39:56Z</updated>
    <published>2012-08-07T22:39:56Z</published>
    <category scheme="http://funcptr.net/" term="C" />
    <category scheme="http://funcptr.net/" term="IPv6" />
    <category scheme="http://funcptr.net/" term="OpenIndiana" />
    <category scheme="http://funcptr.net/" term="OpenSolaris" />
    <category scheme="http://funcptr.net/" term="FreeBSD" />
    <category scheme="http://funcptr.net/" term="Linux" />
    <summary type="html"><![CDATA[IPv6 -- getaddrinfo() and bind() ordering with V6ONLY]]></summary>
    <content type="html" xml:base="http://funcptr.net/2012/08/07/ipv6----getaddrinfo()-and-bind()-ordering-with-v6only"><![CDATA[<p>Recently I ran into an issue that took me a while to sort out, and it is
regarding inconsistent behaviour on various OS's with regards to IPv6 sockets
(<a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_socket.h.html"><code>AF_INET6</code></a><sup id="fnref:20120807afvspf"><a href="#fn:20120807afvspf" rel="footnote">1</a></sup>) and calling <a href="http://www.freebsd.org/cgi/man.cgi?query=bind&amp;apropos=0&amp;sektion=2&amp;manpath=FreeBSD+9.0-RELEASE&amp;arch=default&amp;format=html"><code>bind(2)</code></a> after getting the
results back from <a href="http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&amp;apropos=0&amp;sektion=3&amp;manpath=FreeBSD+9.0-RELEASE&amp;arch=default&amp;format=html"><code>getaddrinfo(3)</code></a>.</p>
<p>A call to <code>getaddrinfo()</code> with the hints set to <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_socket.h.html"><code>AF_UNSPEC</code></a> in <code>ai_family</code>
and <a href="http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&amp;apropos=0&amp;sektion=3&amp;manpath=FreeBSD+9.0-RELEASE&amp;arch=default&amp;format=html"><code>AI_PASSIVE</code></a> in <code>ai_flags</code> will return to us 1 or more results that we
can <code>bind()</code> to. Sample code for that looks like this:</p>
<table class="codehilitetable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29</pre></div></td><td class="code"><div class="codehilite"><pre><span class="k">struct</span> <span class="n">addrinfo</span> <span class="n">hints</span><span class="p">,</span> <span class="o">*</span><span class="n">addrlist</span><span class="p">;</span>

<span class="n">memset</span><span class="p">(</span><span class="o">&amp;</span><span class="n">hints</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">hints</span><span class="p">));</span>

<span class="c1">// Ask for TCP</span>
<span class="n">hints</span><span class="p">.</span><span class="n">ai_socktype</span> <span class="o">=</span> <span class="n">SOCK_STREAM</span><span class="p">;</span>

<span class="c1">// Any family works for us ...</span>
<span class="n">hints</span><span class="p">.</span><span class="n">ai_family</span> <span class="o">=</span> <span class="n">AF_UNSPEC</span><span class="p">;</span>

<span class="c1">// Set some hints</span>
<span class="n">hints</span><span class="p">.</span><span class="n">ai_flags</span> <span class="o">=</span> 
            <span class="n">AI_PASSIVE</span>    <span class="o">|</span> <span class="c1">// We want to use this with bind</span>
            <span class="n">AI_ADDRCONFIG</span><span class="p">;</span>  <span class="c1">// Only return IPv4 or IPv6 if they are configured</span>

<span class="kt">int</span> <span class="n">rv</span><span class="p">;</span>

<span class="k">if</span> <span class="p">((</span><span class="n">rv</span> <span class="o">=</span> <span class="n">getaddrinfo</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="s">&quot;7020&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">hints</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">addrlist</span><span class="p">))</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;getaddrinfo: %s&quot;</span><span class="p">,</span> <span class="n">gai_strerror</span><span class="p">(</span><span class="n">rv</span><span class="p">));</span>
    <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">// Use the list in *addrlist</span>
<span class="k">for</span> <span class="p">(</span><span class="n">addr</span> <span class="o">=</span> <span class="n">addrlist</span><span class="p">;</span> <span class="n">addr</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">addr</span> <span class="o">=</span> <span class="n">addr</span><span class="o">-&gt;</span><span class="n">ai_next</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// use *addr as appropriate</span>
<span class="p">}</span>

<span class="c1">// Clean up the memory from getaddrinfo()</span>
<span class="n">freeaddrinfo</span><span class="p">(</span><span class="n">addrlist</span><span class="p">);</span>
</pre></div>
</td></tr></table>

<p>On Linux there are two entries returned when the host it is run on has both
IPv4 and IPv6 enabled. An <code>AF_INET</code> which was followed by an <code>AF_INET6</code>. Now,
it is not said that you are required to use all of the results that are
returned, but if you want to listen on all address families it is off course
suggested.</p>
<p>Following the steps below for each of the returned results should result in
having 1 or more different sockets that are bound to a single port.</p>
<ol>
<li>Create the socket()</li>
<li>Set any socket options you want (<code>SO_REUSEADDR</code> for example)</li>
<li>Then bind() the socket</li>
<li>After that call listen() (followed off course by accept() on the socket)</li>
</ol>
<p>Only for some unknown reason (and <code>errno</code> is no help) <code>bind()</code> fails when you
get to the <code>AF_INET6</code>, which was returned second. Searching online as to why
the bind would fail doesn't give you any good results and the thing that is
even worse is that if you run the same code on another platform such as
<a href="http://www.freebsd.org">FreeBSD</a>, <a href="http://openindiana.org">OpenIndiana</a> or <a href="http://www.apple.com/osx/">Mac OS X</a> no such failure exists. However
I started suspecting something was up when I started looking at the output from
<code>netstat -lan | grep 7020</code> on Mac OS X. Where 7020 is the port I passed into
<code>getaddrinfo()</code>.</p>
<div class="codehilite"><pre>tcp46      0      0  *.7020                 *.*  LISTEN     
tcp4       0      0  *.7020                 *.*  LISTEN
</pre></div>


<p>Wait a minute ... one of the sockets is on both IPv4 and on IPv6. Some more
time spent searching the internet I came across <a href="http://tools.ietf.org/html/rfc3493#page-22">RFC 3493 section 5.3</a>,
which is titled "<code>IPV6_V6ONLY</code> option for <code>AF_INET6</code> Sockets".</p>
<blockquote>
<p>As stated in section &lt;3.7 Compatibility with IPv4 Nodes&gt;, <code>AF_INET6</code> sockets
may be used for both IPv4 and IPv6 communications.  Some applications may
want to restrict their use of an <code>AF_INET6</code> socket to IPv6 communications
only.</p>
</blockquote>
<p>This was going down the right route, so I changed my code so that in the steps
listed above in number 2 I added the following code if the socket type is
<code>AF_INET6</code>:</p>
<table class="codehilitetable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5</pre></div></td><td class="code"><div class="codehilite"><pre><span class="k">if</span> <span class="p">(</span><span class="n">setsockopt</span><span class="p">(</span><span class="n">sockfd</span><span class="p">,</span> <span class="n">IPPROTO_IPV6</span><span class="p">,</span> <span class="n">IPV6_V6ONLY</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">yes</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="kt">int</span><span class="p">))</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">close</span><span class="p">(</span><span class="n">sockfd</span><span class="p">);</span>
    <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;setsockopt: %s IPV6_V6ONLY</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">strerror</span><span class="p">(</span><span class="n">errno</span><span class="p">));</span>
    <span class="k">continue</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</td></tr></table>

<p>The RFC 3493 section 5.3 also states that this option should be turned off by
default, which means that all IPv6 sockets can also communicate over IPv4. Thus
technically setting the option manually in code the best way to fix the issue.
FreeBSD has had this feature turned on (as in IPv6 sockets can only communicate
with IPv6 and NOT IPv4) since 5.x.</p>
<p>The biggest issue is that the remaining operating systems (OS X and
OpenIndiana) don't have the same behaviour as Linux which makes troubleshooting
this issue more difficult than it should be. The issue is that the RFC doesn't
specify what exactly the operating should do when it encounters a request to
bind to the same port on IPv4 and IPv6. The only place where I have found this
documented is in <a href="http://www.amazon.com/Network-Programming-Jun-ichiro-itojun-Hagino/dp/1555583180">"IPv6 Network Programming"</a> under "Tips in IPv6
Programming" chapter 4, section 4, appropriately titled "bind(2) Ordering and
Conflicts".</p>
<hr />
<p>If you get a <code>bind()</code> error when attempting to bind to an <code>AF_INET6</code> socket
please make sure that you set the socket option <code>IPV6_V6ONLY</code> on the <code>AF_INET6</code>
socket. The default as required by RFC 3493 is to have that option be off. The
default is wrong, and the RFC should have been more specific regarding what the
right behaviour is when attempting to bind on an <code>AF_INET6</code> socket when already
bound on an <code>AF_INET</code> while <code>IPV6_V6ONLY</code> is set to false.</p>
<p>The full code that I used for testing, along with a little bit more information
is available as a <a href="https://gist.github.com/3231892">gist on github</a>.</p>
<div class="footnote">
<hr />
<ol>
<li id="fn:20120807afvspf">
<p>The old BSD style <a href="http://www.freebsd.org/cgi/man.cgi?query=socket&amp;apropos=0&amp;sektion=2&amp;manpath=FreeBSD+9.0-RELEASE&amp;arch=default&amp;format=html"><code>socket()</code></a> called for defines
starting with <code>PF_</code> such as <code>PF_INET</code> and <code>PF_INET6</code> with the <code>PF</code> standing for
protocol family. POSIX starts them with <code>AF_</code>, and calls them an address
family. On almost every operating system <code>PF_INET</code> is the same as <code>AF_INET</code>. If
the define doesn't exist you can always create it.&#160;<a href="#fnref:20120807afvspf" rev="footnote" title="Jump back to footnote 1 in the text">&#8617;</a></p>
</li>
</ol>
</div>]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://funcptr.net/</uri>
    </author>
    <title type="html"><![CDATA[FreeBSD 8.2 to 9.0 update with ZFS on root (mirror)]]></title>
    <link rel="alternate" type="text/html" href="http://funcptr.net/2012/04/24/freebsd-8.2-to-9.0-update-with-zfs-on-root-(mirror)" />
    <id>http://funcptr.net/2012/04/24/freebsd-8.2-to-9.0-update-with-zfs-on-root-(mirror)</id>
    <updated>2012-04-24T18:36:20Z</updated>
    <published>2012-04-24T18:36:20Z</published>
    <category scheme="http://funcptr.net/" term="ZFS" />
    <category scheme="http://funcptr.net/" term="FreeBSD" />
    <category scheme="http://funcptr.net/" term="freebsd-update" />
    <summary type="html"><![CDATA[FreeBSD 8.2 to 9.0 update with ZFS on root (mirror)]]></summary>
    <content type="html" xml:base="http://funcptr.net/2012/04/24/freebsd-8.2-to-9.0-update-with-zfs-on-root-(mirror)"><![CDATA[<p>Upgrading from one version of FreeBSD to another has become much simpler with
<a href="http://www.daemonology.net/freebsd-update/"><code>freebsd-update</code></a> than before, a full rebuild of the FreeBSD kernel/world
source used to be required (other upgrade paths existed but were not widely
touted). <code>freebsd-update</code> works extremely well when using UFS as your file
system, there are however some gotcha's that one needs to look out for when
using FreeBSD Root on ZFS. Two machines needed upgrading, both are running with
a ZFS root mirror on FreeBSD 8.2-RELEASE. I had followed the <a href="http://wiki.freebsd.org/RootOnZFS/GPTZFSBoot/Mirror">FreeBSD Root on
ZFS (mirror)</a> wiki article and everything has been running smoothly ever
since.</p>
<div class="codehilite"><pre>  <span class="n">pool</span><span class="p">:</span> <span class="n">zroot</span>
 <span class="n">state</span><span class="p">:</span> <span class="n">ONLINE</span>
 <span class="n">scrub</span><span class="p">:</span> <span class="n">scrub</span> <span class="n">completed</span> <span class="n">after</span> 0<span class="n">h35m</span> <span class="n">with</span> 0 <span class="n">errors</span> <span class="n">on</span> <span class="n">Mon</span> <span class="n">Mar</span>  5 10<span class="p">:</span>58<span class="p">:</span>19 2012
<span class="n">config</span><span class="p">:</span>

    <span class="n">NAME</span>           <span class="n">STATE</span>     <span class="n">READ</span> <span class="n">WRITE</span> <span class="n">CKSUM</span>
    <span class="n">zroot</span>          <span class="n">ONLINE</span>       0     0     0
      <span class="n">mirror</span>       <span class="n">ONLINE</span>       0     0     0
        <span class="n">gpt</span><span class="o">/</span><span class="n">disk0</span>  <span class="n">ONLINE</span>       0     0     0
        <span class="n">gpt</span><span class="o">/</span><span class="n">disk1</span>  <span class="n">ONLINE</span>       0     0     0

<span class="n">errors</span><span class="p">:</span> <span class="n">No</span> <span class="n">known</span> <span class="n">data</span> <span class="n">errors</span>
</pre></div>


<p>Wanting to take advantage of some of the advancements made in <a href="http://www.freebsd.org/releases/9.0R/announce.html">FreeBSD
9.0-RELEASE</a> such as the updated ZFS, a bug that was fixed that stopped
jails from owning a ZFS file system, improved dtrace, and better IPv6 support
required that the plunge be taken and an upgrade was in order.  There were a
couple reports of people having done source upgrades and then having issues
booting their system, but I found one <a href="http://lists.freebsd.org/pipermail/freebsd-questions/2012-January/237308.html">mailling list post</a> that suggested
that everything went well using <code>freebsd-update</code>, so that is the route I went
with.</p>
<p>I read through the entirety of the <a href="http://www.FreeBSD.org/releases/9.0R/relnotes-detailed.html#UPGRADE">FreeBSD 9.0-ERLEASE Release Notes</a>
before moving forward to make sure I didn't miss any important changes that
would cause my system to not restart correctly or would require changing system
configuration files before attempting the upgrade. I would advise you to do the
same.</p>
<p>I ran <code>freebsd-update -r 9.0-RELEASE upgrade</code> and after accepting the list of
components that were installed, I got an error saying:</p>
<div class="codehilite"><pre><span class="c"># freebsd-update -r 9.0-RELEASE upgrade</span>
<span class="n">Looking</span> <span class="n">up</span> <span class="n">update</span><span class="p">.</span><span class="n">FreeBSD</span><span class="p">.</span><span class="n">org</span> <span class="n">mirrors</span><span class="p">...</span> 4 <span class="n">mirrors</span> <span class="n">found</span><span class="p">.</span>
<span class="n">Fetching</span> <span class="n">metadata</span> <span class="n">signature</span> <span class="k">for</span> 8<span class="p">.</span>2<span class="o">-</span><span class="n">RELEASE</span> <span class="n">from</span> <span class="n">update2</span><span class="p">.</span><span class="n">freebsd</span><span class="p">.</span><span class="n">org</span><span class="p">...</span> <span class="n">done</span><span class="p">.</span>
<span class="n">Fetching</span> <span class="n">metadata</span> <span class="nb">index</span><span class="p">...</span> <span class="n">done</span><span class="p">.</span>
<span class="n">Inspecting</span> <span class="nb">system</span><span class="p">...</span> <span class="n">done</span><span class="p">.</span>

<span class="n">The</span> <span class="n">following</span> <span class="n">components</span> <span class="n">of</span> <span class="n">FreeBSD</span> <span class="n">seem</span> <span class="n">to</span> <span class="n">be</span> <span class="n">installed</span><span class="p">:</span>
<span class="n">kernel</span><span class="o">/</span><span class="n">generic</span> <span class="n">src</span><span class="o">/</span><span class="n">base</span> <span class="n">src</span><span class="o">/</span><span class="n">bin</span> <span class="n">src</span><span class="o">/</span><span class="n">cddl</span> <span class="n">src</span><span class="o">/</span><span class="n">contrib</span> <span class="n">src</span><span class="o">/</span><span class="n">crypto</span> <span class="n">src</span><span class="o">/</span><span class="n">etc</span>
<span class="n">src</span><span class="o">/</span><span class="n">games</span> <span class="n">src</span><span class="o">/</span><span class="n">gnu</span> <span class="n">src</span><span class="o">/</span><span class="n">include</span> <span class="n">src</span><span class="o">/</span><span class="n">krb5</span> <span class="n">src</span><span class="o">/</span><span class="n">lib</span> <span class="n">src</span><span class="o">/</span><span class="n">libexec</span> <span class="n">src</span><span class="o">/</span><span class="n">release</span>
<span class="n">src</span><span class="o">/</span><span class="n">rescue</span> <span class="n">src</span><span class="o">/</span><span class="n">sbin</span> <span class="n">src</span><span class="o">/</span><span class="n">secure</span> <span class="n">src</span><span class="o">/</span><span class="n">share</span> <span class="n">src</span><span class="o">/</span><span class="n">sys</span> <span class="n">src</span><span class="o">/</span><span class="n">tools</span> <span class="n">src</span><span class="o">/</span><span class="n">ubin</span>
<span class="n">src</span><span class="o">/</span><span class="n">usbin</span> <span class="n">world</span><span class="o">/</span><span class="n">base</span> <span class="n">world</span><span class="o">/</span><span class="n">catpages</span> <span class="n">world</span><span class="o">/</span><span class="n">dict</span> <span class="n">world</span><span class="o">/</span><span class="n">doc</span> <span class="n">world</span><span class="o">/</span><span class="n">games</span>
<span class="n">world</span><span class="o">/</span><span class="nb">info</span> <span class="n">world</span><span class="o">/</span><span class="n">lib32</span> <span class="n">world</span><span class="o">/</span><span class="n">manpages</span>

<span class="n">The</span> <span class="n">following</span> <span class="n">components</span> <span class="n">of</span> <span class="n">FreeBSD</span> <span class="k">do</span> <span class="nb">not</span> <span class="n">seem</span> <span class="n">to</span> <span class="n">be</span> <span class="n">installed</span><span class="p">:</span>
<span class="n">world</span><span class="o">/</span><span class="n">proflibs</span>

<span class="n">Does</span> <span class="n">this</span> <span class="n">look</span> <span class="n">reasonable</span> <span class="p">(</span><span class="n">y</span><span class="o">/</span><span class="n">n</span><span class="p">)</span>? <span class="n">y</span>

<span class="n">Fetching</span> <span class="n">metadata</span> <span class="n">signature</span> <span class="k">for</span> 9<span class="p">.</span>0<span class="o">-</span><span class="n">RELEASE</span> <span class="n">from</span> <span class="n">update2</span><span class="p">.</span><span class="n">freebsd</span><span class="p">.</span><span class="n">org</span><span class="p">...</span> <span class="n">done</span><span class="p">.</span>
<span class="n">Fetching</span> <span class="n">metadata</span> <span class="nb">index</span><span class="p">...</span> <span class="n">done</span><span class="p">.</span>

<span class="n">The</span> <span class="n">update</span> <span class="n">metadata</span> <span class="n">is</span> <span class="n">correctly</span> <span class="n">signed</span><span class="p">,</span> <span class="n">but</span>
<span class="n">failed</span> <span class="n">an</span> <span class="n">integrity</span> <span class="n">check</span><span class="p">.</span>
<span class="n">Cowardly</span> <span class="n">refusing</span> <span class="n">to</span> <span class="n">proceed</span> <span class="nb">any</span> <span class="n">further</span><span class="p">.</span>
</pre></div>


<p>Specifically the line stating "Cowardly refusing to proceed further", a quick
<a href="http://google.com/">Google</a> later I found the <a href="http://lists.freebsd.org/pipermail/freebsd-stable/2011-October/064321.html">9.0-RC1 mailling list post</a> that suggested
the following one line fix:</p>
<div class="codehilite"><pre><span class="n">sed</span> <span class="o">-</span><span class="nb">i</span> <span class="s">&#39;&#39;</span> <span class="o">-</span><span class="n">e</span> <span class="s">&#39;s/=_/=%@_/&#39;</span> <span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="n">sbin</span><span class="o">/</span><span class="n">freebsd</span><span class="o">-</span><span class="n">update</span>
</pre></div>


<p>After that quick fix, a re-run of <code>freebsd-update</code> functioned without issues
and finished, showing me what it would change, asking me if it seemed
acceptable and telling me what it was going to remove and what was going to be
installed.</p>
<p>Next we run <code>freebsd-update</code> for the first time in this three step process:</p>
<div class="codehilite"><pre><span class="n">freebsd</span><span class="o">-</span><span class="n">update</span> <span class="n">install</span>
</pre></div>


<p>Don't restart yet (although it tells you to)! We need to go back and make sure
we update the boot records first.</p>
<p>Going back to the <a href="http://lists.freebsd.org/pipermail/freebsd-questions/2012-January/237308.html">mailling list post made by Magnus Strahlert</a>, I made note
of the following: </p>
<blockquote>
<p>Had to upgrade the gpt bootcode as instructed when upgrading the zpool for
the system to boot.</p>
</blockquote>
<p>This is the only comment that worried me, and nowhere in the email thread does
the poster describe what commands he ran. In any case I figure he meant
re-running the boot code commands from the FreeBSD Root on ZFS wiki article:</p>
<div class="codehilite"><pre><span class="n">gpart</span> <span class="n">bootcode</span> <span class="o">-</span><span class="n">b</span> <span class="o">/</span><span class="n">boot</span><span class="o">/</span><span class="n">pmbr</span> <span class="o">-</span><span class="n">p</span> <span class="o">/</span><span class="n">boot</span><span class="o">/</span><span class="n">gptzfsboot</span> <span class="o">-</span><span class="nb">i</span> 1 <span class="n">da0</span>
<span class="n">gpart</span> <span class="n">bootcode</span> <span class="o">-</span><span class="n">b</span> <span class="o">/</span><span class="n">boot</span><span class="o">/</span><span class="n">pmbr</span> <span class="o">-</span><span class="n">p</span> <span class="o">/</span><span class="n">boot</span><span class="o">/</span><span class="n">gptzfsboot</span> <span class="o">-</span><span class="nb">i</span> 1 <span class="n">da1</span>
</pre></div>


<p>After running these commands, it told me that it had updated the boot code and then I ran:</p>
<div class="codehilite"><pre><span class="n">shutdown</span> <span class="o">-</span><span class="n">r</span> <span class="n">now</span>
</pre></div>


<p>After the machine came back online (it is in those moments when you have a
small heartattack when the machine doesn't come up as fast as you had expected
...) you log back in and run:</p>
<div class="codehilite"><pre><span class="n">freebsd</span><span class="o">-</span><span class="n">update</span> <span class="n">install</span>
</pre></div>


<p>This will install all of the updated binaries that came with FreeBSD 9.0, at
this point FreeBSD update will tell you to upgrade all installed software and
ports, and then run <code>freebsd-update</code> one more time to remove all unnecessary
shared libraries. If you want to have certain software continue functioning,
yet you want <code>freebsd-update</code> to remove any other remaining old 8.x files, you
can install <a href="http://www.freshports.org/misc/compat8x/"><code>misc/compat8x</code></a> from the ports tree. This is the suggested
route to go if you want to keep the 8.x libraries around for compatibility
reasons.</p>
<div class="codehilite"><pre><span class="n">cd</span> <span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="n">ports</span><span class="o">/</span><span class="n">misc</span><span class="o">/</span><span class="n">compat8x</span>
<span class="n">make</span> <span class="n">install</span> <span class="n">clean</span>
# <span class="n">or</span>
# <span class="n">portmaster</span> <span class="n">misc</span><span class="o">/</span><span class="n">compat8x</span>
</pre></div>


<p>I use <code>portmaster</code> and the following command will simply rebuild every port
installed on the system:</p>
<div class="codehilite"><pre><span class="n">portmaster</span> <span class="o">-</span><span class="n">aPf</span> # <span class="o">-</span><span class="n">P</span> <span class="n">means</span> <span class="n">look</span> <span class="k">for</span> <span class="n">package</span> <span class="n">and</span> <span class="k">if</span> <span class="n">available</span> <span class="n">use</span> <span class="n">it</span><span class="p">,</span> <span class="k">otherwise</span> <span class="n">build</span> <span class="n">from</span> <span class="n">port</span>
</pre></div>


<p>Run <code>freebsd-update</code> one last time:</p>
<div class="codehilite"><pre><span class="n">freebsd</span><span class="o">-</span><span class="n">update</span> <span class="n">install</span>
</pre></div>


<p>Since we are running ZFS we will most likely also want to upgrade our pool to
the latest version of ZFS to take advantage of any new goodies (such as
deduplication!), upgrading a zpool is easy:</p>
<div class="codehilite"><pre><span class="n">zpool</span> <span class="n">upgrade</span> <span class="n">zroot</span>
</pre></div>


<p>That upgrades to the latest pool version, now we will want to upgrade our
existing file systems to the latest version of ZFS, do note that this will make
them incompatible with older file system verisons (so if you use zfs send for
backups, your other endpoint will need to be of the same ZFS version)</p>
<div class="codehilite"><pre><span class="n">zfs</span> <span class="n">upgrade</span> # <span class="n">List</span> <span class="n">all</span> <span class="n">ZFS</span> <span class="n">file</span> <span class="n">systems</span> <span class="n">that</span> <span class="n">need</span> <span class="n">to</span> <span class="n">be</span> <span class="n">upgraded</span>
<span class="n">zfs</span> <span class="n">upgrade</span> <span class="o">-</span><span class="n">a</span> # <span class="n">Upgrade</span> <span class="n">all</span> <span class="n">file</span> <span class="n">systems</span>
</pre></div>


<p>After this one last reboot to make sure that all the processes come back online
using the newer libraries and that you didn't accidentally miss something.</p>
<div class="codehilite"><pre><span class="n">shutdown</span> <span class="o">-</span><span class="n">r</span> <span class="n">now</span>
</pre></div>


<p>At this point the system has been upgraded from FreeBSD 8.0-RELEASE to FreeBSD
\9.0-RELEASE and has all of the latest updates and enhancements.</p>]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://funcptr.net/</uri>
    </author>
    <title type="html"><![CDATA[OpenSSL as a Filter (or non-blocking OpenSSL)]]></title>
    <link rel="alternate" type="text/html" href="http://funcptr.net/2012/04/08/openssl-as-a-filter-(or-non-blocking-openssl)" />
    <id>http://funcptr.net/2012/04/08/openssl-as-a-filter-(or-non-blocking-openssl)</id>
    <updated>2012-04-08T16:50:14Z</updated>
    <published>2012-04-08T16:50:14Z</published>
    <category scheme="http://funcptr.net/" term="C" />
    <category scheme="http://funcptr.net/" term="programming" />
    <category scheme="http://funcptr.net/" term="OpenSSL" />
    <category scheme="http://funcptr.net/" term="C++" />
    <summary type="html"><![CDATA[OpenSSL as a Filter (or non-blocking OpenSSL)]]></summary>
    <content type="html" xml:base="http://funcptr.net/2012/04/08/openssl-as-a-filter-(or-non-blocking-openssl)"><![CDATA[<p><a href="http://openssl.org/">OpenSSL</a> as a library at first glance is complicated, and then you realise
that a lot of the <a href="http://openssl.org/docs/ssl/ssl.html" title="ssl(3) documentation">documentation</a> seems to be incomplete or missing.
Generally the individual man pages for the various functions are not bad, and
they will give you relevant information to help you along, but it can be hard
to find.</p>
<p>The idea is to write a filter in such a way that OpenSSL can easily be disabled
or removed. We don't want to rely on OpenSSL specific functionality in our
code, for instance in the future we may want to change to using <a href="http://botan.randombit.net/">Botan</a> or
another SSL/TLS library without having to change a lot of core functionality.</p>
<h2>Possible methods</h2>
<p>There are various ways of doing non-blocking OpenSSL, the main one is to simply
set the underlying socket to non-blocking and pass it into OpenSSL, at that
point the functions <code>SSL_write()</code> and <code>SSL_read()</code> will enter various error
states that can be read by <a href="http://www.openssl.org/docs/ssl/SSL_get_error.html"><code>SSL_get_error()</code></a>, more specifically the
function will return either <code>SSL_ERROR_WANT_READ</code> or <code>SSL_ERROR_WANT_WRITE</code>.</p>
<p>The other method, the one used below, was described by <a href="http://lists.schmorp.de/pipermail/libev/2008q2/000325.html">Marc Lehmann in a post
to the libev mailling list</a> and uses <a href="http://www.openssl.org/docs/crypto/bio.html">memory BIO</a> objects. Specifically
he linked to some Perl sample code; the OpenSSL <a href="http://ue.tst.eu/f7383715351b4427b6b9db660b6289f8.txt">setup</a>, and the function
called for new incoming data/data to be written: <a href="http://ue.tst.eu/2f4cfee5166db411bd85a40e06de6dbf.txt">dotls function</a>.</p>
<blockquote>
<p>The code is very new and might still be buggy, but it outlines the
principles: use a memory stream, which will avoid all issues with blocking in
openssl</p>
</blockquote>
<p>It shows the idea pretty clearly but unless you know Perl it can be really
confusing as to what is going on.</p>
<h2>The SSL Filter implementation</h2>
<p>The <a href="http://www.openssl.org/docs/ssl/SSL_CTX_new.html"><code>SSL_CTX</code></a> that is passed in contains all of the initialisation that is
done for OpenSSL in general, which is not shown here. The <code>SSLFilter</code> is
created for each time you want to have a socket start doing SSL.</p>
<table class="codehilitetable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25</pre></div></td><td class="code"><div class="codehilite"><pre><span class="c1">// openssl_filter.h</span>

<span class="k">class</span> <span class="nc">SSLFilter</span> <span class="p">{</span>
    <span class="k">public</span><span class="o">:</span>
        <span class="n">SSLFilter</span><span class="p">(</span><span class="n">SSL_CTX</span><span class="o">*</span> <span class="n">ctxt</span><span class="p">,</span>
                  <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">*</span> <span class="n">nread</span><span class="p">,</span>
                  <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">*</span> <span class="n">nwrite</span><span class="p">,</span>
                  <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">*</span> <span class="n">aread</span><span class="p">,</span>
                  <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">*</span> <span class="n">awrite</span><span class="p">);</span>
        <span class="k">virtual</span> <span class="o">~</span><span class="n">SSLFilter</span><span class="p">();</span>

        <span class="kt">void</span> <span class="n">update</span><span class="p">();</span>

    <span class="k">private</span><span class="o">:</span>
        <span class="kt">bool</span> <span class="n">continue_ssl_</span><span class="p">(</span><span class="kt">int</span> <span class="n">function_return</span><span class="p">);</span>

        <span class="n">SSL</span> <span class="o">*</span> <span class="n">ssl</span><span class="p">;</span>
        <span class="n">BIO</span> <span class="o">*</span> <span class="n">rbio</span><span class="p">;</span>
        <span class="n">BIO</span> <span class="o">*</span> <span class="n">wbio</span><span class="p">;</span>

        <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">*</span> <span class="n">nread</span><span class="p">;</span>
        <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">*</span> <span class="n">nwrite</span><span class="p">;</span>
        <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">*</span> <span class="n">aread</span><span class="p">;</span>
        <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">*</span> <span class="n">awrite</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>
</td></tr></table>

<p>The class contains mainly various different bits of state, when you create the
filter you pass in a pointer to four different strings, they are used as
follows:</p>
<ul>
<li><code>nread</code>: This contains data to be processed by the filter, from the network</li>
<li><code>nwrite</code>: This contains data that has been processed by the filter, and has
   to be sent to the network</li>
<li><code>aread</code>: This contains data that has been processed by the filter, and is
   ready to be processed by the application</li>
<li><code>awrite</code>: This contains data that the application wants to send out to the
   network and is ready for processing by the filter.</li>
</ul>
<p>The other private variables contain various different pieces of state and are
created by the filters constructors.</p>
<ul>
<li><code>ssl</code>: Contains the state for the current SSL connection.</li>
<li><code>rbio</code>: Contains the data that the SSL functions will read from, data put in
   here is copied from <code>nread</code>.</li>
<li><code>wbio</code>: Contains the data that the SSL functions will write to, data from
   this BIO is copied to <code>nwrite</code>.</li>
</ul>
<p>The implementation is the really interesting part.</p>
<table class="codehilitetable"><tr><td class="linenos"><div class="linenodiv"><pre>  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105</pre></div></td><td class="code"><div class="codehilite"><pre><span class="c1">// openssl_filter.cc</span>

<span class="cp">#include &lt;stdexcept&gt;</span>

<span class="cp">#include &quot;openssl_filter.h&quot;</span>

<span class="n">SSLFilter</span><span class="o">::</span><span class="n">SSLFilter</span><span class="p">(</span><span class="n">SSL_CTX</span><span class="o">*</span> <span class="n">ctxt</span><span class="p">,</span> 
                     <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">*</span> <span class="n">nread</span><span class="p">,</span> 
                     <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">*</span> <span class="n">nwrite</span><span class="p">,</span>
                     <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">*</span> <span class="n">aread</span><span class="p">,</span>
                     <span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">*</span> <span class="n">awrite</span><span class="p">)</span>
                      <span class="o">:</span>
                     <span class="n">nread</span><span class="p">(</span><span class="n">nread</span><span class="p">),</span> 
                     <span class="n">nwrite</span><span class="p">(</span><span class="n">nwrite</span><span class="p">),</span> 
                     <span class="n">aread</span><span class="p">(</span><span class="n">aread</span><span class="p">),</span> 
                     <span class="n">awrite</span><span class="p">(</span><span class="n">awrite</span><span class="p">)</span>

    <span class="n">rbio</span> <span class="o">=</span> <span class="n">BIO_new</span><span class="p">(</span><span class="n">BIO_s_mem</span><span class="p">());</span>
    <span class="n">wbio</span> <span class="o">=</span> <span class="n">BIO_new</span><span class="p">(</span><span class="n">BIO_s_mem</span><span class="p">());</span>

    <span class="n">ssl</span> <span class="o">=</span> <span class="n">SSL_new</span><span class="p">(</span><span class="n">ctxt</span><span class="p">);</span>

    <span class="n">SSL_set_accept_state</span><span class="p">(</span><span class="n">ssl</span><span class="p">);</span>
    <span class="n">SSL_set_bio</span><span class="p">(</span><span class="n">ssl</span><span class="p">,</span> <span class="n">rbio</span><span class="p">,</span> <span class="n">wbio</span><span class="p">);</span>
<span class="p">}</span>

<span class="n">SSLFilter</span><span class="o">::~</span><span class="n">SSLFilter</span><span class="p">()</span> <span class="p">{</span>
    <span class="n">SSL_free</span><span class="p">(</span><span class="n">_ssl</span><span class="p">);</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="n">SSLFilter</span><span class="o">::</span><span class="n">update</span><span class="p">(</span><span class="n">Filter</span><span class="o">::</span><span class="n">FilterDirection</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// If we have data from the network to process, put it the memory BIO for OpenSSL</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">nread</span><span class="o">-&gt;</span><span class="n">empty</span><span class="p">())</span> <span class="p">{</span>
        <span class="kt">int</span> <span class="n">written</span> <span class="o">=</span> <span class="n">BIO_write</span><span class="p">(</span><span class="n">rbio</span><span class="p">,</span> <span class="n">nread</span><span class="o">-&gt;</span><span class="n">c_str</span><span class="p">(),</span> <span class="n">nread</span><span class="o">-&gt;</span><span class="n">length</span><span class="p">());</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">written</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="n">nread</span><span class="o">-&gt;</span><span class="n">erase</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">written</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="c1">// If the application wants to write data out to the network, process it with SSL_write</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">awrite</span><span class="o">-&gt;</span><span class="n">empty</span><span class="p">())</span> <span class="p">{</span>
        <span class="kt">int</span> <span class="n">written</span> <span class="o">=</span> <span class="n">SSL_write</span><span class="p">(</span><span class="n">ssl</span><span class="p">,</span> <span class="n">awrite</span><span class="o">-&gt;</span><span class="n">c_str</span><span class="p">(),</span> <span class="n">awrite</span><span class="o">-&gt;</span><span class="n">length</span><span class="p">());</span>

        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">continue_ssl_</span><span class="p">())</span> <span class="p">{</span>
            <span class="k">throw</span> <span class="n">std</span><span class="o">::</span><span class="n">runtime_error</span><span class="p">(</span><span class="s">&quot;An SSL error occured.&quot;</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">written</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="n">awrite</span><span class="o">-&gt;</span><span class="n">erase</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">written</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="c1">// Read data for the application from the encrypted connection and place it in the string for the app to read</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
        <span class="kt">char</span> <span class="o">*</span><span class="n">readto</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">char</span><span class="p">[</span><span class="mi">1024</span><span class="p">];</span>
        <span class="kt">int</span> <span class="n">read</span> <span class="o">=</span> <span class="n">SSL_read</span><span class="p">(</span><span class="n">ssl</span><span class="p">,</span> <span class="n">readto</span><span class="p">,</span> <span class="mi">1024</span><span class="p">);</span>

        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">continue_ssl_</span><span class="p">())</span> <span class="p">{</span>
            <span class="k">delete</span> <span class="n">readto</span><span class="p">;</span>
            <span class="k">throw</span> <span class="n">std</span><span class="o">::</span><span class="n">runtime_error</span><span class="p">(</span><span class="s">&quot;An SSL error occured.&quot;</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">read</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">size_t</span> <span class="n">cur_size</span> <span class="o">=</span> <span class="n">aread</span><span class="o">-&gt;</span><span class="n">length</span><span class="p">();</span>
            <span class="n">aread</span><span class="o">-&gt;</span><span class="n">resize</span><span class="p">(</span><span class="n">cur_size</span> <span class="o">+</span> <span class="n">read</span><span class="p">);</span>
            <span class="n">std</span><span class="o">::</span><span class="n">copy</span><span class="p">(</span><span class="n">readto</span><span class="p">,</span> <span class="n">readto</span> <span class="o">+</span> <span class="n">read</span><span class="p">,</span> <span class="n">aread</span><span class="o">-&gt;</span><span class="n">begin</span><span class="p">()</span> <span class="o">+</span> <span class="n">cur_size</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="k">delete</span> <span class="n">readto</span><span class="p">;</span>

        <span class="k">if</span> <span class="p">(</span><span class="k">static_cast</span><span class="o">&lt;</span><span class="n">size_t</span><span class="o">&gt;</span><span class="p">(</span><span class="n">read</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">1024</span> <span class="o">||</span> <span class="n">written</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c1">// Read any data to be written to the network from the memory BIO and copy it to nwrite</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
        <span class="kt">char</span> <span class="o">*</span><span class="n">readto</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">char</span><span class="p">[</span><span class="mi">1024</span><span class="p">];</span>
        <span class="kt">int</span> <span class="n">read</span> <span class="o">=</span> <span class="n">BIO_read</span><span class="p">(</span><span class="n">wbio</span><span class="p">,</span> <span class="n">readto</span><span class="p">,</span> <span class="mi">1024</span><span class="p">);</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">read</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">size_t</span> <span class="n">cur_size</span> <span class="o">=</span> <span class="n">nwrite</span><span class="o">-&gt;</span><span class="n">length</span><span class="p">();</span>
            <span class="n">nwrite</span><span class="o">-&gt;</span><span class="n">resize</span><span class="p">(</span><span class="n">cur_size</span> <span class="o">+</span> <span class="n">read</span><span class="p">);</span>
            <span class="n">std</span><span class="o">::</span><span class="n">copy</span><span class="p">(</span><span class="n">readto</span><span class="p">,</span> <span class="n">readto</span> <span class="o">+</span> <span class="n">read</span><span class="p">,</span> <span class="n">nwrite</span><span class="o">-&gt;</span><span class="n">begin</span><span class="p">()</span> <span class="o">+</span> <span class="n">cur_size</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="k">delete</span> <span class="n">readto</span><span class="p">;</span>

        <span class="k">if</span> <span class="p">(</span><span class="k">static_cast</span><span class="o">&lt;</span><span class="n">size_t</span><span class="o">&gt;</span><span class="p">(</span><span class="n">read</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">1024</span> <span class="o">||</span> <span class="n">read</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="kt">bool</span> <span class="n">SSLFilter</span><span class="o">::</span><span class="n">continue_ssl_</span><span class="p">(</span><span class="kt">int</span> <span class="n">function_return</span><span class="p">)</span> <span class="p">{</span>
    <span class="kt">int</span> <span class="n">err</span> <span class="o">=</span> <span class="n">SSL_get_error</span><span class="p">(</span><span class="n">ssl</span><span class="p">,</span> <span class="n">function_return</span><span class="p">);</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">err</span> <span class="o">==</span> <span class="n">SSL_ERROR_NONE</span> <span class="o">||</span> <span class="n">err</span> <span class="o">==</span> <span class="n">SSL_ERROR_WANT_READ</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">return</span> <span class="kc">true</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">err</span> <span class="o">==</span> <span class="n">SSL_ERROR_SYSCALL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">ERR_print_errors_fp</span><span class="p">(</span><span class="n">stderr</span><span class="p">);</span>
        <span class="n">perror</span><span class="p">(</span><span class="s">&quot;syscall error: &quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="kc">false</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">err</span> <span class="o">==</span> <span class="n">SSL_ERROR_SSL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">ERR_print_errors_fp</span><span class="p">(</span><span class="n">stderr</span><span class="p">);</span>
        <span class="k">return</span> <span class="kc">false</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="kc">true</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</td></tr></table>

<h3>Explanation of the SSL Filter class</h3>
<p><strong>Line 7 - 25</strong>, we create the two memory BIO's and then call <code>SSL_new()</code> using
the passed in <code>SSL_CTX</code>, set the accept set for SSL and then we hook up the two
BIO objects to the <code>ssl</code> object.</p>
<p><strong>Line 27 - 29</strong>, All we do in the destructor is <code>SSL_free()</code> the SSL state,
which automatically takes care of freeing the two memory BIOs that were given
to it.</p>
<p><strong>Line 33 - 36</strong>, if <code>nread</code> is not empty we copy the data into <code>rbio</code>. <code>rbio</code>
is used by the SSL functions to read from (as if it were reading from a
socket). We read into the memory BIO as much as possible, technically this
should be everything, but it is possible it won't read everything due to memory
constraints, next time <code>SSLFilter::update()</code> is called it will get emptied as
much as possible again.</p>
<p><strong>Line 39 - 47</strong>, we see if there is anything that the app wants to write out
to the remote client, if there is we call <code>SSL_write()</code>. After the call to
<code>SSL_write()</code> we call <code>continue_ssl_()</code> to see if we can safely continue using
SSL.</p>
<p><strong>Line 50 - 68</strong>, this is where try to read as much data from <code>SSL_read()</code> as
we can and place it in <code>aread</code>. This is data that has been decrypted by OpenSSL
and can be used by the application. After the call to <code>SSL_read()</code> we call
<code>continue_ssl_()</code> to see if we can safely continue using SSL.</p>
<p><strong>Line 71 - 84</strong>, if OpenSSL has to write something to the network, either
directly due to something the app did (by filling <code>awrite</code>) or because of
something the remote client sent, it will place it in its memory buffer
(<code>wbio</code>), what we do here is drain that memory buffer and fill <code>nwrite</code>.</p>
<p><strong>Line 87 - 105</strong>, the <code>continue_ssl_()</code> function gets the SSL errors using
<a href="http://www.openssl.org/docs/ssl/SSL_get_error.html"><code>SSL_get_error</code></a> and checks that either it is <code>SSL_ERROR_NONE</code> or
<code>SSL_ERROR_WANT_READ</code> both of which are acceptable errors, any other errors and
we check to see if it is an error due to a system call or due to an SSL error,
we print out the errors to standard error and return false. At that point the
calling code is free to go about its business as it pleases (most likely
throwing an error).</p>
<h4>Notes regarding this sample code ...</h4>
<p>The only thing missing in this example code is checking to see if the SSL
connection has gone into an <code>SSL_shutdown()</code> mode. This should be added so that
you cleanly shut down an SSL connection, but it is not absolutely required,
especially since it seems to be shaky as to whether or not it will work,
especially if you are using SSLv3 or SSLv2.</p>
<h3>How to use the SSL Filter</h3>
<p>Here are the steps to using this filter:</p>
<ol>
<li>At program startup set up the <code>SSL_CTX</code> structure as required, so that it
    be used in the <code>SSLFilter</code></li>
<li>Set up socket/event loop and accept() new socket.</li>
<li>Create four new <code>std::string</code>'s and create a new SSLFilter, pass in the
    <code>SSL_CTX</code> you created, and the four buffers.</li>
<li>Add the new socket to the event loop to wait for reading.</li>
</ol>
<p>Now upon receiving a read ready status from the event loop, the following should be done:</p>
<ol>
<li>Read data into <code>nread</code> buffer.</li>
<li>call <code>SSLFilter::update()</code></li>
<li>See if <code>aread</code> is not empty, process the data as you please</li>
<li>Write data to <code>awrite</code> as needed, if data is written to <code>awrite</code>, call
    <code>SSLFilter::update(WRITE)</code> to process the data</li>
<li>See if <code>nwrite</code> is not empty, if so add socket to event loop for write
    readiness.</li>
</ol>
<p>Once you receive a write ready status from the event loop, you should do the following:</p>
<ol>
<li>Write data in <code>nwrite</code> to the socket.</li>
<li>If <code>nwrite</code> is empty, remove the socket from the event loop for writing (so
    that you don't have the event loop notifying you of the ability to write,
    even-though you have nothing to write).</li>
</ol>
<p>Now it becomes simple to add OpenSSL to any open socket, in a way that is easy
to refactor later and or disable depending on parameters passed in as arguments
to the program. If you set <code>nread</code> to the same string as <code>aread</code> and <code>nwrite</code>
to <code>awrite</code> and don't create an SSLFilter you have bypassed the filter...</p>]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://funcptr.net/</uri>
    </author>
    <title type="html"><![CDATA[Converting KVM virtual machines to VirtualBox]]></title>
    <link rel="alternate" type="text/html" href="http://funcptr.net/2012/04/01/converting-kvm-virtual-machines-to-virtualbox" />
    <id>http://funcptr.net/2012/04/01/converting-kvm-virtual-machines-to-virtualbox</id>
    <updated>2012-04-01T01:03:32Z</updated>
    <published>2012-04-01T01:03:32Z</published>
    <category scheme="http://funcptr.net/" term="Virtualisation" />
    <category scheme="http://funcptr.net/" term="KVM" />
    <category scheme="http://funcptr.net/" term="FreeBSD" />
    <category scheme="http://funcptr.net/" term="VirtualBox" />
    <category scheme="http://funcptr.net/" term="Linux" />
    <summary type="html"><![CDATA[Converting KVM virtual machines to VirtualBox]]></summary>
    <content type="html" xml:base="http://funcptr.net/2012/04/01/converting-kvm-virtual-machines-to-virtualbox"><![CDATA[<p>Recently the requirement came up to take a <a href="http://www.linux-kvm.org/" title="Kernel Virtual Machine">KVM</a> based virtual machine and
move it over to a <a href="https://www.virtualbox.org/" title="Oracle VirtualBox">VirtualBox</a> image. Which turned out to be a fairly simple
endeavour, and was fairly painless. The longest part was transferring over the
40 GB image from one machine to the other where the conversion could take
place. The machine the image was coming from was only on a 100 Mbit/sec
connection so that took a good hour.</p>
<p>Converting from KVM to VirtualBox for a FreeBSD image was pretty
simple, the <code>VBoxManage</code> command has a <code>convertdd</code> command that allows you to
convert from raw disk <code>.img</code> format to <code>.vdi</code> format.</p>
<div class="codehilite"><pre>VBoxManage convertdd KVM-image.img VB-image.vdi
</pre></div>


<p>After this, unfortunately, there is no way to to automatically convert over the
settings that the virtual machine had, such as the network cards, the memory
allocations and hard drive settings. You will have to go to VirtualBox and
create a new virtual machine and replicate all of the settings. Once that is
done make sure to select the same type of disk controller (SATA or IDE) so that
the drive will hopefully be assigned the same name in the device tree so that
you don't need to alter your <code>/etc/fstab</code>.</p>
<p>Hopefully everything boots without any issues. If not try creating a new
virtual machine, attach the converted image as a secondary drive and see if you
can mount the converted image within your new install. If so maybe transferring
the data using <code>rsync</code> or <code>dump</code>/<code>restore</code> would be an option.</p>]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://funcptr.net/</uri>
    </author>
    <title type="html"><![CDATA[Generating stylesheets for pygments]]></title>
    <link rel="alternate" type="text/html" href="http://funcptr.net/2011/11/27/generating-stylesheets-for-pygments" />
    <id>http://funcptr.net/2011/11/27/generating-stylesheets-for-pygments</id>
    <updated>2011-11-27T11:40:00Z</updated>
    <published>2011-11-27T11:40:00Z</published>
    <category scheme="http://funcptr.net/" term="Python" />
    <category scheme="http://funcptr.net/" term="code highlighting" />
    <category scheme="http://funcptr.net/" term="pygments" />
    <summary type="html"><![CDATA[Generating stylesheets for pygments]]></summary>
    <content type="html" xml:base="http://funcptr.net/2011/11/27/generating-stylesheets-for-pygments"><![CDATA[<p>For this blog I am using <a href="http://freewisdom.org/projects/python-markdown/">Python markdown</a> with the <a href="http://pygments.org/">Pygments</a> plugin
that is available. Pygments does all of the code highlighting and outputs the
required <code>span</code> tags and inputs them within the page.</p>
<p>If you were to look at the <code>&lt;div&gt;&lt;pre&gt;&lt;/pre&gt;&lt;/div&gt;</code> block that is generated
you'd see something like this:</p>
<div class="codehilite"><pre><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;codehilite&quot;</span><span class="nt">&gt;&lt;pre&gt;&lt;span</span> <span class="na">class=</span><span class="s">&quot;k&quot;</span><span class="nt">&gt;</span>def<span class="nt">&lt;/span&gt;</span> <span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">&quot;nf&quot;</span><span class="nt">&gt;</span>function<span class="nt">&lt;/span&gt;&lt;span</span> <span class="na">class=</span><span class="s">&quot;p&quot;</span><span class="nt">&gt;</span>(<span class="nt">&lt;/span&gt;&lt;span</span> <span class="na">class=</span><span class="s">&quot;n&quot;</span><span class="nt">&gt;</span>var<span class="nt">&lt;/span&gt;&lt;span</span> <span class="na">class=</span><span class="s">&quot;o&quot;</span><span class="nt">&gt;</span>=<span class="nt">&lt;/span&gt;&lt;span</span> <span class="na">class=</span><span class="s">&quot;bp&quot;</span><span class="nt">&gt;</span>None<span class="nt">&lt;/span&gt;&lt;span</span> <span class="na">class=</span><span class="s">&quot;p&quot;</span><span class="nt">&gt;</span>):<span class="nt">&lt;/span&gt;</span>
<span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">&quot;k&quot;</span><span class="nt">&gt;</span>if<span class="nt">&lt;/span&gt;</span> <span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">&quot;n&quot;</span><span class="nt">&gt;</span>var<span class="nt">&lt;/span&gt;</span> <span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">&quot;ow&quot;</span><span class="nt">&gt;</span>is<span class="nt">&lt;/span&gt;</span> <span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">&quot;ow&quot;</span><span class="nt">&gt;</span>not<span class="nt">&lt;/span&gt;</span> <span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">&quot;bp&quot;</span><span class="nt">&gt;</span>None<span class="nt">&lt;/span&gt;&lt;span</span> <span class="na">class=</span><span class="s">&quot;p&quot;</span><span class="nt">&gt;</span>:<span class="nt">&lt;/span&gt;</span>
    <span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">&quot;k&quot;</span><span class="nt">&gt;</span>print<span class="nt">&lt;/span&gt;</span> <span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">&quot;n&quot;</span><span class="nt">&gt;</span>var<span class="nt">&lt;/span&gt;</span>
<span class="nt">&lt;/pre&gt;&lt;/div&gt;</span>
</pre></div>


<p>which is generated from the following snippet of code:</p>
<div class="codehilite"><pre><span class="k">def</span> <span class="nf">function</span><span class="p">(</span><span class="n">var</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">var</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
        <span class="k">print</span> <span class="n">var</span>
</pre></div>


<p>As you see the top css <code>class</code> is <code>codehilite</code>, and then underneath that there
are a bunch of other classes such as <code>k</code>, <code>n</code>, <code>o</code>, and so forth. Those are all
classes that can be styled. Now one could write such a stylesheet by hand or we
can simply use one of the stylesheets that Pygments ships with.</p>
<p>The documentation for Pygments tells you how to get <a href="http://pygments.org/docs/styles/#builtin-styles">built-in styles</a>, which
is as simple as:</p>
<div class="codehilite"><pre><span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">pygments.styles</span> <span class="kn">import</span> <span class="n">get_all_styles</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">styles</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">get_all_styles</span><span class="p">())</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">styles</span>
<span class="p">[</span><span class="s">&#39;monokai&#39;</span><span class="p">,</span> <span class="s">&#39;manni&#39;</span><span class="p">,</span> <span class="s">&#39;perldoc&#39;</span><span class="p">,</span> <span class="s">&#39;borland&#39;</span><span class="p">,</span> <span class="s">&#39;colorful&#39;</span><span class="p">,</span> <span class="s">&#39;default&#39;</span><span class="p">,</span> <span class="o">...</span><span class="p">]</span>
</pre></div>


<p>These are all the styles that are available to you the user, now how do we get
the style into an actual <code>.css</code> file that we can link to in our sites HTML
file? We use the <code>pygmentize</code> command line tool:</p>
<div class="codehilite"><pre><span class="n">pygmentize</span> <span class="o">-</span><span class="n">f</span> <span class="n">html</span> <span class="o">-</span><span class="n">S</span> <span class="n">trac</span> <span class="o">-</span><span class="n">a</span> <span class="p">.</span><span class="n">codehilite</span> <span class="o">&gt;</span> <span class="n">pygments</span><span class="p">.</span><span class="n">css</span>
</pre></div>


<p>Feel free to replace <code>trac</code> with any of the styles you have installed on your
system. <code>-f</code> tells it what formatter to use, since we want it to output the css
we ask it to use the HTML formatter, <code>-S</code> tells <code>pygmentize</code> what style to
use, and <code>-a</code> prepends the <code>.codehilite</code> class before every rule (this way we
don't pollute the whole CSS namespace with all the aforementioned class's such
as <code>k</code>, <code>o</code>, <code>ow</code> and others).</p>]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://funcptr.net/</uri>
    </author>
    <title type="html"><![CDATA[NAT with PF on an interface with multiple IP addresses]]></title>
    <link rel="alternate" type="text/html" href="http://funcptr.net/2011/09/08/nat-with-pf-on-an-interface-with-multiple-ip-addresses" />
    <id>http://funcptr.net/2011/09/08/nat-with-pf-on-an-interface-with-multiple-ip-addresses</id>
    <updated>2011-09-08T02:40:00Z</updated>
    <published>2011-09-08T02:40:00Z</published>
    <category scheme="http://funcptr.net/" term="pf" />
    <category scheme="http://funcptr.net/" term="FreeBSD" />
    <summary type="html"><![CDATA[NAT with PF on an interface with multiple IP addresses]]></summary>
    <content type="html" xml:base="http://funcptr.net/2011/09/08/nat-with-pf-on-an-interface-with-multiple-ip-addresses"><![CDATA[<p>If you want to do NAT for your currently running jail instances on FreeBSD so
that they can have outgoing connections you could try the following <code>pf.conf</code>
to set up NAT on the interface that the jails have their IP addresses on.</p>
<div class="codehilite"><pre><span class="n">ext_if</span><span class="p">=</span>&quot;<span class="n">em0</span>&quot;    # <span class="n">The</span> <span class="n">network</span> <span class="n">card</span> <span class="n">your</span> <span class="n">default</span> <span class="n">gateway</span> <span class="n">is</span> <span class="n">on</span>
<span class="n">jail_if</span><span class="p">=</span>&quot;<span class="n">lo1</span>&quot;   # <span class="n">The</span> <span class="n">interface</span> <span class="n">that</span> <span class="n">your</span> <span class="n">jails</span> <span class="n">have</span> <span class="n">IP</span> <span class="n">addresses</span> <span class="n">on</span>

# <span class="n">Set</span> <span class="n">some</span> <span class="n">options</span>
<span class="n">set</span> <span class="n">optimization</span> <span class="n">aggressive</span>
<span class="n">set</span> <span class="n">block</span><span class="o">-</span><span class="n">policy</span> <span class="n">drop</span>
<span class="n">set</span> <span class="n">skip</span> <span class="n">on</span> <span class="n">lo</span>

# <span class="n">NAT</span> <span class="n">on</span> <span class="n">the</span> <span class="n">external</span> <span class="n">interface</span> <span class="n">when</span> <span class="n">coming</span> <span class="n">from</span> <span class="n">the</span> <span class="n">jail</span> <span class="n">interface</span>
<span class="n">nat</span> <span class="n">on</span> $<span class="n">ext_if</span> <span class="n">from</span> $<span class="n">jail_if</span><span class="p">:</span><span class="n">network</span><span class="p">:</span>0 <span class="n">to</span> <span class="n">any</span> <span class="o">-&gt;</span> <span class="p">(</span>$<span class="n">ext_if</span><span class="p">)</span>

# <span class="n">We</span> <span class="n">just</span> <span class="n">pass</span> <span class="n">everything</span>
<span class="n">pass</span> <span class="n">quick</span> <span class="n">all</span>
</pre></div>


<p>What I have done is create IP addresses within the private network range
(<code>10/8</code>, <code>172.16/12</code>, <code>192.168/16</code>) on the <code>lo1</code> interface. These can't be in
the <code>127/8</code> range because those addresses can't be NAT'ed (not sure if this is
a limitation in pf or if this is a FreeBSD limitation), which is a shame
because using <code>127.1.0.1/24</code> would be pretty awesome in my opinion.</p>
<p>What I did find though is that the above will not work correctly if your main
network card (the one your default gateway is on, in the example <code>em0</code>)
contains multiple IP addresses. At that point the syntax <code>($ext_if)</code> does not
function correctly and will cause packet loss/drop. <sup id="fnref:2011-09-08freebsdversion"><a href="#fn:2011-09-08freebsdversion" rel="footnote">1</a></sup></p>
<p>So instead of using the syntax above we simply replace <code>($ext_if)</code> with the
actual IP address of the interface. This takes care of the issue and will let
your jails have proper internet access without issues.</p>
<div class="codehilite"><pre><span class="n">ext_if</span><span class="p">=</span>&quot;<span class="n">em0</span>&quot;
<span class="n">jail_if</span><span class="p">=</span>&quot;<span class="n">lo1</span>&quot;

<span class="n">set</span> <span class="n">optimization</span> <span class="n">aggressive</span>
<span class="n">set</span> <span class="n">block</span><span class="o">-</span><span class="n">policy</span> <span class="n">drop</span>
<span class="n">set</span> <span class="n">skip</span> <span class="n">on</span> <span class="n">lo</span>

<span class="n">nat</span> <span class="n">on</span> $<span class="n">ext_if</span> <span class="n">from</span> $<span class="n">jail_if</span><span class="p">:</span><span class="n">network</span><span class="p">:</span>0 <span class="n">to</span> <span class="n">any</span> <span class="o">-&gt;</span> 192<span class="p">.</span>168<span class="p">.</span>1<span class="p">.</span>2 # <span class="n">Your</span> <span class="n">IP</span>!

<span class="n">pass</span> <span class="n">quick</span> <span class="n">all</span>
</pre></div>


<p>The other way you can solve this problem off course is to provide your jails
with IP addresses within the same range that go to your default gateway thereby
solving the problem of needing to NAT in the first place.</p>
<div class="footnote">
<hr />
<ol>
<li id="fn:2011-09-08freebsdversion">
<p>Do note that I am using FreeBSD 8.2, so this may
be fixed in the new FreeBSD 9 that is due to be released soon.&#160;<a href="#fnref:2011-09-08freebsdversion" rev="footnote" title="Jump back to footnote 1 in the text">&#8617;</a></p>
</li>
</ol>
</div>]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://funcptr.net/</uri>
    </author>
    <title type="html"><![CDATA[FreeBSD running within KVM: Serial Console]]></title>
    <link rel="alternate" type="text/html" href="http://funcptr.net/2011/08/21/freebsd-running-within-kvm:-serial-console" />
    <id>http://funcptr.net/2011/08/21/freebsd-running-within-kvm:-serial-console</id>
    <updated>2011-08-21T18:53:52Z</updated>
    <published>2011-08-21T18:53:52Z</published>
    <category scheme="http://funcptr.net/" term="kvm" />
    <category scheme="http://funcptr.net/" term="console" />
    <category scheme="http://funcptr.net/" term="FreeBSD" />
    <category scheme="http://funcptr.net/" term="Linux" />
    <summary type="html"><![CDATA[FreeBSD running within KVM: Serial Console]]></summary>
    <content type="html" xml:base="http://funcptr.net/2011/08/21/freebsd-running-within-kvm:-serial-console"><![CDATA[<p>Instead of using virtualisation technology such as VMWare of VirtualBox I
decided to give the new <a href="http://www.linux-kvm.org/page/Main_Page" title="Kernel based Virtual Machine">KVM</a> technology that is included with Linux. It is
fast, and has been extremely reliable. However I wanted to be able to access
the console on the guest FreeBSD instances.</p>
<p>I used virt-manager, a graphical tool, to set up everything, including creating
the virtual machine, I didn't want to have to deal with XML configuration files
and whatnot. After installing FreeBSD there are a few changes I made to get a
virtual console working, this allows virsh console &lt;domain&gt; to function
as expected.</p>
<p>First we add a new file to the root file system (which should be the first
slice on the drive):</p>
<div class="codehilite"><pre><span class="n">echo</span> &quot;<span class="o">-</span><span class="n">Dh</span>&quot; <span class="o">&gt;</span> <span class="o">/</span><span class="n">boot</span><span class="p">.</span><span class="n">config</span>
</pre></div>


<p>See <a href="http://www.freebsd.org/cgi/man.cgi?query=boot.config&amp;amp;sektion=5">man 5 boot.config</a> for more information. Basically -D says that FreeBSD
should boot with a dual console configuration (built-in over VGA) and serial
console, and -h says to force the serial console to on.</p>
<p>If you were to reboot now and use the virsh command:</p>
<div class="codehilite"><pre><span class="n">virsh</span> <span class="n">console</span> <span class="n">FreeBSD</span>
</pre></div>


<p>you would see the system go through the boot process and show output starting
from when the boot block gains control, at this point however you still have no
way to login to this new console since we never specified that we wanted any
ttys on the serial console, for that we need to edit /etc/ttys.</p>
<p>We are looking for the ttyu0 entry, we want to make sure to change dialup to
vt100, and off to on, so that it should look like this:</p>
<div class="codehilite"><pre><span class="n">ttyu0</span>   &quot;<span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="n">libexec</span><span class="o">/</span><span class="n">getty</span> <span class="n">std</span><span class="p">.</span>9600&quot;   <span class="n">vt100</span>   <span class="n">on</span> <span class="n">secure</span>
</pre></div>


<p>Now when we reboot once more we will get the usual login display that we have
come to expect of console on FreeBSD, and we can login over the serial console.
This way we don't have to open up the virtual machine manager to get a console,
and can continue to do almost everything from a terminal window.</p>]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://funcptr.net/</uri>
    </author>
    <title type="html"><![CDATA[PostgreSQL setup for external connections]]></title>
    <link rel="alternate" type="text/html" href="http://funcptr.net/2011/08/16/postgresql-setup-for-external-connections" />
    <id>http://funcptr.net/2011/08/16/postgresql-setup-for-external-connections</id>
    <updated>2011-08-16T17:48:54Z</updated>
    <published>2011-08-16T17:48:54Z</published>
    <category scheme="http://funcptr.net/" term="PostgreSQL" />
    <category scheme="http://funcptr.net/" term="FreeBSD" />
    <summary type="html"><![CDATA[PostgreSQL setup for external connections]]></summary>
    <content type="html" xml:base="http://funcptr.net/2011/08/16/postgresql-setup-for-external-connections"><![CDATA[<p>PostgreSQL is a fantastic open-source RDBMS which is extremely powerful, once
installed on FreeBSD getting it set up is pretty simple. We do want to change
some of the defaults though. By default the system will be set up to trust any
user using the local socket to connect as any user to any database.</p>
<p>By setting up the <a href="http://www.postgresql.org/docs/8.2/static/app-initdb.html"><code>initdb</code></a> flags we can change how PostgreSQL generates
the default configuration files. Adding <code>-A md5</code> tells it to use the <a href="http://www.postgresql.org/docs/8.2/static/auth-methods.html#AUTH-PASSWORD">md5
authentication mechanism</a>, which requires that passwords sent over the wire
are md5 hashed.</p>
<p>Add the following to <a href="http://www.freebsd.org/cgi/man.cgi?query=rc.conf&amp;sektion=5" title="man 5 rc.conf"><code>/etc/rc.conf</code></a> for the initdb flags, and enable
PostgreSQL as a service:</p>
<div class="codehilite"><pre><span class="n">postgresql_initdb_flags</span><span class="p">=</span>&quot;<span class="o">-</span><span class="n">D</span> <span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="n">local</span><span class="o">/</span><span class="n">pgsql</span><span class="o">/</span><span class="n">data</span> <span class="o">-</span><span class="n">W</span> <span class="o">-</span><span class="n">A</span> <span class="n">md5</span>&quot;
<span class="n">postgresql_enable</span><span class="p">=</span>&quot;<span class="n">YES</span>&quot;
</pre></div>


<p>And then run:</p>
<div class="codehilite"><pre>/usr/local/etc/rc.d/postgresql initdb
</pre></div>


<p>This will initialise and create the configuration as well as setting up some of
the default tables. You will want to navigate to the folder specified in the
<code>initdb_flags</code> above:</p>
<div class="codehilite"><pre><span class="nb">cd</span> /usr/local/pgsql/data
</pre></div>


<p>this is where you will find the files that we are going to modify next to get
PostgreSQL set up to listen to connections coming in on a private network
(<code>192.168.1.1/24</code>) and where we allow connections coming in from servers on
that network. This is strictly for setting up PostgreSQL in a situation where
you have multiple servers accessing it as a client on a private network.</p>
<p>After this we need to modify a few files to get it to listen to TCP/IPv4
connections, first we start with <a href="http://www.postgresql.org/docs/8.2/static/runtime-config-connection.html#RUNTIME-CONFIG-CONNECTION-SETTINGS"><code>postgresql.conf</code></a> and add:</p>
<div class="codehilite"><pre><span class="n">listen_addresses</span> <span class="p">=</span> <span class="s">&#39;127.0.0.1,192.168.1.1&#39;</span>
</pre></div>


<p>Then in <a href="http://www.postgresql.org/docs/8.2/static/auth-pg-hba-conf.html"><code>pg_hba.conf</code></a> we add a new line:</p>
<div class="codehilite"><pre><span class="n">host</span>    <span class="n">all</span>     <span class="n">all</span>     192<span class="p">.</span>168<span class="p">.</span>1<span class="p">.</span>1<span class="o">/</span>24      <span class="n">md5</span>
</pre></div>


<p>This allows anyone in the 192.168.1.1/24 range to connect to our PostgreSQL
instance and to use the databases. This is exactly what we want to allow, now
we start PostgreSQL using the rc script:</p>
<div class="codehilite"><pre>/usr/local/etc/rc.d/postgresql start
</pre></div>]]></content>
  </entry>
</feed>
