<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<atom:link href="https://paulgorman.org/technical/blog/rss.xml" rel="self" type="application/rss+xml" />
<title>paulgorman.org</title>
<link>https://paulgorman.org/technical/blog/</link>
<description>Linux, BSD, networking, programming, etc.</description>
<item>
<title>A quick and dirty gateway through OpenVPN</title>
<link>https://paulgorman.org/technical/blog/20200606153428.html</link>
<description>&lt;h1&gt;A quick and dirty gateway through OpenVPN&lt;/h1&gt;

&lt;p&gt;Suppose our Linux box has an existing OpenVPN tunnel to a remote LAN.
We want this machine to act as a gateway, sending traffic from one of its interfaces across that OpenVPN tunnel.&lt;/p&gt;

&lt;p&gt;The need is short-term, so we don&amp;rsquo;t care about persisting the setup over reboots, and we&amp;rsquo;ll be a little devil-may-care with firewalling.&lt;/p&gt;

&lt;p&gt;We plug a switch into a USB NIC for our new, short-term local LAN.
Linux calls the NIC &lt;code&gt;enx8cae4ce94ec2&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Set up the network interface with a new address on a new subnet (192.168.222.0/24) for our short-term local LAN:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;🐚 ~ $ ip addr show enx8cae4ce94ec2
16: enx8cae4ce94ec2: &amp;lt;BROADCAST,MULTICAST,UP,LOWER_UP&amp;gt; mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 8c:ae:4c:e9:4e:c2 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::2e40:5f30:7d9b:db20/64 scope link noprefixroute 
        valid_lft forever preferred_lft forever
🐚 ~ $ sudo ip addr add 192.168.222.1/24 dev enx8cae4ce94ec2
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Run &lt;code&gt;dnsmasq&lt;/code&gt; on that interface to provide DHCP.
We don&amp;rsquo;t care about providing DNS by &lt;code&gt;dnsmasq&lt;/code&gt;, since we want these short-term clients to use DNS servers on the remote LAN (i.e., 10.0.0.2 and 10.0.0.3).&lt;/p&gt;

&lt;p&gt;Here&amp;rsquo;s the minimal &lt;code&gt;dnsmasq.conf&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;interface=enx8cae4ce94ec2
domain=example.com
dhcp-option=6,10.0.0.2,10.0.0.3
dhcp-range=192.168.222.50,192.168.222.150,255.255.255.0,12h
port=0
domain-needed
bogus-priv
strict-order
dhcp-name-match=set:wpad-ignore,wpad
dhcp-ignore-names=tag:wpad-ignore
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Check the syntax of our config file, then fire up &lt;code&gt;dnsmasq&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;🐚 ~ $ /usr/sbin/dnsmasq -C ./dnsmasq.conf --test
dnsmasq: syntax check OK.
🐚 ~ $ sudo /usr/sbin/dnsmasq -C ./dnsmasq.conf
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Because this temporary setup lives in a fairly trusted environment, we won&amp;rsquo;t worry about firewalling things:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;🐚 ~ $ sudo sysctl -w net.ipv4.ip_forward=1
🐚 ~ $ sudo iptables --policy FORWARD ACCEPT
🐚 ~ $ sudo iptables -A INPUT -i enx8cae4ce94ec2 -j ACCEPT
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Make sure our OpenVPN is up as &lt;code&gt;tun0&lt;/code&gt;, then:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;🐚 ~ $ sudo iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE
🐚 ~ $ sudo iptables -t nat -A POSTROUTING -o br0 -j MASQUERADE
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(&lt;code&gt;br0&lt;/code&gt; is the &amp;ldquo;outside&amp;rdquo;/main interface of our gateway, through which traffic not bound for example.com/OpenVPN will flow.)&lt;/p&gt;

&lt;p&gt;That does it.
Devices hanging off the switch attached to &lt;code&gt;enx8cae4ce94ec2&lt;/code&gt; should be able to hit things on the other side of &lt;code&gt;tun0&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If this was a long-term setup, we&amp;rsquo;d carefully firewall the new LAN and make sure our process supervisor/init manages the &lt;code&gt;dnsmasq&lt;/code&gt; server.&lt;/p&gt;

&lt;p&gt;#linux&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20200606153428.html</guid>
</item><item>
<title>Grow a guest block device live</title>
<link>https://paulgorman.org/technical/blog/20200217161042.html</link>
<description>&lt;h1&gt;Grow a guest block device live&lt;/h1&gt;

&lt;p&gt;There&amp;rsquo;s nothing surprising about the following, except that it works very well.&lt;/p&gt;

&lt;p&gt;Suppose a Windows guest on a KVM/libvirt hypervisor runs low on disk space.
Assuming the guest has the VirtIO storage drivers installed, we can grow its partition without a reboot.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Find the VM. In this case, &amp;ldquo;postiffice&amp;rdquo;.&lt;/li&gt;
&lt;li&gt;Find its too-small block device — &lt;code&gt;vgb&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Make sure the hypervisor&amp;rsquo;s storage pool has enough room, then grow the storage.
In this configuration, we extend the LVM volume underlying &lt;code&gt;vgb&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Ask libvirth to notify the guest about the change with &lt;code&gt;virsh blockresize&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;In the Windows guest, claim the new space with Disk Manager.&lt;/li&gt;
&lt;/ol&gt;

&lt;pre&gt;&lt;code&gt;🐚  hypervisor  ~ $ sudo virsh list
 Id    Name                           State
----------------------------------------------------
 2     brak                           running
 3     postoffice                     running

🐚  hypervisor  ~ $ sudo virsh domblklist --details postoffice
Type       Device     Target     Source
------------------------------------------------
block      disk       vda        /dev/vg0/postoffice-os
block      disk       vdb        /dev/vg0/postoffice-data
block      disk       vdc        /dev/vg0/antarctica-mail
file       cdrom      hdc        -

🐚  hypervisor  ~ $ sudo virsh domblkinfo postoffice vdb
Capacity:       289910292480
Allocation:     0
Physical:       289910292480

🐚  hypervisor  ~ $ sudo vgdisplay vg0 | grep -e Total -e Alloc -e Free
  Total PE              714947
  Alloc PE / Size       462855 / 1.77 TiB
  Free  PE / Size       252092 / 984.73 GiB
🐚  hypervisor  ~ $ sudo lvextend -L+30G /dev/vg0/postoffice-data
  Size of logical volume vg0/postoffice-data changed from 270.00 GiB (69120 extents) to 300.00 GiB (76800 extents).
  Logical volume vg0/postoffice-data successfully resized.
🐚  hypervisor  ~ $ sudo virsh domblkinfo postoffice vdb
Capacity:       289910292480
Allocation:     0
Physical:       322122547200

🐚  hypervisor  ~ $ sudo virsh blockresize postoffice /dev/vg0/postoffice-data 322122547200B
Block device &#39;/dev/vg0/postoffice-data&#39; is resized
🐚  hypervisor  ~ $ sudo virsh domblkinfo postoffice vdb
Capacity:       322122547200
Allocation:     0
Physical:       322122547200
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then, in Windows, tell Device Manager to &amp;ldquo;Scan for hardware changes&amp;rdquo;.
After refreshing its view, Disk Manager shows 30 GB of unallocated space.
Have Disk Manager grow the partition.&lt;/p&gt;

&lt;p&gt;Note that &lt;code&gt;virsh blockresize&lt;/code&gt; take KiB as its default unit, so be sure to specify &lt;code&gt;B&lt;/code&gt; if using a size from &lt;code&gt;virsh domblkinfo&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;#libvirt #linux #windows&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20200217161042.html</guid>
</item><item>
<title>Simple VPN failover between pfSense and EdgeOS</title>
<link>https://paulgorman.org/technical/blog/20200117105521.html</link>
<description>&lt;h1&gt;Simple VPN failover between pfSense and EdgeOS&lt;/h1&gt;

&lt;p&gt;I recently started testing a simple setup for VPN failover.
It&amp;rsquo;s been working well so far.&lt;/p&gt;

