Reboot E-mail Via Google's SMTP

Setting up NTP server is easy. But actually monitoring that server is a bit more difficult. A bare minimum should be getting an e-mail after reboot. However, even that simple step requires a bit of setup.

First you need to install sendmail, its configuration compiler, and a few SASL authentication methods:

yum install -y sendmail sendmail-cf cyrus-sasl-plain cyrus-sasl-md5

Next step is preparing authentication database (do substitute e-mail and password):

mkdir -p -m 700 /etc/mail/authinfo
echo 'AuthInfo: "U:root" "I:^^relay@gmail.com^^" "P:^^password^^"' > /etc/mail/authinfo/mail
makemap hash /etc/mail/authinfo/mail > /etc/mail/authinfo/mail

The last configuration step is adding the following lines into /etc/mail/sendmail.mc just ABOVE the first MAILER line:

…
define(`SMART_HOST',`[smtp.gmail.com]')dnl
define(`RELAY_MAILER_ARGS', `TCP $h 587')dnl
define(`ESMTP_MAILER_ARGS', `TCP $h 587')dnl
define(`confAUTH_OPTIONS', `A p')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
define(`confCACERT', `/etc/pki/tls/certs/ca-bundle.trust.crt')dnl
TRUST_AUTH_MECH(`EXTERNAL DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash -o /etc/mail/authinfo/gmail.db')dnl
…

With configuration out of the way, we can proceed with “compiling” that new configuration and restarting the daemon:

make -C /etc/mail
systemctl start sendmail

Finally, we are ready to test e-mail via command line:

echo "Subject: Test via sendmail from `hostname`" | sendmail -v ^^youremail@example.com^^

Assuming everything works, the only remaining task is adding cron task (crontab -e):

@reboot  echo -e "Subject: `hostname` status\n\nHost rebooted at `date -R`." | /usr/sbin/sendmail -v ^^youremail@example.com^^

Now every reboot will result in a e-mail message.

Random Slacking

It all started as a joke.

As few of us started using Slack it seemed oddly appropriate that #random channel should have a freshly squeezed random number every day. But there were some complaints about the quality. The first issue arose when 42 was randomly selected a few days in a row and it all went down hill from there culminating in a whole weekend without a random number. Unforgivable!

To replace such flawed human being a simple script was needed. It was clear from the get-go that script would be written in Bash. Not only my favorite but also supported on my personal servers and extremely easy to schedule via crontab.

Albeit single digit number had a previous occurrence, single-person decision was made that two-digit numbers look the best and should be used going forward. Due to the previous issue with number 42, it was also decided such number cannot appear too often. After all, you don’t answer the question of life, the universe, and everything more than once in a blue moon.

Too keep things on a low key, it was necessary to avoid any Slack bot interface. No, the message should always appear to come from a user. After a while chat.postMessage call was discovered enabling just that. This did require a (legacy) token and came at a cost of future extensibility but it also allowed a lot of faking so it all worked out.

In any case, here is the final script:

#!/bin/bash

TOKEN="xoxp-111111111111-222222222222-333333333333-abcdefabcdefabcdefabcdefabcdef"
CHANNEL="random"
USERNAME="myuser"

TAGLINE_FILE="/srv/taglines.txt"

NUMBER=$(( RANDOM % 89 + 10)) #random number 10-99
if (( $NUMBER == 42 )) ; then NUMBER=$(( RANDOM % 89 + 10)) ; fi  #about 0.01% chance to get 42 second time

TAGLINE=`shuf -n 1 $TAGLINE_FILE | cut -d'*' -f1`

TEXT="Random number of the day is ${NUMBER}.\\n${TAGLINE}"

curl -X POST \
     -H "Authorization: Bearer $TOKEN" \
     -H 'Content-type: application/json; charset=utf-8' \
     --data "{\"channel\":\"$CHANNEL\",\"text\":\"$TEXT\",\"as_user\":\"true\",\"username\":\"$USERNAME\"}" \
     https://slack.com/api/chat.postMessage

PS: No, illusion is not full, as there will be hints this is sent via API and not by human being. However, hints are small enough that not many will note.

Broken Korean and Japanese in RichTextBox

For a while now my QText utility had an elusive issue. I got multiple reports from Korean and Japanese people that text input doesn’t work properly. Unfortunately they often wouldn’t leave e-mail or wouldn’t feed me with more information to understand the issue.

But eventually, one nice Korean gentleman did manage to show the problem by taking video of him taking notes in Notepad and QText side by side. To reproduce it on my side, I installed Korean keyboard and tried to repeat his (English) sequence: EKS CNR ZL.

In Notepad that sequence resulted with “단축키” while my QText caused text to read “단ㅊㅜㄱ키”. Due to my knowledge of the Korean Starcraft scene, I was aware that Korean letters are grouped into blocks. And obviously QText was somehow messing it up.

After a bit of bumbling around, I found the issue was in OnSelectionChanged handler with further analysis showing the SelectionLength property to be the one causing the actual issue:

protected override void OnSelectionChanged(EventArgs e) {
  this.IsSelectionEmpty = (^^this.SelectionLength^^ == 0);
  if (^^this.SelectionLength^^ == 0) { this.CaretPosition = this.SelectionStart; }
  base.OnSelectionChanged(e);
}

Next stop was Microsoft’s Reference Source for .NET where took a look into RichTextBox.cs and SelectionLength property only to see the following comment:

// RichTextBox allows the user to select the EOF character,
// but we don't want to include this in the SelectionLength.
// So instead of sending EM_GETSEL, we just obtain the SelectedText and return
// the length of it.

This little innocent note actually pointed toward SelectedText property which does a lot of work internally, including sending EM_STREAMOUT message. This call unfortunately terminates IME entry a bit early and Korean character block boundaries get broken.

Fix I decided on was to ignore EOF issue from the comment and use EM_EXGETSEL message to determine what is the current selection length. Short version of committed code went something like this:

protected override void OnSelectionChanged(EventArgs e) {
  var range = new NativeMethods.CHARRANGE();
  NativeMethods.SendMessage(this.Handle, NativeMethods.EM_EXGETSEL, IntPtr.Zero, ref range);
  this.IsSelectionEmpty = this.IsSelectionEmpty = (range.cpMin == range.cpMax);
  if (this.IsSelectionEmpty) { this.CaretPosition = range.cpMin; }
}

private class NativeMethods {
  internal const int WM_USER = 0x0400;
  internal const int EM_EXGETSEL = WM_USER + 52;

  [StructLayout(LayoutKind.Sequential)]
  internal struct CHARRANGE {
    public int cpMin;
    public int cpMax;
  }

  [DllImport("user32.dll", CharSet = CharSet.Unicode)]
  internal static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, IntPtr wParam, ref CHARRANGE lParam);
}

Interpreting File Explorer GPS Coordinates

Illustration

Do you notice something wrong with coordinates of this picture taken in Pasco, Washington?

Let’s disregard for moment a pointless precision. Four decimals on Lat/Lon seconds already bring you into a millimeter precision range. With 15 decimals Windows show we are talking about less than picometer - couple orders of magnitude smaller than a virus and more than adequate to locate a single DNA strand (still in nanometer range).

Anything over 2 decimals on seconds (or 6 decimals on degrees) is already way better than any standard GPS can resolve. If we are talking about specialized equipment, we can probably justify 5 decimal digits. Going to 15 digits is just a sign of programmer too lazy to round.

Let’s not even discuss that semicolon is used instead of proper signs for decimal degrees. Yes, latitude should be written as 46° 15′ 12.51″ instead but that is not the biggest fault.

Did you notice it yet? Yep, latitude has no north/south specifier nor is east/west shown for longitude. Alternative approach of having negative numbers instead of south and west is also not here. How do I know? Because this picture has been taken in North America and not in China.

Positive latitude is correct since picture was taken in the north hemisphere. However, longitude is very wrong as degrees number should have a negative prefix for west hemisphere where picture was taken.

In any case, I made a little calculator to convert Microsoft’s coordinates into standard ones:

DegreesMinutesSeconds
Latitude:
Longitude:
LatitudeLongitude

Disabling SSH Password Prompt

After cancelling my hosting, I noticed my e-mail reports stopped working. Since I also upgraded my server with a troublesome version, I originally didn’t connect those two. However, issue with reports persisted even after I fixed the e-mail issue.

Manually running report immediately identified the problem. You see, I login to every server using public key. As my login on DreamHost server was gone, SSH simply decided to fallback to keyboard authentication. And so report waited for keyboard input that was never to come.

Solution intended for this troublesome issue actually already exists in the form of BatchMode option. Appending -o BatchMode=yes to SSH command will cause it to rather fail than ask user for anything. Exactly what doctor prescribed for my report script.

With this update, my “standard” SSH crypto settings for the report got updated to:

ssh
  -2
  -o KexAlgorithms=diffie-hellman-group-exchange-sha256
  -c aes192-ctr
  -o MACs=hmac-sha2-256
  -o BatchMode=yes
  example.com