<?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>phaq</title>
	<atom:link href="http://phaq.phunsites.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://phaq.phunsites.net</link>
	<description>my daily IT madness</description>
	<lastBuildDate>Tue, 10 Apr 2012 22:20:37 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.3</generator>
		<item>
		<title>Swisscom FTTH: 6RD mit Cisco 892F nutzen</title>
		<link>http://phaq.phunsites.net/2012/04/10/swisscom-ftth-6rd-mit-cisco-892f-nutzen/</link>
		<comments>http://phaq.phunsites.net/2012/04/10/swisscom-ftth-6rd-mit-cisco-892f-nutzen/#comments</comments>
		<pubDate>Tue, 10 Apr 2012 22:20:37 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Cisco]]></category>
		<category><![CDATA[HowTo's]]></category>
		<category><![CDATA[Networking]]></category>

		<guid isPermaLink="false">http://phaq.phunsites.net/?p=990</guid>
		<description><![CDATA[Wie bereits aufgezeigt, kann man statt dem Centro Grande oder Centro Piccolo auch problemlos einen Cisco 892F an einem Swisscom Vivo FTTH-Anschluss betreiben. Hat man diese Hürde erstmal geschafft, möchte man den Cisco vielleicht am Swisscom-eigenen IPv6 6RD Gateway anbinden um in den Genuss von IPv6 zu kommen. Klar, man kann dafür natürlich auch auf [...]]]></description>
			<content:encoded><![CDATA[<p>Wie bereits aufgezeigt, kann man statt dem Centro Grande oder Centro Piccolo auch problemlos einen <a href="/2012/04/09/swisscom-vivo-ftth-anschluss-mit-cisco-router-betreiben/">Cisco 892F an einem Swisscom Vivo FTTH-Anschluss betreiben</a>.</p>
<p>Hat man diese Hürde erstmal geschafft, möchte man den Cisco vielleicht am Swisscom-eigenen <a href="http://en.wikipedia.org/wiki/IPv6_rapid_deployment" target="_blank">IPv6 6RD</a> Gateway anbinden um in den Genuss von IPv6 zu kommen.</p>
<p>Klar, man kann dafür natürlich auch auf einen IPv6 Tunnel Broker wie <a href="http://www.sixxs.net/main/" target="_blank">SIXXS</a> oder <a href="http://tunnelbroker.net/" target="_blank">Hurricane Electric</a> verwenden, doch wozu in die Ferne schweifen, wenn man den Gateway quasi vor der Haustüre hat?</p>
<p>Es sei dazu höchstens noch anzumerken, dass 6RD nicht ganz dasselbe ist wie ein Teredo, ISATAP or 6to4 Tunnel, obwohl alle Varianten letztlich zum Ziel haben eine IPv6-Anbindung über IPv4-Netze hinweg zu ermöglichen.<br />
Wer zum Beispiel seinen &#8220;eigenen&#8221; IPv6 Prefix zu sich nach hause tunneln möchte, ist mit einem Tunnel Broker besser bedient. 6RD weist nämlich ausschliesslich Adressen aus dem Swisscom-eigenen 6RD-Pool zu. Wenn allerdings nur die reine Konnektivität ohne Sonderwünsche gefragt ist, dann ist 6RD wiederum vollkomen ausreichend.</p>
<p>Die unten gezeigte Konfiguration setzt 6RD auf dieselbe Weise um wie die Centro Router. Zwar muss man  IPv6 im Kundencenter bislang selbst einschalten, wer jedoch wie in diesem Beispiel seinen eigenen Cisco-Router mit 6RD aufmöbeln möchte, kann hierauf verzichten.</p>
<p>Vom Prinzip her wird einfach ein neues Tunnel-Interface <strong>Tunnel1</strong> erzeugt, dem das Swisscom-spezifische 6RD-Prefix <strong>2A02:1200::/28</strong> zugewiesen wird, als Gegenstelle nimmt <strong>193.5.122.254</strong> (6rd.ip-plus.net) die Funktion des Tunnel Relays wahr.<br />
Ausserdem wird der 6RD-Prefix von Tunnel1 zudem auf den Bezeichner <strong>6RD-SWISSCOM</strong> gemappt.</p>
<p>Im Beispiel wird davon ausgegangen, dass das lokale LAN-Interface auf Vlan1 liegt, entsprechend wird dort IPv6 aktiviert, die IPv6-Adresse wird aus dem zuvor erwähntem Prefix-Mapping <strong>6RD-SWISSCOM</strong> und der Host-Adresse ::1 kombiniert. Dabei wurde ein /64 Prefix zugewiesen, damit man später noch weitere IPv6 Subnets zuweisen könnte. Wer das nicht vor hat, kann auch direkt den /60 Prefix verwenden, wovon ich allerdings eher abraten würde.</p>
<p>Zum Schluss wird noch eine IPv6 Default Route via 2A02:120C:1057:AFE0:: eingerichtet. Diese Adresse entspricht dem 6RD Gateway (berechnet indem der globale Prefix 2A02:1200::/28 mit der in Hex umgerechneten IPv4-Adresse 193.5.122.254 von 6rd.ip-plus.net kombiniert wird, wer wirklich wissen will wie das geht, kann mich ja fragen).</p>
<p>Hier also die relevante Konfiguration:</p>
<pre>
ipv6 general-prefix 6RD-SWISSCOM 6rd Tunnel1
!
interface Tunnel1
 description Swisscom 6RD Tunnel to Local LAN
 no ip address
 no ip redirects
 ipv6 enable
 ipv6 mtu 1480
 tunnel source GigabitEthernet0.10
 tunnel mode ipv6ip 6rd
 tunnel 6rd prefix 2A02:1200::/28
 tunnel 6rd br 193.5.122.254
!
interface Vlan1
 description Local LAN
 ipv6 enable
 ipv6 address 6RD-SWISSCOM ::1/64
!
ipv6 route ::/0 Tunnel1 2A02:120C:1057:AFE0::
!
</pre>
<p>Wie man sieht braucht&#8217;s also eigentlich gar nicht viel, damit das zum Fliegen kommt.</p>
<p>Mit dem Befehl <strong>show tunnel 6rd</strong> kann verifiziert werden, ob der Tunnel zum 6RD-Gateway aufgebaut wurde.<br />
Als <strong>Tunnel Source</strong> wird die IPv4-Adresse von Interface Gig0.10 ausgewiesen.<br />
Unter <strong>General Prefix</strong> ist der vom 6RD Gateway zugewiesene IPv6 Prefix ausgewiesen, der zugleich auf <strong>6RD-SWISSCOM</strong> gemappt wird.</p>
<pre>
#sh tunnel 6rd
Interface Tunnel1:
  Tunnel Source: 188.63.nnn.nn1
  6RD: Operational, V6 Prefix: 2A02:1200::/28
       V4 Prefix, Length: 0, Value: 0.0.0.0
       V4 Suffix, Length: 0, Value: 0.0.0.0
       Border Relay address: 193.5.122.254
  General Prefix: 2A02:120B:C3F7:8D0::/60
</pre>
<p>Man beachte auch, dass ein /60 Prefix zugewiesen wird, was der enorm grossen Anzahl von 295&#8217;147&#8217;905&#8217;179&#8217;352&#8217;830&#8217;000 IPv6-Adressen gleichkommt.<br />
Wow, fast 300 Trillionen (!) IPv6-Adressen für zu Hause! <img src='http://phaq.phunsites.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /><br />
Man kann das natürlich auch subnetten, z.B. in 16 * /64 Prefixe, wovon jeder immer noch rund 18.5 Trillionen Adressen umfasst. Wie oben erwähnt, habe ich dem LAN-Interface ein /64 zugewiesen, wonach noch 15 weitere solcher Netze für Tests und anderweitige Spielereien zur Verfügung stehen.</p>
<p>Einen kurzen Verbindungstest schadet auch nicht, beispielsweise indem man die Public IPv6-Adresse von www.heise.de anpingt:</p>
<p><a href="http://phaq.phunsites.net/files/2012/04/cisco_ping6.png" rel="lightbox[990]"><img src="http://phaq.phunsites.net/files/2012/04/cisco_ping6-300x47.png" alt="" width="300" height="47" class="aligncenter size-medium wp-image-997" /></a></p>
<p>Wenn der Cisco mal soweit eingerichtet ist, geht&#8217;s mit dem Clients weiter.<br />
Dies würde jetzt allerdings etwas weit führen, ausserdem gehe ich davon aus, dass sich die potentiellen Leser dieses Beitrag bereits soweit mit IPv6 auskennen, dass die Client-Konfiguration die geringste aller Schwierigkeiten sein dürfte <img src='http://phaq.phunsites.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://phaq.phunsites.net/2012/04/10/swisscom-ftth-6rd-mit-cisco-892f-nutzen/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fix iTunes refraining from syncing the iPhone</title>
		<link>http://phaq.phunsites.net/2012/04/10/fix-itunes-refraining-from-syncing-the-iphone/</link>
		<comments>http://phaq.phunsites.net/2012/04/10/fix-itunes-refraining-from-syncing-the-iphone/#comments</comments>
		<pubDate>Tue, 10 Apr 2012 21:23:00 +0000</pubDate>
		<dc:creator>gdelmatto</dc:creator>
				<category><![CDATA[Bits and Bytes]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[HowTo's]]></category>
		<category><![CDATA[OS X]]></category>

		<guid isPermaLink="false">http://phaq.phunsites.net/?p=994</guid>
		<description><![CDATA[Out of a sudden iTunes struck me with this error: The iPhone &#8220;&#8230;&#8221; could not be synced because the sync session failed to start I did web research, but did not really find a proper solution to this. Well, there were a few which either did some funny things on Windows (I run a Mac [...]]]></description>
			<content:encoded><![CDATA[<p>Out of a sudden iTunes struck me with this error: <strong>The iPhone &#8220;&#8230;&#8221; could not be synced because the sync session failed to start</strong></p>
<p>I did web research, but did not really find a proper solution to this.<br />
Well, there were a few which either did some funny things on Windows (I run a Mac &#8230;.), or recommended to restore the iPhone from a previous backup, removing just one app, installing just one new app through the iTunes store, and, well, some other curious and strange things.</p>
<p>After all, I thought to give the restore thing a try, however that changed nothing. Same message came up. So I disabled WLAN sync as to not interfere with the iPhone being hooked up by the cable already &#8212; again to no avail.</p>
<p>So I decided to look into the iTunes internals. There I found a primising folder within the <strong>Application Library</strong> folder called <strong>SyncServices</strong>. It was not that big, around 6 megs. But inside there where clear traces of synchronisation stuff.</p>
<p>My solution to the above error was then to quit iTunes, remove the SyncServices folders completely. And voila, iTunes would just start syncing my iPhone as if nothing bad had ever happened.</p>
]]></content:encoded>
			<wfw:commentRss>http://phaq.phunsites.net/2012/04/10/fix-itunes-refraining-from-syncing-the-iphone/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A backup volume switcher for Apple&#8217;s TimeMachine</title>
		<link>http://phaq.phunsites.net/2012/04/09/a-backup-volume-switcher-for-apples-timemachine/</link>
		<comments>http://phaq.phunsites.net/2012/04/09/a-backup-volume-switcher-for-apples-timemachine/#comments</comments>
		<pubDate>Mon, 09 Apr 2012 00:32:33 +0000</pubDate>
		<dc:creator>gdelmatto</dc:creator>
				<category><![CDATA[OS X]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Shells]]></category>

		<guid isPermaLink="false">http://phaq.phunsites.net/?p=911</guid>
		<description><![CDATA[So here&#8217;s another piece of code I hacked up tonight. Since I&#8217;m roaming around with my MacBook every now and then, the need arised, that I would need to switch my TimeMachine destination volumes based on location. So while in the office, I&#8217;d like to backup to my external USB drive there. Being at my [...]]]></description>
			<content:encoded><![CDATA[<p>So here&#8217;s another piece of code I hacked up tonight.<br />
Since I&#8217;m roaming around with my MacBook every now and then, the need arised, that I would need to switch my TimeMachine destination volumes based on location.</p>
<p>So while in the office, I&#8217;d like to backup to my external USB drive there.<br />
Being at my home office, i&#8217;d like to backup to my NAS, while on the road, I&#8217;d love to habe my external mobile drive to kick in (and yes, I know about the &#8220;mobile backup feature&#8221; of OS X Lion, but that&#8217;s not the point &#8230;)<br />
<span id="more-911"></span></p>
<p>So I hacked up a script, which will check if a TimeMachine volume is actually connected or not. If none is connected, it will check which targets are available by either looking for connected USB drives (by the use of &#8220;diskutil&#8221;) or by checking connectivity to specified NAS servers. If it sees necessity to switch volumes it will also force creating an immediate backup in that case.</p>
<p>So, below is the code. I hope the comment section is clear enough. You&#8217;d need to change the USB_Volumes and NET_Volumes sections to fit your needs.<br />
And yes, it works with the TimeMachine mobile feature enabled or disabled, that makes no difference.</p>
<pre>#!/bin/bash
#
# tm_switcher -- a backup volume switchr for Apple's TimeMachine
#
# ####################################################################
# This script will help to automatically switch backup destination
# on Apple's TimeMachine according to available destination volumes.
# You can have one or more of both USB and network devices, of which
# the first available destination is used
# ####################################################################
# released to the public "as-is" under the terms of the GPL Version 2
# ####################################################################
# r0.1 2012/01/25
# - initial release 

# specify zero or more USB volumes as backup destinations
# you must give only the volume label
# specify multiple volumes like this:
# USB_Volumes=("Volume1" "Volume2")
#
USB_Volumes=("My Passport")

# specify zero or more NETWORK volumes as backup destinations
# you must give the full AFP volume path
# specify multiple volumes identically as described
# in the "USB Volumes" section above
#
NET_Volumes=("afp://TMUsername:TMPassword@HOSTorIPAddress/TMShare")

# get current TimeMachine directory
#
current_tm_dir=`/usr/bin/tmutil machinedirectory`

# check if we are disconnected
#
[ "$current_tm_dir" == "" ] &amp;&amp; tm_status=CONNECT_NONE

# check if we are connected to an USB disk
#
for volume in "${USB_Volumes[@]}"; do
	echo $current_tm_dir | grep -e "$volume" &gt; /dev/null 2&gt;&amp;1
	[ "$?" == "0" ] &amp;&amp; tm_status=CONNECT_USB
done

# check if we are connected to an Network Volume (TimeCapsule)
#
for volume in "${NET_Volumes[@]}"; do
	_volume_basename=`basename ${volume}`
	/sbin/mount | grep " on /Volumes/${_volume_basename}" &gt; /dev/null 2&gt;&amp;1
	[ "$?" == "0" ] &amp;&amp; tm_status=CONNECT_NET
done

# check if we need to switch TimeMachine locations
#
if [ "${tm_status}" == "CONNECT_NONE" ]; then
	echo "NOTICE: TimeMachine is disconnected, current status is: ${tm_status}"

	# check if we can reach any of the NET_Volumes hosts given
	#
	for volume in "${NET_Volumes[@]}"; do
		_dest_server=`echo $volume | grep -P -o '@([[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}|(\b.*\b\.?)+)/' | sed -E 's:(@|/)::g'`

		# always recheck that TimeMachine is not yet connected
		#
		if [ "${tm_status}" == "CONNECT_NONE" ]; then
			# perform a simple connectivity test
			ping -c 1 $_dest_server &gt; /dev/null 2&gt;&amp;1
			if [ "$?" == "0" ]; then
				echo "NOTICE: We found this volume to be available for backups: $volume"
				echo "        We will be switching TimeMachine volumes now ..."
				sudo tmutil setdestination "$volume"
				tm_status=CONNECT_NET
			fi
		fi
	done

	# check if we can reach any of the NET_Volumes hosts given
	#
	for volume in "${USB_Volumes[@]}"; do
		# always recheck that TimeMachine is not yet connected
		#
		if [ "${tm_status}" == "CONNECT_NONE" ]; then
			# check if the volume is available
			diskutil info "$volume" &gt; /dev/null 2&gt;&amp;1
			if [ "$?" == "0" ]; then
				# try to mount the volume
				diskutil mount "/Volumes/$volume" &gt; /dev/null 2&gt;&amp;1
				if [ "$?" == "0" ]; then
					sleep 5
					echo "NOTICE: We found this volume to be available for backups: $volume"
					echo "        We will be switching TimeMachine volumes now ..."
					sudo tmutil setdestination "/Volumes/$volume"
					tm_status=CONNECT_USB
				fi
			fi
		fi
	done

	# bail out if we failed on finding a proper backup volume
	#
	if [ "${tm_status}" == "CONNECT_NONE" ]; then
		echo "ERROR: Failed in finding a TimeMachine Voloume on USB or on the LAN available for backups."
		echo "       Exiting now."
		exit
	else
		echo "NOTICE: A suitable backup volume has been located for TimeMachine backups."
		echo "        Starting backup now ..."
		tmutil startbackup
	fi
else
	if [ "${tm_status}" == "CONNECT_USB" -o "${tm_status}" == "CONNECT_NET" ]; then
		echo "NOTICE: TimeMachine is already connected, current status is: ${tm_status}"
		echo "        TimeMachine destinations will not be switched!"
	else
		echo "ERROR: Unable to figure current TimeMachine status."
	fi
fi

exit
</pre>
<p>And here&#8217;s the script in action:</p>
<p><a href="http://phaq.phunsites.net/files/2012/04/tm_switcher.png" rel="lightbox[911]"><img src="http://phaq.phunsites.net/files/2012/04/tm_switcher-300x64.png" alt="" width="300" height="64" class="aligncenter size-medium wp-image-986" /></a></p>
<p>To complement this it&#8217;s a great idea to add this to Launch Daemon to have this script run on a recurring basis, so you wont need to run it manually.</p>
]]></content:encoded>
			<wfw:commentRss>http://phaq.phunsites.net/2012/04/09/a-backup-volume-switcher-for-apples-timemachine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Swisscom Vivo FTTH Anschluss mit Cisco Router betreiben</title>
		<link>http://phaq.phunsites.net/2012/04/09/swisscom-vivo-ftth-anschluss-mit-cisco-router-betreiben/</link>
		<comments>http://phaq.phunsites.net/2012/04/09/swisscom-vivo-ftth-anschluss-mit-cisco-router-betreiben/#comments</comments>
		<pubDate>Mon, 09 Apr 2012 00:19:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Cisco]]></category>
		<category><![CDATA[Networking]]></category>

		<guid isPermaLink="false">http://phaq.phunsites.net/?p=969</guid>
		<description><![CDATA[Wer das Glück hat in einem mit Glasfaser erschlossenen Quartier zu wohnen, kann statt DSL mit Lichtgeschwindigkeit surfen &#8211; FTTH (Fibre to the Home) macht&#8217;s möglich. Bei Swisscom Vivo FFTH-Anschlüssen für Privatkunden wird man mit dem Centro Piccolo oder dem Centro Grande ausgestattet, was für die meisten Kunden auch mehr als ausreichend sein dürfe. Möchte [...]]]></description>
			<content:encoded><![CDATA[<p>Wer das Glück hat in einem mit Glasfaser erschlossenen Quartier zu wohnen, kann statt DSL mit Lichtgeschwindigkeit surfen &#8211; FTTH (Fibre to the Home) macht&#8217;s möglich. Bei Swisscom Vivo FFTH-Anschlüssen für Privatkunden wird man mit dem Centro Piccolo oder dem Centro Grande ausgestattet, was für die meisten Kunden auch mehr als ausreichend sein dürfe.</p>
<p>Möchte man allerdings seinen FTTH-Anschluss richtig ausreizen, bietet sich der Einsatz eines Cisco 892F Routers an. Zugegebenermassen nicht gerade ein billiges Gerät (ab rund 1000 Franken Listenpreis), dafür kriegt man aber auch alles, was ein Cisco typischerweise so zu bieten hat.<br />
<span id="more-969"></span><br />
Für den Anschluss an einen Swisscom FTTH-Anschluss benötigt man zwingend ein GLC-FE-100BX-U SFP-Modul (1310 nm TX/1550 nm RX, Simplex Single Mode Fiber) sowie das dazu passende Glasfaserkabel.<br />
Spezifikationen zur FTTH Inhouse-Verkabelung und den OTO-Steckdosen (Optical Terminations Outlet) können <a href="http://www.swisscom.ch/content/dam/swisscom/nl/ghq/obsolete/documents/Technische_Leistungsmerkmale_FTTH_Inhouse_V20.pdf" target="_blank">bei Swisscom heruntergeladen</a> werden. Ein passendes Kabel sollte in der Regel als Simplex (also Einzelfaser, _keine_ Zwillingsfaser) Single Mode ausgeführt sein, mit LC/APC-Stecker für die Wandsteckdose und LC/PC-Stecker für das SFP-Modul.</p>
<p><strong>Doch bevor wir uns der Konfiguration zuwenden hier noch der obligate Hinweis: Das nachfolgend beschriebene Verfahren wird nicht offiziell von Swisscom unterstützt, will heissen: Auf eigene Verantwortung, es gibt keine Gewährleistung und keinen Support durch Swisscom.</strong></p>
<p>Bei den FFTH-Anschlüssen werden, anders als bei den DSL-Anschlüssen, keine Logindaten benötigt, es läuft alles über DHCP.<br />
Wer nun aber seinen Cisco einfach einstöpselt und darauf hofft, eine IP zu erhalten, dürfte aber schnell enttäuscht sein &#8212; da läuft nämlich erstmal gar nichts.</p>
<p>Zuerst ist es erforderlich, dass auf dem WAN-Interface ein zusätzliches VLAN Interface erzeugt wird (VLAN ID 10). Über dieses Interface muss auch der DHCP Request erfolgen. Allerdings muss dafür auch die DHCP client class ID korrekt gesetzt werden, ansonsten wird keine IP-Adresse zugewiesen.</p>
<p>Die Class ID sieht wie folgt aus:</p>
<p><em>100008,0001,Cisco,WAN_MAC_ADDR,FIRMWARE,FIRMWARE_VERSION,SERIAL</em></p>
<p>Dabei werden die Platzhalter wie folgt ermittelt:</p>
<table>
<tbody>
<tr>
<td><strong>TOKEN</strong></td>
<td><strong>Ermittelt mit</strong></td>
</tr>
<tr>
<td>WAN_MAC_ADDR</td>
<td>show int gi0 | i address</td>
</tr>
<tr>
<td>FIRMWARE</td>
<td>show ver | i IOS</td>
</tr>
<tr>
<td>FIRMWARE_VERSION</td>
<td>show ver | i IOS</td>
</tr>
<tr>
<td>SERIAL</td>
<td>show ver | i board</td>
</tr>
</tbody>
</table>
<p>Die fertige Class ID sieht dann ungefähr so aus:</p>
<pre>100008,0001,Cisco,ffff.ffff.ffff,C890-UNIVERSALK9-M,15.1(4)M2,FCZ1234ABCD</pre>
<p>Aber bitte diese Zeichenkette nicht unbesehen kopieren, sondern die richtigen Werte aus eurem Router auslesen. Mit den Beispieldaten klappt&#8217;s nämlich definitiv nicht <img src='http://phaq.phunsites.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Hier folgt nun der Konfigurationsschnippsel. Die Platzhalter _CLASSID_ und _HOSTNAME_ werden darin durch die zuvor ermittelte Class ID sowie den Hostnamen des Routers ersetzt.</p>
<pre>interface GigabitEthernet0
 description Physical WAN Interface (Fibre)
 bandwidth 100000
 no ip address
 load-interval 30
 duplex full
 speed 100
 media-type sfp
 no cdp enable
!
interface GigabitEthernet0.10
 description Logical WAN Interface (DHCP)
 encapsulation dot1Q 10
 ip dhcp client client-id GigabitEthernet0
 ip dhcp client class-id <strong>_CLASSID_</strong>
 ip dhcp client hostname <strong>_HOSTNAME_</strong>
 ip address dhcp
 no ip redirects
 no ip unreachables
 no ip proxy-arp
 ip nat outside
 ip virtual-reassembly in
 no cdp enable
!</pre>
<p>Damit sollte nun mit den DHCP Request klappen und der Router seine IP erhalten. Falls nicht, ggf. das WAN-Interface temporär auf Shutdown setzen und anschliessend mit dem Befehl &#8220;show dhcp lease&#8221; den Status überprüfen:</p>
<pre>HOSTNAME#show dhcp lease
Temp IP addr: 188.63.nnn.nn1  for peer on Interface: GigabitEthernet0.10
Temp  sub net mask: 255.255.252.0
   DHCP Lease server: 213.3.239.242, state: 5 Bound
   DHCP transaction id: 1F4C
   Lease: 7200 secs,  Renewal: 300 secs,  Rebind: 600 secs
Temp default-gateway addr: 188.63.112.1
   Next timer fires after: 00:03:21
   Retry count: 0   Client-ID: ffff.ffff.ffff
   Client-ID hex dump: FFFFFFFFFFFF
   Hostname: HOSTNAME</pre>
<p>Sobald der Router eine DHCP IP-Adresse bezogen hat, ist es Zeit für einen ersten Verbindungstest im Browser.</p>
<p>Hierbei sind im ersten Anlauf jedoch keine Websites direkt abrufbar, stattdessen startet der webbasierte Einrichtungsassistent von Swisscom. Wer zuvor schon den Centro Grande/Piccolo an seinem Anschluss in Betrieb genommen hat, kennt den Assistenten bereits. Man darf sich hier aber auch nicht wundern dass dieser nun erneut angezeigt wird, das hängt mit dem Anschliessen des neuen Geräts zusammen. Daher muss der Assistent einmalig nochmals durchgespielt werden bis zum Schluss dann folgende Seite erscheint:</p>
<p><a href="http://phaq.phunsites.net/files/2012/04/ffth_setup.png" rel="lightbox[969]"><img class="aligncenter size-medium wp-image-976" src="http://phaq.phunsites.net/files/2012/04/ffth_setup-300x101.png" alt="" width="300" height="101" /></a></p>
<p>Damit wäre nun der Centro Grande erfolgreich durch einen Cisco Router ersetzt worden. Mission accomplished <img src='http://phaq.phunsites.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Ich sollte allerdings erwähnen, dass es zusätzliche Schritte benötigt um den Router beispielsweise an den Swisscom 6RD Gateway anzubinden &#8211; für alle diejenigen interessant, die schon heute IPv6 auch zu Hause nutzen möchten.<br />
Ausserdem läuft beim FTTH Anschluss auch der Telefonanschluss drüber, und zwar als klassisches Voice-over-IP. Hierfür benötigt es, ebenso wie für die Nutzung von Swisscom TV, weiterführende Konfiguration.</p>
<p>Doch dazu ein anderes mal mehr <img src='http://phaq.phunsites.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://phaq.phunsites.net/2012/04/09/swisscom-vivo-ftth-anschluss-mit-cisco-router-betreiben/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cheat sheet for Check Point Firewall</title>
		<link>http://phaq.phunsites.net/2012/04/07/cheat-sheet-for-check-point-firewall/</link>
		<comments>http://phaq.phunsites.net/2012/04/07/cheat-sheet-for-check-point-firewall/#comments</comments>
		<pubDate>Sat, 07 Apr 2012 22:02:44 +0000</pubDate>
		<dc:creator>gdelmatto</dc:creator>
				<category><![CDATA[Check Point]]></category>

		<guid isPermaLink="false">http://phaq.phunsites.net/?p=958</guid>
		<description><![CDATA[For everyone who&#8217;s interested in Check Point Firewall, find some valuable cheat sheets over at Jens Roesen&#8217;s Website. Great thing indeed, and yet very helpful if you need just a quick lookup instead of going through the full official documentation. Here&#8217;s the direct links: Check Point CLI Cheat Sheet Check Point&#8217;s &#8220;fw monitor&#8221; Cheat Sheet [...]]]></description>
			<content:encoded><![CDATA[<p>For everyone who&#8217;s interested in Check Point Firewall, find some valuable cheat sheets over at <a href="http://roesen.org/download.php" target="_blank">Jens Roesen&#8217;s Website</a>.</p>
<p>Great thing indeed, and yet very helpful if you need just a quick lookup instead of going through the full official documentation.<br />
Here&#8217;s the direct links:</p>
<p><a href="http://www.roesen.org/files/cp_cli_ref_card.pdf" target="_blank">Check Point CLI Cheat Sheet</a><br />
<a href="http://www.roesen.org/files/fw_monitor.pdf" target="_blank">Check Point&#8217;s &#8220;fw monitor&#8221; Cheat Sheet</a></p>
<p>Thanks to Jens for assembling these.</p>
]]></content:encoded>
			<wfw:commentRss>http://phaq.phunsites.net/2012/04/07/cheat-sheet-for-check-point-firewall/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FreeBSD ganz klein &#8211; Main Story in freeX 3-4/2012</title>
		<link>http://phaq.phunsites.net/2012/04/04/freebsd-ganz-klein-main-story-in-freex-3-42012/</link>
		<comments>http://phaq.phunsites.net/2012/04/04/freebsd-ganz-klein-main-story-in-freex-3-42012/#comments</comments>
		<pubDate>Wed, 04 Apr 2012 20:14:33 +0000</pubDate>
		<dc:creator>gdelmatto</dc:creator>
				<category><![CDATA[Publications]]></category>

		<guid isPermaLink="false">http://phaq.phunsites.net/?p=947</guid>
		<description><![CDATA[German Unix Magazine freeX has published my latest article on FreeBSD: How to shrink FreeBSD to fit embedded system by the help of NanoBSD and bsdbox. Read more about this story in the current issue 3-4/2012.]]></description>
			<content:encoded><![CDATA[<p>German Unix Magazine freeX has published my latest article on FreeBSD: How to shrink FreeBSD to fit embedded system by the help of NanoBSD and bsdbox.</p>
<p>Read more about this story in the current issue 3-4/2012.</p>
<div align="center">
<a href="http://phaq.phunsites.net/files/2012/04/freex3-42012cg.jpg" rel="lightbox[947]"><img src="http://phaq.phunsites.net/files/2012/04/freex3-42012cg.jpg" alt="" class="aligncenter size-full wp-image-948" /></a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://phaq.phunsites.net/2012/04/04/freebsd-ganz-klein-main-story-in-freex-3-42012/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mount a dd Disk Image with Partition Table inside</title>
		<link>http://phaq.phunsites.net/2012/02/05/mount-a-dd-disk-image-with-partition-table-inside/</link>
		<comments>http://phaq.phunsites.net/2012/02/05/mount-a-dd-disk-image-with-partition-table-inside/#comments</comments>
		<pubDate>Sun, 05 Feb 2012 21:06:52 +0000</pubDate>
		<dc:creator>gdelmatto</dc:creator>
				<category><![CDATA[Debian GNU/Linux]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[RHEL]]></category>

		<guid isPermaLink="false">http://phaq.phunsites.net/?p=943</guid>
		<description><![CDATA[After making a backup from a hard disk ta a disk image using plain old &#8216;dd&#8217;, I was just looking into mounting it using the Linux loopback device. If you &#8216;dd&#8217; a single partition into an image file, then this is very straight forward. But if your image file contains multiple partition partitions including the [...]]]></description>
			<content:encoded><![CDATA[<p>After making a backup from a hard disk ta a disk image using plain old &#8216;dd&#8217;, I was just looking into mounting it using the Linux loopback device.</p>
<p>If you &#8216;dd&#8217; a single partition into an image file, then this is very straight forward. But if your image file contains multiple partition partitions including the partition table itself, then you need to take additional steps.<br />
<span id="more-943"></span><br />
So the first thing to know is the exact offset of the partition to be mounted.<br />
You may examine this easily using parted. Just provide it with the path to the image file instead of a block device.</p>
<pre>
root@debian:~# parted full_hd.dd
GNU Parted 2.3
Using /root/full_hd.dd
Welcome to GNU Parted! Type 'help' to view a list of commands.
</pre>
<p>Now switch parted to use &#8216;Byte&#8217; units, then print the partition table:</p>
</pre>
<p>(parted) unit B<br />
(parted) print<br />
Model:  (file)<br />
Disk /root/full_hd.dd: 8012390400B<br />
Sector size (logical/physical): 512B/512B<br />
Partition Table: msdos</p>
<p>Number  Start     End          Size         Type     File system  Flags<br />
 1      1048576B  8012169215B  8011120640B  primary  ext4         boot
</pre>
<p>Keep a record of the 'Start' offset, you'll need this shortly. Quit parted using the 'quit' command.</p>
<p>Let's look into mounting the partition: pass the partition offset to the mount command using the 'offset=' option like this:</p>
<pre>
root@debian:~# mount -t ext4 -o loop,offset=1048576 full_hd.dd /mnt/test/
</pre>
<p>It may well be possible, that receive this error message as a result to your mount command if you try to mount the disk image read-only:</p>
<p><code><br />
mount: wrong fs type, bad option, bad superblock on /dev/loop0,<br />
       missing codepage or helper program, or other error<br />
       In some cases useful info is found in syslog - try<br />
       dmesg | tail  or so<br />
</code></p>
<p>In this case, examining the system logs, may reveal something like this:</p>
<p><code><br />
[ 8754.209469] EXT4-fs (loop0): VFS: Can't find ext4 filesystem<br />
[ 8758.913583] EXT4-fs (loop0): INFO: recovery required on readonly filesystem<br />
[ 8758.913587] EXT4-fs (loop0): write access unavailable, cannot proceed<br />
</code></p>
<p>To get around this, try adding the 'noload' option to skip journal recovery:</p>
<pre>
root@debian:~# mount -t ext4 -o loop,ro,noload,offset=1048576 full_hd.dd /mnt/test/
</pre>
]]></content:encoded>
			<wfw:commentRss>http://phaq.phunsites.net/2012/02/05/mount-a-dd-disk-image-with-partition-table-inside/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Install Icinga with MySQL and IDOUtils on FreeBSD</title>
		<link>http://phaq.phunsites.net/2012/01/28/install-icinga-with-mysql-and-idoutils-on-freebsd/</link>
		<comments>http://phaq.phunsites.net/2012/01/28/install-icinga-with-mysql-and-idoutils-on-freebsd/#comments</comments>
		<pubDate>Sat, 28 Jan 2012 17:24:23 +0000</pubDate>
		<dc:creator>gdelmatto</dc:creator>
				<category><![CDATA[FreeBSD]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[Utilities]]></category>

		<guid isPermaLink="false">http://phaq.phunsites.net/?p=920</guid>
		<description><![CDATA[It&#8217;s not hard to install Icinga on FreeBSD, at least if you&#8217;re satisfied with default options. Should you however require Icinga with IDOUtils and MySQL support, then you need to take additional steps. Note: This howto requires a patch to your FreeBSD ports tree. The patch has been submitted to the FreeBSD port maintainers. I [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s not hard to install <a href="http://www.icinga.org" target="_blank">Icinga</a> on FreeBSD, at least if you&#8217;re satisfied with default options.<br />
Should you however require Icinga with IDOUtils and MySQL support, then you need to take additional steps.</p>
<p><span id="more-920"></span></p>
<p><b>Note: This howto requires a <a href="http://phaq.phunsites.net/files/2012/01/patch_icinga_1.5.1_idoutils_fbs_port.txt">patch</a> to your FreeBSD ports tree. The patch has been submitted to the FreeBSD port maintainers. I hope that it will eventually end up in the ports tree.</b></p>
<p>My initial readings about this was on the official Icinga docs covering <a href="http://docs.icinga.org/latest/en/quickstart-idoutils-freebsd.html" target="_blank">installing Icinga on FreeBSD with IDOUtils</a>.<br />
However, as it turned out, the docs our a bit outdated, and yet do not reflect a way of doing the install using ports.</p>
<p>So here&#8217;s just a short primer on what I did do install Icinga from ports, imposing as little additional work four you, my fellow reader, as well <img src='http://phaq.phunsites.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Now let&#8217;s turn to Icinga, which has a port on it&#8217;s own, which you&#8217;ll find it at <strong>/usr/ports/net-mgtm/icinga</strong>. First change to that directory.</p>
<pre>cd /usr/ports/net-mgtm/icinga</pre>
<p>Now download the <a href="http://phaq.phunsites.net/files/2012/01/patch_icinga_1.5.1_idoutils_fbs_port.txt">patch file</a> I made into your ports directory.<br />
The patch will inject a new rc-script for ido2db and enable your port to build IDOutils.</p>
<pre>[root@localhost /usr/ports/net-mgmt/icinga]# fetch http://phaq.phunsites.net/files/2012/01/patch_icinga_1.5.1_idoutils_fbs_port.txt</pre>
<p>Then apply the patch like this:</p>
<pre>[root@localhost /usr/ports/net-mgmt/icinga]# patch -p0 &lt; patch_icinga_1.5.1_idoutils_fbs_port.txt
Hmm...  Looks like a unified diff to me...
The text leading up to this was:
--------------------------
|--- Makefile.org	2012-01-28 16:36:46.000000000 +0000
|+++ Makefile	2012-01-28 17:51:38.000000000 +0000
--------------------------
Patching file Makefile using Plan A...
Hunk #1 succeeded at 27.
Hunk #2 succeeded at 109.
Hmm...  The next patch looks like a unified diff to me...
The text leading up to this was:
--------------------------
|--- /dev/null	2012-01-28 18:00:51.000000000 +0000
|+++ files/ido2db.in	2012-01-28 18:00:30.000000000 +0000
--------------------------
(Creating file files/ido2db.in...)
Patching file files/ido2db.in using Plan A...
Hunk #1 succeeded at 1.
Hmm...  The next patch looks like a unified diff to me...
The text leading up to this was:
--------------------------
|--- files/pkg-message.in.org	2012-01-28 17:48:37.000000000 +0000
|+++ files/pkg-message.in	2012-01-28 17:49:38.000000000 +0000
--------------------------
Patching file files/pkg-message.in using Plan A...
Hunk #1 succeeded at 4.
done</pre>
<p>Now you&#8217;re ready to configure the port:</p>
<pre>[root@localhost /usr/ports/net-mgmt/icinga]# make config</pre>
<p>Note the now <strong>IDOUtils</strong> option that now has appeared. Check it to enable IDOUtils.</p>
<p><a href="http://phaq.phunsites.net/files/2012/01/idoutils_config_screen.png" rel="lightbox[920]"><img class="aligncenter size-medium wp-image-929" src="http://phaq.phunsites.net/files/2012/01/idoutils_config_screen-300x180.png" alt="" width="300" height="180" /></a></p>
<p>Then compile and install as usual. The port will install also all required dependies, two of them being mysql55-client and libdbi-drivers, both to be found at /usr/ports/databases.</p>
<pre>[root@localhost /usr/ports/net-mgmt/icinga]# make install clean</pre>
<p>Afterwards, you should end up with a few additional files, which would not be installed with the stock FreeBSD port.</p>
<pre>[root@localhost /usr/ports/net-mgmt/icinga]# ls -l /usr/local/bin/ido*
-rwxrwxr--  1 root  wheel  238326 Jan 28 16:53 /usr/local/bin/ido2db
-rwxrwxr--  1 root  wheel   80419 Jan 28 16:53 /usr/local/bin/idomod.o

[root@mgmp-bs01 /usr/ports/net-mgmt/icinga]# ls -l /usr/local/etc/rc.d/ido2db
-r-xr-xr-x  1 root  wheel  738 Jan 28 18:00 /usr/local/etc/rc.d/ido2db</pre>
<p>Now you can enable Icinage and IDO2DB in /etc/rc.conf by adding these lines:</p>
<pre>icinga_enable="YES"
ido2db_enable="YES"</pre>
<p>Of course, you still need to perform the usual Icinga configuration steps, which are not covered in this post.<br />
Please check with the <a href="http://docs.icinga.org/latest/en" target="_blank">official docs</a> for this procedure.</p>
<p>If your configuration is proper, you should notice this in your logs indicating that IDOMOD (IDOUtils) is really working.</p>
<pre>[1327773651] Icinga 1.5.1 starting... (PID=95448)
[1327773651] Local time is Sat Jan 28 18:00:51 UTC 2012
[1327773651] LOG VERSION: 2.0
[1327773651] idomod: IDOMOD 1.5.1 (09-09-2011) Copyright (c) 2005-2008 Ethan Galstad (nagios@nagios.org), Copyright (c) 2009-2011 Icinga Development Team (http://www.icinga.org))
[1327773651] idomod: Successfully connected to data sink.  26 queued items to flush.
[1327773651] idomod: Successfully flushed 26 queued items to data sink.
[1327773651] Event broker module '/usr/local/bin/idomod.o' initialized successfully.
[1327773651] Finished daemonizing... (New PID=95450)</pre>
<p>That&#8217;s it, you conquered the beast!</p>
]]></content:encoded>
			<wfw:commentRss>http://phaq.phunsites.net/2012/01/28/install-icinga-with-mysql-and-idoutils-on-freebsd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working around WordPress&#8217; wpdb limitations with MySQL User Variables</title>
		<link>http://phaq.phunsites.net/2012/01/27/working-around-wordpress-wpdb-limitations-with-mysql-user-variables/</link>
		<comments>http://phaq.phunsites.net/2012/01/27/working-around-wordpress-wpdb-limitations-with-mysql-user-variables/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 12:14:04 +0000</pubDate>
		<dc:creator>gdelmatto</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://phaq.phunsites.net/?p=914</guid>
		<description><![CDATA[Think about retrieving a data set from MySQL, where you need to add distinct, auto-incremented ID to each row retrieved. Sounds easy? Well, the ID has to be generated on-the-fly and out of nowhere. Still easy? One might think about using MySQL user variables to accomplish this, sure. But what if your framework does not [...]]]></description>
			<content:encoded><![CDATA[<p>Think about retrieving a data set from MySQL, where you need to add distinct, auto-incremented ID to each row retrieved. Sounds easy?</p>
<p>Well, the ID has to be generated on-the-fly and out of nowhere. Still easy?</p>
<p>One might think about using MySQL user variables to accomplish this, sure. But what if your framework does not allow injecting chained queries because of SQL injection countermeasures?<br />
<span id="more-914"></span><br />
The framework I used, WordPress&#8217; wpdb API to be exact, has such a restriction, which caused my to find an alternate way.</p>
<p>To illustrate the problem, I start with the date retrieved, which would normally look as shown below.</p>
<pre>mysql&gt; SELECT value1, value2 FROM sample_table;
+-----------------+-----------------+
| value1          | value2          |
+-----------------+-----------------+
| sample_value_1  | sample_value_2  |
| sample_value_a  | sample_value_b  |
+-----------------+-----------------+
2 rows in set (0.00 sec)</pre>
<p>Now, I need a line number for each record. When talking abut the line number, I&#8217;m strictly talking about a representation of &#8220;this is the first line&#8221;, &#8220;this is the second line&#8221;, etc.<br />
This particular line number must therefore not be identical to the tupel ID, if that even would exist.<br />
So this is what I would expect:</p>
<pre>
+------------+-----------------+-----------------+
| line_num   | value1          | value2          |
+------------+-----------------+-----------------+
| 1          | sample_value_1  | sample_value_2  |
| 2          | sample_value_a  | sample_value_b  |
+------------+-----------------+-----------------+
</pre>
<p>To generate this by the means of a query, one would usually use a MySQL user variable, that would be dynamically increased for each data row.<br />
In SQL speech the query would then look like this:</p>
<pre>
SELECT @line:=0;
SELECT @line:=@line+1 AS line_num, value1, value2 FROM sample_table;
+------------+-----------------+-----------------+
| line_num   | value1          | value2          |
+------------+-----------------+-----------------+
| 1          | sample_value_1  | sample_value_2  |
| 2          | sample_value_a  | sample_value_b  |
+------------+-----------------+-----------------+
</pre>
<p>It&#8217;s actually easy and conventient, and you get real, dynamically calculated &#8220;line numbers&#8221;. But this technique requires to actually run two statements to be run in a series.<br />
If you&#8217;re using your own database routines, this may not be a problem at all. But if you rely on a given framework, you may trip into SQL injection counter measures which will simply throw away a query constructed like this:</p>
<pre>
$my_query = "SELECT @line:=0; SELECT @line:=@line+1 AS line_num, value1, value2 FROM sample_table;";

$my_result = $pseudo_call_to_my_db_framework-&gt;execute( $my_query );
</pre>
<p>This was ecactly what I was trying to do with WordPress&#8217; wpdb API. However, as I found, SQL injection filters kicked in. This is absolutely not to blame the WordPress folks, of course. The filters in place serve a good purpose and thus forced me in taking a different approach.</p>
<p>After some searching on the net I found that I seemed to be the only one to be using users vars with wpdb :-/<br />
Of course, while this may not be widely used, I insisted in this approach. Suggestions in adding a loop or an extra-query where inappropriate to me, because it had to fit within the existing code base. That again required me to specifically do it in one SQL query, because I simply did not want to bloat the code by adding another loop in there.</p>
<p>So, the question is: Can the procedure described above be performed within ONE single query.</p>
<p>The answer is: Yes, but you&#8217;re required to invole a sub-query to achive this.</p>
<p>At first, leave the initial variable assignment away, so you end up with this query:</p>
<pre>
SELECT @line:=@line+1 AS line_num, value1, value2 FROM sample_table;
</pre>
<p>This would of course not yet work, because the user variable @line wouldn&#8217;t yet be defined at runtime.<br />
Since you can&#8217;t prepend the declaration, you need to embed it using a sub-query. This is needed to have the variable declaration ready at the earliest stage possible, namely while parsing the query, and not during result processing.</p>
<p>Let&#8217;s look at the final query and the comments:</p>
<pre>
SELECT
        @line:=@line+1 AS line_num,                     # increase the @line user variable for each row retrieved
        sample_table.value1,                            # include column 'value1' from table 'sample_table'
        sample_table.value2                             # include column 'value2' from table 'sample_table'
FROM
        (SELECT @line:=0) AS tmp_line,                  # this will fire during parsing: initialize the user var by selecting it into a dummy table
        sample_table;                                   # now add our actual data table as well
</pre>
<p>This way, you end up getting the same result as shown earlier. And yet, this query can be performed with WordPress&#8217; wpdb API and maybe other frameworks as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://phaq.phunsites.net/2012/01/27/working-around-wordpress-wpdb-limitations-with-mysql-user-variables/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Run command in background from PHP</title>
		<link>http://phaq.phunsites.net/2012/01/18/run-command-in-background-from-php/</link>
		<comments>http://phaq.phunsites.net/2012/01/18/run-command-in-background-from-php/#comments</comments>
		<pubDate>Tue, 17 Jan 2012 23:40:21 +0000</pubDate>
		<dc:creator>gdelmatto</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://phaq.phunsites.net/?p=904</guid>
		<description><![CDATA[While working on my newest project, a PHP- and AJAX-based network management application, I came along the need to run multiple commands on the server and track their return states (basically if they were run successful or not). While sticking together my framework, I found that forking a process into background from PHP requires some [...]]]></description>
			<content:encoded><![CDATA[<p>While working on my newest project, a PHP- and AJAX-based network management application, I came along the need to run multiple commands on the server and track their return states (basically if they were run successful or not).</p>
<p>While sticking together my framework, I found that forking a process into background from PHP requires some additional steps if you don&#8217;t want to break AJAX functionality.<br />
<span id="more-904"></span><br />
Here&#8217;s a sketch of the basic concept. It involves a Dispatcher, which creates a workqueue item in a database, and then forks a background process, which will perform various tasks. The latter will then report back the states of the tasks performed to the workqueue item in the database.<br />
On the other end, a Tracker will check the database for the running states and push progress information into the browser.</p>
<p><a href="http://phaq.phunsites.net/files/2012/01/ajax_dispatcher.png" rel="lightbox[904]"><img src="http://phaq.phunsites.net/files/2012/01/ajax_dispatcher-300x300.png" alt="" width="300" height="300" class="aligncenter size-medium wp-image-905" /></a></p>
<p>While it was working to some extent, my initial attempts at forking a background process from PHP failed terribly, because PHP always kept waiting for the command to complete.<br />
This behaviour had the side effect that the Dispatcher couldn&#8217;t immediately return the workqueue id to the AJAX client (the browser). But since the workqueue id was required by the AJAX-client to subsequently fire the Tracker, the initial request to the Dispatcher had to be synchronous instead of asynchronous.<br />
The blocking behaviour did however screw everything, so I had to find a way around.</p>
<p>Of course, I was thinking about the various methods in calling external commands from PHP, starting with simple backticks, exec(), passthru() and even popen(), despite some others as well.</p>
<p>People familiar to Unix/Linux environments would of course say, that a background task can be started easily by appending an ampersand to the end, making it look like this:</p>
<p><code><br />
exec( '/path/to/my/command &amp;' );<br />
system( '/path/to/my/command &amp;' );<br />
</code></p>
<p>But that does not work in PHP, because all calls are always waiting for the command to return.<br />
PHP effectively binds the STDERR and STDOUT I/O streams during execution, which is why a simple ampersand doesn&#8217;t work out.<br />
To get this to work, one must really detach the to-be-backgrounded program from the controlling terminal to trick PHP into returning from exec.</p>
<p>This can be done easily by redirecting STDOUT and STDERR to a logfile or /dev/null before background the program, and just return the pid.<br />
That would then look similar to this:</p>
<p><code><br />
exec( '/path/to/some/program &gt; /dev/null 2&gt;&amp;1 &amp; echo $!' );<br />
</code></p>
<p>The above example would detach the programm into background while returning control to your PHP application at once.</p>
<p>Consider the output destination being required in any case, otherwise the I/O streams won&#8217;t get detached.<br />
So this syntax, while being perfectly valid, will definitely run your command, but won&#8217;t place it into background at all:</p>
<p><code><br />
exec( '/path/to/some/program 2&gt;&amp;1 &amp; echo $!' );<br />
</code></p>
<p>That&#8217;s it <img src='http://phaq.phunsites.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://phaq.phunsites.net/2012/01/18/run-command-in-background-from-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