&lt;p&gt;The scenario:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Several &lt;em&gt;branch offices&lt;/em&gt; connect to a &lt;em&gt;central office&lt;/em&gt; by IPsec VPN.&lt;/li&gt;
&lt;li&gt;Each branch office has a single Internet connection and a Ubiquiti EdgeRouter.&lt;/li&gt;
&lt;li&gt;The central office has two Internet connections from two providers with different IP addresses owned by the providers.&lt;/li&gt;
&lt;li&gt;The central office terminates its Internet connections and VPN&amp;rsquo;s in a pfSense box.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The goal:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If one of the central office Internet connections goes down, the branch offices should fail over their VPN&amp;rsquo;s to the central office&amp;rsquo;s other Internet connection.&lt;/li&gt;
&lt;li&gt;Don&amp;rsquo;t resort to GRE tunnels and routing protocols.&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&#34;box-drawing&#34;&gt;

             ┏━━━━━━━━━━━┓                                       ┏━━━━━━━━━━┓
             ┃           ┠─198.51.100.37───────────┬─192.0.2.173─┨  Branch  ┃     LAN
             ┃           ┃         │               ┆             ┃ office 1 ┠─10.0.6.0/24
             ┃           ┃         │  ┌╌╌╌╌╌╌╌╌╌╌╌╌┘             ┃ (EdgeOS) ┃
    LAN      ┃  Central  ┃         │  ┆                          ┗━━━━━━━━━━┛
10.0.0.0/24 ─┨  office   ┃         │  ┆
             ┃ (pfSense) ┃         │  ┆                          ┏━━━━━━━━━━┓
             ┃           ┃         └───────────────┬─192.0.2.208─┨  Branch  ┃     LAN
             ┃           ┃            ┆            ┆             ┃ office 2 ┠─10.0.99.0/24
             ┃           ┠─203.0.113.204╌╌╌╌╌╌╌╌╌╌╌┘             ┃ (EdgeOS) ┃
             ┗━━━━━━━━━━━┛                                       ┗━━━━━━━━━━┛

&lt;/div&gt;

&lt;p&gt;Both pfSense and EdgeOS use strongSwan for IPsec (IKEv2).&lt;/p&gt;

&lt;p&gt;On the central office pfSense box:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a &amp;ldquo;gateway group&amp;rdquo; that includes both Internet connections.&lt;/li&gt;
&lt;li&gt;In the IPsec config for each tunnel, set the &amp;ldquo;Interface&amp;rdquo; to the gateway group.&lt;/li&gt;
&lt;li&gt;Enable MOBIKE. (I think strongSwan enables MOBIKE by default, but pfSense disables it by default.)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On the branch office EdgeRouters:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ubnt@branch-office:~$ configure
ubnt@branch-office# set vpn ipsec site-to-site peer 198.51.100.37,203.0.113.204 authentication mode pre-shared-secret
ubnt@branch-office# set vpn ipsec site-to-site peer 198.51.100.37,203.0.113.204 authentication pre-shared-secret *************************
ubnt@branch-office# set vpn ipsec site-to-site peer 198.51.100.37,203.0.113.204 connection-type initiate
ubnt@branch-office# set vpn ipsec site-to-site peer 198.51.100.37,203.0.113.204 ike-group FOO0
ubnt@branch-office# set vpn ipsec site-to-site peer 198.51.100.37,203.0.113.204 ikev2-reauth inherit
ubnt@branch-office# set vpn ipsec site-to-site peer 198.51.100.37,203.0.113.204 local-address 192.0.2.173
ubnt@branch-office# set vpn ipsec site-to-site peer 198.51.100.37,203.0.113.204 tunnel 1 allow-nat-networks disable
ubnt@branch-office# set vpn ipsec site-to-site peer 198.51.100.37,203.0.113.204 tunnel 1 allow-public-networks disable
ubnt@branch-office# set vpn ipsec site-to-site peer 198.51.100.37,203.0.113.204 tunnel 1 esp-group FOO0
ubnt@branch-office# set vpn ipsec site-to-site peer 198.51.100.37,203.0.113.204 tunnel 1 local prefix 10.0.6.0/24
ubnt@branch-office# set vpn ipsec site-to-site peer 198.51.100.37,203.0.113.204 tunnel 1 remote prefix 10.0.0.0/24
ubnt@branch-office# commit
ubnt@branch-office# save
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With this setup, VPN failover occurs automatically, though not always instantly.
Failover takes somewhere between a couple seconds and ten minutes after pfSense downs the primary interface in the gateway group.
I&amp;rsquo;m not sure what accounts for the delay.&lt;/p&gt;

&lt;p&gt;The only bit of weirdness I&amp;rsquo;ve noticed is that the EdgeRouter web GUI&amp;rsquo;s &amp;ldquo;Config Tree&amp;rdquo; gets confused about having two addresses in &amp;ldquo;vpn → ipsec → site-to-site → peer&amp;rdquo;, but this doesn&amp;rsquo;t seem to actually hurt anything.&lt;/p&gt;

&lt;p&gt;As of this writing, the branch office EdgeRouters run EdgeOS 2.0.8, which includes strongSwan 5.6.3.
The central office box runs pfSense 2.4.4-RELEASE-p3, which includes strongSwan 5.7.1.&lt;/p&gt;

&lt;p&gt;I&amp;rsquo;d feel more confident about this setup if StrongSwan included the &lt;code&gt;right=x.x.x.x,y.y.y.y&lt;/code&gt; syntax among their numerous &lt;a href=&#34;https://wiki.strongswan.org/projects/strongswan/wiki/ConfigurationExamples&#34;&gt;configuration examples&lt;/a&gt;.
I asked about it on the strongSwan IRC channel, but didn&amp;rsquo;t get any replies.&lt;/p&gt;

&lt;p&gt;#vpn #pfsense #edgeos&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20200117105521.html</guid>
</item><item>
<title>Making systemd supervise qemu-guest-agent</title>
<link>https://paulgorman.org/technical/blog/20190430170333.html</link>
<description>&lt;h1&gt;Making systemd supervise qemu-guest-agent&lt;/h1&gt;

&lt;p&gt;I&amp;rsquo;m something of a systemd curmudgeon, though (non-unixy design aside) its reliability and documentation has improved.
This is a case where systemd won by making something I expected to be annoying relatively painless.&lt;/p&gt;

&lt;p&gt;Debian Stretch still ships &lt;code&gt;qemu-guest-agent&lt;/code&gt; with a SysV init script.
The agent sometimes dies, breaking VM backups.
So, I went looking for a way to make systemd supervise it.&lt;/p&gt;

&lt;p&gt;For anything systemd finds in &lt;code&gt;/etc/init.d&lt;/code&gt;, its &lt;code&gt;systemd-sysv-generator&lt;/code&gt; creates a unit file.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;~ #  systemctl status qemu-guest-agent.service
● qemu-guest-agent.service - LSB: QEMU Guest Agent startup script
   Loaded: loaded (/etc/init.d/qemu-guest-agent; generated; vendor preset: enabled)
   Active: active (exited) since Fri 2019-04-12 10:02:44 EDT; 1 weeks 0 days ago
     Docs: man:systemd-sysv-generator(8)
    Tasks: 0 (limit: 4915)
   Memory: 0B
      CPU: 0
   CGroup: /system.slice/qemu-guest-agent.service

~ $  cat /run/systemd/generator.late/qemu-guest-agent.service
# Automatically generated by systemd-sysv-generator

[Unit]
Documentation=man:systemd-sysv-generator(8)
SourcePath=/etc/init.d/qemu-guest-agent
Description=LSB: QEMU Guest Agent startup script
Before=multi-user.target
Before=multi-user.target
Before=multi-user.target
Before=graphical.target
After=remote-fs.target

[Service]
Type=forking
Restart=no
TimeoutSec=5min
IgnoreSIGPIPE=no
KillMode=process
GuessMainPID=no
RemainAfterExit=yes
SuccessExitStatus=5 6
ExecStart=/etc/init.d/qemu-guest-agent start
ExecStop=/etc/init.d/qemu-guest-agent stop
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So, the generated unit file defaults to not restarting a service, or at least not a forking one.
How do we override this?&lt;/p&gt;

&lt;p&gt;&lt;code&gt;systemd.unit(5)&lt;/code&gt; says:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;There are two methods of overriding vendor settings in unit files: copying the unit file from /lib/systemd/system to /etc/systemd/system and modifying the chosen settings. Alternatively, one can create a directory named unit.d/ within /etc/systemd/system and place a drop-in file name.conf there that only changes the specific settings one is interested in. Note that multiple such drop-in files are read if present.&lt;/p&gt;

