<?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>Code Of Honor</title>
	<atom:link href="http://www.codeofhonor.com/blog/feed" rel="self" type="application/rss+xml" />
	<link>http://www.codeofhonor.com/blog</link>
	<description>Coding and beyond</description>
	<lastBuildDate>Thu, 03 May 2012 22:57:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Reducing perceived latency</title>
		<link>http://www.codeofhonor.com/blog/reducing-perceived-latency?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=reducing-perceived-latency</link>
		<comments>http://www.codeofhonor.com/blog/reducing-perceived-latency#comments</comments>
		<pubDate>Thu, 03 May 2012 22:57:05 +0000</pubDate>
		<dc:creator>webcoyote</dc:creator>
				<category><![CDATA[Game design]]></category>
		<category><![CDATA[latency]]></category>

		<guid isPermaLink="false">http://www.codeofhonor.com/blog/?p=156</guid>
		<description><![CDATA[Before Instagram was a billion dollar company, Mike Krieger posted a presentation called Secrets to Lightning Fast Mobile Design about how his team made the Instagram photo-sharing application feel so responsive, which is one of the key reasons their company &#8230; <a href="http://www.codeofhonor.com/blog/reducing-perceived-latency">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Before Instagram was a billion dollar company, Mike Krieger posted a presentation called <a href="http://speakerdeck.com/u/mikeyk/p/secrets-to-lightning-fast-mobile-design">Secrets to Lightning Fast Mobile Design</a> about how his team made the Instagram photo-sharing application feel so responsive, which is one of the key reasons their company has garnered so many users so quickly. This slide caught my attention because the same trick is a cornerstone of good online game design:</p>

<div id="attachment_158" class="wp-caption aligncenter" style="width: 846px"><a href="http://www.codeofhonor.com/blog/wp-content/uploads/2012/05/we-upload-here.jpg"><img src="http://www.codeofhonor.com/blog/wp-content/uploads/2012/05/we-upload-here.jpg" alt="Instagram appears to upload faster because it starts uploading sooner than other apps" title="we upload here" width="836" height="554" class="aligncenter size-full wp-image-158" /></a><p class="wp-caption-text">Why Instagram is worth big bucks</p></div>

<p>To ensure a great online game-play experience, your job as a game designer is to minimize the perceived latency between initiating an action and having that action actually take effect in-game, even though there may be 300-400 hundred milliseconds of actual latency between the game client and game server. Actually, I might be dating myself a bit &#8212; early Real-Time Strategy (RTS) games had to expect such huge latency because most players were using modems. Internet latency is much lower now but user expectations are higher, so every trick we can use to hide that latency is still useful.</p>

<p>First, it&#8217;s important to recognize why latency is so high in RTS games. Games like Warcraft, Starcraft, and Age of Empires are built using a &#8220;lockstep model&#8221;. All of the computers running a game simulation perform player actions &#8220;at the same time&#8221;. Well, not at <em>exactly</em> the same time, but during the same game &#8220;turn&#8221;.</p>

<p>It works like this: when you tell your Ogre Mage to attack my Peasant, your computer sends a network message to my computer. And then your computer ignores the attack action for a while. What?!? Yeah, your computer can&#8217;t act on that action yet because, if it did, your computer and my computer would be &#8220;out of sync&#8221;. <em>Your</em> computer has to wait until it receives <em>my</em> message for <em>that</em> game turn, and then both of our messages can be processed at once. Here&#8217;s a diagram that shows what&#8217;s going on:</p>

<div id="attachment_157" class="wp-caption aligncenter" style="width: 1011px"><a href="http://www.codeofhonor.com/blog/wp-content/uploads/2012/05/packet-timeline.jpg"><img src="http://www.codeofhonor.com/blog/wp-content/uploads/2012/05/packet-timeline.jpg" alt="Actions initiated on turn one don&#039;t take effect until turn four!" title="packet timeline" width="1001" height="371" class="size-full wp-image-157" /></a><p class="wp-caption-text">Delaying execution of actions allows time for packets to arrive from remote players</p></div>

<p>If you&#8217;re interested in implementation details, Mark Terrano wrote <a href="http://www.gamasutra.com/view/feature/3094/1500_archers_on_a_288_network_.php">1500 Archers on a 28.8: Network Programming in Age of Empires and Beyond</a>. The Warcraft and Starcraft RTS games used the basic same network model a couple of years prior, but Mark gets big props for writing the first article. And here I am just starting to blog 15+ years later!</p>

<p>So anyway, what this means is that, even though your game engine <em>knows</em> your Ogre Mage is going to attack, it can&#8217;t do anything to modify the state of the game world or the simulation will be de-synchronized.</p>

<p>Which means that you&#8217;re not getting any feedback that you&#8217;re about to kick my ass. No fun!</p>

<p>So here&#8217;s the solution: provide instantaneous visual and auditory feedback, without making changes to the game simulation.</p>

<p>Remember all those funny voices in Warcraft: &#8220;Yes, milord&#8221;; &#8220;At once, sire&#8221;, &#8220;Daboo&#8221;, &#8220;Zug Zug&#8221;? While quite entertaining in and of themselves, their fundamental purpose is to immediately reassure players by confirming that their orders are being obeyed.</p>

<p>In addition to playing a sound effect &#8216;Craft games also played an animation effect on the map-screen which, while it had no effect on the game-play, showed the target of the action.</p>

<p>So there you go, another tool to add to your game-designer toolbox. Improving online game responsiveness is not just about writing better networking code to minimize Internet latency, it&#8217;s about finding ways to minimize perceived latency by providing instantaneous feedback to user requests.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codeofhonor.com/blog/reducing-perceived-latency/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Choosing a game network library</title>
		<link>http://www.codeofhonor.com/blog/choosing-a-game-network-lib?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=choosing-a-game-network-lib</link>
		<comments>http://www.codeofhonor.com/blog/choosing-a-game-network-lib#comments</comments>
		<pubDate>Mon, 09 Apr 2012 19:39:09 +0000</pubDate>
		<dc:creator>webcoyote</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.codeofhonor.com/blog/?p=111</guid>
		<description><![CDATA[Since I’ve been developing online games since 1991, many folks have asked me to recommend a 3rd-party network library for their game project. Unfortunately, I can’t! At least I can’t recommend one from personal experience because the projects I’ve worked &#8230; <a href="http://www.codeofhonor.com/blog/choosing-a-game-network-lib">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Since I’ve been developing online games since 1991, many folks have asked me to recommend a 3rd-party network library for their game project.</p>

<p>Unfortunately, I can’t! At least I can’t recommend one from personal experience because the projects I’ve worked on &#8212; Warcraft, Diablo, Starcraft, battle.net and Guild Wars – were all built on proprietary, &#8220;from the ground up&#8221; network code I developed or co-developed.</p>

<p>But I’ve been meaning to do some research into 3rd-party network libraries so I don’t have to write something from scratch next time; it just takes too long. The core networking libraries I wrote for Guild Wars comprise about 50K lines of code and took several years to fully stabilize because of esoteric issues. To give you a brief idea of some of the scary bits:</p>

<ul>
<li>Setting TCP window size: enabling high throughput over long-distance connections without exposing servers to distributed denial-of-service (DDoS) attacks from clients connected to the same server.</li>
<li>Message buffering: don’t drop a connection just because the other side stalled, but be careful not to allow DDoS attacks.</li>
<li>Socket shutdown issues: close sockets “nicely” to avoid disconnect delay but don’t expose servers to DDoS attacks.</li>
<li>Rate-limiting connections &amp; throughput: ensure that servers can’t be abused by DDoS attacks – are you noticing a pattern here?!?</li>
</ul>

<p>It is difficult to select a network library because there are so many parameters. Are you looking for a reliable message-pusher? Should it use TCP, UDP or both? Do you want object synchronization? Should object synchronization include client-side prediction? Do you want only client-to-server, or do you also need to handle server-to-server communications too? Cryptography? Network firewall traversal (aka <a href="http://en.wikipedia.org/wiki/UDP_hole_punching">UDP hole-punching</a>)?</p>

<p>I’m going to start by eliminating libraries that don&#8217;t have a cross-platform story; let&#8217;s choose something that works for PC, console and mobile. While game projects don&#8217;t need to run on all of them, it is desirable for the programming team to be able to switch to different platforms without having to relearn everything.</p>

<p>Further, using a high-level API is a good choice for most game teams. Sending packets isn’t hard; sending reliable, compressed, scalable, encrypted, low-latency object-synchronization messages is hard. Let someone else do the work!</p>

<p>These high-level, cross-platform network libraries all look like they’re appropriate for game development:</p>

<ul>
<li><a href="http://www.jenkinssoftware.com/features.html">Raknet</a></li>
<li><a href="http://www.zeroc.com/overview.html">Ice</a></li>
<li><a href="http://pocoproject.org/index.html">PocoProject</a></li>
</ul>

<p>Here are some other high-level libraries I looked at but don’t think are appropriate:</p>

<ul>
<li><a href="http://www.zoidcom.com">Zoidcom</a> – no pricing available on the site, which is a hassle up front.</li>
<li><a href="http://opentnl.sourceforge.net/doxydocs/fundamentals.html">Torque Network Library (TNL)</a> &#8211; no longer supported.</li>
<li><a href="http://github.com/nardo/tnl2">TNL2</a> &#8211; also appears dead; GPL license prevents use in commercial game clients.  </li>
<li><a href="http://enet.bespin.org/Features.html">ENet</a> &#8211; lacking high-level documentation.  </li>
<li><a href="http://www.cs.wustl.edu/~schmidt/ACE.html">ACE</a> &#8211; looks dauntingly complex.</li>
</ul>

<p>And here are some lower-level or more purpose-specific libraries:</p>

<ul>
<li><a href="http://www.zeromq.org">ZeroMQ</a> &#8211; great for server-to-server but I wouldn’t use it for client->server: not robust against hacking.</li>
<li><a href="http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/overview.html">Boost ASIO</a> &#8211; solid and complete, but (flame) using boost is a religious issue for some because it is especially hard-to-read C++ code, and can dramatically increase build-time (/flame).</li>
<li><a href="http://libevent.org">LibEvent</a> &#8211; doesn’t support Windows well (only uses select, not IOCP).  </li>
<li><a href="http://cvs.schmorp.de/libev/README">LibEv</a> &#8211; doesn’t support Windows  </li>
<li><a href="http://code.google.com/p/protobuf">Google Protocol Buffers</a></li>
<li><a href="http://thrift.apache.org">Apache Thrift</a></li>
</ul>

<p>So that’s a start on the choosing anyway; I hope that helps reduce the scope of research required to get you started on your next game. Now can I join your beta?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codeofhonor.com/blog/choosing-a-game-network-lib/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing Server and Network Code for Your Online Game</title>
		<link>http://www.codeofhonor.com/blog/writing-server-and-network-code-for-your-online-game?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=writing-server-and-network-code-for-your-online-game</link>
		<comments>http://www.codeofhonor.com/blog/writing-server-and-network-code-for-your-online-game#comments</comments>
		<pubDate>Fri, 06 Apr 2012 04:54:53 +0000</pubDate>
		<dc:creator>webcoyote</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.codeofhonor.com/blog/?p=92</guid>
		<description><![CDATA[I spoke this year at the Game Developers Conference (GDC 2012) on &#8220;Writing Server and Network Code for Your Online Game&#8221;. Since I tend to talk quickly, to say the least, I thought it only fair to post my presentation &#8230; <a href="http://www.codeofhonor.com/blog/writing-server-and-network-code-for-your-online-game">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I spoke this year at the Game Developers Conference (GDC 2012) on &#8220;Writing Server and Network Code for Your Online Game&#8221;. Since I tend to talk quickly, to say the least, I thought it only fair to post my presentation slides for those who attended but didn&#8217;t manage to take notes fast enough.</p>

<p>I find that many slide decks tend are quite worthless because, while the slides outline up the presentation, what the speaker has to say is far more useful. Consequently I&#8217;ve included extensive commentary in the &#8220;speaker notes&#8221; section of each page of the presentation, which I hope you&#8217;ll find useful.</p>

<p><a href='http://www.codeofhonor.com/blog/wp-content/uploads/2012/04/Patrick-Wyatt-Writing-reliable-online-game-services.pdf'>Writing reliable online game services [PDF]</a></p>

<p>Incidentally, the folks who run GDC also recorded a video, which you can download (with paid membership) from <a href='http://www.gdcvault.com'>GDC Vault</a>. You may note that there&#8217;s an odd jump in the video; the first half of the video was lost due to some sort of electrical issue (record button not pressed perhaps?) so they re-recorded it with me in front of an empty hall; consequently you&#8217;ll miss the scintillating display of me interacting with a live audience for the first bit.</p>

<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codeofhonor.com/blog/writing-server-and-network-code-for-your-online-game/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing firewall exception rules programmatically</title>
		<link>http://www.codeofhonor.com/blog/installing-firewall-exception-rules?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=installing-firewall-exception-rules</link>
		<comments>http://www.codeofhonor.com/blog/installing-firewall-exception-rules#comments</comments>
		<pubDate>Thu, 22 Dec 2011 08:37:11 +0000</pubDate>
		<dc:creator>webcoyote</dc:creator>
				<category><![CDATA[Installation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Visual Basic]]></category>

		<guid isPermaLink="false">http://www.codeofhonor.com/blog/?p=76</guid>
		<description><![CDATA[Writing installers for applications requires a substantial effort, even when using tools like InstallShield. My challenge for today was to write as little code as possible (because I&#8217;m lazy) to configure Windows Firewall exception rules so that the game I&#8217;m &#8230; <a href="http://www.codeofhonor.com/blog/installing-firewall-exception-rules">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Writing installers for applications requires a substantial effort, even when using tools like InstallShield. My challenge for today was to write as little code as possible (because I&#8217;m lazy) to configure Windows Firewall exception rules so that the game I&#8217;m working on wouldn&#8217;t &#8220;pop&#8221; a dialog box asking the user to configure firewall settings &#8212; this freaks out users and is generally considered a bad thing.</p>
<p>Of course I relied upon Google to find a solution, but boy did I have a tough time finding code to do the job. Many folks run external commands like &#8220;netsh&#8221; to configure firewall exceptions, but this sucks because the netsh.exe command has different syntax in different versions of Windows. Yuck!</p>
<p>Here&#8217;s my solution in visual basic (cscript.exe), which has the virtue of being installed on every modern (XP+) Windows computer in the world.</p>
<pre>
'configure-firewall.vbs
'Sets Windows firewall permissions for a specific application
'Grants full inbound/outbound access for TCP/UDP
'by Patrick Wyatt 12/22/2011
'MIT License - do with as you will; no warranty

option explicit

'**************************************
const NET_FW_IP_PROTOCOL_TCP  = 6
const NET_FW_IP_PROTOCOL_UDP  = 17

const NET_FW_RULE_DIR_IN  = 1
const NET_FW_RULE_DIR_OUT = 2

'**************************************
sub UpdateFirewallRule (addRules, policy, groupName, ruleName, exePath, netProtocol, direction)
  'Prettify the rule name
  dim <span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre="">name
  name</span></span></span></span></span> = ruleName
  name = name &#038; " - Allow"
  if netProtocol = NET_FW_IP_PROTOCOL_TCP then
    name = name &#038; " TCP"
  elseif netProtocol = NET_FW_IP_PROTOCOL_UDP then
    name = name &#038; " UDP"
  end if
  if direction = NET_FW_RULE_DIR_IN then
    name = name &#038; " IN"
  elseif direction = NET_FW_RULE_DIR_OUT then
    name = name &#038; " OUT"
  end if

  'Set rule parameters
  dim rule
  set rule              = CreateObject("HNetCfg.FwRule")
  rule.Enabled          = true
  rule.Grouping         = groupName
  rule.Name             = name
  rule.ApplicationName  = exePath
  rule.Protocol         = netProtocol
  rule.Direction        = direction

  'Remove old rule
  if addRules < 0 then
    Wscript.echo "  Removing rule '" &#038; name
  end if

  'Always remove old rule to prevent duplicates
  policy.Rules.Remove rule.name

  if Err.Number <> 0 then
    Wscript.Echo "  Removing rule '" &#038; name &#038; "'failed with error '" &#038; Err.Description &#038; "' (" &#038; Err.Number &#038; ")"
    Wscript.Quit 1
  end if

  'Add new rule
  if addRules > 0 then
    Wscript.echo "  Adding rule '" &#038; name
    policy.Rules.Add rule
    if Err.Number <> 0 then
      Wscript.Echo "  Adding rule '" &#038; name &#038; "'failed with error '" &#038; Err.Description &#038; "' (" &#038; Err.Number &#038; ")"
      Wscript.Echo "  did you remember to run this script as administrator?"
      Wscript.Quit 1
    end if
  end if

end sub

'**************************************
sub DisplayRules (policy, groupName)
  dim RulesObject
  set RulesObject = policy.Rules

  Wscript.echo "Displaying firewall rules"

  dim Rule
  for each Rule in RulesObject
    if Rule.Grouping = groupName then
      Wscript.Echo "  Rule: " &#038; Rule.Name
    end if
  next

  Wscript.echo ""

end sub

'**************************************
'Main program
  dim command, groupName, ruleName, exePath
  command   = Wscript.Arguments.Named("Command")
  groupName = Wscript.Arguments.Named("GroupName")
  ruleName  = Wscript.Arguments.Named("RuleName")
  exePath   = Wscript.Arguments.Named("ExePath")

  Wscript.echo "Firewall rule update arguments:"
  Wscript.echo "  Command:  " &#038; command
  Wscript.echo "  Grouping: " &#038; groupName
  Wscript.echo "  RuleName: " &#038; ruleName
  Wscript.echo "  ExePath:  " &#038; exePath
  Wscript.echo ""

  'Parse command line
  dim addRules
  if command = "install" then
    Wscript.echo "Installing firewall rules"
    addRules = 1
  elseif command = "remove" then
    Wscript.echo "Removing firewall rules"
    addRules = -1
  elseif command = "display" then
    addRules = 0
  else
    Wscript.echo "Unknown command: " &#038; command
    Wscript.Quit 1
  end if

  dim policy
  set policy = CreateObject("HNetCfg.FwPolicy2")

  if addRules <> 0 then
    UpdateFirewallRule addRules, policy, groupName, ruleName, exePath, NET_FW_IP_PROTOCOL_TCP, NET_FW_RULE_DIR_IN
    UpdateFirewallRule addRules, policy, groupName, ruleName, exePath, NET_FW_IP_PROTOCOL_TCP, NET_FW_RULE_DIR_OUT
    UpdateFirewallRule addRules, policy, groupName, ruleName, exePath, NET_FW_IP_PROTOCOL_UDP, NET_FW_RULE_DIR_IN
    UpdateFirewallRule addRules, policy, groupName, ruleName, exePath, NET_FW_IP_PROTOCOL_UDP, NET_FW_RULE_DIR_OUT
    Wscript.echo ""
  end if

  DisplayRules policy, groupName

  Wscript.echo "Success"
  Wscript.Quit 0
</pre>
<p>And here&#8217;s a batch file to call this script. Now in real life you wouldn&#8217;t use a batch file; you would call the configure-firewall.vbs script directly from your installer script. That&#8217;s one of the reasons that the command-line validation of my script doesn&#8217;t do much error checking &#8212; it&#8217;s not for end-users, it&#8217;s for you programmer-types.</p>
<pre>
::sample-firewall-configuration.bat
@echo off
SETLOCAL EnableExtensions

if "%1" == "" (
  echo Usage:
  echo   %0 display
  echo   %0 install
  echo   %0 remove
  exit /B 1
)

%SystemRoot%\System32\cscript.exe //nologo configure-firewall.vbs /GroupName:"!GroupNameHere" /RuleName:"!RuleNameHere" /ExePath:"C:\Windows\notepad.exe" /Command:%1
</pre>
<p>Use the code as you see fit!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codeofhonor.com/blog/installing-firewall-exception-rules/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Your new() is not my new()</title>
		<link>http://www.codeofhonor.com/blog/your-new-is-not-my-new?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=your-new-is-not-my-new</link>
		<comments>http://www.codeofhonor.com/blog/your-new-is-not-my-new#comments</comments>
		<pubDate>Thu, 10 Nov 2011 06:59:01 +0000</pubDate>
		<dc:creator>webcoyote</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.codeofhonor.com/blog/?p=53</guid>
		<description><![CDATA[One of the problems I&#8217;ve experienced using third-party DLLs is the way that they handle new and delete for C++ classes, which can lead to memory leaks or even memory corruption. This was a particular problem when developing the Guild &#8230; <a href="http://www.codeofhonor.com/blog/your-new-is-not-my-new">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the problems I&#8217;ve experienced using third-party DLLs is the way that they handle new and delete for C++ classes, which can lead to memory leaks or even memory corruption. This was a particular problem when developing the Guild Wars model and animation exporter for 3ds Max, since 3ds Max uses plugins extensively, many written by different teams without the same coding standards as the original authors.</p>
<p>Here&#8217;s an example class API defined in a header file:</p>
<pre>
// FoozleDll.h
class CFoozle { ... };
CFoozle * MakeFoozle (CBarzle * bar);
</pre>
<p>And the associated CPP file:</p>
<pre>
// FoozleDll.cpp
CFoozle * MakeFoozle (CBarzle * bar) {
    return new CFoozle(bar);
}
</pre>
<p>In the application code we&#8217;re supposed to create and later delete this object, so here goes:</p>
<pre>
// Main.cpp
void ProcessData (CBarzle * bar, iostream * outfile) {
    CFoozle * foo = MakeFoozle(bar);
    foo->WriteResults(outfile);
    delete foo;
}
</pre>
<p>That all looks pretty straightforward, but what isn&#8217;t immediately obvious is that the call to new() is made in the context of the Foozle DLL file, and the delete() call is done in the context of the application, which might be using an entirely different memory manager.</p>
<p>Since the DLL was compiled separately, it might link to the release version of the C runtime library, where new() calls malloc() behind the scenes. But the call to delete() occurs in the application code, which could link to the Debug library, which calls _free_dbg() instead of free(). When the application releases the memory via the call to delete it is calling the wrong memory manager, which leads to problems like the inability of the application to coalesce adjacent free memory blocks (memory leakage) or random memory corruption.</p>
<p>The correct solution is that a module which allocates an object should also free the object:</p>
<pre>
// FoozleDll.h
class CFoozle {
public:
    ...

    // This function must not be implemented in the header or the
    // linker will build the code to call the application delete()
    // function instead of the library delete() function.
    void DeleteThis ();

private:
    ~CFoozle (); // private so it can only be called by DeleteThis();
};
</pre>
<p>And the implementation:</p>
<pre>
// FoozleDll.cpp
void CFoozle::DeleteThis () {
    delete this;  // called from the right "delete context"
}
</pre>
<p>By calling delete() from within the same compilation unit, we can ensure that the compiler will generate a call to the correct delete function.</p>
<p>Incidentally, this same type of problem can occur in C, where a DLL function returns (for example), the result of strdup(), and the application is expected to call free() on the resulting string.</p>
<p>C++: so powerful, so easy to break things.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codeofhonor.com/blog/your-new-is-not-my-new/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Using transaction rate-limiting to improve service reliability</title>
		<link>http://www.codeofhonor.com/blog/using-transaction-rate-limiting-to-improve-service-reliability?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-transaction-rate-limiting-to-improve-service-reliability</link>
		<comments>http://www.codeofhonor.com/blog/using-transaction-rate-limiting-to-improve-service-reliability#comments</comments>
		<pubDate>Fri, 04 Nov 2011 05:15:14 +0000</pubDate>
		<dc:creator>webcoyote</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.codeofhonor.com/blog/?p=17</guid>
		<description><![CDATA[I develop and publish multiplayer games for a living, and have discovered some useful solutions for running reliable online services. The one I&#8217;m writing about today is how to implement reasonable usage limits so that services are less likely to &#8230; <a href="http://www.codeofhonor.com/blog/using-transaction-rate-limiting-to-improve-service-reliability">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I develop and publish multiplayer games for a living, and have discovered some useful solutions for running reliable online services. The one I&#8217;m writing about today is how to implement reasonable usage limits so that services are less likely to be abused by hackers.</p>
<p>Y&#8217;see, hackers find ways to manipulate games by simulating the behavior of human players, but in ways that exploit bugs and misfeatures; for example, by performing tasks faster than humans could ever hope to do. One example is a &#8220;speed hack&#8221;, where a player is able to perform actions like swinging a sword more rapidly than should be possible according to the rules of the game. If you&#8217;ve ever seen a monster go from full health to instant death in a flurry of blows you&#8217;ve likely seen a speed-hack.</p>
<p>Now honestly a speed hack doesn&#8217;t sound like such a bad thing; before I was a game programmer I speed-hacked games myself, and thought it was more fun than playing! And I also had to &#8220;slow-hack&#8221; several older games (including one I developed &#8212; Warcraft) to make them playable on fast computers, because the programmers (me included) had forgotten that computers keep getting faster every year.</p>
<p>But then there are professional cyber-criminals, who steal accounts, use speed-hacks to generate lots of game-gold, and sell it for real money to other players, something known as Real Money Trading, or RMT for short. And with such hacks it becomes impossible for honest players to keep up. So what&#8217;s to be done?</p>
<p>The code I&#8217;ve shared below implements rate-limiting useful for preventing many forms of speed hacking. I&#8217;ve used similar code for login rate-limiting, to prevent hackers from brute-force cracking account passwords. It can be used to moderate online chat so that one person can&#8217;t &#8220;flood&#8221; a channel with messages. It&#8217;s great for transaction rate-limiting to ensure that no one person can overwhelm a server with requests. And in fact I&#8217;ve used it to successfully mitigate distributed denial of service (<a href="http://en.wikipedia.org/wiki/Denial-of-service_attack" title="DDOS">DDOS</a>) attacks, which I&#8217;ll detail in a future article.</p>
<p>Here&#8217;s how to use the rate-limiter:</p>
<pre>
// Using these values a player can attempt to login once
// every 30 seconds, but with as many as ten login attempts
// in a burst. While this sounds like a lot many players
// forget their passwords and need a number of attempts to
// remember it, which I discovered by analyzing log files.
// They should try LastPass, which is an awesome solution
// to this problem.
const unsigned LOGIN_COST_MS      = 30 * 1000;
const unsigned MAX_LOGIN_COST_MS  = 10 * LOGIN_COST_MS;

ErrorCode CPlayer::PlayerLogin () {
    if (!m_rateLimiter.AddTime(LOGIN_COST_MS, MAX_LOGIN_COST_MS))
        return ERROR_LOGIN_RATE_LIMIT;
    ... login code here
}
</pre>
<p>In any event, here&#8217;s the code, which is surprisingly trivial considering how powerful it is. The algorithm is a modified form of the &#8220;<a href="http://en.wikipedia.org/wiki/Leaky_bucket" title="Leaky Bucket Algorithm as a Meter">Leaky Bucket Algorithm as a Meter</a>&#8220;, but uses the passage of time instead of incrementing a counter to perform its magic.</p>
<p>RateLimiter.h definitions:</p>
<pre>
class CRateLimiter {
public:
    CRateLimiter ();
    bool AddTime (unsigned costMs, unsigned maxCostMs);

private:
    unsigned m_timeMs;
};
</pre>
<p>RateLimiter.cpp implementation:</p>
<pre>
CRateLimiter::CRateLimiter ()
:   m_timeMs(PlatformTimeMs())
{}

bool CRateLimiter::AddTime (unsigned costMs, unsigned maxCostMs) {
    ASSERT(costMs &lt; maxCostMs);

    // Reset rate-limiter time value if it has expired
    // - handles integer overflow safely
    unsigned currTimeMs = PlatformTimeMs();
    if ((int) (currTimeMs - m_timeMs) &gt; 0)
        m_timeMs = currTimeMs;

    // Has the user accrued too much time-cost?
    // - handles integer overflow safely
    unsigned newTimeMs = m_timeMs + costMs;
    if ((int) (newTimeMs - currTimeMs) &gt;= (int) maxCostMs)
        return false;

    m_timeMs = newTimeMs;
    return true;
}
</pre>
<p>And somewhere you&#8217;ll have to define the PlatformTimeMs function:</p>
<pre>
unsigned PlatformTimeMs () {
#if defined(_WINDOWS_)
    return GetTickCount();
#else
    #error Your implementation here
   // something like clock_gettime(CLOCK_MONOTONIC, ...) for Unix/Linux
#endif
}
</pre>
<p>I hope you&#8217;ll find this code useful for your project, and would enjoy hearing about the novel purposes you find for it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codeofhonor.com/blog/using-transaction-rate-limiting-to-improve-service-reliability/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A better way to update SQL stored procedures</title>
		<link>http://www.codeofhonor.com/blog/6?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=6</link>
		<comments>http://www.codeofhonor.com/blog/6#comments</comments>
		<pubDate>Sun, 30 Oct 2011 00:10:41 +0000</pubDate>
		<dc:creator>webcoyote</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.codeofhonor.com/blog/?p=6</guid>
		<description><![CDATA[A common pattern to manage SQL stored procedures is to drop the current procedure and recreate it. Unfortunately, this doesn&#8217;t work if you&#8217;re trying to run a high-availability service. Here&#8217;s the (broken) drop+create pattern: -- Delete the stored procedure if &#8230; <a href="http://www.codeofhonor.com/blog/6">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A common pattern to manage SQL stored procedures is to drop the current procedure and recreate it. Unfortunately, this doesn&#8217;t work if you&#8217;re trying to run a high-availability service. Here&#8217;s the (broken) drop+create pattern:</p>
<pre>-- Delete the stored procedure if it already exists
if exists (
  select * from sys.objects where object_id = OBJECT_ID(N'p_MyProc')
  and type = N'P'
) then
  drop procedure p_MyProc
end

-- Now create it again
create procedure p_MyProc as begin
  -- awesome code here
end

-- And set permissions
grant execute on p_MyProc to SomeRole</pre>
<p>There&#8217;s nothing wrong with this code. Just kick all your users off the server, switch to single user mode, execute the code above and it will work fine.</p>
<p>Oh, what&#8217;s that? You&#8217;re running a service that needs to be highly available, and you can&#8217;t take a maintenance period every time you want to change code?</p>
<p>Using the drop+create method there is obviously a small window of time when the stored procedure does not exist. And as we know from examples like the Seattle monorail crash (see notes at the end of this article), any system that is designed with a built-in flaw will eventually fail because of that flaw.</p>
<p>Here is a better solution:</p>
<pre>-- if the stored procedure does not exist then create a placeholder
if not exists (
  select * from sys.objects where object_id = OBJECT_ID(N' p_MyProc')
  and type = N'P'
) then
  create procedure p_MyProc as RAISERROR ('MyProc not defined', 16, 1);
  grant execute on p_MyProc to SomeRole
end

-- update stored proc
alter procedure p_MyProc as begin
  -- awesome code here
end</pre>
<p>This ensures that the stored procedure always exists, and (because SQL is transactional) it is possible to have one caller finishing a call to the old version of the stored procedure while the new version is added and called.</p>
<p>I&#8217;ve used this trick successfully for the development of Guild Wars using SQL Server 2000, and later SQL Server 2005, and have not encountered any problems using this technique, even on servers running sustained load of 3000+ transactions per second. In fact the standard operating procedure for our database updates was to update all stored procedures (several hundred of them) every time we performed a deployment.</p>
<p>I assume that similar tricks will work for MySQL and PostgreSQL, and would love to hear from users of those platforms about their experiences.</p>
<p>Update (11/5/2011):</p>
<p>It turns out that MySQL doesn&#8217;t support atomic updates of stored procedures; apparently this is a long-standing bug, first filed in 2005 and still not fixed (<a href="http://bugs.mysql.com/bug.php?id=9588">http://bugs.mysql.com/bug.php?id=9588</a>). And PostgreSQL and Oracle both do properly support this feature with a different SQL syntax: &#8220;CREATE OR REPLACE PROCEDURE&#8221;.</p>
<p>Notes:</p>
<p>In case you&#8217;re wondering about the reference to the Seattle monorail crash, which is a great example of design failure, here&#8217;s a bit more information. The original Seattle monorail was built for 1962 World&#8217;s Fair, and had two sets of tracks so that two trains could operate side-by-side. The tracks were shortened in the 1988 to end at the newly constructed Westlake Center mall. The new design allowed for an automatic passenger-loading ramp to extend to the trains, but led to the tracks being too close together for two trains to be there at the same time. As you might imagine, this design eventually failed, though it took seventeen years (<a href="http://seattletimes.nwsource.com/html/localnews/2002650818_monorail28m.html">http://seattletimes.nwsource.com/html/localnews/2002650818_monorail28m.html</a>). Of course, when you&#8217;re running several thousand SQL transactions per second, such failures are all the more likely.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codeofhonor.com/blog/6/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

