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

<channel>
	<title>echelon &#187; software</title>
	<atom:link href="http://www.soa-world.de/echelon/category/software/feed" rel="self" type="application/rss+xml" />
	<link>http://www.soa-world.de/echelon</link>
	<description>A personal  technology  blog about software  development  and other interesting stuff.</description>
	<lastBuildDate>Wed, 28 Dec 2011 15:43:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>C99: casting to variable-length arrays</title>
		<link>http://www.soa-world.de/echelon/2011/11/c99-casting-to-variable-length-arrays.html</link>
		<comments>http://www.soa-world.de/echelon/2011/11/c99-casting-to-variable-length-arrays.html#comments</comments>
		<pubDate>Wed, 30 Nov 2011 14:01:24 +0000</pubDate>
		<dc:creator>Sebastian Schaetz</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://www.soa-world.de/echelon/?p=1212</guid>
		<description><![CDATA[C99 understands variable-length arrays. They look something like this: Now the question is, how to properly cast a pointer to this type when passing it to a function that accepts such a type in a way that makes the compiler happy? The syntax is somewhat unusual: Tested with gcc 4.6.1 and the &#8211;std=c99 compiler option. [...]]]></description>
			<content:encoded><![CDATA[<p>C99 understands variable-length arrays. They look something like this:</p>
<pre class="brush: cpp; title: ; notranslate">
int d1, d2, d3, d4;
// runtime-assign those variables
int vla[d1][d2][d3][d3];
</pre>
<p>Now the question is, how to properly cast a pointer to this type when passing it to a function that accepts such a type in a way that makes the compiler happy? The syntax is somewhat unusual:</p>
<pre class="brush: cpp; title: ; notranslate">
void func(int d1, int d2, int d3, int d4, int vla[d1][d2][d3][d4]){}
// ...
int * x = malloc();
func(d1, d2, d3, d4, (int (*)[(int)(d2)][(int)(d3)][(int)(d4)])x);
</pre>
<p>Tested with gcc 4.6.1 and the &#8211;std=c99 compiler option. I could not find information about this anywhere on the web so I hope this will help others who wonder how it should be done. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.soa-world.de/echelon/2011/11/c99-casting-to-variable-length-arrays.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Mozilla Thunderbird and Flowed Format</title>
		<link>http://www.soa-world.de/echelon/2011/11/mozilla-thunderbird-and-flowed-format.html</link>
		<comments>http://www.soa-world.de/echelon/2011/11/mozilla-thunderbird-and-flowed-format.html#comments</comments>
		<pubDate>Wed, 02 Nov 2011 16:37:35 +0000</pubDate>
		<dc:creator>Sebastian Schaetz</dc:creator>
				<category><![CDATA[personal]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.soa-world.de/echelon/?p=1178</guid>
		<description><![CDATA[I like my e-mails to look a particular way. I send plain-text only e-mails with line wrapping at about 80 characters. This way I feel I can control to some degree what the e-mail will look like at the receivers end. And I want my e-mails to look like that even when I&#8217;m quoting someone. [...]]]></description>
			<content:encoded><![CDATA[<p>I like my e-mails to look a particular way. I send plain-text only e-mails with line wrapping at about 80 characters. This way I feel I can control to some degree what the e-mail will look like at the receivers end. And I want my e-mails to look like that even when I&#8217;m quoting someone.</p>
<p>Up until now I hated to use Thunderbird because it did not allow me to send e-mails like that. Since gmail looks ugly as hell now I came back to Thunderbird and set out to solve this issue once and for all. I searched for &#8220;thunderbird plain text wrap&#8221; and whatnot. A smart fellow on a forum had the <a href="http://forums.mozillazine.org/viewtopic.php?p=10718801&#038;sid=0d845b11f5c40cde6d2e1baf154e3fc9#p10718801">answer</a>:</p>
<p>There are two hidden preference settings which one can access through Edit > Preference > Advanced > General > Config Editor button:</p>
<ul>
<li><strong>mailnews.display.disable_format_flowed_support</strong> must be set to true to avoid rewarpping of messages received for which the sender allows flowed formatting</li>
<li>
<strong>mailnews.send_plaintext_flowed</strong> must be set to &#8220;false&#8221; to avoid sending flowed format e-mails</li>
</ul>
<p>The problem seems to be something called &#8220;<a href="http://kb.mozillazine.org/Plain_text_e-mail_-_Thunderbird#Flowed_format">flowed format</a>&#8221; but I&#8217;m too ignorant to go into the details of what it does, what it means and why I would want it. I&#8217;m just happy the e-mails my Thunderbird sends look the way I want them to look. Finally. Thank you rsx11m!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.soa-world.de/echelon/2011/11/mozilla-thunderbird-and-flowed-format.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cryptography for the Masses</title>
		<link>http://www.soa-world.de/echelon/2011/10/cryptography-for-the-masses.html</link>
		<comments>http://www.soa-world.de/echelon/2011/10/cryptography-for-the-masses.html#comments</comments>
		<pubDate>Mon, 10 Oct 2011 19:58:07 +0000</pubDate>
		<dc:creator>Sebastian Schaetz</dc:creator>
				<category><![CDATA[software]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.soa-world.de/echelon/?p=945</guid>
		<description><![CDATA[&#8220;The multiple human needs and desires that demand privacy among two or more people in the midst of social life must inevitably lead to cryptology wherever men thrive and wherever they write.&#8221; wrote David Kahn in his book &#8220;The Codebreakers&#8221;, chronicling the history of cryptography. The book was published in 1967. Almost 45 years later [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;The multiple human needs and desires that demand privacy among two or more people in the midst of social life must inevitably lead to cryptology wherever men thrive and wherever they write.&#8221; wrote David Kahn in his book &#8220;The Codebreakers&#8221;, chronicling the history of cryptography. The book was published in 1967. Almost 45 years later cryptography is seldom used to protect our privacy.</p>
<p>The information age spawned databases and networks capable of extracting and storing large amounts of private data. Those databases are often unknown to us and if we know of their existence we can not control them. They store personal information, communication and financial transactions. This gathering of private data happens against our will if we believe <a href="http://www.pewinternet.org/Reports/2010/Reputation-Management.aspx">surveys</a> that show that we actually do care about privacy. Skeptics and experts <a href="http://www.nytimes.com/2010/03/17/technology/17privacy.html">caution</a> us but the majority of web users is forced to give in to the subtle but grave disintegration of privacy, pushed forward by industry and government. They are growing their databases steadily, expanding the records they keep on all of us. </p>
<p><img src="http://www.soa-world.de/echelon/wp-content/uploads/2011/09/who.jpg" alt="" title="who" width="640" height="426" class="alignnone size-full wp-image-1024" /><br />
<em style="font-size: 10px">Good question, image by <a href="http://www.flickr.com/photos/garrettc/3740752626/">Garrett Coakley</a></em></p>
<p>We can see the consequences of these uncontrollable, central databases today. In what is believed to be one of the largest data security breaches in history, attackers <a href="http://en.wikipedia.org/wiki/PlayStation_Network_outage">stole</a> personally identifiable information of 77 million PlayStation Network users earlier this year.</p>
<p>Accidental exposure of personal data is another problem. It is very difficult to control who has access to which <a href="http://www.theregister.co.uk/2008/10/23/sickie_woo/">piece of information</a>. People get <a href="http://www.nea.org/home/38324.htm">fired</a> for how they behave online because they confuse personal with public communication. The web does not <a href="http://www.nytimes.com/2010/07/25/magazine/25privacy-t2.html">forget</a>. And ever since the uprisings in the Arab world it should be clear to everybody that what one posts online can have severe <a href="http://www.technologyreview.com/web/38379/">consequences</a>, including imprisonment and torture.</p>
<p>There are a variety of interesting judicial and ethical approaches to cope with these issues. And there is cryptography &#8211; a technological means of preserving privacy. Cryptography enables <a href="http://en.wikipedia.org/wiki/Anonymity"><em>anonymity</em></a>, the concept of &#8216;publishing information while ones identity is publicly unknown&#8217; as well as <a href="http://en.wikipedia.org/wiki/Privacy"><em>privacy</em></a>, the ability to to &#8216;seclude oneself or information about oneself and reveal oneself selectively&#8217;.</p>
<p>But almost nobody uses cryptography. Asked if he encrypts his e-mail, Bruce Schneier, cryptographer and highly regarded computer security specialist <a href="http://www.zdnetasia.com/schneier-warns-of-marketers-and-dancing-pigs-62058903.htm">answers</a> &#8220;I do not, except for special circumstances&#8221;. He further argues that for more people to encrypt their communication, services like Gmail would have to do it by default. This will of course never happen, since those services draw their revenue from <a href="http://mail.google.com/support/bin/answer.py?answer=6603">reading</a> our messages.</p>
<p><strong>It has to work out of the box</strong></p>
<p>But the more important point Schneier makes is this: what has to happen to spread the use of cryptology? It has to work out of the box. No additional application should be required, no plug-in, no add-on and certainly no driver installation. There exists a concept that could potentially offer a transparent solution for everyone: browser based cryptography. </p>
<p>Browsers have evolved from being a mere presentation and navigation tool for the world wide web to a platform for collaboration and information sharing web applications. If browsers were able to do cryptography, every web users could potentially benefit from it. JavaScript engines have evolved rapidly to a point where they are efficient enough to <a href="http://crypto.stanford.edu/sjcl/">handle</a> the complex algorithms that cryptography entails. It is ironic that the same web applications that threaten our privacy are the main reason such powerful engines were developed in the first place.</p>
<p>The idea of browser based cryptography is simple: before users upload their personal data to application hosts they encrypt the data in the browser. The host only receives encrypted blobs of data and since users don&#8217;t share their key with the host the data is secure. If they decide to share their data with someone else they can provide them with means of decrypting the blobs. Users are in control at all times.</p>
<p>But JavaScript cryptography has <a href="http://rdist.root.org/2010/11/29/final-post-on-javascript-crypto/">many</a> <a href="http://www.matasano.com/articles/javascript-cryptography/">critics</a> and there has been some <a href="http://news.ycombinator.com/item?id=2935220">discussion</a> whether or not it is a viable solution. But the potential is vast and the issue of retaking privacy is too important to dismiss the technology right away. The discussion should not stop here. Solutions can be found to the given objections.</p>
<p><strong>JavaScript Cryptography Criticism</strong></p>
<p>The trust model certainly is a problem and seems inconsistent. The general assumption is that users don&#8217;t trust application providers with their data, thus the need for encryption. Modern web applications however download their code from the very same provider and consequently also download the code required for decryption and encryption. A contradiction: users don&#8217;t entrust providers with their data but they trust the provider to deliver the application and most importantly the correct cryptography code. Critics argue that users can decide to either trust or not trust whoever hosts an application. If they trust the host there is no need for encryption. If they don&#8217;t trust the host they should not share their data in the first place. If someone suspects a host has malicious intentions JavaScript cryptology is worthless.</p>
<p>The situation changes if the &#8216;honest-but-curious&#8217; adversary model is taken as a basis. It assumes that the company providing a web services carries out the stated instructions and is not lying to the user. It is further assumed that it might do more than it promised such as storing the data for an unreasonably long time or even sharing data with third parties. In such a case JavaScript cryptography might be viable. Furthermore if the company is attacked and database dumps are stolen, the data is worthless. For an attacker to gain access to the data the web application source code has to be modified and users have to use the malicious application. To defeat such attacks, browsers would have to be able to validate web applications to make sure that they were not modified.</p>
<p><img src="http://www.soa-world.de/echelon/wp-content/uploads/2011/10/alarm.jpg" alt="" title="alarm" width="640" height="427" class="alignnone size-full wp-image-1172" /><br />
<em style="font-size: 10px">Dystopia 2, image by <a href="http://www.flickr.com/photos/rimmedwithfire/2828538083/">Hervé Girod</a></em></p>
<p>Today the browser is an environment not very well suited for cryptography. There is the threat of cross-site attacks: a web page loads content from many sources and all of those can potentially modify the cryptography code. Due to the dynamic nature of the JavaScript language, an attacker can replace correct code with a malicious version. Such an attack can only be discovered through tedious code analysis of all sources.</p>
<p>Critics also argue that browsers lack some crucial primitives important for cryptography such as a random number generation. Fortunately <a href="https://developer.mozilla.org/en/JavaScript_crypto">browser</a> <a href="http://blog.chromium.org/2011/06/new-chromium-security-features-june.html">vendors</a> see the need for such functions and are moving toward implementing them. Browsers further lack a secure key store, a crucial component in every crypto-system. It is also important to have the ability to securely erase secrets from memory once they are no longer needed. Since JavaScript engines employ garbage collection there is no way to control when objects are deleted and secrets are forgotten.</p>
<p>These issues are significant but they can all be addressed with care. Web developers, cryptographers and browser vendors will have to work together to find solutions to these shortcomings. Once this happens I expect to see secure JavaScript cryptography applications that satisfy even the skeptics. There is still a lot to be done but the potential is tremendous. So we should get to work.</p>
<p><strong>Existing Implementations</strong></p>
<p>Despite the criticism there are already some implementations that utilize JavaScript cryptography out there. They try to make do with the current state of browser support for de- and encryption. Some supplement browser capabilities with custom add-ons. This of course defeats the purpose of JavaScript cryptography but is a necessity at the moment since browser support is still in its infancy.</p>
<p>Aldo Cortesi&#8217;s <a href="http://cryp.sr/">cryp.sr</a> is the most interesting project. It is an online list-manager that encrypts user data in the browser and sends only an encrypted blob to the host. It inspired people to think about what JavaScript cryptology can do and what it means to encrypt data in the browser. Encrypted user data is completely exposed as the application intentionally lacks authentication (except to prevent overwrites). Only the passphrase protects the data. Cortesi uses the expression &#8216;host-proof&#8217; in his documentation of the project which is a <a href="http://en.wikipedia.org/wiki/Wikipedia:Articles_for_deletion/Host-proof_hosting">dubious</a> term, especially in the context of JavaScript cryptography. It was coined by <a href="http://web.archive.org/web/20051216161158/http://smokey.rhs.com/web/blog/PowerOfTheSchwartz.nsf/d6plinks/RSCZ-6C5G54">Richard Schwartz</a> and emphasizes that the host does not have to be trusted. This is a difficult claim. Users still have to trust the host because it grants the privilege of encrypting the data and it can revoke that privilege at any time. The &#8216;honest-but-curious&#8217; adversary model again makes more sense.</p>
<p>More questionable applications are <a href="https://www.lockify.com/">Lockify</a>, <a href="http://www.zkbox.com/">Zero-Knowledge Box</a> and <a href="http://www.clipperz.com/">Clipperz</a> because they explicitly advertise the security of their products that is solely based on JavaScript cryptography. Critics argue that appearance of security is worse than no security at all. Their claim of increased security should indeed be taken with a grain of salt: data that otherwise would not be uploaded due to security considerations should not be stored with those hosts. Even so, the cryptology is a welcome addition to the security measures these companies take. It accomplishes the goal of preserving privacy. </p>
<p><img src="http://www.soa-world.de/echelon/wp-content/uploads/2011/10/mailboxes.jpg" alt="" title="mailboxes" width="640" height="448" class="alignnone size-full wp-image-1175" /><br />
<em style="font-size: 10px">Vintage Mail Boxes, image by <a href="http://www.flickr.com/photos/witty_nickname/4140744881/">Nathen Jantzen</a>, all rights reserved</em></p>
<p>When asked to choose between a regular web application and a JavaScript cryptography enabled one, the latter is preferable due to privacy considerations since the user does not lose control of his data. Claiming that JavaScript cryptography enabled applications, with the current state of research and browser support, are more secure than others is debatable. We are not there yet.</p>
<p><strong>Alternatives</strong></p>
<p>There are a number of alternatives and especially the concept of storing encrypted data with a curious or even untrusted <a href="http://www.tarsnap.com/">host</a> is not new. Traditionally, <a href="http://www.truecrypt.org/">host applications</a> have been used to handle cryptographic operations. These tools must be installed and have to be properly set up by the user. Mobile platforms might be an ideal environment for these alternatives. Installing applications is hassle-free and very common on mobile devices. Due to the well defined platform, developers can keep user effort to configure these applications to a minimum.</p>
<p>Another promising alternative is a browser add-on called <a href="http://www.cipherbox.org/">Cipherbox</a>. Its developers recognize that it is unlikely that application providers will enable cryptography as well as the shortcomings of current JavaScript solutions. In their architecture they make a point of separating the interaction with the web content from the cryptology functionality. This could proof to be a significant security advantage over other solutions that give web content access to cryptology functions.</p>
<p>A colleague and I devised the idea of a cryptography enabled http proxy that is similar to the Cipherbox. The proxy is a trusted instance possibly hosted locally or connected via a VPN. All http traffic is sent through the proxy. It analyzes the traffic and encrypts and encrypts relevant parts like messages or images depending on its configuration. We implemented a prototype that is capable of transparently encrypting and decrypting Facebook messages using <a href="http://www.gnupg.org/">gpg</a>. A proxy like this could run on a user&#8217;s <a href="http://freedomboxfoundation.org/">FreedomBox</a> and can in theory be extended to provide crypto-functionality for various platforms including for example Gmail.</p>
<p>A special form of cryptography called <a href="http://en.wikipedia.org/wiki/Homomorphic_encryption">homomorphic encryption</a> could enable users to take advantage of both cryptography and computing as a service at the same time. If encrypted data is sent to hosts, they usually can not process the data. If instead a homomorphic encryption scheme is <a href="http://www.technologyreview.com/computing/37197/">in place</a>, for certain algebraic functions on the plaintext, equivalent functions exist that can be applied to the ciphertext. Proponents of this technology <a href="http://www.technologyreview.com/computing/38239/">argue</a> that it could enable widespread use of cloud computing by ensuring the confidentiality of private data.</p>
<p><strong>Conclusion</strong></p>
<p>Controlling ones personal data is more difficult with every new database and network based innovation. At the same time privacy is more important than ever in a world that prepares to conglomerate health records, gathers and centralizes consumer behavior data and merges individual financial records into powerful profiles. Cryptography is an effective safeguard we must implement to prevent exploitation and discrimination based on our personal information. Every user must be enabled to use cryptology to control the data he wishes to share.</p>
<p>Browsers vendors must implement the building blocks required for cryptography including a secure key store that can be managed by the user. They should also include means of validating a running application against a checksum. Cryptographers and web developers must work together to implement correct and easy to use de- and encryption functionality for browser based applications.</p>
<p>More people must start thinking about this problem, more ideas are needed and should be carefully vetted by cryptographers and security experts. User interface specialists should work on making cryptography a transparent process. We need to get everyone involved and try to revert the damage that has already been done.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.soa-world.de/echelon/2011/10/cryptography-for-the-masses.html/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>The Decentralized Web Movement</title>
		<link>http://www.soa-world.de/echelon/2011/09/the-decentralized-web-movement.html</link>
		<comments>http://www.soa-world.de/echelon/2011/09/the-decentralized-web-movement.html#comments</comments>
		<pubDate>Sun, 04 Sep 2011 12:47:27 +0000</pubDate>
		<dc:creator>Sebastian Schaetz</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[interesting stuff]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.soa-world.de/echelon/?p=754</guid>
		<description><![CDATA[Over the years computers grew in numbers and a logical step in their evolution was to connect them together to allow their users to share things. Little networks grew into huge networks and some computers gained more power than the rest: they called themselves &#8220;servers&#8221;. Today millions of people are connected online at the mercy [...]]]></description>
			<content:encoded><![CDATA[<p>Over the years computers grew in numbers and a logical step in their evolution was to connect them together to allow their users to share things. Little networks grew into huge networks and some computers gained more power than the rest: they called themselves &#8220;servers&#8221;. Today millions of people are connected online at the mercy of middleman who control the servers of the world.</p>
<p>This is not an introduction to an dystopian fantasy world but an excerpt from a promotion video for Opera Unite, a framework that allows users to host information from their home computer. It was a bold attempt to change the centralized architecture of the Internet. A <a href="http://dl.acm.org/citation.cfm?id=1578010">number</a> of <a href="http://en.wikipedia.org/wiki/Friend-to-friend">smart</a> <a href="http://en.wikipedia.org/wiki/Web_of_trust">people</a> have been pondering this idea even before Opera&#8217;s experiment <a href="http://factoryjoe.com/blog/2009/06/16/thoughts-on-opera-unite/">failed miserably</a>.</p>
<p><img src="http://www.soa-world.de/echelon/wp-content/uploads/2011/08/breakdown.jpg" alt="" title="breakdown" width="640" height="426" class="alignnone size-full wp-image-906" /><br />
<em style="font-size: 10px">Communication breakdown, image by <a href="http://www.flickr.com/photos/miuenski/3640424543/">miuenski</a></em></p>
<p>And the concept of a decentralized web is gaining traction: more and more people realize something has to change. The cause for this trend is obvious: the number of data security and privacy disasters that were made public has spiked in recent times . In April &#8217;11 for example an update to the <a href="https://www.dropbox.com/terms/#security">security terms of service</a> of the widely used Dropbox tool <a href="http://tirania.org/blog/archive/2011/Apr-19.html">revealed</a> that contrary to previous claims, Dropbox Inc. has full access to user data. </p>
<p>An <a href="http://www.eff.org/deeplinks/2010/04/facebook-timeline">analysis</a> of the changes to the Facebook privacy policy over time paints a gloomy picture of how the world&#8217;s largest social network changed &#8220;from a private communication space to a platform that shares user information with advertising and business partners while limiting the users&#8217; options to control their own information&#8221;. </p>
<p>With more and more of our personal data moving to centralized servers or &#8220;cloud services&#8221; &#8211; a term that should be used as an euphemism &#8211; we&#8217;re no longer in control. But there is hope in sight: there are dozens of projects out there that try to stop the trend of centralization and data consolidation.</p>
<p><strong>Decentralized Applications</strong></p>
<p>The most popular of the lot is probably <a href="https://joindiaspora.com/">Diaspora</a>. The project got a lot of attention in April 2010 when they managed to raise about $200.000 from almost 6500 supporters. The software looks and feels very much like Facebook or Google+. The innovation is that users are allowed and even encouraged to set up their own Diaspora node. This essentially means allowing users to set up their own Facebook server at home (or wherever they want). The Diaspora nodes are able to interact with each other to form one distributed social network. Furthermore, instead of users having to log in to one central server, they may choose one of many servers administered by different entities. In the end they can decide whom to trust with their data and there is no one entity that has access to all the data.</p>
<p>A social network project that is also worth mentioning follows the same principle. Its name is <a href="http://buddycloud.com/">Buddycloud</a>. The main difference between Buddycloud and Diaspora can be found in their implementation details: Buddycloud builds upon <a href="http://en.wikipedia.org/wiki/Extensible_Messaging_and_Presence_Protocol">XMPP</a> (Extensible Messaging and Presence Protocol), a more than 10 year old and often implemented specification for &#8220;near-real-time, extensible instant messaging, presence information, and contact list maintenance&#8221;. There are many unknowns in this area so building on such proven protocols instead of defining new standards might proof to be an advantage. But there are many more social networking projects out there. Wikipedia has a <a href="http://en.wikipedia.org/wiki/Distributed_social_network">nice list</a>. </p>
<p>The <a href="http://unhosted.org/">Unhosted</a> project implements another concept. Instead of providing a specific decentralized service it aims to be a meta-service. And after talking to Michiel de Jong I have the impression his plan is even more crucial. He aims to create something fundamental, a protocol, an architecture, a new way of writing web applications. The idea is the following: the traditional architecture of a hosted website provides both processing and storage. An unhosted website only hosts the application, not the data. Unhosted wants to separate the application from the data. By storing the data in another location and combining both application and data only in the browser, the application provider can never access the data. An ingenious and very ambitious idea. I hope they succeed!</p>
<p><strong>Decentralized Storage</strong></p>
<p>A project that aims to replace Dropbox is <a href="http://owncloud.org/">ownCloud</a>, an open personal cloud which runs on your personal server. It enables accessing your data from all of your devices. Sharing with other people is also possible. It supports automatic backups, versioning and encryption.</p>
<p>The <a href="http://lockerproject.org/">Locker Project</a> has similar goals. They allow self-hosting (installing their software on your own server) and offer a hosted service similar to what Dropbox provides. The service pulls in and archives all kinds of data that the user has permission to access and stores this data into the user’s personal Locker: Tweets, photos, videos, click-streams, check-ins, data from real-world sensors like heart monitors, health records and financial records like transaction histories (<a href="http://lifestreamblog.com/introducing-the-locker-project-an-open-lifestreaming-platform-for-the-future/">source</a>).</p>
<p><img src="http://www.soa-world.de/echelon/wp-content/uploads/2011/08/hope.jpg" alt="" title="hope" width="640" height="479" class="alignnone size-full wp-image-949" /><br />
<em style="font-size: 10px">Shimmering, image by <a href="http://www.flickr.com/photos/jason-samfield/5325558533/">Jason A. Samfield</a></em></p>
<p>A third project worth mentioning is <a href="http://sparkleshare.org/">sparkleshare</a>. It is similar to the other projects in this category but allows pluggable backends. That means you can choose to use for example Github as backend for your data or of course your personal server. Awesome!</p>
<p><strong>Freedom to the Networks</strong></p>
<p>Projects such as <a href="http://k0a1a.net/netless/">netless</a> carry the idea even further because after the data is liberated, the connection itself is a soft spot. Network connections should be liberated from corporate and government control by circumventing the big centralized data hubs and instead installing a decentralized wireless mesh network where everyone can participate and communicate. </p>
<p>The adventurous netless project plans to use the city transportation grid as its data backbone. Nodes of the network are attached to city vehicles &#8211; trams, buses, taxis and possibly &#8211; pedestrians. Information exchange between the nodes happens only when the carriers pass by each other in the city traffic. Digital data switches its routes just the same way you&#8217;d switch from tram number 2 to bus number 5. Very inspiring.</p>
<p>Another idea is to utilize networks of mobile phones to create a mesh network. The <a href="http://www.servalproject.org/">serval project</a> is working on this. And they have a prototype for the Android platform ready.</p>
<p>The German <a href="http://www.freifunk.net/">Freifunk</a> community pursues a similar goal. It is a non-commercial open initiative to support free radio networks in the German region. It is part of the international movement for free and wireless radio networks (<a href="http://en.wikipedia.org/wiki/Freifunk">source</a>).</p>
<p>A purely software based project is <a href="https://www.torproject.org/">Tor</a>. It is free software and an open network that helps its users to defend against a form of network surveillance that threatens personal freedom and privacy as well as confidential business activities and relationships.</p>
<p><strong>Peer to Peer Currency</strong></p>
<p>One integral thing this article did not talk about yet is money. <a href="http://www.bitcoin.org/">Bitcoin</a>, a peer to peer currency, might be the missing puzzle piece. The Bitcoin system has no central authority that issues new money or tracks transactions &#8211; it is managed collectively by the network.</p>
<p>A major problem of digital currency has been preventing double-spending. Digital money can be copied multiple times so a mechanism is necessary to forbid spending money twice. Bitcoin refrains from having actual digital coins. The system is merely one large transaction log that tracks what money was transferred where.</p>
<p>Each participant has a pair of public and private keys to sign transactions and to allow others to verify transactions. The transactions are entered into a global ever running log that is signed in regular intervals. The signing of the log is designed to require extensive computation time. The entire network of participating users is required to sign the log. </p>
<p>This protects the entire system from false signatures and from anyone tempering with the log and modifying past transactions. An attacker would have to have more computational power at his disposal than the entire Bitcoin network to forge transactions.</p>
<p>Users that give their computing time to the network are rewarded with Bitcoins for their troubles. This is also how the money is generated in the first place. In addition, participants that transfer money are free to include a transaction fee in their order. This extra money is given to the particular user signing the transaction.</p>
<p>A considerable number of <a href="https://en.bitcoin.it/wiki/Trade">sites</a> have emerged that accept Bitcoins in exchange for services or goods. You can buy for example socks online or even pay for your lunch at a burger restaurant in Berlin. </p>
<p><strong>Conclusion</strong></p>
<p>In closing, I find it encouraging, that so many people feel that things have to change and are developing ideas and projects to make it happen. We will see many exciting things in the future and despite the overwhelming might of well-established products, I am hopeful.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.soa-world.de/echelon/2011/09/the-decentralized-web-movement.html/feed</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>MGPU v0.1</title>
		<link>http://www.soa-world.de/echelon/2011/08/mgpu-v0-1.html</link>
		<comments>http://www.soa-world.de/echelon/2011/08/mgpu-v0-1.html#comments</comments>
		<pubDate>Thu, 04 Aug 2011 19:00:21 +0000</pubDate>
		<dc:creator>Sebastian Schaetz</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[interesting stuff]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.soa-world.de/echelon/?p=824</guid>
		<description><![CDATA[Today I&#8217;m proud to announce the first release of my MGPU library. The library strives to simplify the implementation of high performance applications and algorithms on multi-GPU systems. Its main goal is both to abstract platform dependent functions and vendor specific APIs, as well as simplifying communication between different compute elements. The library is currently [...]]]></description>
			<content:encoded><![CDATA[<p>Today I&#8217;m proud to announce the first release of my MGPU library. The library strives to simplify the implementation of high performance applications and algorithms on multi-GPU systems. Its main goal is both to abstract platform dependent functions and vendor specific APIs, as well as simplifying communication between different compute elements. The library is currently an alpha release containing only limited yet already useful functionality.</p>
<p><img src="http://www.soa-world.de/echelon/wp-content/uploads/2011/08/4498443106_531213b279_z.jpg" alt="" title="4498443106_531213b279_z" width="640" height="426" class="alignnone size-full wp-image-835" /><br />
<em style="font-size: 10px">Launch of Shuttle Discovery, image by <a href="http://www.flickr.com/photos/hdrphotographyblog/4498443106/">Scott Kublin</a></em></p>
<p>The repository can be found here: <a href="https://github.com/sschaetz/mgpu">https://github.com/sschaetz/mgpu</a> and documentation is available from here: <a href="http://sschaetz.github.com/mgpu/">http://sschaetz.github.com/mgpu/</a> </p>
<p>There are also archives available: <a href="https://github.com/sschaetz/mgpu/raw/archives/mgpu_0_1.tar.bz2">mgpu_0_1.tar.bz2</a> and <a href="https://github.com/sschaetz/mgpu/raw/archives/mgpu_0_1.zip">mgpu_0_1.zip</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.soa-world.de/echelon/2011/08/mgpu-v0-1.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Nvidia Driver Version on Linux</title>
		<link>http://www.soa-world.de/echelon/2011/07/nvidia-driver-version-on-linux.html</link>
		<comments>http://www.soa-world.de/echelon/2011/07/nvidia-driver-version-on-linux.html#comments</comments>
		<pubDate>Fri, 01 Jul 2011 13:29:53 +0000</pubDate>
		<dc:creator>Sebastian Schaetz</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[interesting stuff]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.soa-world.de/echelon/?p=822</guid>
		<description><![CDATA[How to get the version of the Nvidia kernel module on Linux? I&#8217;m posting this here because I&#8217;m sure I will forget this again. This is very relevant when evaluating that the proper driver is installed for CUDA use. On my system this returns:]]></description>
			<content:encoded><![CDATA[<p>How to get the version of the Nvidia kernel module on Linux? I&#8217;m posting this here because I&#8217;m sure I will forget this again. This is very relevant when evaluating that the proper driver is installed for CUDA use.</p>
<pre class="brush: bash; title: ; notranslate">
cat /proc/driver/nvidia/version
</pre>
<p>On my system this returns:</p>
<pre class="brush: bash; title: ; notranslate">
NVRM version: NVIDIA UNIX x86_64 Kernel Module  270.41.19
GCC version:  gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.soa-world.de/echelon/2011/07/nvidia-driver-version-on-linux.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Talks Page</title>
		<link>http://www.soa-world.de/echelon/2011/05/talks-page.html</link>
		<comments>http://www.soa-world.de/echelon/2011/05/talks-page.html#comments</comments>
		<pubDate>Thu, 26 May 2011 21:10:11 +0000</pubDate>
		<dc:creator>Sebastian Schaetz</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[interesting stuff]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.soa-world.de/echelon/?p=815</guid>
		<description><![CDATA[I added a Talks-page to this blog. I plan to list and publish interesting talks I gave at various occasions. Currently the page lists two talks: a GPGPU seminar I gave a year ago at my old university and just recently I had the honor of speaking at BoostCon about the project I worked on [...]]]></description>
			<content:encoded><![CDATA[<p>I added a <a href="http://www.soa-world.de/echelon/talks">Talks-page</a> to this blog. I plan to list and publish interesting talks I gave at various occasions. Currently the page lists two talks: a GPGPU seminar I gave a year ago at my old <a href="http://www.hs-regensburg.de/funktion/english.html">university</a> and just recently I had the honor of speaking at <a href="http://boostcon.boost.org/">BoostCon</a> about the project I worked on last year: a library for the <a href="http://en.wikipedia.org/wiki/Cell_%28microprocessor%29">Cell processor</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.soa-world.de/echelon/2011/05/talks-page.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stallman was right</title>
		<link>http://www.soa-world.de/echelon/2011/04/stallman-was-right.html</link>
		<comments>http://www.soa-world.de/echelon/2011/04/stallman-was-right.html#comments</comments>
		<pubDate>Thu, 07 Apr 2011 20:33:05 +0000</pubDate>
		<dc:creator>Sebastian Schaetz</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[interesting stuff]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.soa-world.de/echelon/?p=480</guid>
		<description><![CDATA[&#8220;Stallman was right&#8221; is one of the important messages Eben Moglen conveys in his recent talks about Freedom and the Cloud. He&#8217;s a convincing speaker, his arguments are striking and the cause might very well be one of the most important challenges the Internet faces right now. GNUtralized, image by Bruce Bottomley He speaks about [...]]]></description>
			<content:encoded><![CDATA[<p><em>&#8220;Stallman was right&#8221;</em> is one of the important messages <a href="http://emoglen.law.columbia.edu/">Eben Moglen</a> conveys in his <a href="http://isoc-ny.org/p2/?p=1773">recent</a> <a href="http://www.isoc-ny.org/?p=1338">talks</a> about Freedom and the Cloud. He&#8217;s a convincing speaker, his arguments are striking and the cause might very well be one of the most important challenges the Internet faces right now.</p>
<p><img src="http://www.soa-world.de/echelon/wp-content/uploads/2011/04/stallman.jpg" alt="" title="stallman" width="650" height="434" class="alignnone size-full wp-image-725" /><br />
<em style="font-size: 10px">GNUtralized, image by <a href="http://www.flickr.com/photos/bruceley/3235933298/">Bruce Bottomley</a></em></p>
<p>He speaks about privacy: the freedom to choose who to share what information with. He speaks about freedom of speech: the liberty to speak and communicate freely without censorship. He speaks about how we give up those freedoms, often without noticing or worse, without caring. By signing up to facebook. By using Gmail. </p>
<p>It&#8217;s insane if you think about it. We communicate with our friends, send them private messages, through a database in Northern California. We store our personal information including images in that same database. And while we put more and more information, more and more of our lives in that database, its owners are busy thinking about ways of how to make money with our data. By now I&#8217;m sure they have come to at least one conclusion: to make money they will share our data with entities we never intended to share it with.</p>
<p>It gets worse, and Eben Moglen elaborates this very well in his <a href="http://isoc-ny.org/p2/?p=1773">keynote</a> speech at <a href="http://www.fosdem.org/2011/">Fosdem 2011</a>. All our data is routed through and even stored in a company&#8217;s database. We can choose to trust that particular company to not do anything bad with our data. But we can never be sure that the company will act in our interest if it is offered incentives (&#8220;We won&#8217;t shut you down if you comply&#8221;) to share certain data with certain government agencies. Since our data is stored in a centralized manner, agencies <a href="http://projects.washingtonpost.com/top-secret-america/articles/monitoring-america/">the likes of NSA</a> would have a field day.</p>
<p>So indeed, Stallman was right when he called <a href="http://www.guardian.co.uk/technology/2008/sep/29/cloud.computing.richard.stallman">cloud computing a trap</a>. He advises us &#8220;to stay local and stick with our own computers&#8221;.</p>
<p><img src="http://www.soa-world.de/echelon/wp-content/uploads/2011/04/libre.jpg" alt="" title="libre" width="650" height="465" class="alignnone size-full wp-image-737" /><br />
<em style="font-size: 10px">free, image by <a href="http://www.flickr.com/photos/gi/121409547/">Gisela Giardino</a></em></p>
<p>Eben Moglen sees the urgency of these problems so he is taking action: informing the public with persuasive talks and gathering smart, ingenious and influential people to find solutions under the newly founded <a href="http://www.freedomboxfoundation.org/">FreedomBox Foundation</a>. The ingredients to the solution, in accordance to Stallman&#8217;s suggestion have been identified: </p>
<ol>
<li>cheap, compact <a href="http://en.wikipedia.org/wiki/Plug_computer">plug computers</a> that can be used as personal servers</li>
<li>a free (as in freedom) software stack that is designed to respect and preserve the user&#8217;s privacy</li>
<li><a href="http://en.wikipedia.org/wiki/Mesh_networking">mesh networking</a> technology to keep the network alive if centralized internet connections fail</li>
</ol>
<p>The idea is simple: replace all cloud services (social network, e-mail, photo storage etc) with distributed systems. The FreedomBox project aims to provide everyone with a compact, cheap, low-power plug computer. Such a device will come preloaded with free software that &#8220;knows how to securely contact your friends and business associates, is able to store and securely backup your personal data and generally maintaining your presence in the various networks you have come to rely on for communicating with people in society&#8221;.</p>
<p>There are a number of other projects out there that are worth mentioning here. A very interesting assessment of the current state of the social web and existing standards is the W3C Social Web Incubator Group <a href="http://www.w3.org/2005/Incubator/socialweb/XGR-socialweb-20101206/">report</a>. The <a href="https://joindiaspora.com/">Diaspora</a> project develops distributed and secure social networking software and is worth keeping an eye on. The FreedomBox community maintains a <a href="http://wiki.debian.org/FreedomBox/ExampleProjects">comprehensive list</a> of existing projects.</p>
<p>I expect the foundation to develop a software package that provides stable system software and that encompasses a number of existing projects that allow users to move from cloud services to their own server. I will help were I can and so should you!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.soa-world.de/echelon/2011/04/stallman-was-right.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>C++ Workspace Class</title>
		<link>http://www.soa-world.de/echelon/2011/03/c-workspace-class.html</link>
		<comments>http://www.soa-world.de/echelon/2011/03/c-workspace-class.html#comments</comments>
		<pubDate>Thu, 31 Mar 2011 18:35:35 +0000</pubDate>
		<dc:creator>Sebastian Schaetz</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[interesting stuff]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.soa-world.de/echelon/?p=624</guid>
		<description><![CDATA[Oftentimes algorithms require buffers for communication or need to store intermediate results. Or they need to pre-compute and store auxiliary data. Those algorithms are often called in loops with similar or identical parameters but different data. Creating required resources an algorithm needs in every invocation is inefficient and can be a performance bottleneck. I would [...]]]></description>
			<content:encoded><![CDATA[<p>Oftentimes algorithms require buffers for communication or need to store intermediate results. Or they need to pre-compute and store auxiliary data. Those algorithms are often called in loops with similar or identical parameters but different data. Creating required resources an algorithm needs in every invocation is inefficient and can be a performance bottleneck. I would like to give users a means of reusing objects across multiple calls to algorithms.</p>
<p><img src="http://www.soa-world.de/echelon/wp-content/uploads/2011/03/133895010_96c5ba668d_o.jpg" alt="" title="133895010_96c5ba668d_o" width="650" height="366" class="alignnone size-full wp-image-709" /><br />
<em style="font-size: 10px">Bethany Cooper, image by <a href="http://www.flickr.com/photos/schneertz/133895010/">Joe Futrelle</a></em></p>
<p>The basic idea is to have a generic class that either creates the required objects for you or returns an existing object, if you already created it. Inefficient code like this:</p>
<pre class="brush: cpp; title: ; notranslate">
algorithm(T1 input, T2 output, parameters)
{
  buffer mybuff(buffer_parameters);
  calculation(input, output, buffer);
  // buffer goes out of scope and is destroyed
}

for() algorithm(input, output, parameters);
</pre>
<p>creates a buffer object in each invocation of <em>algorithm</em>. This is oftentimes unnecessary. The buffer object could be reused in subsequent calls which would result in code such as:</p>
<pre class="brush: cpp; title: ; notranslate">
algorithm(T1 input, T2 output, parameters, workspace &amp; ws)
{
  buffer &amp; mybuff = ws.get&lt;buffer&gt;(name, buffer_parameters);
  calculation(input, output, buffer);
  // buffer is not destroyed
}

{
  workspace ws;
  for() algorithm(input, output, parameters, ws);
} // workspace goes out of scope; all objects are destoryed
</pre>
<p>The name in the above code acts as an object identifier. If the same object should be used a second time it has to be accessed using the same object identifier.</p>
<p><strong>More Features</strong></p>
<p>Specifying only the name of an object as its identifier might not be enough. The following code could be ambiguous and might result in an error:</p>
<pre class="brush: cpp; title: ; notranslate">
buffer &amp; mybuff = ws.get&lt;buffer&gt;(&quot;mybuff&quot;, size(1024));
// later call
buffer &amp; mybuff = ws.get&lt;buffer&gt;(&quot;mybuff&quot;, size(2048));
</pre>
<p>When using mybuff after the later call, it might be expected that the buffer has a size of 2048. But the workspace object returns the object created before which is smaller. A simple workaround would be to always resize the buffer before it is used. </p>
<p>As an alternative the workspace object can be instructed to not only consider the name as an object identifier when checking if the object already exists but also some parameter of the constructor. Wrapping parameters with the &#8220;arg&#8221; method marks them to be considered when resolving existing objects.</p>
<pre class="brush: cpp; title: ; notranslate">
buffer &amp; mybuff = ws.get&lt;buffer&gt;(&quot;mybuff&quot;, workspace::arg(size(1024)));
// later call
buffer &amp; mybuff = ws.get&lt;buffer&gt;(&quot;mybuff&quot;, workspace::arg(size(2048)));
</pre>
<p>This code will create two different buffer objects.</p>
<p><strong>Implementation</strong></p>
<p>The workspace holds a map of pointers to the objects it manages. The map&#8217;s key is an arbitrary name for the resource. In addition to the pointer, a functor that properly destroys the object referenced by the pointer is stored.</p>
<p>A call to <em>get&lt;T&gt;</em> will check if an object with &#8216;name&#8217; already exists. If not, an object is created using the parameters (as well as a function object to destroy it). If it exists a reference is returned.</p>
<p>If the workspace goes out of scope, the destructor iterates over all object the workspace holds and destroys them in reverse order of creation.</p>
<p>I used some of the nifty new C++0x language features (variadic templates, std::function and the lambda functions) to implement the workspace class. I thought this was a good idea since the Final Draft International Standard was <a href="http://herbsutter.com/2011/03/25/we-have-fdis-trip-report-march-2011-c-standards-meeting/">approved recently</a>. I found the features to be very powerful as well as incredibly useful.</p>
<p>The argument dependent lookup is implemented in a crude way: the arguments are appended to the name string as characters. This should be sufficient for basic use and works well for all built-in types.</p>
<p>Arguments that are supposed to be added to the object identifier are detected as they are wrapped in a special_arg class. Partial template specialization and the unpack operator help appending the arguments to the object identifier.</p>
<p>The current implementation can be found in my <a href="https://github.com/sschaetz/workspace">workspace git repository</a>.</p>
<p><strong>Discussion</strong></p>
<p>It might very well be that something like this already exists in a more elegant form and that I have simply not been aware of or failed to identify as a solution to this problem. I&#8217;m for example aware of pool allocators but I believe that I propose a more abstract concept. Buffers that are part of a workspace still could use a pool allocator.</p>
<p>Also the code in the repository is written rather quickly and I&#8217;m quite sure there are some rough edges where the code is not as efficient as it could be (passing by reference comes to mind).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.soa-world.de/echelon/2011/03/c-workspace-class.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A simple lock-free queue in C++</title>
		<link>http://www.soa-world.de/echelon/2011/02/a-simple-lock-free-queue-in-c.html</link>
		<comments>http://www.soa-world.de/echelon/2011/02/a-simple-lock-free-queue-in-c.html#comments</comments>
		<pubDate>Tue, 01 Feb 2011 18:13:15 +0000</pubDate>
		<dc:creator>Sebastian Schaetz</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[interesting stuff]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.soa-world.de/echelon/?p=524</guid>
		<description><![CDATA[A while ago I needed a simple lock-free queue in C++ that supports a single producer as well as one consumer. The reason to use a lock-free data structure instead of a regular std::queue guarded by mutex and condition variable for me was to avoid the overhead of exactly those mechanisms. Also since I never [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago I needed a simple lock-free queue in C++ that supports a single producer as well as one consumer. The reason to use a lock-free data structure instead of a regular std::queue guarded by mutex and condition variable for me was to avoid the overhead of exactly those mechanisms. Also since I never came in contact with the interesting concept of lock-free data types, I thought this was an excellent opportunity to look into the matter.</p>
<p><img src="http://www.soa-world.de/echelon/wp-content/uploads/2011/02/lock1-e1296581808981.jpg" alt="" title="lock" width="600" height="347" class="alignnone size-full wp-image-587" /><br />
<em style="font-size: 10px">You can never go too far, image by <a href="http://www.flickr.com/photos/baboon/115446241/">Baboon</a></em></p>
<p>Unfortunately (or fortunately) I could not find a production ready lock-free queue in C++ for my platform (Linux). There is the <a href="http://msdn.microsoft.com/en-us/library/ee355358.aspx">concurrent_queue</a> class available in Visual Studio 2010, there&#8217;s the unofficial <a href="http://tim.klingt.org/boost_lockfree/">Boost.Lockfree</a> library (code is <a href="http://www.boostpro.com/vault/index.php?&#038;direction=0&#038;order=&#038;directory=Concurrent%20Programming">here</a>) but those options were not satisfying. I needed something simple that worked right out of the box.</p>
<p>Herb Sutter wrote an excellent <a href="http://www.drdobbs.com/high-performance-computing/210604448">article</a> a while back about designing a lock-free queue. It&#8217;s straight forward and functional. The only flaw it has from my point of view is the use of C++0x atomics which I wanted to refrain from including in my project for now. There&#8217;s of course the unofficial <a href="http://www.chaoticmind.net/~hcb/projects/boost.atomic/">Boost.Atomic</a> library, but again I wanted something simple.</p>
<p>So I reread Herbs article, especially the passage that explains the requirements for a &#8220;lock-free-safe&#8221; variable: atomicity, order and the availability of a compare and swap operation. Digging into the Boost.Atomic code I found that it is rather simple to get atomicity and order when using gcc. I&#8217;m using version 4.4.3. </p>
<p>Atomicity can be ensured using the <a href="http://gcc.gnu.org/onlinedocs/gcc-4.4.3/gcc/Atomic-Builtins.html">atomic functions</a> of gcc and order can be ensured using a memory barrier trick:</p>
<pre class="brush: cpp; title: ; notranslate">
type __sync_lock_test_and_set (type *ptr, type value)
asm volatile(&quot;&quot; ::: &quot;memory&quot;)
</pre>
<p>The first line is an atomic test and set operation and the second line is equivalent to a full memory barrier. With this functionality I was all set. Here is the modified code for the method the producer calls:</p>
<pre class="brush: cpp; title: ; notranslate">
void produce(const T&amp; t)
{
  last-&gt;next = new Node(t);                      // add the new item
  asm volatile(&quot;&quot; ::: &quot;memory&quot;);                   // memory barrier
  (void)__sync_lock_test_and_set(&amp;last, last-&gt;next);
  while(first != divider)                       // trim unused nodes
  {
    Node* tmp = first;
    first = first-&gt;next;
    delete tmp;
  }
}
</pre>
<p>I replaced the <code>atomic<Node*></code> members with regular pointers but exchanged the assignments that require atomicity and order by calls to <code>__sync_lock_test_and_set</code> preceded by the full memory barrier trick. The function call must be cast to <code>void</code> to prevent a &#8220;value computed is not used&#8221; warning.</p>
<pre class="brush: cpp; title: ; notranslate">
bool consume(T&amp; result)
{
  if(divider != last)                        // if queue is nonempty
  {
    result = divider-&gt;next-&gt;value; 	              // C: copy it back
    asm volatile(&quot;&quot; ::: &quot;memory&quot;);                 // memory barrier
    (void)__sync_lock_test_and_set(&amp;divider, divider-&gt;next);
    return true;          	                       // report success
  }
  return false;           	                    // else report empty
}
</pre>
<p>The full class can be downloaded <a href="http://www.soa-world.de/echelon/uploaded_files/lockfreequeue.cpp">here</a>. Please note that the class lacks some important functionality if your use-case is non-trivial (a proper copy-constructor comes to mind).</p>
<p><strong>What it is all about</strong></p>
<p>There is a collection of definitions of lock-free and non-blocking and wait-free algorithms and data structures that can be interesting to <a href="http://en.wikipedia.org/wiki/Non-blocking_algorithm">read</a>. </p>
<p>The idea of lock-free data structures is that they are written in a way that allows simultaneous access by multiple threads without the use of critical sections. They must be defined in a way that at any point in time any thread that has access to the data sees a well defined state of the structure. A modification was either done or not done, there is no in-between, no inconsistency. </p>
<p>This is why all critical modifications to the structure are implemented as atomic operations. It also explains why order is important: before critical stuff can be done, preparations have to be finished and must be seen by all participants.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.soa-world.de/echelon/2011/02/a-simple-lock-free-queue-in-c.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