&lt;p&gt;[…]&lt;/p&gt;

&lt;p&gt;Note that for drop-in files, if one wants to remove entries from a setting that is parsed as a list (and is not a dependency), such as ConditionPathExists= (or e.g.  ExecStart= in service units), one needs to first clear the list before re-adding all entries except the one that is to be removed. See below for an example.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Does this work for unit files generated by &lt;code&gt;systemd-sysv-generator&lt;/code&gt;?
Yes!&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;~ #  mkdir /etc/systemd/system/qemu-guest-agent.service.d
~ #  vi /etc/systemd/system/qemu-guest-agent.service.d/local.conf
~ #  cat /etc/systemd/system/qemu-guest-agent.service.d/local.conf
[Service]
PIDFile=
PIDFile=/var/run/qemu-ga.pid
RemainAfterExit=
RemainAfterExit=no
Restart=
Restart=always
RestartSec=20

~ #  systemctl daemon-reload
~ #  systemctl stop qemu-guest-agent.service
~ #  systemctl start qemu-guest-agent.service
~ #  kill $(sudo cat /var/run/qemu-ga.pid) &amp;amp;&amp;amp; sleep 60 &amp;amp;&amp;amp; sudo systemctl status qemu-guest-agent.service
● qemu-guest-agent.service - LSB: QEMU Guest Agent startup script
   Loaded: loaded (/etc/init.d/qemu-guest-agent; generated; vendor preset: enabled)
  Drop-In: /etc/systemd/system/qemu-guest-agent.service.d
           └─local.conf
   Active: active (running) since Fri 2019-04-26 12:02:21 EDT; 39s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 364 ExecStop=/etc/init.d/qemu-guest-agent stop (code=exited, status=0/SUCCESS)
  Process: 392 ExecStart=/etc/init.d/qemu-guest-agent start (code=exited, status=0/SUCCESS)
 Main PID: 398 (qemu-ga)
    Tasks: 1 (limit: 4915)
   Memory: 484.0K
      CPU: 9ms
   CGroup: /system.slice/qemu-guest-agent.service
           └─398 /usr/sbin/qemu-ga --daemonize -m virtio-serial -p /dev/virtio-ports/org.qemu.guest_agent.0

Apr 26 12:02:21 box systemd[1]: qemu-guest-agent.service: Service hold-off time over, scheduling restart.
Apr 26 12:02:21 box systemd[1]: Stopped LSB: QEMU Guest Agent startup script.
Apr 26 12:02:21 box systemd[1]: Starting LSB: QEMU Guest Agent startup script...
Apr 26 12:02:21 box systemd[1]: qemu-guest-agent.service: PID file /var/run/qemu-ga.pid not readable (yet?) after start: No such file or directory
Apr 26 12:02:21 box systemd[1]: Started LSB: QEMU Guest Agent startup script.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;#systemd #linux&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20190430170333.html</guid>
</item><item>
<title>Fixing iptables on a KVM hypervisor after a Docker install</title>
<link>https://paulgorman.org/technical/blog/20181130111416.html</link>
<description>&lt;h1&gt;Fixing iptables on a KVM hypervisor after a Docker install&lt;/h1&gt;

&lt;p&gt;I run a number of KVM hypervisors that provide network to guests using a &lt;a href=&#34;https://www.linux-kvm.org/page/Networking#Public_Bridge&#34;&gt;public bridge&lt;/a&gt; (&lt;code&gt;br0&lt;/code&gt;).
The guest domains individually firewall themselves, so I leave the hypervisors&amp;rsquo; iptables &lt;code&gt;FORWARD&lt;/code&gt; chain defaulted to &lt;code&gt;ACCEPT&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This worked well until I &lt;a href=&#34;https://docs.docker.com/install/linux/docker-ce/debian/&#34;&gt;installed Docker&lt;/a&gt;.
Docker flips the default policy on the &lt;code&gt;FORWARD&lt;/code&gt; chain to &lt;code&gt;DROP&lt;/code&gt;, thereby cutting off network access for all the KVM guests attached to the bridge.
Ouch.&lt;/p&gt;

&lt;p&gt;Passing the &lt;code&gt;--iptables=false&lt;/code&gt; flag to the Docker daemon prevents Docker from touching iptables, but &lt;a href=&#34;https://docs.docker.com/network/iptables/#prevent-docker-from-manipulating-iptables&#34;&gt;that&amp;rsquo;s inconvenient&lt;/a&gt;.
To let Docker have its way while returning unfettered access our KVM guests using &lt;code&gt;br0&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#  iptables -I FORWARD -i br0 -o br0 -j ACCEPT
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Remember to persist this rule using, e.g., &lt;code&gt;iptables-save&lt;/code&gt;/&lt;code&gt;iptables-restore&lt;/code&gt;!&lt;/p&gt;

&lt;p&gt;#linux #docker #libvirt&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20181130111416.html</guid>
</item><item>
<title>Asterisk file locking in Go</title>
<link>https://paulgorman.org/technical/blog/20180306221308.html</link>
<description>&lt;h1&gt;Asterisk file locking in Go&lt;/h1&gt;

&lt;p&gt;I recently looked into &lt;a href=&#34;20180118194827.html&#34;&gt;how Asterisk locks files&lt;/a&gt;.
I&amp;rsquo;m working on a service written in Go that needs to mess with Asterisk voicemail files.
I don&amp;rsquo;t want to step on Asterisk&amp;rsquo;s toes (or let it step on mine).
This is a first take on a Go library for Asterisk-compatible file/directory locking.&lt;/p&gt;

&lt;p&gt;The Go functions largely follow their Asterisk C counterparts.
Go&amp;rsquo;s &lt;a href=&#34;https://godoc.org/golang.org/x/sys/unix&#34;&gt;&lt;code&gt;golang.org/x/sys/unix&lt;/code&gt; package&lt;/a&gt; provides  an interface to the low-level operating system primitives.
This Go package doesn&amp;rsquo;t provide much documentation, but we can refer to the OpenBSD man pages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://man.openbsd.org/open&#34;&gt;open&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://man.openbsd.org/close&#34;&gt;close&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://man.openbsd.org/link&#34;&gt;link&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://man.openbsd.org/unlink&#34;&gt;unlink&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://man.openbsd.org/flock&#34;&gt;flock&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://man.openbsd.org/fstat&#34;&gt;fstat&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://man.openbsd.org/stat&#34;&gt;stat&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;pre&gt;&lt;code&gt;// Package asterisk provides functions to interoperate with Asterisk.
package asterisk

import (
	&amp;quot;fmt&amp;quot;
	&amp;quot;math/rand&amp;quot;
	&amp;quot;path&amp;quot;
	&amp;quot;time&amp;quot;

	&amp;quot;golang.org/x/sys/unix&amp;quot;
)

const maxRetries int = 12
const waitTime time.Duration = time.Millisecond * 500

func init() {
	rand.Seed(time.Now().UnixNano())
}

