<?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>engin aydogan</title>
	<atom:link href="http://engin.bzzzt.biz/feed/" rel="self" type="application/rss+xml" />
	<link>http://engin.bzzzt.biz</link>
	<description>&#039;s journal</description>
	<lastBuildDate>Wed, 28 Jul 2010 06:35:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Chrome UTF-8 bug</title>
		<link>http://engin.bzzzt.biz/2010/07/28/chrome-utf-8-bug/</link>
		<comments>http://engin.bzzzt.biz/2010/07/28/chrome-utf-8-bug/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 06:27:31 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=217</guid>
		<description><![CDATA[I cannot believe what I&#8217;m seeing. UTF-8 implementations failed miserably. There&#8217;s a character in Turkish alphabet, it is capital &#8220;i&#8221;, just like &#8220;I&#8221; but with a dot on top of it. Why am I describing it instead of just showing it ? Well, WordPress also seems to be unable to handle it. From now on,]]></description>
			<content:encoded><![CDATA[<p>I cannot believe what I&#8217;m seeing. UTF-8 implementations failed miserably.</p>
<p>There&#8217;s a character in Turkish alphabet, it is capital &#8220;i&#8221;, just like &#8220;I&#8221; but with a dot on top of it. Why am I describing it instead of just showing it ? Well, WordPress also seems to be unable to handle it. From now on, [ci] refers to this special character in this post.</p>
<p><span style="font-size: large;"><strong>Chrome bug</strong></span></p>
<p>toLowerCase() of Chrome 5.0.375.99 is buggy. If a string contains [ci], the resulting string has artifacts. For instance assume you have the original string &#8220;[ci]ello&#8221;, which is 5 characters long. When you feed it to toLowerCase() the resulting string will be 6 characters long with a &#8220;garbage&#8221; data after the converted [ci]. The results is something like i\xxxello. There&#8217;s a garbage after &#8220;i&#8221; which you can see via charCodeAt().</p>
<p><span style="font-size: large;"><strong>Firefox is plagued too</strong></span></p>
<p>Then I tried in-case-sensitive RegExp matching. Trying to match &#8220;[ci]ello&#8221; with &#8220;/iello/i&#8221; failed both on Chrome 5.0.375.99 and Firefox 3.6.8.</p>
<p><span style="font-size: large;"><strong>Internet Explorer 8 kicked ass or what ?</strong></span></p>
<p>Even though I, very objectively, hate IE series too I should note that IE8&#8242;s toLowerCase and RegExp matching works perfectly. In your face, all Microsoft haters :)</p>
<p><span style="font-size: large;"><strong>What about toUpperCase() ?</strong></span></p>
<p>On all browsers toUpperCase converts &#8220;i&#8221; to &#8220;I&#8221; and not to &#8220;[ci]&#8221; and they should, since the context (language) is not known and English is naturally assumed to be the one in use, converting &#8220;i&#8221; to &#8220;I&#8221; is perfectly acceptable. Though it doesn&#8217;t make it right. In Turkish toUpperCase(&#8220;i&#8221;) should return &#8220;[ci]&#8220;. Which makes Javascript look inadequate at handling internationalization.</p>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2010/07/28/chrome-utf-8-bug/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>zero-configuration connectivity on embedded computers</title>
		<link>http://engin.bzzzt.biz/2010/07/20/zero-configuration-connectivity-on-embedded-computers/</link>
		<comments>http://engin.bzzzt.biz/2010/07/20/zero-configuration-connectivity-on-embedded-computers/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 10:33:39 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[dhcp]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[enda]]></category>
		<category><![CDATA[plc]]></category>
		<category><![CDATA[uip]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=207</guid>
		<description><![CDATA[Our device is networked. It is supposed to: Work when you plug it into any traditional Ethernet network (i.e. with router with embedded DHCP server). It is also supposed to work when you directly connect it to another node (i.e. a computer which you&#8217;re want to configure the device with &#8212; where no DHCP server is available).]]></description>
			<content:encoded><![CDATA[<p>Our device is networked. It is supposed to:</p>
<ul>
<li>Work when you plug it into any traditional Ethernet network (i.e. with router with embedded DHCP server).</li>
<li>It is also supposed to work when you directly connect it to another node (i.e. a computer which you&#8217;re want to configure the device with &#8212; where no DHCP server is available).</li>
</ul>
<p>So our goal is:</p>
<ul>
<li>Zero-configuration connectivity on above two scenarios.</li>
</ul>
<p>Our requirement:</p>
<ul>
<li>Severely scarce resources. Firmware should fit in a 64kb space.</li>
</ul>
<p>Most such networked devices comes with a static IP already set and the node which is supposed to configure them (usually a PC) is supposed to be set to a specific IP address in the same subnet to configure them. This has several drawbacks:</p>
<ul>
<li>Users need to have administration privilleges</li>
<li>Users need to have experience with computers</li>
<li>And this is OS dependent.</li>
</ul>
<p>There are other zero-configuration technology stacks, even though I don&#8217;t have a scientific fact, from their specs I think they&#8217;d take up significant code space.</p>
<p>So here&#8217;s what I&#8217;ve did</p>
<ol>
<li>During device boot I assign it a link-local IP address (i.e. AUTOIP or <a href="http://tools.ietf.org/html/rfc3927">http://tools.ietf.org/html/rfc3927</a>). I did not implement RFC3927 and just generated a fixed IP address according to MAC of the device &#8212; partly because I don&#8217;t have a quality random number generator, as there&#8217;s no clock on most of the devices and reading analog inputs often give same results.</li>
<li>Then I start DHCP negotiations</li>
</ol>
<p>With the scenario the device is able to communicate with another node which also have been assigned to a link-local address without waiting for a DHCP timeout. So when you plug your device directly to your computer you can communicate with the device as soon as your computer also assigned itself a link-local address. This varies from OS to OS but we&#8217;re pleased with the results. Our customers are able to connect to their devices without any configuration.</p>
<p>But there&#8217;s a problem! Even though this configuration worked on our network at the office and many other places where we sold the devices to, it didn&#8217;t work on my home network. It turned out that my linksys router in my home network does not honor DHCP DISCOVER requests if their source IP addresses are not 0.0.0.0</p>
<p>Problem:</p>
<ul>
<li>Some DHCP servers does not honor DHCP DISCOVER requests from 169.254.C.D. They strictly require source IP of the requests to be 0.0.0.0</li>
</ul>
<p>To solve this problem I could either</p>
<ul>
<li>First assign my device IP address 0.0.0.0 and then wait for DHCP timeout, then fallback to AUTO IP. This way DHCP DISCOVER request would work with all routers but other party would have to wait for my device to timeout DHCP and fallback to link-local IP before starting communicating with it &#8212; this is a serious tradeoff.</li>
<li>Or Add UDP IP Spoofing on top of our current implementation hence just make the DHCP DISCOVER source IP 0.0.0.0 and keep the rest the same.</li>
</ul>
<p>Obviously I chose the second approach and patched uIP with the following code:</p>
<pre>$ svn diff
Index: uip/uip.c
===================================================================
--- uip/uip.c   (revision 226)
+++ uip/uip.c   (working copy)
@@ -1181,7 +1181,17 @@
   BUF-&gt;srcport  = uip_udp_conn-&gt;lport;
   BUF-&gt;destport = uip_udp_conn-&gt;rport;

-  uip_ipaddr_copy(BUF-&gt;srcipaddr, uip_hostaddr);
+  extern int g_udp_spoof;
+  extern uip_ipaddr_t g_udp_spoof_ip;
+  if(!g_udp_spoof)
+  {
+    uip_ipaddr_copy(BUF-&gt;srcipaddr, uip_hostaddr);
+  }
+  else
+  {
+       g_udp_spoof = 0;
+       uip_ipaddr_copy(BUF-&gt;srcipaddr, g_udp_spoof_ip);
+  }
   uip_ipaddr_copy(BUF-&gt;destipaddr, uip_udp_conn-&gt;ripaddr);

   uip_appdata = &amp;uip_buf[UIP_LLH_LEN + UIP_IPTCPH_LEN];</pre>
<p>Now our device apparently has best of both worlds.</p>
<ul>
<li>It can communicate with any node with link-local IP address right away at boot time &#8212; without waiting for any sort of (DHCP) timeout.</li>
<li>While link-local communication is working, it tries to acquire an IP address from DHCP server in parallel &#8212; thanks to source IP &#8220;spoofing&#8221;.</li>
</ul>
<p>I&#8217;ll see if further testing will reveal any side effects.</p>
<p>See also:<br />
DHCP RFC: <a href="http://tools.ietf.org/html/rfc2131">http://tools.ietf.org/html/rfc2131</a><br />
Link-local IP Address (AUTO IP): <a href="http://tools.ietf.org/html/rfc3927">http://tools.ietf.org/html/rfc3927</a></p>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2010/07/20/zero-configuration-connectivity-on-embedded-computers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ExternalInterface performance on different browsers</title>
		<link>http://engin.bzzzt.biz/2010/04/15/externalinterface-performance-on-different-browsers/</link>
		<comments>http://engin.bzzzt.biz/2010/04/15/externalinterface-performance-on-different-browsers/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 18:13:06 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[web]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[firefox]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[flex]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=192</guid>
		<description><![CDATA[ExternalInterface is the API provided by Flash to communicate with its hosting environment. For my case, it is the browsers hosting the Flash &#8220;movie&#8221;. I noticed different performance behavior on each browser. This is my attempt to measure performance penalty caused by each browser. Here&#8217;s the software versions: Flash plugin version: 10,0,32,18 Chrome 4.1.249 Firefox 3.6.3]]></description>
			<content:encoded><![CDATA[<p><a href="http://engin.bzzzt.biz/wp-content/uploads/2010/04/flash_js_overhead.png"><img class="aligncenter size-full wp-image-204" title="flash_js_overhead" src="http://engin.bzzzt.biz/wp-content/uploads/2010/04/flash_js_overhead.png" alt="" width="800" height="400" /></a>ExternalInterface is the API provided by Flash to communicate with its hosting environment. For my case, it is the browsers hosting the Flash &#8220;movie&#8221;. I noticed different performance behavior on each browser. This is my attempt to measure performance penalty caused by each browser.</p>
<h3><span style="text-decoration: underline;">Here&#8217;s the software versions:</span></h3>
<p>Flash plugin version: 10,0,32,18</p>
<p>Chrome 4.1.249<br />
Firefox 3.6.3<br />
IE 8.0</p>
<h3><span style="text-decoration: underline;">How did I measure</span></h3>
<p>1. I call Been.FComm.send() function in Javascript and timestamp (T<sub>js1</sub>) it. This JS function calls the send() in the Flash.</p>
<p>2. In the Flash application I timestamp (T<sub>f1</sub>) send() function call.</p>
<p>3. In the Flash application I also timestamp (T<sub>f2</sub>) handleData() and call been_fcomm_handle JS function.</p>
<p>4. Then I timestamp (T<sub>js2</sub>) been_fcomm_handle() in Javascript.</p>
<p>Flash application is written in Flex. It sends a data over a TCP socket and reads the response back. As all functions, send() and handleData() functions in my application also has a debug() call &#8212; which includes a timestamp.</p>
<p>Here&#8217;s how I implemented measurement in Flash:</p>
<pre>private function debug(str:String):void
{
	var date:Date = new Date();
	output.appendText(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "." + date.getMilliseconds() + ": " + str);
}

private function handleData(event:ProgressEvent):void
{
	var data:String = m_socket.readUTF();
	debug("handleData"+data+"\n");
	ExternalInterface.call("been_fcomm_handle", data);
}

private function send (value:String):void
{
	debug("sending "+value+"\n");
	m_socket.writeUTF(value);
	m_socket.flush();
}</pre>
<p>So that I can measure how long Flash thinks it takes my server to give a response.</p>
<p>On the other hand, I also measure the timings in JS layer. Here&#8217;s the related code pieces &#8212; simplified to death to only contain relevant codes.</p>
<p>Here&#8217;s how I implemented measurement in Javascript:</p>
<pre>Been.Debug = new function() {
    this.info = function(m) {
        log(date.toLocaleTimeString() + "." + date.getUTCMilliseconds() + ": " + m);
    };
};

Been.FComm = new function() {
    this.handle = function(msg) {
        Been.Debug.info("Been.FComm.Handle: " + msg);
    }

    this.send = function(data) {
        Been.Debug.info("Been.FComm.send: " + data);
        Been.Utils.getFlashMovieObject("FlashComm").send(data);
    }
    /* rest of the implementation */
};</pre>
<h3><span style="text-decoration: underline;">Results</span></h3>
<p>Here are the results samples.</p>
<pre>Chrome

Avarage Flash request/response: 8.3ms
Avarage JS request/response: 161ms
Flash JS communication (marshaling) overhead: 161 - 8.3 = 152.7ms

Flash output
---------------------------------------------------------------------------------------
20:34:20.731: handleData{"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:34:20.719: sending {asf}
20:34:19.519: handleData{"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:34:19.513: sending {asf}
20:34:9.713: handleData{"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:34:9.706: sending {asf}

Javascript output
---------------------------------------------------------------------------------------
20:34:20.990: Been.FComm.Handle: {"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:34:20.720: Been.FComm.send: {asf}
20:34:19.710: Been.FComm.Handle: {"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:34:19.512: Been.FComm.send: {asf}
20:34:09.718: Been.FComm.Handle: {"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:34:09.702: Been.FComm.send: {asf}</pre>
<pre>Firefox

Avarage Flash request/response: 76ms
Avarage JS request/response: 77.6ms
Flash JS communication (marshaling) overhead: 77.6 - 76 = 1.6ms

Flash output
---------------------------------------------------------------------------------------
20:35:55.385: handleData{"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:35:55.276: sending {asf}
20:35:54.582: handleData{"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:35:54.506: sending {asf}
20:35:53.687: handleData{"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:35:53.644: sending {asf}

Javascript output
---------------------------------------------------------------------------------------
20:35:55.414: Been.FComm.Handle: {"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:35:55.303: Been.FComm.send: {asf}
20:35:54.610: Been.FComm.Handle: {"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:35:54.533: Been.FComm.send: {asf}
20:35:53.715: Been.FComm.Handle: {"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:35:53.670: Been.FComm.send: {asf}</pre>
<pre>IE

Avarage Flash request/response: 5.3ms
Avarage JS request/response: 7.6ms
Flash JS communication (marshaling) overhead:  7.6 - 5.3 = 1.3ms

Flash output
---------------------------------------------------------------------------------------
20:36:51.166: handleData{"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:36:51.162: sending {asf}
20:36:48.211: handleData{"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:36:48.207: sending {asf}
20:36:47.467: handleData{"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:36:47.459: sending {asf}

Javascript output
---------------------------------------------------------------------------------------
20:36:51.166: Been.FComm.Handle: {"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:36:51.161: Been.FComm.send: {asf}
20:36:48.211: Been.FComm.Handle: {"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:36:48.206: Been.FComm.send: {asf}
20:36:47.469: Been.FComm.Handle: {"Status":"FAILED","Error":"Internal server error.","ErrorNo":500}
20:36:47.456: Been.FComm.send: {asf}</pre>
<h3><span style="text-decoration: underline;">Summary</span></h3>
<table border="0">
<tbody>
<tr>
<td style="text-align: center;"><strong>Browser</strong></td>
<td style="text-align: center;"><strong>Flash &#8211; JS communication overhead (ms)</strong></td>
</tr>
<tr>
<td>Chrome</td>
<td style="text-align: center;">152.7</td>
</tr>
<tr>
<td>IE</td>
<td style="text-align: center;">1.3</td>
</tr>
<tr>
<td>FF</td>
<td style="text-align: center;">1.6</td>
</tr>
</tbody>
</table>
<p>It looks like Chrome suffers from the most significant overhead, while IE and FF could be considered on a par.</p>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2010/04/15/externalinterface-performance-on-different-browsers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cross-domain data-push methods compared</title>
		<link>http://engin.bzzzt.biz/2010/03/31/cross-domain-data-push-methods-compared/</link>
		<comments>http://engin.bzzzt.biz/2010/03/31/cross-domain-data-push-methods-compared/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 12:25:51 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=152</guid>
		<description><![CDATA[I&#8217;ve been playing with cross-domain (XD) data-pushing techniques lately and now I&#8217;ll try to compare each available technique. These techniques allows server to push messages to the client. A brief summary of comparison is available in the table below, following the table you can find more detailed explanation for each technique. Technology Reading Data Writing Data (HTTP]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;">I&#8217;ve been playing with cross-domain (<strong>XD</strong>) data-pushing techniques lately and now I&#8217;ll try to compare each available technique. These techniques allows server to push messages to the client. A brief summary of comparison is available in the table below, following the table you can find more detailed explanation for each technique.</p>
<table id="eng_xd_tbl" style="width: 100%; text-align: center; cursor: default; border: 1px solid black;">
<tbody>
<tr>
<td class="style7" style="background-color: #000066; text-align: center; color: white;">Technology</td>
<td style="background-color: #000066; color: #ffffff; text-align: center;" colspan="2">Reading Data</td>
<td class="style1" style="background-color: #000066; color: #ffffff; text-align: center;" colspan="2" bgcolor="DarkBlue">Writing Data (HTTP GET)</td>
<td style="background-color: #000066; color: #ffffff; text-align: center;" colspan="2">Writing Data (HTTP POST)</td>
<td style="background-color: #000066; color: #ffffff; text-align: center;">Advantages</td>
<td style="background-color: #000066; color: #ffffff; text-align: center;">Disadvantages</td>
<td style="background-color: #000066; color: #ffffff; text-align: center;">Conclusion</td>
</tr>
<tr>
<td class="style7" style="font-weight: bolder; text-align: left;">XHR</td>
<td class="style5" style="background-color: red; text-align: center;" colspan="2">No</td>
<td class="style4" style="background-color: orange; text-align: center;" colspan="2">Yes</td>
<td class="style4" style="background-color: red; text-align: center;" colspan="2">No</td>
<td class="style12">XHR is good at error handling</td>
<td class="style4">
<ul>
<li><span style="line-height: normal;">Only very recent browsers implementing access-control specs allow requests to be made.</span></li>
<li><span style="line-height: normal;">Cannot read responses at all</span></li>
<li><span style="line-height: normal;">Data writing is limited to 2kb</span></li>
</ul>
</td>
<td style="background-color: red; text-align: center;">
<h2>FAIL</h2>
<p>Because: a cross browser method with XHR for XD communication does NOT exist.</td>
</tr>
<tr>
<td class="style8" style="font-weight: bolder; text-align: left;">Script</td>
<td class="style9" style="background-color: #90ee90; text-align: center;" colspan="2">Yes</td>
<td class="style6" style="background-color: #90ee90; text-align: center;" colspan="2">Yes</td>
<td class="style6" style="background-color: red; text-align: center;" colspan="2">No</td>
<td class="style13">
<ul>
<li><span style="line-height: normal;">Can read the responses</span></li>
<li><span style="line-height: normal;">Easy to implement</span></li>
</ul>
</td>
<td class="style6">
<ul>
<li><span style="line-height: normal;">Hard to detect connection problems</span></li>
<li><span style="line-height: normal;">Data writing is limited to 2kb</span></li>
<li><span style="line-height: normal;">Long-polling is required.</span></li>
<li><span style="line-height: normal;">If remote site is not trusted, can run arbitrary code on your site.</span></li>
</ul>
</td>
<td style="background-color: #90ee90;">
<h2 style="text-align: center;">Works</h2>
</td>
</tr>
<tr>
<td class="style7" style="font-weight: bolder; text-align: left;">IFRAME + hack</td>
<td class="style9" style="background-color: #90ee90; text-align: center;" colspan="2">Yes</td>
<td style="background-color: #90ee90; text-align: center;" colspan="2">Yes</td>
<td class="style4" style="background-color: red; text-align: center;" colspan="2">No</td>
<td class="style11">
<ul>
<li><span style="line-height: normal;">Can read responses</span></li>
<li><span style="line-height: normal;">Remote sites response can be filtered by your proxy program (i.e. php) on the origin, hence a not trusted remote site can be used.</span></li>
</ul>
</td>
<td>
<ul>
<li><span style="line-height: normal;">A relaying/proxying dynamic program (i.e. php) is necessary on the domain the request is originating from.</span></li>
<li><span style="line-height: normal;">Long polling is required.</span></li>
</ul>
</td>
<td style="background-color: #90ee90;">
<h2 style="text-align: center;">Works</h2>
</td>
</tr>
<tr>
<td class="style7" style="font-weight: bolder; text-align: left;">IFRAME + form</td>
<td class="style9" style="background-color: red; text-align: center;" colspan="2">No</td>
<td style="background-color: orange; text-align: center;" colspan="2">Yes</td>
<td style="background-color: orange; text-align: center;" colspan="2">Yes</td>
<td class="style11">Can send large data</td>
<td>
<ul>
<li><span style="line-height: normal;">Cannot read responses</span></li>
<li><span style="line-height: normal;">&#8220;Start navigation&#8221; (aka click) sound of IE when you do form.submit() is really a sad deal breaker.</span></li>
</ul>
</td>
<td style="background-color: red; text-align: center;">
<h2>FAIL</h2>
<p>Because: see Disadvantages</td>
</tr>
<tr>
<td class="style3" style="font-weight: bolder; text-align: left;">IFRAME + form + hack</td>
<td class="style9" style="background-color: #90ee90; text-align: center;" colspan="2">Yes</td>
<td style="background-color: #90ee90; text-align: center;" colspan="2">Yes</td>
<td class="style4" style="background-color: #90ee90; text-align: center;" colspan="2">Yes</td>
<td class="style12">
<ul>
<li><span style="line-height: normal;">Can send large data</span></li>
</ul>
</td>
<td>&#8220;Start navigation&#8221; (aka click) sound of IE when you do form.submit()<br />
<strong>(NOTE: This really is a deal breaker, funny fun though)</strong></td>
<td style="background-color: red; text-align: center;">
<h2>FAIL</h2>
<p>Because: see Disadvantages</td>
</tr>
<tr>
<td class="style3" style="font-weight: bolder; text-align: left;">Flash</td>
<td class="style10" style="background-color: #90ee90; text-align: center;" colspan="2">Yes</td>
<td class="style4" style="background-color: #90ee90; text-align: center;" colspan="2">Yes</td>
<td class="style4" style="background-color: #90ee90; text-align: center;" colspan="2">Yes</td>
<td class="style12">
<ul>
<li><span style="line-height: normal;">A true persistent TCP connection ready to be used.</span></li>
<li><span style="line-height: normal;">Good error handling</span></li>
<li><span style="line-height: normal;">Can deal with binary protocols, hence can save bandwidth around 90%</span></li>
</ul>
</td>
<td class="style4">Note that I&#8217;ve tried very very hard to find disadvantages of this method.</p>
<ul>
<li><span style="line-height: normal;">Plug-in availability debate.</span></li>
<li><span style="line-height: normal;">Not available in mobile platforms </span></li>
<li>Slim chance of network problems</li>
</ul>
</td>
<td style="background-color: #90ee90; text-align: center;">
<h2>Works</h2>
</td>
</tr>
<tr>
<td colspan="10"><span style="background-color: #90ee90;">Yes</span>: Able to send request and read the response. i.e. Being able to send a request to http://foo.com/write.php?data=bar, which writes data &#8220;bar&#8221;, and in return being able to read the response (such as &#8220;Write Successful&#8221; or &#8220;Write Fail&#8221;<br />
<span style="background-color: orange;">Yes</span>: Able to send request but cannot read the response<br />
<span style="background-color: red;">No</span>: Cannot send request nor response.</td>
</tr>
</tbody>
</table>
<h2>Introduction</h2>
<p>I&#8217;ve studied cross domain communication as it is two separate tasks; one is <strong>reading</strong> other one is <strong>writing.</strong></p>
<h2>Available Methods</h2>
<h3>1. XHR</h3>
<p>XHR is the way to go with same-origin requests (i.e. non-XD), unfortunately it does not with with XD requests. So far browsers would simply throw an exception when you tried to do a XD request via XHR, which is defined by the standard.</p>
<blockquote><p>If the <a href="http://www.w3.org/TR/XMLHttpRequest/#origin">origin</a> of <var>url</var> is not <a href="http://www.w3.org/TR/XMLHttpRequest/#same-origin">same origin</a> with the <a href="http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest-origin"><code>XMLHttpRequest</code> origin</a> the user agent should raise a <code><a href="http://www.w3.org/TR/XMLHttpRequest/#security-err">SECURITY_ERR</a></code> exception and terminate these steps.</p></blockquote>
<p>A new standard is worked out called <a title="Access Control" href="http://www.w3.org/TR/access-control/#requirements">access-control</a> which now enables you to do XD XHR requests. Essentially it is what Flash&#8217;s policy file is to the XHR. XHR is only allowed when the target domain explicitly allows your domain.</p>
<blockquote>
<ol>
<li>Should not allow loading and exposing of resources from 3rd party servers without explicit consent of these servers as such resources can contain sensitive information.</li>
</ol>
</blockquote>
<p>You can find more detailed information about the reasons of these decisions in my <a title="Cross-domain XHR, Access-Control, preflight" href="http://engin.bzzzt.biz/2010/01/25/cross-domain-xhr-access-control-preflight/">previous post</a>.</p>
<p>So what this means is;</p>
<ul>
<li>Only if a very new browser with the new specs implement is being used,
<ul>
<li>and target domain explicitly allows the originating domain then XHR can be used for XD communication.</li>
<li>and if target domain does NOT explicitly allows the originating domain, only simple requests such as GET will be send to the target domain, and response will not be readable by the script.</li>
</ul>
</li>
<li>If a browser with new specs implement is NOT being used, then a security exception will be thrown right away.</li>
</ul>
<h3><strong>Conclusion: <span style="color: #ff0000;">FAIL</span></strong><strong>.</strong></h3>
<p>Because a cross browser method with XHR for XD communication does NOT exist.</p>
<h2>2. Script</h2>
<p style="text-align: left;">Script is one of the elements which are not restricted by the same-origin policy (SOP). Script is abused in such a manner that it allows us to do XD communication. Below figure demonstrates how script method works.</p>
<p style="text-align: left;">
<p style="text-align: left;"><a href="http://engin.bzzzt.biz/wp-content/uploads/2010/03/xdscript_web.png"><img class="size-full wp-image-177 aligncenter" title="xdscript_web" src="http://engin.bzzzt.biz/wp-content/uploads/2010/03/xdscript_web.png" alt="Script method workflow" width="430" height="210" /></a></p>
<p>Here&#8217;s what&#8217;s going on in the above figure:</p>
<ol>
<li>origin.com tries to load a JS script from remote.com/service.php</li>
<li>as the script from remote.com loads, it immediately calls a message handler in origin.com</li>
<li>hence remote.com passed information to origin.com which is an actual XD communication.</li>
</ol>
<p>Here&#8217;s what the mysterious $.getScript does roughly;</p>
<ol>
<li>Create a &lt;script&gt; element in the origin.com</li>
<li>Set src (source) property to &#8220;http://remote.com/service.php&#8221;.</li>
<li>Adds the newly created script element to &lt;head&gt; element of the page.</li>
</ol>
<p>Of course, in practice JQuery does a little bit more to ensure performance and browser <a title="JQuery browser compability" href="http://docs.jquery.com/Browser_Compatibility">compatibility</a>.</p>
<h3><strong>Conclusion: <span style="color: #99cc00;">Works </span>but&#8230;</strong></h3>
<ul>
<li>Data writing is handled with query parameters in the URL of the HTTP GET request. Such as http://remote.com/service.php?data=value. This comes with the restriction of the URL length. In practice, a 2kb of URL is said to be cross-browser compatible. So data writing is limited to 2kb.</li>
<li>Long-polling is required to get a persistent connection going. i.e. once the server gives the response, you need to re-establish the connection. This wastes resources such as bandwidth.</li>
<li>Error detection is not built-in. Browser does not tell if you if the server broke the ongoing TCP connection (which is the HTTP GET request). So you need to handle errors in your code.</li>
<li>remote.com should be trusted, as it will execute code on your page.</li>
</ul>
<h2>3. IFRAME hack</h2>
<p>This is a hack which is explained quite well in <a title="Facebook Wiki" href="http://wiki.developers.facebook.com/index.php/Cross_Domain_Communication">Facebook wiki</a>.</p>
<p><a href="http://engin.bzzzt.biz/wp-content/uploads/2010/03/Docs_xdcomm.png"><img class="aligncenter size-full wp-image-182" title="IFRAME Hack" src="http://engin.bzzzt.biz/wp-content/uploads/2010/03/Docs_xdcomm.png" alt="" width="825" height="745" /></a>Different from script method, this hack requires a proxy program (xd_receiver.php in the figure above). This has the advantage of you can filter the data coming from remote.com (facebook.com in the figure). But this is also has the disadvantage of adding another layer of maintenance in the chain.</p>
<h3><strong>Conclusion: <span style="color: #99cc00;">Works </span>but&#8230;</strong></h3>
<ul>
<li>All the problems with the script methods applies to this method, except the lust one, the remote.com trust issue.</li>
</ul>
<h2>4. IFRAME + form</h2>
<p>This technique enables you to post data to remote.com, without apparent reload of the page (i.e. AJAX-ish).</p>
<p>Here&#8217;s how:</p>
<ol>
<li>You create a &lt;form&gt; element, set it&#8217;s .method to &#8220;POST&#8221; and .action to &#8220;http://remote.com/service.php&#8221;</li>
<li>Create an &lt;iframe&gt; and insert the &lt;form&gt; element you&#8217;ve just craeted</li>
<li>Call form.submit();</li>
</ol>
<p>From my tests with Chrome and Firefox I&#8217;ve seen that this actually posts the data (I can see it on my server) but cannot read the returned result from the server. Which means you cannot see if the result of POSTing actually did something on the server. You just POST it.</p>
<p>Another deal breaker is the &#8220;click&#8221; sound Internet Explorer makes each time you call submit(). This practically renders this method useless itself.</p>
<h3><strong>Conclusion: </strong><span style="color: #ff0000;"><strong>FAILS </strong></span><strong>because&#8230;</strong></h3>
<ul>
<li>You cannot read the response from the server from Javascript.</li>
<li>Each time you call submit() method, Internet Explorer makes the click noise (which is called &#8220;Start Navigation&#8221;)</li>
</ul>
<h2>5. IFRAME + form + hack</h2>
<p>I haven&#8217;t tested this technique in theory you should be able to merge the technique 3 and 4 together to form this. To make this happen, http://remote.com/service.php should make a HTTP redirect to http://origin.com/xc_receiver.php?data=response.</p>
<p>Though the &#8220;click&#8221; sound of Internet Explorer practically renders this solution useless too.</p>
<h3><strong>Conclusion: </strong><span style="color: #ff0000;"><strong>FAILS </strong></span><strong>because&#8230;</strong></h3>
<ul>
<li>Each time you call submit() method, Internet Explorer makes the click noise (which is called &#8220;Start Navigation&#8221;)</li>
</ul>
<h2>6. Flash</h2>
<p>This method has so much advantages that I&#8217;m very surprised that it is so rarely used. i.e. it is not used for Facebook chat.</p>
<p>In this method you use an invisible Flash object which provides an interface to the Javascript code via ExternalInterface.addCallback, and access to Javascript code via ExternalInterface.call(). It works like a charm and TCP connection capabilities of the Flash is naturally much much more robust than the above hacks. Flash also provides very good error handling.</p>
<p>Plus you can use binary protocols with this, which can reduce bandwidth from 10x to x easily. You can upload any amount of data and receive any amount of data. You can a real TCP connection ready for your command for all times. Spectacular!</p>
<p>As an example a sample Facebook chat packet is 686 bytes including HTTP headers but the actual data is only 179 bytes. Facebook uses long polling, so every packet must be wrapped in a HTTP packet, hence the overhead is quite significant. Also this data is packed in rather verbose JSON format. If it was also a binary format the savings would be more, such as 80 bytes instead of 686 bytes. Rationally speaking though, packing data in binary for WEB might not be very wise and might not just worth the effort. Just getting rid of off HTTP overhead saves %73 bandwidth. On the other hand a hypothetical binary protocol could have save 88%. While that little %15 bandwidth could mean a lot for high scale web sites, it might well not worth the effort since it complicates things and adds other layers to design. Anyways&#8230;</p>
<p>Flash is so good that it is hard to find an argument against it. I&#8217;ve tried really hard;</p>
<p><strong>Flash is a plug-in!</strong></p>
<p>Availability of Flash can be questioned. According to <a href="http://www.adobe.com/products/player_census/flashplayer/version_penetration.html">http://www.adobe.com/products/player_census/flashplayer/version_penetration.html</a>, market penetration of Flash 9 is 99%. I think, this makes Flash a even more portable way than above solutions. And according to google-analytics of our site which receives 30k visits (I know not very big), 100% of the users have Flash.</p>
<p><strong>Not available in mobile platforms!</strong></p>
<p>True. Currently Flash support on mobile devices are limited. Though there&#8217;s this fact that, each mobile device inevitably requires its very own UI design. For instance, Facebook&#8217;s mobile HTML page dose not offer Chat functionality at all. Though other native applications for iPhone and Windows Mobile offers this service.</p>
<p>That&#8217;s to say, each mobile device will inevitably has its own UI anyway (which doesn&#8217;t use Flash). So this argument is not very sound neither.</p>
<p><strong>Flash&#8217;s TCP connection could be blocked!</strong></p>
<p>Common firewall set ups do not block outgoing TCP connections. And if you use a known port for your remote.com such as 80 or 443, your Firewall most likely can&#8217;t tell the difference. To tell the difference a statefull Firewall is required, and if a network has those firewalls most likely most of the sites (such as Facebook) are blocked anyway.</p>
<p>Another network problem could be that, all TCP connections are blocked and only HTTP Proxy is allowed, so that your browser is configured to use that HTTP Proxy by default. In this case Flash will fail. Though other methods mentioned above could also fail when a proxy is present. i.e. a long persistent connection which long polls use are not what HTTP Proxies are designed for.</p>
<h3><strong>Conclusion: </strong><span style="color: #99cc00;"><strong>Works</strong></span></h3>
<h1>Finally</h1>
<p>As you might have already noticed my personal bias is towards Flash, though I&#8217;m not sure why it isn&#8217;t wildly deployed as I&#8217;d imagine. I have successfully implemented the &lt;script&gt; and Flash methods myself, and I believe Flash is superior. I think only time can tell which is the best solution :)</p>
<p>Cheers.</p>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2010/03/31/cross-domain-data-push-methods-compared/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Show off time! ENDA PLC controlling 2-axis servo motors via iPhone</title>
		<link>http://engin.bzzzt.biz/2010/02/25/show-off-time-enda-plc-controlling-2-axis-servo-motors-via-iphone/</link>
		<comments>http://engin.bzzzt.biz/2010/02/25/show-off-time-enda-plc-controlling-2-axis-servo-motors-via-iphone/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 18:14:01 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=127</guid>
		<description><![CDATA[This is the project I&#8217;ve mentioned in my previous post. In this project our goal was to control a mini golf club via iPhone accelerometers, in a wireless Wii-like manner, to demonstrate the connectivity capabilities of our device. What we did is, iPhone continuously sending its absolute direction to our ENDA PLC (programmable logic controller),]]></description>
			<content:encoded><![CDATA[<p>This is the project I&#8217;ve mentioned in my <a title="Application deployment in jailbreak iPhone 3.1.2 with Xcode 3.2.1" href="http://engin.bzzzt.biz/2010/01/05/application-deployment-in-jailbreak-iphone-3-1-2-with-xcode-3-2-1/">previous post</a>.</p>
<p>In this project our goal was to control a mini golf club via iPhone accelerometers, in a wireless Wii-like manner, to demonstrate the connectivity capabilities of our device.</p>
<p>What we did is, iPhone continuously sending its absolute direction to our <a href="http://www.enda.com.tr/ENG/Products/Urunler.aspx?UrunID=225">ENDA PLC</a> (programmable logic controller), and guest software (<a title="Ladder logic" href="http://en.wikipedia.org/wiki/Ladder_logic">ladder</a> program) running on top of the firmware does some filtering and drives the servo motors.</p>
<p style="text-align: center;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="344" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/Yq1xuADImuA&amp;hl=en_US&amp;fs=1&amp;rel=0" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="425" height="344" src="http://www.youtube.com/v/Yq1xuADImuA&amp;hl=en_US&amp;fs=1&amp;rel=0" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p style="text-align: center;">YouTube video &#8211; while we were testing the system for the first time.</p>
<p style="text-align: left;">The guy controlling the golf club at first is my colleague who is the director of the whole PLC division, and he is the developer of the graphical ladder logic editor software which is available for free with our PLC devices. I&#8217;m the one responsible for the firmware of the device and some other stuff, and I&#8217;m the one scoring at 2:22 :)</p>
<p style="text-align: left;">So, this is basically a little visually programmable computer. You get the device, plot your logic in the graphical editor, it generates rather optimized C code, which is then compiled and downloaded to the PLC. Then the firmware runs this guest application.</p>
<p style="text-align: left;">Firmware&#8217;s goal is to provide a solid real time OS with robust IO. I&#8217;ve tried to engineer a completely asynchronous IO infrastructure, the result is well received by industry veterans as the device is able to handle simultaneous communication over all the communication ports (UART0, UART1, SPI0, SPI1, I2C, Eth) with no apparent overhead to the guest application. At some point, I could open-source the firmware &#8212; only after I clean up the ugly parts though :)</p>
<p style="text-align: left;">I&#8217;m also working on a relaying server project which offers zero-configuration connectivity to our devices. If the network it is attached to is connected to internet, you&#8217;ll be able to connect to the device without any configuration at all and no matter where the device is located in the world. Only things you need to know is the serial (MAC) and password of the device. I&#8217;m making initial tests of this system at the moment. I might write about it later.</p>
<p style="text-align: left;">Cheers :)</p>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2010/02/25/show-off-time-enda-plc-controlling-2-axis-servo-motors-via-iphone/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cross-domain XHR, Access-Control, preflight</title>
		<link>http://engin.bzzzt.biz/2010/01/25/cross-domain-xhr-access-control-preflight/</link>
		<comments>http://engin.bzzzt.biz/2010/01/25/cross-domain-xhr-access-control-preflight/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 11:18:46 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=113</guid>
		<description><![CDATA[It looks like my previous post about the browsers sending OPTIONS request instead of GET has nothing to do with Dojo, which got quite obvious as I saw Prototype is also behaving the same way. I&#8217;ve researched about the topic and here&#8217;s my insights. It turned out that some new specifications were implemented in IE8,]]></description>
			<content:encoded><![CDATA[<p>It looks like my <a title="First Dojo impressions" href="http://engin.bzzzt.biz/2010/01/22/first-dojo-impression/">previous post</a> about the browsers sending OPTIONS request instead of GET has nothing to do with Dojo, which got quite obvious as I saw Prototype is also behaving the same way. I&#8217;ve researched about the topic and here&#8217;s my insights.</p>
<p>It turned out that some new specifications were implemented in IE8, Safari 4, FF 3.5 and Chrome which allows you to do cross-domain XHR. Which means the pure JS implementation I have demonstrated wasn&#8217;t supposed to work at all unless this new specification was implemented. Here&#8217;s what the old XHR spec has to say about cross-domain (cross-origin) requests. Taken from <a href="http://www.w3.org/TR/XMLHttpRequest/#the-open-method">http://www.w3.org/TR/XMLHttpRequest/#the-open-method</a></p>
<blockquote style="width: 90%;"><p>If the <a href="http://www.w3.org/TR/XMLHttpRequest/#origin">origin</a> of <var>url</var> is not <a href="http://www.w3.org/TR/XMLHttpRequest/#same-origin">same origin</a> with the <a href="http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest-origin"><code>XMLHttpRequest</code> origin</a> the user agent <em>should</em> raise a <code><a href="http://www.w3.org/TR/XMLHttpRequest/#security-err">SECURITY_ERR</a></code> exception and terminate these steps.</p></blockquote>
<p>Not allowing cross-domain XHR was and is really a deal breaker and actually it pretty much stops you from implementing SOA (service oriented architectures) flexibly. But for some good reasons.</p>
<p>Here are a few theoretical scenarios:</p>
<ol>
<li>Imagine you are visiting <em>attacker.com</em> which serves a script that requests <em>bank.com/?action=money_transfer&amp;to=attacker&amp;amount=999999. </em>Assuming you have an active session with the bank, if your browser sends this request to bank.com along with the session cookie, attacker would be able to transfer money to himself. This is called <a href="http://en.wikipedia.org/wiki/CSRF">CSRF</a> (Cross-site request forgery)</li>
<li>Imagine you are visiting <em>attacker.com</em> which serves a script that requests <em>10.0.0.50/confidential_intranet_document.html</em> and sends it to himself via script. This means any client in the trusted LAN network might leak information from the LAN to internet.</li>
<li>Imagine you are visiting <em>trusted.com</em> which happens to have a security hole so that the attacker can inject malicious code in its web pages. For instance, imagine you could embed Javascript in the messages in Facebook. When other users see that message and the Javascript code you injected works on their browser, you could read their cookies, hence steal Facebook session. This is called <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> (cross-site scripting).</li>
</ol>
<p>Though there are other transport mechanisms, such as &lt;script&gt; element which is not restricted by this Same Origin Policy. These mechanisms were used instead of the obvious XHR method to achieve cross-domain requests so far. Though these elements are restricted in their own ways, see below for more detail.</p>
<p>There is a new specification being drafted to address these issues,  <a href="http://www.w3.org/TR/access-control/">http://www.w3.org/TR/access-control/</a> which is the reason why OPTIONS request was being sent instead of GET in my previous post. The new spec says that it is OK to send a simple request (which is defined as GET, HEAD and POST) cross-domain as long as there&#8217;s no custom header in it. If these conditions are <strong>not </strong>met, there should be a preflight request to ensure that the domain we&#8217;re requesting the document from allows us to fetch it &#8212; much like Flash&#8217;s policy file.</p>
<p>Note the <strong>custom headers</strong> clause above. That&#8217;s the exact reason why Prototype and Dojo was causing an OPTIONS request instead of GET, where regular JS was simply sending GET request. Dojo and Prototype adds custom headers to the requests.</p>
<p>So you might ask; cross-domain XHR was not allowed for a good reason, why is it being allowed now ?</p>
<p>Yes, cross-domain XHR is allowed now, but apparently no different than cross-domain requests you can send via img or script elements. Remember that you could always do cross-domain requests with img element too, but img element has two features that makes it not a security problem:</p>
<ol>
<li>img only can send the cookies for the domain it is loaded from. i.e. it is hard to use a remote session since it won&#8217;t send the target site&#8217;s cookie.<br />
Consider the first scenario above. If the request does not include a cookie for the bank.com, there&#8217;ll be no session. It will be a anonymous request. (Of course unless the target site uses session ID as a part of the URL, and the attacker got that SID, which is very unlikely. And if he has the SID he&#8217;ll hijack your session all together anyway).</li>
<li>You cannot read the contents of an img element, hence you cannot steal sensitive information which you aren&#8217;t supposed to read.</li>
</ol>
<p>Now, I have demonstrated myself in my previous post that cross-domain XHR worked out fine. My server received the GET request. BUT in the client xhr.responseText was empty and xhr.status was 0 (not 200). It is true that the request was actually made, but you cannot read the contents of the resource. Here&#8217;s what access-control spec says about this in <a href="http://www.w3.org/TR/access-control/#requirements">http://www.w3.org/TR/access-control/#requirements</a></p>
<blockquote style="width: 90%;">
<ol>
<li>Should not allow loading and exposing of resources from 3<sup>rd</sup> party servers without explicit consent of these servers as such resources can contain sensitive information.</li>
</ol>
</blockquote>
<p>One of the requirements of the spec is not to expose resources without explicit consent. From what I understand, here, explicit consent means Access-Control-Allow-Origin header. If the third party server allows other hosts to read its resources via this header, everything will be fine. So, this means that the new XHR is no security hole bigger than the IMG itself.</p>
<p>In fact, I&#8217;ve tested this. It turns out that when you add this header to your resource, cross-domain XHR starts to work to the fullest. i.e. you can read the content of the requested resource, as in, it is readable in xhr.responseText.</p>
<p>For your information, you can add any headers to your resources with mod_header module of Apache httpd. Just add this directive for whatever directory you want;</p>
<pre>Header set Access-Control-Allow-Origin "*"</pre>
<p>Keep in mind that, this will expose all of your resources in that directory for anyone to read. So, do this if your resources are public anyway. Or just allow the hosts you want. It could be better to do this in the programming layer, such as PHP or ASP.NET.</p>
<p>So in conclusion, with the new access-control spec, XHR is pretty similar to the Flash&#8217;s security design. Browser checks if the third party host allows you to read your resources, if so your script is allowed to read it. Note that you can make the request anyway, but reading the resource is not allowed.</p>
<p>This is a nice step forward actually, but since it will take some time that majority of the market is using browsers implement this new spec, web developers are bound to use iframe or script transports for cross-domain request.</p>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2010/01/25/cross-domain-xhr-access-control-preflight/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>First Dojo impressions</title>
		<link>http://engin.bzzzt.biz/2010/01/22/first-dojo-impression/</link>
		<comments>http://engin.bzzzt.biz/2010/01/22/first-dojo-impression/#comments</comments>
		<pubDate>Fri, 22 Jan 2010 15:40:36 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=106</guid>
		<description><![CDATA[I started implementing a daemon in Java. Essentially all our devices will connect to it and wait for commands over TCP/IP. Additionally it will offer a web service REST API over HTTP, so that administrators can send/receive data from the devices. This is basically a relaying architecture between devices and administrators. It overcomes any network]]></description>
			<content:encoded><![CDATA[<p>I started implementing a daemon in Java. Essentially all our devices will connect to it and wait for commands over TCP/IP. Additionally it will offer a web service REST API over HTTP, so that administrators can send/receive data from the devices. This is basically a relaying architecture between devices and administrators. It overcomes any network topology problem (i.e. NAT traversals.) with performance penalty and bandwidth costs of relaying. Web service API is going to be totally self-sufficient, such that totally static HTML pages with Javascript can interact with it.</p>
<p>I&#8217;ve implemented the skeleton of the daemon, devices connect to it and it also offers web service API. I tested the web service API by simply requesting the web service URL from the browser as I would do any other URL and confirmed that the correct (JSON) response is given. It was time to see how it is to build a web UI for it. Given its reputation and apparent support, I chose Dojo to implement the web UI with totally static HTML pages. Here&#8217;s my experience.</p>
<p><strong>Documentation</strong></p>
<p>From the main Dojo site, it was stated that latest stable release was 1.4.0, and it was the default download link. So I grabbed it. By looking at an example in the demo section, I get an Ajax query working in seconds, only to find out that it is not working for me. Instead of a GET request it was sending OPTIONS request, more on this later. Obviously, I wanted to look at the documentation. Clicking on the Documentation link on the main Dojo site takes you to a place where documentation for 1.4.0 is not offered.</p>
<p>Luckily there were a handful of helpful folks in #dojo @ irc.freenode.net, whom told me that new documentation UI is on its way.</p>
<ul>
<li><a href="http://api-staging.dojotoolkit.org/">http://api-staging.dojotoolkit.org/</a></li>
<li><a href="http://doc-staging.dojocampus.org/dojo/index.html">http://doc-staging.dojocampus.org/dojo/index.html</a></li>
</ul>
<p>The first one was inaccurate by the time I&#8217;m writing this Dojo.xhrGet property list was quite short. I found doc-staging to be more accurate and since it is documentation rather than just reference it also offered much more detail.</p>
<p><strong>Dojo.xhrGet results in OPTIONS request instead of GET</strong></p>
<p>The firs thing I&#8217;ve tried with Dojo was obviously the Ajax API.</p>
<pre>function getText() {
  dojo.xhrGet({
    url: "http://localhost:8182/hello",
    load: function(responseObject, ioArgs){
      return responseObject;
    },
    error: function(response, ioArgs){
      dojo.byId("toBeReplaced").innerHTML =
        "An error occurred, with response: " + response;
      return response;
    },
    handleAs: "json"
  });
}</pre>
<p>This code snippet is taken from Dojo examples which can be found in the official web site. I removed the content of the first function though, it was supposed to do DOM manipulation obviously.</p>
<p>When I run this code, I noticed OPTIONS request in my daemon&#8217;s logs. When I was requesting the same URL by writing it to the address bar of the browser all I see was GET requests in my logs, as expected.</p>
<p>Then I&#8217;ve tried a pure JS implementation.</p>
<pre>var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "http://192.168.1.94:8182/hello");
client.send();</pre>
<p>With this simple implementation I started seeing GET requests in my server as expected. So Dojo should be doing something in a different way. I walked through the Dojo code, thanks to Firebug.  But it turned out that the code is indeed very similar to the regular JS code and there were no obvious bugs, as I expected. Then, I examined the HTTP requests via invaluable Wireshark.</p>
<p>Here&#8217;s what I got for Dojo request.</p>
<pre>OPTIONS /hello HTTP/1.1
Host: 192.168.1.94:8182
Connection: keep-alive
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.49 Safari/532.5
Cache-Control: max-age=0
Access-Control-Request-Method: POST
Origin: file://
Access-Control-Request-Headers: X-Prototype-Version, X-Requested-With, Content-type, Accept
Accept: */*
Accept-Encoding: gzip,deflate
Accept-Language: tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-9,utf-8;q=0.7,*;q=0.3</pre>
<p>And here&#8217;s what a regular JS XHR looks like.</p>
<pre>GET /hello HTTP/1.1
Host: 192.168.1.94:8182
Connection: keep-alive
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.49 Safari/532.5
Cache-Control: max-age=0
Origin: file://
Accept: */*
Accept-Encoding: gzip,deflate
Accept-Language: tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-9,utf-8;q=0.7,*;q=0.3</pre>
<p>Obviously the difference is <em>Access-Control-*</em> properties. I tracked down the source of this was the lines from 10474 to 10477 of dojo.js</p>
<pre> // FIXME: is this appropriate for all content types?
10474 xhr.setRequestHeader("Content-Type", args.contentType || _defaultContentType);
10475 if(!args.headers || !("X-Requested-With" in args.headers)){
10476 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
10477 }</pre>
<p>Funny thing, there&#8217;s a FIXME there :) Anyway, when I commented out these lines the request headers were the same for both pure JS Ajax implementation and the Dojo Ajax implementation. And both are now sending GET requests as expected.</p>
<p>I consulted the folks at #dojo about this problem and at first they couldn&#8217;t create the problem. Than I&#8217;ve stated that the web UI is hosted at X and the web service API of the deamon was at X:P. So it is a cross-domain request. To be precise the script was hosted at http://192.168.1.94/test.html and web service API of the daemon was available at http://192.168.1.94:8182/hello. <em>sfoster</em> from #dojo generously spent some time to test this situation and he also confirmed that OPTIONS requests were being sent. <strong>Apparently when Access-Control-* headers are set and it is a cross-domain request browsers decide to send OPTIONS request instead of GET.</strong> This is tested with Chrome and Firefox.</p>
<p>Though I believe Access-Control-* properties are there for a good reason. This same problem could also be demonstrated on prototype javascript framework, apparently they are taking the same approach on this.</p>
<p>I&#8217;m not sure what is the best practice on this yet, I&#8217;ll try to consult some core Dojo developers about this and figure it out.</p>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2010/01/22/first-dojo-impression/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Application deployment in jailbreak iPhone 3.1.2 with Xcode 3.2.1</title>
		<link>http://engin.bzzzt.biz/2010/01/05/application-deployment-in-jailbreak-iphone-3-1-2-with-xcode-3-2-1/</link>
		<comments>http://engin.bzzzt.biz/2010/01/05/application-deployment-in-jailbreak-iphone-3-1-2-with-xcode-3-2-1/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 10:18:19 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=94</guid>
		<description><![CDATA[I recently got a Macbook to develop an application for our company to show off at the industrial automation fair this year. I&#8217;ll probably post about the project later, if I can manage to build it. Since I have no intention to put any application on App Store, and I don&#8217;t want to wait for]]></description>
			<content:encoded><![CDATA[<p>I recently got a Macbook to develop an application for our company to show off at the industrial automation fair this year. I&#8217;ll probably post about the project later, if I can manage to build it.</p>
<p>Since I have no intention to put any application on App Store, and I don&#8217;t want to wait for the approval process, I decided to deploy my application on a jailbroke iPhone. Here&#8217;s how:</p>
<ol>
<li>Visit <a href="http://blackra1n.com">blackra1n.com</a> and jailbreak your iPhone.</li>
<li>Follow these <a href="http://www.iphonedevwiki.net/index.php?title=Xcode">instructions</a> carefully. (<a href="http://backupurl.com/alkdz7">backup</a>)</li>
<li>Above instructions does not mention that you have to select the certificate you have just created explicitly in Xcode. You can do it by selecting your project in &#8220;<em>Groups &amp; Files</em>&#8221; pane, then hitting <em>Command + I. </em>This will pop up <em>Get Info</em> window for the project. In the <em>Build</em> tab, <em>Code Signing</em> category select the certificate you have just created.</li>
<li>Now you can get the infamous &#8220;No provisioned iPhone OS device is connected.&#8221; error as I did. With the inspiration from this <a href="http://www.macoscoders.com/2009/06/18/error-starting-executable/">article</a> (<a href="http://backupurl.com/z277mp">backup</a>), in Xcode I did <em>Window</em> -&gt; <em>Organizer</em> and selected my iPhone and clicked <em>Use for development.</em></li>
<li><em>Now I&#8217;m able to deploy my apps to the jailbroke iPhone.</em></li>
</ol>
<p>Final words&#8230; I must say, in contrast to this, programming a Windows Mobile device is as easy as plugging the device to your computer and clicking debug button.</p>
<p>Even though Apple&#8217;s intention to strictly supervise the applications going into App Store is a good choice (because you don&#8217;t have crap-ware that cripples your device as you&#8217;d see in Windows platforms), restricting one from programming his own device is plain stupid.</p>
<p>NOTE: Above method is a pain in the ass and it does not support build-and-go/debug feature of Xcode &#8212; though there are documentation that explains how to do it. I end-up buying a subscription for $99, the whole process took 16h, and I had to fax a signed document to Apple. So if you are in a region that you can do subscription online, you&#8217;d be done in much shorter time.</p>
<p>Conclusion: Buy a subscription :)</p>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2010/01/05/application-deployment-in-jailbreak-iphone-3-1-2-with-xcode-3-2-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Fikifiki &#8211; Very simple sudoku solver in C</title>
		<link>http://engin.bzzzt.biz/2009/12/24/fikifiki-very-simple-sudoku-solver-in-c/</link>
		<comments>http://engin.bzzzt.biz/2009/12/24/fikifiki-very-simple-sudoku-solver-in-c/#comments</comments>
		<pubDate>Thu, 24 Dec 2009 16:01:36 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[stuff i coded]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=82</guid>
		<description><![CDATA[It was like 4 months ago. I was waiting for something indefinitely in a hospital. Luckily though I had my old cute iBook with me, which includes a gcc in it! Even Eclipse! Then I saw the sudoku puzzle in the papers. So I quickly coded a sudoku solver in C in a couple of hours.]]></description>
			<content:encoded><![CDATA[<p>It was like 4 months ago. I was waiting for something indefinitely in a hospital. Luckily though I had my old cute iBook with me, which includes a gcc in it! Even Eclipse! Then I saw the sudoku puzzle in the papers. So I quickly coded a sudoku solver in C in a couple of hours. I could have had added many algorithms in it, but I just added the most simplest one and it surprisingly worked in my first try :) This one simple algorithm is able to solve easy leveled sudoku puzzles. Though one can add as many algorithms as necessary. Everything is 655 lines of C code &#8212; with all the formatting and the comments (if any). Here&#8217;s the <a href="http://engin.bzzzt.biz/files/fikifiki.tar.bz2">code</a>. This will probably be used by some lazy ass students  :)</p>
<p>You can compile by either invoking &#8220;make&#8221; in Release or Debug directories, or just import the project in Eclipse and enjoy there.</p>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2009/12/24/fikifiki-very-simple-sudoku-solver-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Macros in C/C++, the right way.</title>
		<link>http://engin.bzzzt.biz/2009/12/12/macros-in-c-the-right-way/</link>
		<comments>http://engin.bzzzt.biz/2009/12/12/macros-in-c-the-right-way/#comments</comments>
		<pubDate>Sat, 12 Dec 2009 10:09:33 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[c]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=50</guid>
		<description><![CDATA[When used appropriately macros are very useful, yet they are very easy to misuse. Before getting into cons and pros, first lets make sure if we really know what is a macro and how does it work. Roughly there are three stages of compilation in C; preprocessing, compiling, linking. It really makes sense and it]]></description>
			<content:encoded><![CDATA[<p>When used appropriately macros are very useful, yet they are very easy to misuse. Before getting into cons and pros, first lets make sure if we really know what is a macro and how does it work.</p>
<p>Roughly there are three stages of compilation in C; preprocessing, compiling, linking. It really makes sense and it is very easy to understand, don&#8217;t think of this as a complex deal. We&#8217;ll mostly talk about the preprocessor stage in this post. As the name implies, this stage just pre-processes the source code before compiling it, it all happens prior to compiling and that&#8217;s it. Preprocessing includes defining some macros, and replacing each macro found in the source code with its value, so that it can be compiled. So get this right once and for all, macros are processed before compilation, they won&#8217;t be in the run-time code.</p>
<p>As an exercise you can use -E parameter of GCC, which will make it stop right after the preprocessing stage.</p>
<p>Now, let&#8217;s begin with a few examples;</p>
<pre>#define ERROR_SEEK 152
if( errno == ERROR_SEEK )
{
    // Handle the error.
}</pre>
<p>This directive defines a macro ERROR_SEEK. Preprocessor will replace every occurrences of ERROR_SEEK with 152 prior to compiling. So, the code that is going to be sent to compiler will have &#8220;if( errno == 152)&#8221; not the ERROR_SEEK because the compiler simply does not know what ERROR_SEEK is. Nothing fancy, dead simple. But it makes the code much more readable. Look at this example;</p>
<pre>#ifdef __GNUC__
#define COMPILER "gcc"
#else
#define COMPILER "proprietary"
#endif</pre>
<p>If __GNUC__ is defined somehow then every occurrences of COMPILER will be replaced with &#8220;gcc&#8221; and &#8220;proprietary&#8221; otherwise. Please note that this all happens before compilation, and this will not result in any executable code. In this special case __GNUC__ is defined by GCC itself. Though we can define a macro via #define directive in the source code, or with -D parameter of the compiler (which will work on most compilers).</p>
<p>Actually the name preprocessor says it all. All these preprocessor directives are pre processed before compilation. Makes sense uh ? Now I think we begin to understand the nature of macros/preprocessors.</p>
<p>Macros can be used to</p>
<ul>
<li>Improve readability (ERROR_SEEK is much more meaningful than 152)</li>
<li>Improve maintainability (When you change ERROR_SEEK in one header, it will be replaced all over the source code)</li>
<li>Ensuring that a block of code is inlined (more on this later)</li>
</ul>
<p>Though, if misused, the first two list items above will do  just the opposite :)</p>
<p>As for the possible disadvantages of preprocessors</p>
<ul>
<li>Could make debugging harder as lines of source lines before and after the preprocessing will be different, so debugger can be confused while stepping the executable code and matching which source line of code it is.</li>
<li>It is easy to misuse preprocessors.</li>
<li>Could cause trouble to static code analyzers.</li>
</ul>
<p>Now, possible misuse scenarios:</p>
<h2>1. Operator precedence</h2>
<p>The most common misuse scenario which you&#8217;ll see in almost every C book is this;</p>
<pre>#define FOO_CONST 83+22
printf("%d\n", FOO_CONST * 5 ); // This macro will expand to 83 + 22 *  5, hence will result 193.</pre>
<p>One could expect the result to be printed 525. But operator precedence would make the calculation 22 * 5 first, then add 83 to the result, so you&#8217;ll see 193 as a result instead of 525. Fixing this problem is easy;</p>
<pre>#define FOO_CONST (83+22)
printf("%d\n", FOO_CONST * 5 ); // This macro will expand to (83+22) * 5, hence will result 525.</pre>
<p>Enclosing the value of a macro is an easy way to ensure that they are evaluated in the right order.</p>
<h2>2. Multiple statements</h2>
<p>You can use multiple-statement macros to force inlining of a code block. Though note that this will increase the code size of your program. Anyway, the problem with the multiple-statements is a less known problem. Now, look at this.</p>
<pre>#define HELLO(X) printf("Hello "); printf( X "\n" );</pre>
<p>The problem with this code is, if you want to conditionally run this code with &#8220;if&#8221; this code will not do what you intend to do.</p>
<pre>if(0)
    HELLO("world"); // You'd expect that this HELLO() is never "executed".</pre>
<p>Above code will expand into</p>
<pre>if(0)
    printf("Hello ");
printf( "world" "\n" );</pre>
<p>As you can see in the above example only the first statement in the macro is conditionally executed, this is not what we intended for. Above code will always print &#8220;world\n&#8221;.</p>
<p>So, first thing comes to mind is to put them in curly brackets. Now let&#8217;s evaluate that.</p>
<pre>#define HELLO(X) { printf("Hello "); printf( X "\n" ); }</pre>
<p>Above code looks fine at first glance, but it will also introduce a sneaky bug that will result in compilation error. Now imagine above macro is used like this;</p>
<pre>if(1)
    HELLO("world");
else
    HELLO("baby");</pre>
<p>This will expand into;</p>
<pre>if(1)
{
    printf("Hello ");
    printf("world" "\n");
}; // WE GOT ERROR HERE
else
{
    printf("Hello ");
    printf("baby" "\n");
};</pre>
<p>So, here&#8217;s the trick which works perfectly. It is the <em>do{} while(0)</em> trick. OK, let&#8217;s see.</p>
<pre>#define HELLO(X) do { printf("Hello "); printf( X "\n"); } while(0)</pre>
<p>You can use this as you please, imagine the <em>if else</em> scenario.</p>
<pre>if(1)
    HELLO("world");
else
    HELLO("baby");</pre>
<p>This will expand into;</p>
<pre>if(1)
    do { printf("Hello "); printf( "world" "\n" ); } while(0);
else
    do { printf("Hello "); printf( "baby" "\n" ); } while(0);</pre>
<p>So <em>do {} while(0)</em> does not break when you place a semi-colon after it and also has a scope. So it&#8217;s a ideal for making sure your multiple-statements are executing as you expected.</p>
<p>Well, I guess that&#8217;s all I&#8217;ve got to say.</p>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2009/12/12/macros-in-c-the-right-way/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