// LockPathLockfile locks a directory with a `.lock` file.
func LockPathLockfile(p string) error {
	var err error
	fs := path.Join(p, fmt.Sprintf(&amp;quot;.lock-%08x&amp;quot;, rand.Int31()))
	s := path.Join(p, &amp;quot;.lock&amp;quot;)
	fd, err := unix.Open(fs, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL, 0600)
	if err != nil {
		return fmt.Errorf(&amp;quot;LockPathLockfile can&#39;t open file descriptor for %s: %v&amp;quot;, fs, err)
	}
	unix.Close(fd)
	for retries := 0; retries &amp;lt; maxRetries; retries++ {
		err = unix.Link(fs, s)
		if err == nil {
			break
		}
		err = fmt.Errorf(&amp;quot;LockPathLockfile can&#39;t link lock files %s and %s: %v&amp;quot;, fs, s, err)
		time.Sleep(waitTime)
	}
	unix.Unlink(fs)
	return err
}

// UnlockPathLockfile unlocks a directory locked by LockPathLockfile.
func UnlockPathLockfile(p string) error {
	var err error
	s := path.Join(p, &amp;quot;.lock&amp;quot;)
	err = unix.Unlink(s)
	if err != nil {
		err = fmt.Errorf(&amp;quot;UnlockPathLockfile can&#39;t unlink %s: %v&amp;quot;, s, err)
	}
	return err
}

// LockPathFlock locks a directory using the `flock` system call on a `lock` file.
func LockPathFlock(p string) error {
	var err error
	fs := path.Join(p, &amp;quot;lock&amp;quot;)
	fd, err := unix.Open(fs, unix.O_WRONLY|unix.O_CREAT, 0600)
	if err != nil {
		return fmt.Errorf(&amp;quot;LockPathFlock can&#39;t open file descriptor for %s: %v&amp;quot;, fs, err)
	}
	for retries := 0; retries &amp;lt; maxRetries; retries++ {
		err = unix.Flock(fd, unix.LOCK_EX|unix.LOCK_NB)
		if err != nil {
			err = fmt.Errorf(&amp;quot;LockPathFlock can&#39;t flock file %s: %v&amp;quot;, fs, err)
			time.Sleep(waitTime)
			continue
		}
		// Avoid the race condition where another prococess flocks our lock file first!
		var st0, st1 unix.Stat_t
		err = unix.Fstat(fd, &amp;amp;st0)
		if err != nil {
			return fmt.Errorf(&amp;quot;LockPathFlock can&#39;t stat file descriptor %v: %v&amp;quot;, fd, err)
		}
		err = unix.Stat(fs, &amp;amp;st1)
		if err != nil {
			return fmt.Errorf(&amp;quot;LockPathFlock can&#39;t stat lock file %s: %v&amp;quot;, fs, err)
		}
		if st0.Ino == st1.Ino {
			break
		}
		time.Sleep(waitTime)
	}
	unix.Close(fd)
	return err
}

// UnlockPathFlock unlocks a directory locked by LockPathFlock.
func UnlockPathFlock(p string) error {
	var err error
	s := path.Join(p, &amp;quot;lock&amp;quot;)
	fd, err := unix.Open(s, unix.O_WRONLY|unix.O_CREAT, 0600)
	if err != nil {
		err = fmt.Errorf(&amp;quot;UnlockPathFlock can&#39;t open lock file descriptor for %s during unlock: %v&amp;quot;, s, err)
	}
	unix.Unlink(s)
	if err != nil {
		err = fmt.Errorf(&amp;quot;UnlockPathFlock can&#39;t unlink %s: %v&amp;quot;, s, err)
	}
	unix.Flock(fd, unix.LOCK_UN)
	if err != nil {
		err = fmt.Errorf(&amp;quot;UnlockPathFlock can&#39;t un-flock file descriptor %v: %v&amp;quot;, fd, err)
	}
	return err
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;#asterisk #golang&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20180306221308.html</guid>
</item><item>
<title>Geek tribalism in Cuckoo&#39;s Egg</title>
<link>https://paulgorman.org/technical/blog/20180220210547.html</link>
<description>&lt;h1&gt;Geek tribalism in Cuckoo&amp;rsquo;s Egg&lt;/h1&gt;

&lt;p&gt;I&amp;rsquo;ve been thoroughly enjoying &lt;a href=&#34;https://www.amazon.com/gp/product/B0083DJXCM/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;amp;tag=whatspaulread-20&amp;amp;creative=9325&amp;amp;linkCode=as2&amp;amp;creativeASIN=B0083DJXCM&amp;amp;linkId=e574ea7e0ed808b4c64146ef7c9e93da&#34;&gt;Cuckoo&amp;rsquo;s Egg&lt;/a&gt;, Cliff Stoll&amp;rsquo;s account of chasing a hacker as a newly-minted sysadmin at Lawrence Berkeley National Lab in 1986. Two things in the book struck me as funny in a the-more-things-change way. The first is how Wayne, the VAX guy, constantly trades barbs with Dave, the Unix guy. The second is how Dave immediately deduces that the hacker isn&amp;rsquo;t local based on his use of &lt;code&gt;ps -eafg&lt;/code&gt; rather than &lt;code&gt;ps aux&lt;/code&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Of course, our lab used Berkeley Unix, as do all right-thinking folks. East Coast people were said to be biased toward AT&amp;amp;T Unix, but then, they hadn&amp;rsquo;t discovered hot tubs either.&lt;/p&gt;

&lt;p&gt;From a single letter, Dave ruled out the entire computing population of the West Coast.&lt;/p&gt;
&lt;/blockquote&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20180220210547.html</guid>
</item><item>
<title>Selectively VPN Services with Linux Network Namespaces</title>
<link>https://paulgorman.org/technical/blog/20180128152453.html</link>
<description>&lt;h1&gt;Selectively VPN Services with Linux Network Namespaces&lt;/h1&gt;

&lt;p&gt;My little home server does two things, mainly:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;resolve DNS for my home network as a sort of custom &lt;a href=&#34;https://pi-hole.net/&#34;&gt;Pi-Hole&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;provide me remote access from outside via SSH&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After the recent FCC repeal of net neutrality regulations, I signed up for a VPN service as a small protest.
Naturally, I&amp;rsquo;d like to make it more difficult for Comcast to harvest my DNS queries by sending the DNS resolver traffic over the VPN.
But if I run OpenVPN, I can&amp;rsquo;t SSH in for remote access.
I need to run some services over the VPN, but leave others out.&lt;/p&gt;

&lt;p&gt;Unfortunately, routing doesn&amp;rsquo;t work that way.
There&amp;rsquo;s no easy way to tell the OS: route most traffic out the default route, but send DNS traffic out the VPN.
Routing operates on IP addresses, not ports.&lt;/p&gt;

&lt;p&gt;My first thought was to use a virtual machine or LXC container.
That would work, but it&amp;rsquo;s a relatively heavy solution that requires additional ongoing administration (OS updates in the container, etc.).&lt;/p&gt;

&lt;p&gt;Then I remembered Linux&amp;rsquo;s &lt;a href=&#34;https://lwn.net/Articles/580893/&#34;&gt;network namespaces&lt;/a&gt;.
The kernel can provide isolation that gives a process its own network interfaces and &lt;em&gt;its own routing table&lt;/em&gt;.
Perfect!&lt;/p&gt;

&lt;p&gt;My server already has a &lt;a href=&#34;https://wiki.archlinux.org/index.php/Network_bridge&#34;&gt;bridge&lt;/a&gt; named &lt;code&gt;br0&lt;/code&gt;, which will help connect the isolated network namespace to the outside:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ ip addr sh br0
3: br0: &amp;lt;BROADCAST,MULTICAST,UP,LOWER_UP&amp;gt; mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 4e:07:25:9d:05:36 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.2/24 brd 10.0.0.255 scope global br0
       valid_lft forever preferred_lft forever
    inet6 fe80::f64d:30ff:fe6f:129c/64 scope link
       valid_lft forever preferred_lft forever
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Creation of a new network namespace is simple:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# ip netns add myns
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Start any process in the namespace using the &lt;code&gt;exec&lt;/code&gt; subcommand of &lt;code&gt;ip-netns&lt;/code&gt;, even a Bash shell:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# ip netns exec myns bash
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This isolated namespace does not share the interfaces or routing table of the host.
Any process executed in the namespace can&amp;rsquo;t get out to the network.
To run Unbound, our DNS resolver, in the namespace, we&amp;rsquo;ll need a connection to the host&amp;rsquo;s bridge.&lt;/p&gt;

&lt;p&gt;Linux offers &amp;ldquo;veth&amp;rdquo; devices that operate in pairs, like virtual patch cables, to connect software bridges or network namespaces.
We create the pair of devices, assign one end to a &lt;code&gt;vpnns&lt;/code&gt; network namespace, and plug the other end into the host&amp;rsquo;s &lt;code&gt;br0&lt;/code&gt; bridge.
Here&amp;rsquo;s a complete shell script to do so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/sh
set -uf
#---------------------------------------------------------------------------
# Create a private network namespace for OpenVPN and things that need to
# use the VPN, like Unbound.
#---------------------------------------------------------------------------
ns=vpnns
ip netns add &amp;quot;$ns&amp;quot;
ip netns exec &amp;quot;$ns&amp;quot; ip li set dev lo up
ip link add veth0 type veth peer name veth1
ip link set veth1 netns &amp;quot;$ns&amp;quot;
ip li set up dev veth0
ip netns exec &amp;quot;$ns&amp;quot; ip addr add 10.0.0.3/24 dev veth1
ip netns exec &amp;quot;$ns&amp;quot; ip li set up dev veth1
ip netns exec &amp;quot;$ns&amp;quot; ip ro add default via 10.0.0.1 dev veth1
ip link set dev veth0 master br0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;After that, the 10.0.0.3 interface should be visible on our LAN, and a ping run from inside the &lt;code&gt;vpnns&lt;/code&gt; namespace should reach the outside:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# ip netns exec vpnns ping -c3 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=60 time=39.0 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=60 time=43.4 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=60 time=42.2 ms

--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 39.013/41.583/43.440/1.891 ms
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Assuming we&amp;rsquo;ve already installed and configured OpenVPN and Unbound, modify their systemd unit files to put them in the new network namespace.
Both unit files need only two minor changes.
Call the &lt;code&gt;netns-vpn-up.sh&lt;/code&gt; shell script to set up the network namespace using systemd&amp;rsquo;s &lt;code&gt;ExecStartPre&lt;/code&gt;.
(It&amp;rsquo;s not a problem if multiple services call this script, or if its runs again when the namespace has already been set up.)
The other change happens to &lt;code&gt;ExecStart&lt;/code&gt;;
prefix the existing command with &lt;code&gt;ip netns exec&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ cat /etc/systemd/system/vpn.service
[Unit]
Description=OpenVPN
Wants=network.target
After=network.target

[Service]
Type=simple
ExecStartPre=-/home/paulgorman/bin/netns-vpn-up.sh
ExecStart=-/bin/ip netns exec vpnns /usr/sbin/openvpn --config /etc/openvpn/ovpn_udp/99.example.com.udp.ovpn

Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;rsquo;s it.
Unbound and OpenVPN run in the &lt;code&gt;vpnns&lt;/code&gt; namespace.
Everything else, including remote SSH access, happens outside the VPN.
To later run another command over the VPN, do &lt;code&gt;ip netns exec vpnns mycommand&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;#vpn #dns #linux #systemd&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20180128152453.html</guid>
</item><item>
<title>Asterisk File Locking</title>
<link>https://paulgorman.org/technical/blog/20180118194827.html</link>
<description>&lt;h1&gt;Asterisk File Locking&lt;/h1&gt;

&lt;p&gt;Asterisk locks files.
For example, when it writes voicemail files, it drops a lock in the mailbox directory to warn away anything else from writing at the same instant.&lt;/p&gt;

&lt;p&gt;Since I&amp;rsquo;m working on a program that mucks around with voicemail, I realized I need to know how Asterisk file locking works.
A quick web search didn&amp;rsquo;t turn up much, so I grabbed the Asterisk source code and grepped.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone https://github.com/asterisk/asterisk
$ cd asterisk
$ grep -r &#39;flock(&#39;
$ grep -r &#39;fcntl(&#39;
$ grep -r &#39;AST_LOCK_TYPE&#39;
$ grep -r &#39;lockfile&#39;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The most interesting results come from &lt;code&gt;asterisk/main/app.c&lt;/code&gt; and &lt;code&gt;asterisk/main/asterisk.c&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Looking in &lt;code&gt;asterisk/main/asterisk.c&lt;/code&gt;, we see:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;} else if (!strcasecmp(v-&amp;gt;name, &amp;quot;lockmode&amp;quot;)) {
	if (!strcasecmp(v-&amp;gt;value, &amp;quot;lockfile&amp;quot;)) {
		ast_set_lock_type(AST_LOCK_TYPE_LOCKFILE);
	} else if (!strcasecmp(v-&amp;gt;value, &amp;quot;flock&amp;quot;)) {
		ast_set_lock_type(AST_LOCK_TYPE_FLOCK);
	} else {
		ast_log(LOG_WARNING, &amp;quot;&#39;%s&#39; is not a valid setting for the lockmode option, &amp;quot;
			&amp;quot;defaulting to &#39;lockfile&#39;\n&amp;quot;, v-&amp;gt;value);
		ast_set_lock_type(AST_LOCK_TYPE_LOCKFILE);
	}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So, &lt;code&gt;lockmode&lt;/code&gt; is an option we can set in &lt;code&gt;/etc/asterisk.conf&lt;/code&gt; to either &lt;code&gt;lockfile&lt;/code&gt; (the default) or &lt;code&gt;flock&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;CHANGES&lt;/code&gt; file*, under the &amp;ldquo;Functionality changes from Asterisk 1.4.X to Asterisk 1.6.0&amp;rdquo; section, we find:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A &amp;ldquo;lockmode&amp;rdquo; option has been added to asterisk.conf to configure the file locking method used for voicemail, and potentially other things in the future.  The default is the old behavior, lockfile.  However, there is a new method, &amp;ldquo;flock&amp;rdquo;, that uses a different method for situations where the lockfile will not work, such as on SMB/CIFS mounts.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What&amp;rsquo;s the difference between the two Asterisk lock modes?&lt;/p&gt;

&lt;p&gt;I recognize &lt;a href=&#34;http://man7.org/linux/man-pages/man2/flock.2.html&#34;&gt;&lt;code&gt;flock&lt;/code&gt;&lt;/a&gt; as a Unix system call.
Indeed, the function in &lt;code&gt;asterisk/main/app.c&lt;/code&gt; uses the &lt;code&gt;flock&lt;/code&gt; system call:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
{
	char *fs;
	int res;
	int fd;
	time_t start;
	struct path_lock *pl;
	struct stat st, ost;

	fs = ast_alloca(strlen(path) + 20);
	snprintf(fs, strlen(path) + 19, &amp;quot;%s/lock&amp;quot;, path);
	...
	if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) &amp;lt; 0) {
	...
	((res = flock(pl-&amp;gt;fd, LOCK_EX | LOCK_NB)) &amp;lt; 0) &amp;amp;&amp;amp;
	...
}

static int ast_unlock_path_flock(const char *path)
{
	char *s;
	struct path_lock *p;

	s = ast_alloca(strlen(path) + 20);

	AST_LIST_LOCK(&amp;amp;path_lock_list);
	AST_LIST_TRAVERSE_SAFE_BEGIN(&amp;amp;path_lock_list, p, le) {
		if (!strcmp(p-&amp;gt;path, path)) {
			AST_LIST_REMOVE_CURRENT(le);
			break;
		}
	}
	AST_LIST_TRAVERSE_SAFE_END;
	AST_LIST_UNLOCK(&amp;amp;path_lock_list);

	if (p) {
		snprintf(s, strlen(path) + 19, &amp;quot;%s/lock&amp;quot;, path);
		unlink(s);
		path_lock_destroy(p);
		ast_debug(1, &amp;quot;Unlocked path &#39;%s&#39;\n&amp;quot;, path);
	} else {
		ast_debug(1, &amp;quot;Failed to unlock path &#39;%s&#39;: &amp;quot;
				&amp;quot;lock not found\n&amp;quot;, path);
	}

	return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that Asterisk creates a file called &lt;code&gt;lock&lt;/code&gt; in the target directory.&lt;/p&gt;

&lt;p&gt;According to the &lt;code&gt;flock(2)&lt;/code&gt; man page, the lock releases with either a &lt;code&gt;flock(fd, LOCK_UN)&lt;/code&gt; call or the closing of the file descriptor.
The &lt;code&gt;ast_unlock_path_flock&lt;/code&gt; function ends the lock by closing and unlinking the &lt;code&gt;lock&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;What does the default &lt;code&gt;lockfile&lt;/code&gt; option do?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
{
	char *s;
	char *fs;
	int res;
	int fd;
	int lp = strlen(path);
	time_t start;

	s = ast_alloca(lp + 10);
	fs = ast_alloca(lp + 20);

	snprintf(fs, strlen(path) + 19, &amp;quot;%s/.lock-%08lx&amp;quot;, path, (unsigned long)ast_random());
	fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
	if (fd &amp;lt; 0) {
		ast_log(LOG_ERROR, &amp;quot;Unable to create lock file &#39;%s&#39;: %s\n&amp;quot;, path, strerror(errno));
		return AST_LOCK_PATH_NOT_FOUND;
	}
	close(fd);

	snprintf(s, strlen(path) + 9, &amp;quot;%s/.lock&amp;quot;, path);
	start = time(NULL);
	while (((res = link(fs, s)) &amp;lt; 0) &amp;amp;&amp;amp; (errno == EEXIST) &amp;amp;&amp;amp; (time(NULL) - start &amp;lt; 5)) {
		sched_yield();
	}

	unlink(fs);

	if (res) {
		ast_log(LOG_WARNING, &amp;quot;Failed to lock path &#39;%s&#39;: %s\n&amp;quot;, path, strerror(errno));
		return AST_LOCK_TIMEOUT;
	} else {
		ast_debug(1, &amp;quot;Locked path &#39;%s&#39;\n&amp;quot;, path);
		return AST_LOCK_SUCCESS;
	}
}

static int ast_unlock_path_lockfile(const char *path)
{
	char *s;
	int res;

	s = ast_alloca(strlen(path) + 10);

	snprintf(s, strlen(path) + 9, &amp;quot;%s/%s&amp;quot;, path, &amp;quot;.lock&amp;quot;);

	if ((res = unlink(s))) {
		ast_log(LOG_ERROR, &amp;quot;Could not unlock path &#39;%s&#39;: %s\n&amp;quot;, path, strerror(errno));
	} else {
		ast_debug(1, &amp;quot;Unlocked path &#39;%s&#39;\n&amp;quot;, path);
	}

	return res;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that asterisk creates a file called &lt;code&gt;.lock&lt;/code&gt; in the target directory, rather than the dotless &lt;code&gt;lock&lt;/code&gt; it uses for &lt;code&gt;flock&lt;/code&gt; mode.&lt;/p&gt;

&lt;p&gt;Chapter 55 of &lt;a href=&#34;https://www.amazon.com/gp/search/ref=as_li_qf_sp_sr_il_tl?ie=UTF8&amp;amp;tag=whatspaulread-20&amp;amp;keywords=9781593272203&amp;amp;index=aps&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;linkCode=xm2&amp;amp;linkId=f347e223a1404fd5cb82fe325ee33c75&#34;&gt;The Linux Programming Interface&lt;/a&gt; describes file locking.
Section 55.7 describes the pattern of &lt;a href=&#34;http://man7.org/linux/man-pages/man2/link.2.html&#34;&gt;&lt;code&gt;link&lt;/code&gt;&lt;/a&gt; plus &lt;a href=&#34;http://man7.org/linux/man-pages/man2/unlink.2.html&#34;&gt;&lt;code&gt;unlink&lt;/code&gt;&lt;/a&gt; calls Asterisk uses here, and its shortcomings.
These are they key lines:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;while (((res = link(fs, s)) &amp;lt; 0) &amp;amp;&amp;amp; (errno == EEXIST) &amp;amp;&amp;amp; (time(NULL) - start &amp;lt; 5)) {
	sched_yield();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If two process try to link the same file, the second one get an &lt;code&gt;EEXIST&lt;/code&gt; error.
If that&amp;rsquo;s us, we have to try again later (&lt;code&gt;sched_yield&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;We could work with either lock method, but &lt;code&gt;flock&lt;/code&gt; seems easier to implement and less error-prone.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;With the &lt;code&gt;link&lt;/code&gt; plus &lt;code&gt;unlink&lt;/code&gt; method we have to handle retries. With &lt;code&gt;flock&lt;/code&gt;, we just wait for the call to unblock.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;link&lt;/code&gt; plus &lt;code&gt;unlink&lt;/code&gt; method is significantly slower than &lt;code&gt;flock&lt;/code&gt;, although the average Asterisk system probably doesn&amp;rsquo;t do enough locking for it to matter.&lt;/li&gt;
&lt;li&gt;If the process dies, the system releases &lt;code&gt;flock&lt;/code&gt;. The lock created with &lt;code&gt;link&lt;/code&gt; does not get automatically released.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;link&lt;/code&gt; and &lt;code&gt;unlink&lt;/code&gt; method may not work on some network file systems (NFS, SMB), while &lt;code&gt;flock&lt;/code&gt; should work.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;*In the &lt;code&gt;CHANGES&lt;/code&gt; file, I also noticed this, which may come into play when messing with Asterisk&amp;rsquo;s voicemail files:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;MWI (Message Waiting Indication) handling has been significantly restructured internally to Asterisk.  It is now totally event based instead of polling based.  The voicemail application will notify other modules that have subscribed to MWI events when something in the mailbox changes. This also means that if any other entity outside of Asterisk is changing the contents of mailboxes, then the voicemail application still needs to poll for changes.  Examples of situations that would require this option are web interfaces to voicemail or an email client in the case of using IMAP storage.  So, two new options have been added to voicemail.conf to account for this: &amp;ldquo;pollmailboxes&amp;rdquo; and &amp;ldquo;pollfreq&amp;rdquo;.  See the sample configuration file for details.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But also:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Added VoicemailRefresh action to allow an external entity to trigger mailbox updates when changes occur instead of requiring the use of pollmailboxes.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;#asterisk #c&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20180118194827.html</guid>
</item><item>
<title>Blocking Ads with DNS</title>
<link>https://paulgorman.org/technical/blog/20171213105509.html</link>
<description>&lt;h1&gt;Blocking Ads with DNS&lt;/h1&gt;

&lt;p&gt;I block advertisements (and malware and various other things) for all the clients on my network by running my own DNS server, and denying outbound DNS queries through the firewall for anything except that server.
&lt;a href=&#34;https://pi-hole.net/&#34;&gt;Pi-hole&lt;/a&gt; does roughly the same thing, but I use &lt;a href=&#34;https://unbound.net/&#34;&gt;Unbound&lt;/a&gt; for DNS.
Excepting adjustment of the Unbound config paths, the same setup runs on pfSense, OpenBSD, and Debian.
Just install Unbound, and schedule a cron job to periodically run this shell script:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/sh
set -euf

bl0=/tmp/ph-0-stevenblack-hosts
bl1=/tmp/ph-1-malwaredomains-justdomains
bl2=/tmp/ph-2-cameleon-hosts
bl3=/tmp/ph-3-zeustracker-domainblocklist
bl4=/tmp/ph-4-disconnect.me-simpletracking
bl5=/tmp/ph-5-disconnect.me-simpleads
bl6=/tmp/ph-6-hosts-file.net-adservers

# Pi-Hole lists found in https://github.com/pi-hole/pi-hole/blob/master/adlists.default
curl --silent --output &amp;quot;$bl0&amp;quot; https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts
curl --silent --output &amp;quot;$bl1&amp;quot; https://mirror1.malwaredomains.com/files/justdomains
curl --silent --output &amp;quot;$bl2&amp;quot; http://sysctl.org/cameleon/hosts
curl --silent --output &amp;quot;$bl3&amp;quot; https://zeustracker.abuse.ch/blocklist.php?download=domainblocklist
curl --silent --output &amp;quot;$bl4&amp;quot; https://s3.amazonaws.com/lists.disconnect.me/simple_tracking.txt
curl --silent --output &amp;quot;$bl5&amp;quot; https://s3.amazonaws.com/lists.disconnect.me/simple_ad.txt
curl --silent --output &amp;quot;$bl6&amp;quot; https://hosts-file.net/ad_servers.txt

if [ -s &amp;quot;$bl0&amp;quot; -a -s &amp;quot;$bl1&amp;quot; -a -s &amp;quot;$bl2&amp;quot; -a -s &amp;quot;$bl3&amp;quot; -a -s &amp;quot;$bl4&amp;quot; -a -s &amp;quot;$bl5&amp;quot; -a -s &amp;quot;$bl6&amp;quot; ]
then
cat &amp;quot;$bl0&amp;quot; &amp;quot;$bl1&amp;quot; &amp;quot;$bl2&amp;quot; &amp;quot;$bl3&amp;quot; &amp;quot;$bl4&amp;quot; &amp;quot;$bl5&amp;quot; &amp;quot;$bl6&amp;quot; &amp;quot;$bl7&amp;quot; &amp;quot;$bl8&amp;quot; | sort | uniq \
        | sed &#39;s/^\.//&#39;  \
        | sed &#39;/^\s*$/d&#39; \
        | sed &#39;/^#.*/d&#39;  \
                | sed &#39;/^deviantart.com$/d&#39; \
                | sed &#39;/^docs.google.com$/d&#39; \
                | sed &#39;/^drive.google.com$/d&#39; \
                | sed &#39;/\.googleusercontent.com$/d&#39; \
                | sed &#39;/\.imgur.com$/d&#39; \
                | sed &#39;/^informit.com$/d&#39; \
                | sed &#39;/^pastebin.com$/d&#39; \
                | sed &#39;/^proboards.com$/d&#39; \
                | sed &#39;/^staticflickr.com$/d&#39; \
        | awk &#39;{print &amp;quot;local-zone: \&amp;quot;&amp;quot;$1&amp;quot;\&amp;quot; redirect\nlocal-data: \&amp;quot;&amp;quot;$1&amp;quot; A 127.0.0.1\&amp;quot;&amp;quot;}&#39; \
        | sed &#39;1 i\
server:
&#39; &amp;gt; /etc/unbound/unbound.conf.d/blacklist.conf
        /usr/sbin/unbound-control -c /etc/unbound/unbound.conf reload
fi
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;#dns&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20171213105509.html</guid>
</item><item>
<title>Automate deletion of old voicemail from full Asterisk mailboxes</title>
<link>https://paulgorman.org/technical/blog/20171206155816.html</link>
<description>&lt;h1&gt;Automate deletion of old voicemail from full Asterisk mailboxes&lt;/h1&gt;

&lt;p&gt;No matter how high the message limit, some users never delete old voicemail.
That can prevent other users from forwarding messages to the full mailboxes.
Here&amp;rsquo;s a quick shell script to run as a nightly cron job that deletes old messages from full or almost-full mailboxes.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/sh
# For mailboxes with 90+ messages, delete messages older than 180 days.
set -eu
threshold=90
days=180
vmroot=/var/spool/asterisk/voicemail/default
find &amp;quot;$vmroot&amp;quot;/*/Old -maxdepth 1 -type d \
        -exec sh -c &amp;quot;echo -n {} &#39; &#39; ; find {} -type f -name &#39;msg*wav&#39; | wc -l&amp;quot; \; \
        | awk &amp;quot;{ if (\$NF &amp;gt; $threshold &amp;amp;&amp;amp; NF == 2) printf \&amp;quot;%s \&amp;quot;, \$1 }&amp;quot; \
        | xargs -I% sh -c &amp;quot;find % -type f -name &#39;msg*&#39; -mtime +$days \
        -exec rm {} \;&amp;quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This purges messages older than 180 days from mailboxes with 90+ messages.&lt;/p&gt;

&lt;p&gt;We can also adapt these bits for ad-hoc use, like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ find /var/spool/asterisk/voicemail/default/*/Old -maxdepth 1 -type d \
  -exec sh -c &amp;quot;echo -n {} &#39; &#39; ; find {} -type f -name &#39;msg*wav&#39; | wc -l&amp;quot; \; \
  | awk &#39;{ if ($NF &amp;gt; 90) print }&#39;
/var/spool/asterisk/voicemail/default/100/Old  100
/var/spool/asterisk/voicemail/default/123/Old  100
/var/spool/asterisk/voicemail/default/341/Old  97
/var/spool/asterisk/voicemail/default/471/Old  100
/var/spool/asterisk/voicemail/default/561/Old  100
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;#asterisk #shell&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20171206155816.html</guid>
</item><item>
<title>Git pre-commit Golang hook</title>
<link>https://paulgorman.org/technical/blog/20171122114720.html</link>
<description>&lt;h1&gt;Git pre-commit Golang hook&lt;/h1&gt;

&lt;pre&gt;&lt;code&gt;$ touch $GOPATH/src/example.com/myproject/.git/hooks/pre-commit
$ chmod a+x $GOPATH/src/example.com/myproject/.git/hooks/pre-commit
$ cat &amp;lt;&amp;lt; &#39;EOF&#39; &amp;gt; $GOPATH/src/example.com/myproject/.git/hooks/pre-commit
#!/bin/sh
go fmt ./...
go vet ./...
go test -cover ./...
find -type f -name &#39;*.go&#39; -exec wc -l {} +
find -type f -name &#39;*.go&#39; -exec sed &#39;/^\s*$/d&#39; {} + | wc -l; echo &#39; ↳ total (non-blank) lines of code&#39;
EOF
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;#golang #git&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20171122114720.html</guid>
</item><item>
<title>Run a Go Binary as a Daemon under systemd</title>
<link>https://paulgorman.org/technical/blog/20171121184114.html</link>
<description>&lt;h1&gt;Run a Go Binary as a Daemon under systemd&lt;/h1&gt;

&lt;p&gt;We want to run our Go program as a daemon on Linux, under systemd.
Specifically, we want it to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;start at the right time (e.g. after networking comes up)&lt;/li&gt;
&lt;li&gt;restart if it dies&lt;/li&gt;
&lt;li&gt;log STDOUT and STDERR&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;First, a little Go program for testing:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// stdout-stderr-test-daemon.go
package main

import (
	&amp;quot;fmt&amp;quot;
	&amp;quot;log&amp;quot;
	&amp;quot;os&amp;quot;
	&amp;quot;time&amp;quot;
)

func main() {
	stderr := log.New(os.Stderr, &amp;quot;&amp;quot;, 0)
	for {
		fmt.Println(&amp;quot;Hello, STDOUT&amp;quot;)
		stderr.Println(&amp;quot;Hello, STDERR&amp;quot;)
		time.Sleep(time.Millisecond * 15000)
	}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Build and install the binary:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ go build stdout-stderr-test-daemon.go
# cp stdout-stderr-test-daemon /usr/local/bin/
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here&amp;rsquo;s our systemd unit file, &lt;code&gt;/etc/systemd/system/stdout-stderr-test-daemon.service&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Unit]
Description=Tests systemd to daemonize a Go binary
Documentation=https://paulgorman.org/technical/blog/20171121184114.html
Wants=network.target
After=network.target

[Service]
Type=simple
DynamicUser=yes
ExecStart=/usr/local/bin/stdout-stderr-test-daemon
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;See &lt;code&gt;systemd.unit(5)&lt;/code&gt;, &lt;code&gt;systemd.service(5)&lt;/code&gt;, and &lt;code&gt;systemd.exec(5)&lt;/code&gt; for unit file documentation.&lt;/p&gt;

&lt;p&gt;Start our service, and watch it log:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# systemctl daemon-reload
# systemctl start stdout-stderr-test-daemon
# journalctl -u stdout-stderr-test-daemon
# journalctl -f -u stdout-stderr-test-daemon
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To start the service at boot:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# systemctl enable stdout-stderr-test-daemon
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;#golang #systemd&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20171121184114.html</guid>
</item><item>
<title>MySQL/MariaDB: &#34;max key length is 767 bytes&#34;</title>
<link>https://paulgorman.org/technical/blog/20171116151321.html</link>
<description>&lt;h1&gt;MySQL/MariaDB: &amp;ldquo;max key length is 767 bytes&amp;rdquo;&lt;/h1&gt;

&lt;p&gt;When running a script through the &lt;code&gt;mysql&lt;/code&gt; CLI client:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;ERROR 1071 (42000) at line 21: Specified key was too long; max key length is 767 bytes&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Working with MariaDB, I&amp;rsquo;ve bumped into this a couple of time lately. MariaDB or Debian must have recently changed a default.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;MariaDB [(none)]&amp;gt; show variables like &#39;char%&#39;;
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8mb4                    |
| character_set_connection | utf8mb4                    |
| character_set_database   | utf8mb4                    |
| character_set_filesystem | binary                     |
| character_set_results    | utf8mb4                    |
| character_set_server     | utf8mb4                    |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

$ mariadb --version
mariadb  Ver 15.1 Distrib 10.1.26-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
$ sudo grep -r utf /etc/mysql
/etc/mysql/mariadb.conf.d/50-client.cnf:default-character-set = utf8mb4
/etc/mysql/mariadb.conf.d/50-mysql-clients.cnf:default-character-set = utf8mb4
/etc/mysql/mariadb.conf.d/50-server.cnf:# utf8 4-byte character set. See also client.cnf
/etc/mysql/mariadb.conf.d/50-server.cnf:character-set-server  = utf8mb4
/etc/mysql/mariadb.conf.d/50-server.cnf:collation-server      = utf8mb4_general_ci
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hmm. Unicode characters (code points) can be multi-byte. Apparently, something like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CREATE TABLE IF NOT EXISTS mytable ( color VARCHAR(255) NOT NULL );
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&amp;hellip; doesn&amp;rsquo;t fly anymore. Instead, we can either do:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CREATE TABLE IF NOT EXISTS mytable ( color VARCHAR(255) CHARACTER SET utf8 NOT NULL );
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&amp;hellip; or:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CREATE TABLE IF NOT EXISTS mytable ( color VARCHAR(191) NOT NULL );
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;a href=&#34;https://stackoverflow.com/questions/1814532/1071-specified-key-was-too-long-max-key-length-is-767-bytes/22515986#22515986&#34;&gt;From Stack Overflow&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;MySQL assumes worst case for the number of bytes per character in the string. For the MySQL &amp;lsquo;utf8&amp;rsquo; encoding, that&amp;rsquo;s 3 bytes per character since that encoding doesn&amp;rsquo;t allow characters beyond U+FFFF. For the MySQL &amp;lsquo;utf8mb4&amp;rsquo; encoding, it&amp;rsquo;s 4 bytes per character, since that&amp;rsquo;s what MySQL calls actual UTF-8.&lt;/p&gt;

&lt;p&gt;&amp;hellip;when using utf8mb4, I need to set them to (at most) 191 as 191*4 = 764 &amp;lt; 767.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Damn emoticons. 😒&lt;/p&gt;

&lt;p&gt;The internet offers some murmurings that this will no longer be an issue come MariaDB 10.2. I&amp;rsquo;m not entirely clear on the details, but search terms include &amp;ldquo;innodb_large_prefix&amp;rdquo;, &amp;ldquo;ROW_FORMAT=DYNAMIC&amp;rdquo;, and &amp;ldquo;innodb_file_format=Barracuda&amp;rdquo;.&lt;/p&gt;

&lt;p&gt;#sql&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20171116151321.html</guid>
</item><item>
<title>Read JSON config file in Golang</title>
<link>https://paulgorman.org/technical/blog/20171113164018.html</link>
<description>&lt;h1&gt;Read JSON config file in Golang&lt;/h1&gt;

&lt;p&gt;How do we read a JSON configuration file for our Go program?&lt;/p&gt;

&lt;p&gt;This is the config file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
	&amp;quot;Db&amp;quot;: {
		&amp;quot;Host&amp;quot;: &amp;quot;localhost&amp;quot;,
		&amp;quot;User&amp;quot;: &amp;quot;maintcall&amp;quot;,
		&amp;quot;Password&amp;quot;: &amp;quot;vEryst0ng-paS5swordheR3&amp;quot;,
		&amp;quot;Database&amp;quot;:  &amp;quot;maintcall&amp;quot;
	},
	&amp;quot;Listen&amp;quot;: {
		&amp;quot;Address&amp;quot;: &amp;quot;*&amp;quot;,
		&amp;quot;Port&amp;quot;: &amp;quot;8000&amp;quot;
	},
	&amp;quot;OutboundCall&amp;quot;: {
		&amp;quot;CallerID&amp;quot;: &amp;quot;\&amp;quot;HT MAINTENANCE\&amp;quot; &amp;lt;+12483522010&amp;gt;&amp;quot;,
		&amp;quot;Retries&amp;quot;: 3,
		&amp;quot;SpoolPath&amp;quot;: &amp;quot;/var/spool/asterisk/outgoing/&amp;quot;
	},
	&amp;quot;VmRoot&amp;quot;: &amp;quot;/var/spool/asterisk/voicemail/default/&amp;quot;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And here&amp;rsquo;s the Go program that reads it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;package main

import (
	&amp;quot;encoding/json&amp;quot;
	&amp;quot;flag&amp;quot;
	&amp;quot;log&amp;quot;
	&amp;quot;os&amp;quot;
)

type Configuration struct {
	Db struct {
		Host     string
		User     string
		Password string
		Database string
	}
	Listen struct {
		Address string
		Port    string
	}
	OutboundCall struct {
		CallerID  string
		Retries   int
		SpoolPath string
	}
	VmRoot string
}

func main() {
	c := flag.String(&amp;quot;c&amp;quot;, &amp;quot;/etc/my-daemon.conf&amp;quot;, &amp;quot;Specify the configuration file.&amp;quot;)
	flag.Parse()
	file, err := os.Open(*c)
	if err != nil {
		log.Fatal(&amp;quot;can&#39;t open config file: &amp;quot;, err)
	}
	defer file.Close()
	decoder := json.NewDecoder(file)
	Config := Configuration{}
	err = decoder.Decode(&amp;amp;Config)
	if err != nil {
		log.Fatal(&amp;quot;can&#39;t decode config JSON: &amp;quot;, err)
	}
	log.Println(Config.Db.Host)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;#golang&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20171113164018.html</guid>
</item><item>
<title>Pulling the plug on Windows (to rejoin a VM to the domain)</title>
<link>https://paulgorman.org/technical/blog/20171110143300.html</link>
<description>&lt;h1&gt;Pulling the plug on Windows (to rejoin a VM to the domain)&lt;/h1&gt;

&lt;p&gt;A Windows computer hosted as a Linux KVM guest has fallen off the domain? Not a big deal.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Virtually disconnect the network cable from the running VM.&lt;/li&gt;
&lt;li&gt;Connect to the guest console, and log in as Administrator.&lt;/li&gt;
&lt;li&gt;Run a PowerShell command on the guest.&lt;/li&gt;
&lt;li&gt;Reconnect the guest&amp;rsquo;s network cable.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;On the hypervisor, find the name of the virtual network interface used by the guest:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# virsh domiflist myvm
Interface  Type       Source     Model       MAC
-------------------------------------------------------
vnet1      bridge     br0        virtio      52:54:00:6c:4c:b6
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Disconnect the virtual network cable:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# virsh domif-setlink myvm vnet1 down
Device updated successfully

# virsh domif-getlink myvm vnet1
vnet1 down
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Connect to the VM console:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# virt-viewer myvm
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Log into the VM as Administrator (or a lesser account with sufficient privileges), and run this PowerShell command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PS C:\&amp;gt; Reset-ComputerMachinePassword -Server domaincontroller.contoso.com -Credential (Get-Credential)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(The &lt;code&gt;Add-Computer&lt;/code&gt; cmdlet may be useful in other circumstances.)&lt;/p&gt;

&lt;p&gt;Plug the network cable back into the VM:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# virsh domif-setlink myvm vnet1 up
Device updated successfully

# virsh domif-getlink myvm vnet1
vnet1 up
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Done. The VM should be back on the domain again.&lt;/p&gt;

&lt;p&gt;#libvirt #powershell&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20171110143300.html</guid>
</item><item>
<title>Golang pass-by-value in &#34;for ... range&#34; loops</title>
<link>https://paulgorman.org/technical/blog/20171103184100.html</link>
<description>&lt;h1&gt;Golang pass-by-value in &amp;ldquo;for &amp;hellip; range&amp;rdquo; loops&lt;/h1&gt;

&lt;p&gt;Most things in Go pass by value, but this one still surprised me.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;func main() {
	points := []Point{{x: 1, y: 1}}
	for _, p := range points {
		p.x += 1
	}
	fmt.Println(points[0].x) // Expected &amp;quot;2&amp;quot; but got &amp;quot;1&amp;quot;. :(
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;range&lt;/code&gt; returns a copy of the value in each iteration of the loop.
Changes to the copy don&amp;rsquo;t survive exit of the loop.
If we want changes to persist, we need to modify the original:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Demonstrate pass-by-value in &amp;quot;for&amp;quot; loops.
package main

import &amp;quot;fmt&amp;quot;

type Point struct {
	x int
	y int
}

func main() {
	points := []Point{{x: 1, y: 1}}
	for i, p := range points {
		fmt.Println(p.x) // 1
		p.x += 1
		fmt.Println(p.x)         // 2
		fmt.Println(points[i].x) // 1 not 2! &amp;quot;p&amp;quot; is only a copy of points[i].
		points[i].x += 1 // This modifies the original value, outside the loop.
	}
	fmt.Println(points[0].x) // 2
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;#golang&lt;/p&gt;
</description>
<guid isPermaLink="true">https://paulgorman.org/technical/blog/20171103184100.html</guid>
</item>
</channel>
</rss>