BT Broadband could be cause of Netflix app’s ui-113 message

A couple of months ago I posted regarding a problem with the Netflix app on my LG smart TV (Netflix – Not fit for purpose?). We use BT Infinity broadband with a BT HomeHub 3. The Netflix app on the TV stopped working in early January and always displayed a Netflix ‘ui-113’ message when trying to connect. As we are paying good money to Netflix, we resorted to trying various DNS server addresses posted on the Web for US Netflix, which only work for a short time. Although US Netflix has more content than UK Netflix, we want the latter as it has UK programmes not available on US Netflix. Not to mention that we live in the UK. And it seems my family is not the only one suffering: BT Broadband Users Suffer Problems with Netflix on UK Smart TVs.

Today I found a YouTube video regarding a different Netflix error code (‘nw-2-5’) but, having tried everything else, I tried the suggested fix anyway (Enable Parental Controls then Disable Parental Controls then Delete Parental Controls) and then changed the DNS server address setting in the TV back to the default 192.168.1.254 for the BT Home Hub. Although the Netflix app first displays the ‘ui-113’ or ‘nw-2-5’ messages, if I retry a few times it now manages to connect to UK Netflix. After a couple of months of hassle with Netflix, that is progress.

The fix suggested in the above-mentioned YouTube video consisted of enabling then disabling and deleting BT Parental Controls via the user’s account page on the BT Web site. Even though I had never previously enabled BT Parental Controls, I logged in to the BT Web site, enabled Parental Controls, and then disabled and deleted them as per the instructions given in the aforementioned YouTube video.

So it seems that BT is either the cause of the problem or a major contributor. I suspect the blame may lie with more than one company, though, because: a) the Netflix app’s ‘ui-113’ and ‘nw-2-5’ messages occur even after I made sure BT Parental Controls really are disabled; b) it is touch and go whether the app is successful in accessing the Netflix site at the first attempt; c) other devices accessing Netflix via my home network don’t suffer from the problem. I just hope LG, Netflix and BT are working together to solve it properly, because the current situation is completely unacceptable.

Thunderbird’s defective method of enabling anti-virus software to scan incoming POP3 e-mail messages

Thunderbird’s method of enabling anti-virus software to scan incoming e-mail messages is explained in the mozillaZine article ‘Download each e-mail to a separate file before adding to Inbox‘ and in Mozilla bug report no. 116443 (the bug report that resulted in the functionality being implemented). It is my contention that the design is deficient and is actually not a solution. In this post I explain why I believe this to be the case. Although here I will discuss Thunderbird in Linux, I believe the deficiency applies to Thunderbird in all OSs.

By default, Thunderbird inserts new incoming e-mail messages into an Inbox file. However, it is possible to configure Thunderbird to first create a temporary file containing each individual e-mail message in the /tmp directory, to enable external anti-virus software to scan each message before Thunderbird inserts it into the Inbox file. This approach only works for POP3 e-mail. The developers’ rationale for implementing this approach was to avoid the possibility of anti-virus software deleting or quarantining an entire Inbox.

In summary, if you want to scan incoming e-mails on your machine without running the risk of losing the entire Thunderbird Inbox, you must:

  1. configure Thunderbird so it creates temporary files /tmp/newmsg* (each file contains a single e-mail message containing ASCII characters);
  2. configure the anti-virus software not to scan the directory containing the Inbox;
  3. configure the anti-virus software to scan the /tmp directory.

Nevertheless, it seems Thunderbird developers would prefer you to disable local scanning of e-mail messages entirely: ‘mozillaZine – Email scanning – pros and cons‘.

Nowadays e-mail servers scan e-mail messages before you even download them. Some e-mail servers even send you an automated e-mail to inform you about an infected incoming e-mail or about an infected outgoing e-mail rejected by a receiving e-mail server. So local scanning of e-mail messages is far less important. Furthermore, I am not sure if the anti-virus software I use (ClamAV) is capable of detecting viruses in e-mail attachments encoded as ASCII characters. Anyway, purely out of curiosity I decided to investigate whether it would be possible to scan Thunderbird’s temporary files reliably.

To configure Thunderbird to create the temporary message files, it is necessary to select ‘Edit’ > ‘Preferences’ > ‘Security’ > ‘Antivirus’ and tick ‘Allow anti-virus clients to quarantine individual incoming messages’ (which sets mailnews.downloadToTempFile to true). Once that option has been selected, Thunderbird creates a temporary file /tmp/newmsg per message, which exists for a very brief (and inconstant) time before Thunderbird deletes it. When downloading several e-mail messages in very rapid succession, Thunderbird creates temporary files with different names (‘newmsg‘, ‘newmsg-1‘, ‘newmsg-2‘, ‘newmsg-3‘ and so on) to avoid overwriting messages, but usually one file named newmsg is sufficient to cater for the message download rate, as Thunderbird only keeps the temporary files for a very short time until it moves the message to the Inbox.

The problem with this approach is that Thunderbird does not provide any handshake mechanism to inform external anti-virus software that it has finished writing to a temporary file and that the file is available for scanning, nor does Thunderbird provide any handshake mechanism for external anti-virus software to inform Thunderbird when the scan of each temporary message file has finished (i.e. to tell Thunderbird that it can go ahead and delete the temporary file). In other words, the Thunderbird ‘solution’ is not a solution at all. In fact, I have found empirically that, if the anti-virus software is not fast enough, it can scan an incomplete temporary message file (i.e. the evaluation of the e-mail message would not be thorough and hence would be invalid). The Bash script below, for example, is sometimes able to scan an entire Thunderbird temporary file but at other times only manages to capture part of the file (it appears Thunderbird opens and closes the temporary file more than once) before Thunderbird deletes it:

#!/bin/bash

# This script only works with Thunderbird.
# This script only works for POP3 e-mail.
#
# You must configure Thunderbird to create temporary files /tmp/newmsg*.
# To do that, set Edit > Preferences > Security > Antivirus and tick
# 'Allow anti-virus clients to quarantine individual incoming messages'
# which sets mailnews.downloadToTempFile to true.

WORK=$HOME/clamtmp
mkdir $WORK 2> /dev/null
rm $WORK/* 2> /dev/null

counter=1

# Watch for newmsg* file(s) created by Thunderbird in /tmp
inotifywait -q -m -e close_write --format '%f' /tmp | while read FILE
do
     if [ "${FILE:0:6}" = "newmsg" ] && [ -s /tmp/$FILE ]; then
          TMPFILE=${counter}$FILE
          cp -p /tmp/$FILE $WORK/$TMPFILE
          # Do not let clamscan write temporary files to /tmp as inotifywait will detect them!
          clamscan --tempdir=$WORK $WORK/$TMPFILE
          counter=$((counter+1))
     fi
done

Below is an example of an incomplete newmsg file that the above script copied to the directory $WORK when Thunderbird downloaded an e-mail message:

From - Sun Feb 21 09:40:58 2016
X-Account-Key: account8
X-UIDL: AAAAAKlA+Ah2LghLoJE4Le5Z5U0BAI04UNOj2gdNjwPO57yvmrIAATVHik4AAA==
X-Mozilla-Status: 0000
X-Mozilla-Status2: 00000000
X-Mozilla-Keys:

I began to wonder if a valid scan would be possible if the script were to lock the temporary file (e.g. using the chattr +i command) until it has completed copying it. The use of the chattr command in the script means it has to be executed by the root user. When I first did that with a modified version of the script using KDialog to display the result of ClamAV’s scan, the following error message was displayed and the script aborted:

kdialog(xxxxxx)/kdeui (kdelibs): Session bus not found
To circumvent this problem try the following command (with Linux and bash)
export $(dbus-launch)

I therefore added the line ‘export $(dbus-launch)‘ to the script as follows:

#!/bin/bash

# This script must be launched by the root user.
export XAUTHORITY="/home/fitzcarraldo/.Xauthority"
export DISPLAY=":0"
export $(dbus-launch)

WORK=$HOME/clamtmp
mkdir $WORK 2> /dev/null
rm $WORK/* 2> /dev/null

inotifywait -q -m -e modify --format '%f' /tmp | while read FILE
do
     # If file name begins with "newmsg" then copy it to work directory and scan it.
     if [ "${FILE:0:6}" = "newmsg" ] && [ -f /tmp/$FILE ]; then
          chattr +i /tmp/$FILE # Stop Thunderbird opening/deleting file.
          cp -p /tmp/$FILE $WORK/
          chattr -i /tmp/$FILE # Allow Thunderbird to open/delete file.
          clamscan --tempdir=$WORK $WORK/$FILE >> $WORK/$FILE.log
          kdialog --msgbox "$(cat $WORK/$FILE.log)"
     fi
done

However, when the above script was running, Thunderbird displayed a pop-up window if it attempted to copy the temporary file to the Inbox before the script released the lock on the file:

There was an error copying the downloaded message from the temporary download file. Perhaps it contained a virus, or you are low on disk space.
From:
Subject: Test to see what happens if script locks newmsg file
Do you want to skip this message?

I clicked ‘No’ and the e-mail message in the file /tmp/newmsg was deleted without being copied to the Inbox, and the message was not deleted from the e-mail server. Subsequent attempts to re-download the message resulted in the same behaviour if the script had not finished processing the message before Thunderbird tried to move the message to the Inbox. Had I clicked ‘Yes’ I assume Thunderbird would simply have deleted the message on the mail server.

I did not bother looking into it further, but presumably the chattr command triggers inotifywait, in which case the script could cycle several times for the same file.

An approach that would probably work would be for Thunderbird to provide some sort of interlock so that it waits to delete newmsg* files until an anti-virus application gives the go-ahead.

An alternative approach would be for Thunderbird not to delete a temporary file after it writes the message to the Inbox and just leave it in the /tmp directory without overwriting it. An anti-virus application would quarantine infected temporary files and leave uninfected temporary files in /tmp, and therefore the anti-virus application would have to be written so that it deletes the temporary file once it has finished scanning it.

The second approach mentioned above would not be as good as the first approach for the following reasons:

  1. It would not stop Thunderbird adding a message to the Inbox (which would mean the user would have to delete a message manually from the Thunderbird Inbox if the virus scanner reported a message as infected).
  2. Thunderbird would have to use a different file name to any existing temporary files (at present it reuses ‘newmsg‘ if a file of that name does not already exist).
  3. The user would have to ensure the temporary files do not accumulate ad infinitum. In my case, the contents of the /tmp directory are deleted each time I reboot, but, in theory, a partition could become full if a user never switched off a machine and received a lot of e-mails.

Regarding the second reason listed above, Thunderbird already names the temporary files ‘newmsg‘, ‘newmsg-1‘, ‘newmsg-2‘ etc., so perhaps the existing Thunderbird code would automatically use a different file name if a file with the same name were still present, rather than overwriting it. If e.g. files newmsg and newmsg-2 happened to exist, I would hope Thunderbird would name the next temporary file ‘newmsg-1‘ or ‘newmsg-3‘.

I wondered if it would be possible to catch up with Thunderbird by just copying the temporary message files from the /tmp directory to another directory (see the script below), and then processing them afterwards with another script. However, even if a script just copies the temporary files to another directory without running ClamAV or KDialog, I found it is still not fast enough to catch all temporary files before Thunderbird deletes them. If Thunderbird downloads a single message and no others are waiting on the server(s) to be downloaded, it seems a script can copy the temporary messages successfully. However, if there are several messages waiting to be downloaded from the e-mail server(s) and Thunderbird downloads them in rapid succession, Thunderbird deletes some of the temporary messages before the script can copy them fully.

#!/bin/bash

WORK=$HOME/clamtmp
# Create work directory if it does not already exist
mkdir $WORK 2> /dev/null
# Delete old working files if they exist
rm $WORK/* 2> /dev/null

counter=1

inotifywait -q -m -e close_write --format '%f' /tmp | while read FILE
do
     if [ "${FILE:0:6}" = "newmsg" ] && [ -s /tmp/$FILE ]; then
          TMPFILE=${counter}$FILE
          cp -p /tmp/$FILE $WORK/$TMPFILE
          counter=$((counter+1))
     fi
done

Consider the following six messages copied to $HOME/clamtmp by the above script (the script adds the first character to the name of the copied file):

-rw-------   1 fitzcarraldo fitzcarraldo    3829 Feb 23 02:24 1newmsg
-rw-------   1 fitzcarraldo fitzcarraldo    3107 Feb 23 02:25 2newmsg
-rw-------   1 fitzcarraldo fitzcarraldo 1158576 Feb 23 02:26 3newmsg
-rw-------   1 fitzcarraldo fitzcarraldo     237 Feb 23 02:28 4newmsg
-rw-------   1 fitzcarraldo fitzcarraldo    2106 Feb 23 02:28 5newmsg-1
-rw-------   1 fitzcarraldo fitzcarraldo    3107 Feb 23 02:28 6newmsg-2

The first three messages were each the sole message on all three e-mail servers accessed, and the copied files newmsg -> 1newmsg, newmsg -> 2newmsg and newmsg -> 3newmsg were all complete messages. However, the last three messages were on three e-mail servers simultaneously waiting to be downloaded, and when I clicked on ‘Get All New Messages’ in Thunderbird, the copied files newmsg -> 4newmsg, newmsg-1 -> 5newmsg-1 and newmsg-2 -> 6newmsg-2 were downloaded by Thunderbird in rapid succession. The copy 4newmsg was incomplete, the copy 5newmsg-1 was complete and the copy 6newmsg-2 was complete. So, even with a faster script, there is no guarantee that a script can catch all the temporary message files. Therefore, as I mentioned earlier, the only way to guarantee that temporary message files are properly scanned would be to modify Thunderbird to provide either a handshake (e.g. a file lock or inter-application flag) or to leave each temporary message file on /tmp and give it a unique file name.

The downside with both the above-mentioned approaches would be that the anti-virus software developer would need to know about the method, and write the software to perform the appropriate actions. If the first approach were adopted, the anti-virus software would need to signal to Thunderbird that it had completed scanning the file (e.g. by releasing a file lock or by an inter-application message). If the second approach were adopted, the anti-virus software would need to delete the message file from /tmp once it had completed scanning the file. The second approach would be easier for a simple Bash script to use, and, had the Thunderbird source code not been so complicated, I would have had a go at patching it to leave temporary message files in the /tmp directory after Thunderbird copies their contents to the Inbox file. But, as e-mail servers already do a good job of scanning messages before Thunderbird downloads them, I will not spend more time on this. Some e-mail servers even send an e-mail to the user informing them about an infected e-mail (see examples below), so it is not worth bothering.

Example 1
Automated e-mail server message to john@smith.com warning him that the e-mail with an infected attachment he sent to dave@hotmail.com was blocked by the receiving e-mail server.

Subject: Mail delivery failed: returning message to sender
Date: Wed, 17 Feb 2016 11:30:10 +0100
From: Mail Delivery System
To: john@smith.com

This message was created automatically by mail delivery software.

A message that you sent could not be delivered to one or more of
its recipients. This is a permanent error. The following address
failed:

Reason:
virus/suspect content found

— The header of the original message is following. —

Example 2
Automated e-mail server message to john@smith.com warning him that an e-mail with an infected attachment sent to him by dave@hotmail.com was blocked by the receiving e-mail server.

Subject: VIRUS SUSPECTED: “Dave (Hotmail)”
Date: Wed, 17 Feb 2016 11:46:07 +0100 (CET)
From: Mail Delivery System
To: john@smith.com

A virus was detected in the following e-mail!

Mail details:

From: “Dave (Hotmail)”
TO: John Smith
Date: Wed, 17 Feb 2016 10:45:55 +0000
Subject: EICAR test file attachment

The concerned e-mail has been handled according to your Virus Protection Settings.

Sincerely
Your E-mail Service Provider Team

[ This is an automatically generated email, do not reply to this sender. You may find more
information in the online help of your client. ]

Other articles of interest: mozillaZine – Antivirus software.

Automatically detecting files placed in my Downloads directory in Gentoo Linux and scanning them for viruses

I have been using Linux for almost a decade and have never been unduly concerned about viruses on my machines running Linux. However, I do receive files from people who use Windows and Mac OS, and some of those files might contain Windows or Mac OS viruses, so, as a matter of courtesy and assistance to others, it would make some sense to scan those files before passing them on. Furthermore, as I use some Windows applications under WINE, it would also make sense to scan received files for Windows viruses if I am going to use those files with a Windows application running under WINE.

External files could get into my Gentoo Linux installations via pen drives, memory cards, optical discs, e-mails, my Dropbox directory and downloads from Web sites. In this post I am going to concentrate on the last of these. All the various e-mail account providers I use already scan e-mails for viruses on their e-mail servers before I even download e-mail into the e-mail client on my laptop (standard practice these days), so e-mail is not a particular worry.

I have had ClamAV and its GUI, ClamTk, installed for a long time. Whilst ClamTk can be used to schedule a daily update of virus signatures and a daily scan of one’s home directory by ClamAV, I normally run ClamTk and ClamAV ad hoc. However, I can see some benefit in launching ClamAV automatically when I download a file from the Internet, so I decided to do the following …

Automatically scan a file downloaded via a Web browser

I use Firefox to browse the Web, and had configured it to download files to the directory /home/fitzcarraldo/Downloads/. I decided to monitor automatically the Downloads directory for the addition of any file. As I use the ext4 file system, the method I opted to use is inotify, specifically the inotifywait command which is available once you install the package sys-fs/inotify-tools.

It is surprisingly easy to create a shell script to detect files downloaded into a directory. The following script, running continuously in a terminal, would detect any files created in my /home/fitzcarraldo/Downloads directory, scan the new files with ClamAV and display a report in the terminal window:

#!/bin/bash

echo
DIR=$HOME/Downloads

inotifywait -q -m -e create --format '%w%f' $DIR | while read FILE
do
     date
     echo "File $FILE has been detected. Scanning it for viruses now ..."
     clamscan $FILE
     echo
done

A usable script would need to be a bit more sophisticated than the one shown above, because an existing file in the directory could be overwritten by one with the same name, or opened and amended. Furthermore, the script above would need a permanently open terminal window. Therefore I created a script to run in the background and use a GUI dialogue tool to pop up a window with the virus scanner’s report when the script detects a new or changed file in the Downloads directory. As this laptop has KDE 4 installed I opted to use KDialog to display the pop-up window, but I could instead have used Zenity. The final script is shown below.

#!/bin/bash

DIR=$HOME/Downloads

# Get rid of old log file
rm $HOME/virus-scan.log 2> /dev/null

inotifywait -q -m -e close_write,moved_to --format '%w%f' $DIR | while read FILE
do
     # Have to check file length is nonzero otherwise commands may be repeated
     if [ -s $FILE ]; then
          date > $HOME/virus-scan.log
          clamscan $FILE >> $HOME/virus-scan.log
          kdialog --title "Virus scan of $FILE" --msgbox "$(cat $HOME/virus-scan.log)"
     fi
done

Now when I download a file in Firefox, a window pops up, displaying a message similar to the following:

Virus scan of /home/fitzcarraldo/Downloads/eicar_com.zip – KDialog

Fri 19 Feb 23:42:02 GMT 2016
/home/fitzcarraldo/Downloads/eicar_com.zip: Eicar-Test-Signature FOUND

———– SCAN SUMMARY ———–
Known viruses: 4259980
Engine version: 0.98.7
Scanned directories: 0
Scanned files: 1
Infected files: 1
Data scanned: 0.00 MB
Data read: 0.00 MB (ratio 0.00:1)
Time: 4.595 sec (0 m 4 s)

Notice in the above message that ClamAV detected a virus in a file eicar_com.zip that I downloaded from the European Expert Group for IT Security Web site (originally ‘European Institute for Computer Antivirus Research’). In fact the executable eicar.com does not contain a real virus; it was designed to contain a known signature that virus scanner creators and users can use in checking anti-virus software. You can find out more about the virus test files on the EICAR Web site.

Of course, if I use applications other than Firefox to download files, I need to make sure they download the files into the applicable directory so that the script can detect and scan the files:

fitzcarraldo@clevow230ss ~ $ cd Downloads/
fitzcarraldo@clevow230ss ~/Downloads $ youtube-dl -o Carnavalito.mp4 -f 18 https://www.youtube.com/watch?v=ZDUL3w7zFD4
ZDUL3w7zFD4: Downloading webpage
ZDUL3w7zFD4: Downloading video info webpage
ZDUL3w7zFD4: Extracting video information
ZDUL3w7zFD4: Downloading MPD manifest
[download] Destination: Carnavalito.mp4
[download] 100% of 16.61MiB in 00:05

So, now I have a shell script that pops up a window informing me whether or not any file I put in $HOME/Downloads/ contains a virus. But I would like the script to be launched automatically when I login to the Desktop Environment. Therefore, as I use KDE 4, I selected ‘System Settings’ > ‘Startup and Shutdown’ and, in the ‘Autostart’ pane, clicked on ‘Add Script…’ and entered the path to my shell script (I left ‘create as symlink’ ticked). Now, every time I use KDE, any file placed (automatically or manually) into $HOME/Downloads/ is scanned for viruses automatically and a window pops up giving the result.

As my laptop is not always connected to the Internet, I prefer to update the ClamAV virus signatures database manually, which I do either using the ClamTk GUI or via the command line using the freshclam command:

fitzcarraldo@clevow230ss ~ $ su
Password:
clevow230ss fitzcarraldo # freshclam
ClamAV update process started at Sat Feb 20 10:51:01 2016
WARNING: Your ClamAV installation is OUTDATED!
WARNING: Local version: 0.98.7 Recommended version: 0.99
DON'T PANIC! Read http://www.clamav.net/support/faq
main.cvd is up to date (version: 55, sigs: 2424225, f-level: 60, builder: neo)
Downloading daily-21375.cdiff [100%]
Downloading daily-21376.cdiff [100%]
Downloading daily-21377.cdiff [100%]
Downloading daily-21378.cdiff [100%]
Downloading daily-21379.cdiff [100%]
Downloading daily-21380.cdiff [100%]
Downloading daily-21381.cdiff [100%]
Downloading daily-21382.cdiff [100%]
Downloading daily-21383.cdiff [100%]
Downloading daily-21384.cdiff [100%]
Downloading daily-21385.cdiff [100%]
Downloading daily-21386.cdiff [100%]
Downloading daily-21387.cdiff [100%]
Downloading daily-21388.cdiff [100%]
Downloading daily-21389.cdiff [100%]
Downloading daily-21390.cdiff [100%]
Downloading daily-21391.cdiff [100%]
daily.cld updated (version: 21391, sigs: 1850214, f-level: 63, builder: neo)
bytecode.cld is up to date (version: 271, sigs: 47, f-level: 63, builder: anvilleg)
Database updated (4274486 signatures) from db.UK.clamav.net (IP: 129.67.1.218)
WARNING: Clamd was NOT notified: Can't connect to clamd through /var/run/clamav/clamd.sock: No such file or directory

KDE Connect on a hotel Wi-Fi network

KDE Connect

I am a fan of KDE Connect (see my 2014 post about an earlier version), but had previously been unable to use it with a hotel network. However today I managed to do that, and here is how I did it …

I first connected my laptop and my Samsung Galaxy Note 4 to the hotel’s Wi-Fi network, then used the ifconfig command in Linux on my laptop to find the IP address of my laptop on the hotel’s network. Note that the IP address one sees if one uses a Web site such as WhatIsMyIPAddress will be the laptop’s outward-facing IP address, not the IP address of the laptop on the hotel network. For example, the ifconfig command has just shown me that my current DHCP-allocated IP address is 10.154.245.40 on this hotel’s network for this session whereas the Web site WhatIsMyIPAddress is showing my IP address as 78.100.57.102.

By the way, I can also use the excellent Android utility Fing on my Galaxy Note 4 to find the IP address of my laptop on the hotel’s network. It is quite interesting to use Fing to see what other devices (their hostname and IP address) are currently connected to the hotel’s network.

Anyway, then I launched KDE Connect on the Galaxy Note 4, tapped and ‘Add devices by IP’, and entered the laptop’s IP address (10.154.245.40 in this specific case). I was able to pair with KDE Connect running on my laptop and send files from my phone to the laptop, and vice versa.

Netflix – Not fit for purpose?

One of my family has a Netflix account. The account is accessible from any of the desktop and laptop computers in the house, whichever OS they are running.

Recently we bought a so-called ‘smart TV’ (an LG 40UF770V 4K Ultra HD TV, as it happens), and are pleased with it. It runs WebOS 2.0 (yay, Linux!) and the LG Content Store contains a Netflix app, which we promptly installed. The app worked perfectly for several weeks but then stopped being able to access Netflix. When the app was launched, the usual screen with the Netflix logo and the ‘Loading’ rotating indicator would appear but, after a minute or so, an error message would be displayed informing us that Netflix error ‘ui-113’ had occurred. One of the on-screen options then offered by the app was to check the network connection, which we tried, but everything was reported to be working correctly. Not to mention that all the other apps that require an Internet connection work fine. In order to watch a film using Netflix over the Christmas period we had to resort to connecting a laptop to the TV via an HDMI cable and accessing Netflix in a Web browser on the laptop. It is ridiculous to have to resort to such measures to view content on smart TVs which have Netflix apps.

I searched the Web and discovered that many, many people experience the same problem with Netflix and smart TVs. As in our case, they had no trouble accessing their Netflix account on their home network with other devices such as computers, tablets and smart phones. I came across reports by owners of smart TVs made by LG, Philips, Samsung, Sony, Toshiba, and other manufacturers. People who had contacted the relevant TV manufacturer were often told the problem is caused by Netflix, and people who had contacted Netflix were often told the problem is caused by the TV manufacturer.

Netflix has a Help page for this error message, but none of the steps Netflix listed worked, and neither did any of the remedies suggested by others on the Web (including in various YouTube videos). Resetting the TV did not solve the problem. Neither did cycling the mains power to the TV, broadband modem and router (however long the power was off). Nor did changing the TV’s setting for the IP address of the DNS server to one of the well-known public DNS servers such as Google’s. Nor did suggestions such as un-installing and re-installing the Netflix app. Nor did configuring the router to perform port forwarding for Netflix on the TV (not that this should be necessary, but I tried it anyway). Several people wrote that the parental lock in their routers caused the problem, but the parental lock is definitely not enabled in my router. I also tried to access Netflix via the TV’s Web browser; it can log-in to the Netflix account but cannot play content as it does not support the Microsoft Silverlight plug-in or HTML5 required by Netflix.

Nothing we tried solved the problem, and two weeks of this messing around was exasperating. Some people reported that changing the DNS server address in the TV to Google’s DNS servers worked, whereas others reported it didn’t. Even if some lucky person managed to get Netflix working on their smart TV using a certain procedure, other people in the same country with the same model of TV could not, even if they used the same procedure.

In addition to people in a given country trying to get the Netflix app in their smart TV to access their Netflix account in that country, I came across posts by people wanting to access Netflix in a different country (mostly people not in the USA wanting to access US Netflix because it offers a wider range of films and programmes, but also expatriates wanting to access Netflix for their home country with their home-country Netflix account). So I tried recommendations to configure the TV to use a DNS server in the US that some people in the UK had recently indicated would give the Netflix app access to US Netflix rather than UK Netflix (even though we wanted to access UK Netflix from the UK). But that didn’t work either.

However, I didn’t give up. I trawled the Web for lists of DNS servers that some people claimed would give access to Netflix in the UK. I found various Web sites listing IP addresses for DNS servers and tried several of them. Eventually I found one that actually enables the Netflix app in the TV to work, but it accesses US Netflix instead of UK Netflix. Given that the Netflix app has not worked for several weeks, I’m not complaining, but it is not what we were trying to achieve (US Netflix does not provide all the UK TV series available on UK Netflix). Furthermore, according to some of the posts I’ve read, periodically you have to change the DNS server address in the TV because Netflix stops working with the existing address.

Now, I’m a technically-oriented person and it took me several hours over a two-week period to find a solution (well, a work-around). Someone with little or no IT knowledge in the same situation would be at a complete loss as to how to get their Netfix account working. In order for streaming media services to become as ubiquitous as e.g. terrestrial TV, they have to be reliable and be accessible easily to paying customers. Use of Geolocation, GeoDNS and other complex techniques should not cause such a headache to bona fide users. Someone with a Netflix account in his/her country of residence and who simply wants to access Netflix on a smart TV should not have to jump through hoops or hit a brick wall. Clearly this is happening to many people.

On top of that, people such as myself who have to travel internationally frequently because of their work need to be certain that, if they subscribe to a streaming media service, it will work in whatever country they happen to be in at the time (except if blocked by Great Firewalls or content filters on proxy servers, of course) and not be purposely or inadvertently prevented from working by the media service provider’s network concept.

I myself had considered signing up for a Netflix account so that I could view films and TV programmes during my overseas work trips, but, after having to struggle for days to help a family member access a valid Netflix account on a smart TV in the country where the account was set up, will definitely not be giving Netflix my business. In this day and age it is ridiculous that users should have to try umpteen DNS server addresses and reset TVs, routers and modems in order to access their account with a media provider. Services such as Netflix will never have my business until their networking and DRM are sorted out properly and made to work reliably. Until Netflix changes its network delivery model, its service will remain a curate’s egg in my opinion.

NetworkManager: Failed to activate – The name org.freedesktop.NetworkManager was not provided by any .service files

Because I need to connect quickly and easily to numerous wired and wireless networks (DHCP or static IP addressing), I use NetworkManager in my Gentoo Linux amd64 installation running OpenRC and KDE 4. My Clevo W230SS laptop has an Intel Dual Band Wireless-AC 7260 Plus Bluetooth adapter card, and my installation uses the iwlwifi module:

# lspci -knn | grep Net -A2
03:00.0 Network controller [0280]: Intel Corporation Wireless 7260 [8086:08b1] (rev bb)
        Subsystem: Intel Corporation Dual Band Wireless-AC 7260 [8086:4070]
        Kernel driver in use: iwlwifi
# lsmod | grep iwl
iwlmvm                143919  0
iwlwifi                75747  1 iwlmvm

As I am using NetworkManager instead of netifrc, in accordance with the instructions in the Gentoo Wiki article on NetworkManager I do not have any net.* services enabled (not even net.lo):

# rc-update show -v
       NetworkManager |      default                 
                acpid |                              
            alsasound |                              
         avahi-daemon |                              
       avahi-dnsconfd |                              
               binfmt | boot                         
            bluetooth |      default                 
             bootmisc | boot                         
         busybox-ntpd |                              
     busybox-watchdog |                              
                clamd |                              
          consolefont |                              
           consolekit |      default                 
               cronie |      default                 
         cups-browsed |      default                 
                cupsd |      default                 
                 dbus |      default                 
                devfs |                       sysinit
               dhcpcd |                              
                dhcpd |                              
             dhcrelay |                              
            dhcrelay6 |                              
                dmesg |                       sysinit
              dropbox |                              
           fancontrol |                              
                 fsck | boot                         
                 fuse |                              
           git-daemon |                              
                  gpm |                              
              hddtemp |                              
             hostname | boot                         
              hwclock | boot                         
            ip6tables |                              
             iptables |                              
              keymaps | boot                         
            killprocs |              shutdown        
    kmod-static-nodes |                       sysinit
           lm_sensors |                              
                local |      default                 
           localmount | boot                         
             loopback | boot                         
      mit-krb5kadmind |                              
          mit-krb5kdc |                              
       mit-krb5kpropd |                              
              modules | boot                         
             mount-ro |              shutdown        
                 mtab | boot                         
                mysql |                              
                  nas |                              
         net.enp4s0f1 |                              
               net.lo |                              
             netmount |      default                 
           ntp-client |                              
                 ntpd |                              
           nullmailer |                              
              numlock |                              
  nvidia-persistenced |                              
           nvidia-smi |                              
              osclock |                              
              pciparm |                              
               procfs | boot                         
              pwcheck |                              
            pydoc-2.7 |                              
            pydoc-3.4 |                              
               rfcomm |                              
                 root | boot                         
               rsyncd |                              
            s6-svscan |                              
                samba |      default                 
                saned |                              
            saslauthd |                              
            savecache |              shutdown        
                 sntp |                              
                 sshd |      default                 
             svnserve |                              
                 swap | boot                         
            swapfiles | boot                         
              swclock |                              
               sysctl | boot                         
                sysfs |                       sysinit
            syslog-ng |      default                 
        teamviewerd10 |                              
         termencoding | boot                         
             timidity |                              
         tmpfiles.dev |                       sysinit
       tmpfiles.setup | boot                         
               twistd |                              
                 udev |                       sysinit
                  ufw | boot                         
              urandom | boot                         
       wpa_supplicant |                              
                  xdm |      default                 
            xdm-setup |

I have left the netmount service enabled in case I want to use network-attached file shares at home or in one of the various office locations where I work.

Networking works fine on my laptop with the many wired and wireless networks I have used except for one particular public wireless network (it is in an airport, has multiple Access Points, and its Access Points only support 802.11a/b/g, which may or may not be relevant) for which the following message would usually appear in a pop-up window when I tried to connect to the network from the KDE network management GUI after start-up:

Failed to activate
The name org.freedesktop.NetworkManager was not provided by any .service files

Error message displayed by KDE when trying to connect to one specific network

Error message displayed by KDE when trying to connect to one specific network


This occurred with both networkmanager-1.0.2-r1 and networkmanager-1.0.6, the two Stable Branch releases of NetworkManager currently available in Gentoo Linux.

The wireless network is not the only network at that particular location, and the ‘Failed to activate’ message occurred whichever network (wireless or wired) I tried to access at that location. When this problem occurred, it transpired that the NetworkManager service was not running (it had crashed):

$ nmcli d
Error: NetworkManager is not running.
$ rc-status
Runlevel: default
 dbus                   [  started  ]
 NetworkManager         [  crashed  ]
 netmount               [  started  ]
 syslog-ng              [  started  ]
 cupsd                  [  started  ]
 samba                  [  crashed  ]
 consolekit             [  started  ]
 cronie                 [  started  ]
 bluetooth              [  started  ]
 xdm                    [  started  ]
 cups-browsed           [  started  ]
 sshd                   [  started  ]
 local                  [  started  ]
Dynamic Runlevel: hotplugged
Dynamic Runlevel: needed
 xdm-setup              [  started  ]
 avahi-daemon           [  started  ]
Dynamic Runlevel: manual

(I am not bothered that Samba crashes in that particular location. It crashes even if a connection is established, because the public wireless network does not provide network file systems. Samba works fine when I connect the laptop to an office network or to my home network.)

Even if the ‘Failed to activate’ message occurred, sometimes (but not always) the laptop could still connect to networks after I restarted the NetworkManager service (albeit sometimes it was necessary to restart it more than once):

# /etc/init.d/NetworkManager restart

When it is possible to connect to networks, the NetworkManager service is of course running:

$ nmcli d
DEVICE    TYPE      STATE        CONNECTION           
sit0      sit       connected    sit0                 
wlp3s0    wifi      connected    Free_Airport_Internet
enp4s0f1  ethernet  unavailable  --                   
lo        loopback  unmanaged    --        
$ rc-status
Runlevel: default
 dbus                   [  started  ]
 NetworkManager         [  started  ]
 netmount               [  started  ]
 syslog-ng              [  started  ]
 cupsd                  [  started  ]
 samba                  [  crashed  ]
 consolekit             [  started  ]
 cronie                 [  started  ]
 bluetooth              [  started  ]
 xdm                    [  started  ]
 cups-browsed           [  started  ]
 sshd                   [  started  ]
 local                  [  started  ]
Dynamic Runlevel: hotplugged
Dynamic Runlevel: needed
 xdm-setup              [  started  ]
 avahi-daemon           [  started  ]
Dynamic Runlevel: manual

I searched the Web for the error message and, based on a recommendation on the Web page ‘nm-applet gives errors‘ claiming the problem is due to the iwlwifi driver when used with an Intel 7260 controller, I created a file /etc/modprobe.d/iwlwifi.conf containing the following line, and rebooted:

options iwlwifi power_save=0

However, the error message still occurred. So I changed the iwlwifi module options line to the following, as also recommended on that page, and rebooted:

options iwlwifi 11n_disable=1 power_save=0

However, the error message still occurred.

The default value for OpenRC’s rc_depend_strict variable is YES if rc_depend_strict is not declared in the file /etc/rc.conf, but I do not think that is the cause of the problem:

# Do we allow any started service in the runlevel to satisfy the dependency
# or do we want all of them regardless of state? For example, if net.eth0
# and net.eth1 are in the default runlevel then with rc_depend_strict="NO"
# both will be started, but services that depend on 'net' will work if either
# one comes up. With rc_depend_strict="YES" we would require them both to
# come up.
#rc_depend_strict="YES"

As already mentioned, sometimes just restarting the NetworkManager service once or more did enable the laptop to connect to the network. This made me wonder whether the problem had something to do either with the timing of the launch of the NetworkManager service or with the timing of the service establishing a connection. As netmount is the only other network-related service enabled at start-up, I checked the netmount service’s configuration file /etc/conf.d/netmount to see what it contained (it’s the same in both the latest stable openrc-0.17 and the latest testing openrc-0.18.2):

# You will need to set the dependencies in the netmount script to match
# the network configuration tools you are using. This should be done in
# this file by following the examples below, and not by changing the
# service script itself.
#
# Each of these examples is meant to be used separately. So, for
# example, do not set rc_need to something like "net.eth0 dhcpcd".
#
# If you are using newnet and configuring your interfaces with static
# addresses with the network script, you  should use this setting.
#
#rc_need="network"
#
# If you are using oldnet, you must list the specific net.* services you
# need.
#
# This example assumes all of your netmounts can be reached on
# eth0.
#
#rc_need="net.eth0"
#
# This example assumes some of your netmounts are on eth1 and some
# are on eth2.
#
#rc_need="net.eth1 net.eth2"
#
# If you are using a dynamic network management tool like
# networkmanager, dhcpcd in standalone mode, wicd, badvpn-ncd, etc, to
# manage the network interfaces with the routes to your netmounts, you
# should list that tool.
#
#rc_need="networkmanager"
#rc_need="dhcpcd"
#rc_need="wicd"
#
# The default setting is designed to be backward compatible with our
# current setup, but you are highly discouraged from using this. In
# other words, please change it to be more suited to your system.
#
rc_need="net"

As I am using NetworkManager rather than netifrc, I followed the instructions in the file’s comments and changed the file’s contents from:

rc_need="net"

to:

rc_need="networkmanager"

After making the above change, the console messages at boot-up included a new message:

* ERROR: netmount needs service(s) networkmanager

That message made sense: rc_need had been set to "networkmanager" and, obviously, netmount can only do its job if NetworkManager is running (AND a network connection has been established). However, notice that the name of the NetworkManager service initscript is /etc/init.d/NetworkManager, not /etc/init.d/networkmanager. In other words, the instructions in /etc/conf.d/netmount are wrong: the name of the service is actually ‘NetworkManager‘, not ‘networkmanager‘. So I changed /etc/conf.d/netmount to contain rc_need="NetworkManager" instead of rc_need="networkmanager" and, unsurprisingly, the above-mentioned error message no longer occurs. I have filed Gentoo Bugzilla Bug Report No. 564846 requesting that the comment in the configuration file be changed.

Nevertheless, the ‘Failed to activate’ message still occurred when I tried to connect to any network at that location by using the DE’s network management GUI, and therefore I still needed to restart the NetworkManager service manually in order to be able to connect to any network there. Although I am not yet sure of the root cause and solution, I have found a work-around which avoids me having to manually restart the NetworkManager service, as explained below.

Although OpenRC correctly launches the NetworkManager service, that service remains inactive until it actually establishes a network connection. This is not a bug, it is the way OpenRC and NetworkManager work (see the explanation in the Gentoo Forums thread NetworkManager has started, but is inactive). This is why the following console message appears during boot-up:

* WARNING: NetworkManager has already started, but is inactive

If you did not configure NetworkManager to connect automatically to a network, after logging-in to the DE you will need to use the DE’s network management GUI (plasma-nm in the case if KDE, nm-applet in the case of e.g. Xfce) to tell NetworkManager to connect to the desired network. However, I found that waiting that long before trying to connect is too late to avoid the ‘Failed to activate’ problem, i.e. NetworkManager crashes after a while. I do not know why this happens, but it usually happens only when I am at the location covered by one specific wireless network (which is why I wonder if the problem is a result of that network only supporting 802.11a/b/g). By configuring NetworkManager to connect automatically to the wireless network which seemed to trigger the problem, the NetworkManager service tries to connect earlier. It is possible to configure NetworkManager to do this either by using the DE network GUI and ticking ‘Automatically connect to this network when it is available’ for the relevant network connection, or by directly editing the relevant connection’s file in the directory /etc/NetworkManager/system-connections/.

Of the various wired and wireless connections I had configured on the laptop, I had named the problematic wireless network’s connection ‘Free_Airport_Internet’. So I edited the file /etc/NetworkManager/system-connections/Free_Airport_Internet and deleted the line ‘autoconnect=false‘ in the [connections] section of the file (the default value of the autoconnect variable is TRUE – see man nm-settings). I could instead have done this by using the DE’s network manager GUI and ticking ‘Automatically connect to this network when it is available’ for that network connection. Now, when the laptop boots, NetworkManager tries to connect to that network and the ‘Failed to activate’ problem is avoided. This works with or without the iwlwifi driver options I mentioned above, so, despite the claim on the Web page I referenced above, the root cause of the problem does not appear to be the iwlwifi driver. What I don’t understand is why the problem only seems to occur with one particular network (a public wireless network which happens to only support 802.11a/b/g), i.e. even if none of the NetworkManager connection files in my installation have been configured to try to establish a connection automatically, with all the other wireless networks I have used in other locations (I believe those all support at least 802.11a/b/g/n) I have been able to establish a connection manually by using the DE’s network management GUI.

The bottom line

If your installation uses NetworkManager and you experience the ‘Failed to activate’ message when trying to connect to networks from the DE’s network management GUI, check if the NetworkManager service is running. You can check by using the command ‘nmcli d‘ in a console. If it is not running, try to restart the NetworkManager service from the command line. If the connection is not already configured to start automatically, configure it to start automatically in order to try to make NetworkManager become active at an early stage.

POSTSCRIPT (November 6, 2015)

The two links below are to old bug reports regarding earlier versions of NetworkManager having trouble using wireless networks with multiple Access Points. I wonder if the problem I saw with NetworkManager crashing when not configured to connect automatically to the specific network I mentioned above is somehow related to those problems:

background scanning causes drivers to disassociate – WiFi roaming causes NetworkManager to lose routing

network-manager roams to (none) ((none)) – background scanning

Roaming to BSSID “(none)” certainly happens with this particular network too, as shown by the messages in the laptop’s system log from yesterday when I was using the laptop with that network (the laptop was stationary the whole time):

# cat /var/log/messages | grep "Nov  5 11" | grep NetworkManager | grep \(none\)
Nov  5 11:01:22 clevow230ss NetworkManager[2459]:   (wlp3s0): roamed from BSSID 04:C5:A4:C3:F9:EE (Free_Airport_Internet) to (none) ((none))
Nov  5 11:01:22 clevow230ss NetworkManager[2459]:   (wlp3s0): roamed from BSSID (none) ((none)) to B8:BE:BF:69:89:6E (Free_Airport_Internet)
Nov  5 11:13:23 clevow230ss NetworkManager[2459]:   (wlp3s0): roamed from BSSID B8:BE:BF:69:89:6E (Free_Airport_Internet) to (none) ((none))
Nov  5 11:13:23 clevow230ss NetworkManager[2459]:   (wlp3s0): roamed from BSSID (none) ((none)) to 04:C5:A4:C3:F9:EE (Free_Airport_Internet)
Nov  5 11:15:23 clevow230ss NetworkManager[2459]:   (wlp3s0): roamed from BSSID 04:C5:A4:C3:F9:EE (Free_Airport_Internet) to (none) ((none))
Nov  5 11:15:23 clevow230ss NetworkManager[2459]:   (wlp3s0): roamed from BSSID (none) ((none)) to B8:BE:BF:69:89:6E (Free_Airport_Internet)
Nov  5 11:19:22 clevow230ss NetworkManager[2459]:   (wlp3s0): roamed from BSSID B8:BE:BF:69:89:6E (Free_Airport_Internet) to (none) ((none))
Nov  5 11:19:23 clevow230ss NetworkManager[2459]:   (wlp3s0): roamed from BSSID (none) ((none)) to B8:BE:BF:69:89:6E (Free_Airport_Internet)
Nov  5 11:49:50 clevow230ss NetworkManager[2459]:   (wlp3s0): roamed from BSSID B8:BE:BF:69:89:6E (Free_Airport_Internet) to (none) ((none))
Nov  5 11:49:50 clevow230ss NetworkManager[2459]:   (wlp3s0): roamed from BSSID (none) ((none)) to 68:BC:0C:A1:3C:DE (Free_Airport_Internet)
Nov  5 11:51:51 clevow230ss NetworkManager[2459]:   (wlp3s0): roamed from BSSID 68:BC:0C:A1:3C:DE (Free_Airport_Internet) to (none) ((none))
Nov  5 11:51:51 clevow230ss NetworkManager[2459]:   (wlp3s0): roamed from BSSID (none) ((none)) to B8:BE:BF:69:89:6E (Free_Airport_Internet)

Today I’m using a hotel network in my hotel room, and that does not roam to BSSID “(none)”, but I don’t know if my room is within range of more than one Access Point:

# cat /var/log/messages | grep "Nov  6" | grep NetworkManager | grep \(none\)
#

Anyway, with the work-around described in this post I have not had any further trouble accessing the particular network, but it would be interesting to know the root cause.

Using a keyboard shortcut in Linux to add an e-mail signature giving current location and local time

In my previous post I showed how to find the current time at any town or city Worldwide from the command line in Gentoo Linux. My interest in a command to do this is not to use it on the command line per se, but to use the command in a keyboard shortcut to insert a signature at the end of my e-mails.

I have to travel internationally frequently because of my work, but I leave my laptop’s hardware clock set to UTC and the system clock set to the local time of my home town. This means that, irrespective of where I am in the World, the e-mail client (Thunderbird, in my case) uses the local time of my home town in e-mail headers and calenders. It is not practical to reconfigure Linux for each timezone I happen to be in (see my post Configuring the Linux clock), and, in any case, I want the file system’s timestamps to use one timezone only and all the timestamps in my e-mails and the e-mail client’s calender to use one timezone only, so there is less chance of me getting confused. I could have configured the installation to use UTC for the system clock, but I prefer the system clock to use the timezone of my home town. Of course, even though the system clock is always set to the timezone of my home town, on the Panel clock I select the timezone of the location where I happen to be, so that the Panel clock displays the local time in that timezone.

I wanted to be able to insert a signature at the end of each e-mail, stating my current location and the current time at that location, so that the person receiving the e-mail could tell from where in the World I sent the e-mail and the local time it was sent, as that local time could differ from the time shown in the e-mail header. For example, let us assume that Jane, who lives in the UK and whose system clock is configured for the timezone Europe/London, is making a brief visit to Perth, Australia and sends an e-mail to Dave in the UK at 06:36 on 11 October (Perth time). The e-mail below illustrates the type of signature I wanted to achieve.

Subject: Site visit
From: Jane <jane@acompany.com>
To: Dave <dave@acompany.com>
Date: Sat Oct 10 2015 23:36:40 GMT+0100 (BST)

Hello Dave,

This is to let you know that I have just arrived in Perth and will be
visiting site at 09:00 local time to speak to the client. Tomorrow p.m.
I have a meeting scheduled with our local project manager, so I would
appreciate it if you would e-mail the latest documentation to me. I will
not have spare time until I’m in my room at the hotel tonight but will
read the documents tomorrow a.m. in readiness for the meeting with
the local project manager. Thanks in advance.

Regards,
Jane
Current location: Perth (Australia)
Local time now: Sat Oct 11 06:36:31 2015 AWST

As you can see above, because the OS on Jane’s and Dave’s laptops is configured for the timezone Europe/London, the e-mail header shows the current time in the UK when the e-mail was sent, which was October 10, 23:36 British Summer Time (22:36 UTC), and the signature shows the corresponding local time in Perth, Australia, which was October 11, 06:36 Australian Western Standard Time. It becomes even more confusing if the computer of the person receiving the e-mail is configured for a third timezone. For example, let’s say Dave is based in Seattle, USA rather than the UK. His e-mail client would then display the time in that timezone when the e-mail was sent. This is usually my case, i.e. my Linux installation is configured for Timezone1 but I happen to be in Timezone2 when I send an e-mail to someone who is based in Timezone3 and whose OS is configured for that timezone.

I wanted to use a keyboard shortcut to add a signature to the end of my e-mails, as shown above. I therefore created the Bash script listed below, which I named timezone_signature_GeoNames.sh:

#!/bin/bash

location=$(kdialog --title "Current Location" --inputbox "Enter your location:")

localtime=$(perl /home/fitzcarraldo/now1.pl $location)
place=`echo $localtime | cut -d'|' -f1`
place=$place" "`echo $localtime | cut -d'|' -f2`
timezone=`echo $localtime | cut -d'|' -f4`

if [ $location != "" ]; then
  echo -n "Current location: "
  echo $place
  echo -n "Local time now:"
  /usr/sbin/zdump ${timezone} | cut -d' ' -f2-
fi
echo

Notice that the Bash script uses the GUI dialogues utility kdialog to display a pop-up window prompting me to enter the name of a town/city. As I am using KDE I opted to use a dialogues utility developed for use in KDE, but I could have used Zenity instead.

The Perl script now1.pl is a variant of the Perl script now.pl described in my previous post, modified very slightly in order to facilitate formatting of the output by the Bash script, and is listed below.

#!perl

use strict;
use warnings;

use DateTime;
use Geo::GeoNames;
use URI::Escape;
use Encode;

binmode STDOUT, ':encoding(UTF-8)';

my $city = decode("UTF-8", @ARGV ? shift : 'London');
# N.B. Replace London with your home town/city.

my $geo = Geo::GeoNames->new( username => '************' );
# N.B. Replace the asterisks with your GeoNames user name.

my $result = $geo->search(
q       => uri_escape_utf8($city),
maxRows => 1,
style   => 'FULL'
);

defined $result->[0] or die "Unrecognized city '$city'\n";

my $city_name    = $result->[0]->{name};
my $country_name = $result->[0]->{countryName};
my $time_zone    = $result->[0]->{timezone}{content};
my $time_now     = DateTime->now( time_zone => $time_zone );

#print "$city_name ($country_name) $time_now ($time_zone)\n";

print "$city_name|($country_name)|$time_now|$time_zone\n";

exit 0;

The only thing remaining was to configure a keyboard shortcut to launch the Bash script. I opted to use the key combination Ctrl-Alt-z for the shortcut. As I am using KDE I could have used KDE’s ‘System Settings’ > ‘Shortcuts and Gestures’> ‘Custom Shortcuts’ to specify the shortcut and the name of the script it launches. However, as I also use AutoKey for various shortcuts, I opted to use that instead, so I used the AutoKey GUI to create a shortcut named ‘Insert Current Time’ to use the following command:

output = system.exec_command("/home/fitzcarraldo/timezone_signature_GeoNames.sh")
keyboard.send_keys(output)

Use

I compose my e-mails as usual, and, after entering my name at the end of the e-mail, I press Ctrl-Alt-z. A window then pops up prompting me to enter my current location, which I do and then click on ‘OK’. The location and current time at that location are then added to the end of the e-mail, and it just remains for me to click on the ‘Send’ button in the e-mail client’s window. As the Perl script now1.pl uses the Internet to access the GeoNames database, my laptop must be connected to the Internet when I use the shortcut.

KDialog window that pops up when I use the keyboard shortcut

KDialog window that pops up when I use the keyboard shortcut

If the town/city name consists of more than one word (Rio de Janeiro, for example) then replace spaces with hyphens when you enter the location name in the pop-up window (Rio-de-Janeiro, for example) and then the keyboard shortcut will return the correct location and local time:

Current location: Rio de Janeiro (Brazil)
Local time now: Fri Oct 16 09:28:19 2015 BRT

Find the time now at any town or city Worldwide from the command line in Gentoo Linux

In my hunt for a command to return the current time at any town or city in the World, I recently found a Perl script now.pl posted in 2012 by Jim Monty on grokbase. The script uses a Perl module to access the database of the GeoNames Web site. To use the module you need to have a user account at the GeoNames Web site and be connected to the Internet. The script also uses the modules URI::Escape and DateTime.

In the case of Gentoo Linux, ebuilds for some of the Perl modules used by now.pl are not available in the main Portage tree, so I installed them from a Portage local overlay, as explained below.

First I created in my local overlay an ebuild for the Perl module Geo::GeoNames and then merged it:

# mkdir -p /usr/local/portage/dev-perl/Geo-GeoNames
# cd /usr/local/portage/dev-perl/Geo-GeoNames
# nano -w Geo-GeoNames-1.01.ebuild
# ebuild Geo-GeoNames-1.01.ebuild manifest
# emerge --ask Geo-GeoNames

The ebuild Geo-GeoNames-1.01.ebuild I created is listed below:

EAPI=5

MODULE_AUTHOR=BDFOY
inherit perl-module

DESCRIPTION="Provides a perl interface to the webservices found at http://api.geonames.org"

SLOT="0"
KEYWORDS="alpha amd64 ~arm hppa ia64 ~mips ppc ppc64 ~s390 ~sh sparc x86 ~amd64-linux ~x86-linux ~ppc-macos ~x86-macos ~sparc-solaris"
IUSE=""

RDEPEND="
        dev-perl/Module-Build
        "
DEPEND="${RDEPEND}"

SRC_TEST=do

I’m not sure if I declared the correct dependencies in DEPEND and RDEPEND, but the Geo::GeoNames module is merged in my installation and functions correctly.

The Perl script also uses the Perl module URI::Escape, which I found out is part of the package dev-perl/URI in the Portage main tree and was already installed, so I did not need to do anything further as far as that was concerned.

Next I needed to install the Perl module Date::Time. Fortunately there is an ebuild for dev-perl/DateTime in the main Portage tree, so I merged that package directly:

# emerge --ask DateTime

Then I surfed to the GeoNames Web site and registered for a user account. My thanks go to the people who provide and maintain the site and database.

I then created a file /home/fitzcarraldo/now.pl containing the Perl script listed in Jim Monty’s post of Aug 19, 2012 on the Web page: [DateTime] Is there timezone data for any Indian cities such as Mumbai, Dehli, &c.?. My thanks also go to Jim Monty for posting his script.

My initial attempts at running now.pl resulted in an error message warning about a missing Mojo::UserAgent Perl module. I therefore needed to install the package Mojolicious but, unfortunately, the main Portage tree does not have an ebuild for it. I could have either added a third-party overlay (e.g. srcshelton) which contains a Mojolicious ebuild or downloaded the ebuild and put it in my local overlay. I opted for the latter, and merged it:

# mkdir -p /usr/local/portage/dev-perl/Mojolicious
# cd /usr/local/portage/dev-perl/Mojolicious
# cp /home/fitzcarraldo/Downloads/Mojolicious-5.30.ebuild .
# ebuild Mojolicious-5.30.ebuild manifest
# emerge --ask Mojolicious

Despite the examples given in Jim Monty’s post using now.pl with place names containing diacritics, in my case the script could not handle them, so I made a couple of small modifications, and the script I’m using is show below:

#!perl
use strict;
use warnings;

use DateTime;
use Geo::GeoNames;
use URI::Escape;
use Encode;

binmode STDOUT, ':encoding(UTF-8)';

my $city = decode("UTF-8", @ARGV ? shift : 'London');

my $geo = Geo::GeoNames->new( username => '***********' );
# N.B. Replace the asterisks with your GeoNames user name.

my $result = $geo->search(
q       => uri_escape_utf8($city),
maxRows => 1,
style   => 'FULL'
);

defined $result->[0] or die "Unrecognized city '$city'\n";

my $city_name    = $result->[0]->{name};
my $country_name = $result->[0]->{countryName};
my $time_zone    = $result->[0]->{timezone}{content};
my $time_now     = DateTime->now( time_zone => $time_zone );

print "$city_name ($country_name) $time_now ($time_zone)\n";

exit 0;

I made the script executable and ensured my user account could use it:

# chmod +x /home/fitzcarraldo/now.pl
# chown fitzcarraldo:fitzcarraldo /home/fitzcarraldo/now.pl

Now if I enter the name of a town or city anywhere in the World while my laptop is connected to the Internet, the script prints the town/city name, country, local time and the time zone’s name as given in the zoneinfo database (a.k.a. ‘Olsen database’, ‘tz database‘ and ‘IANA time zone database’):

$ cd
$ perl now.pl
London (United Kingdom) 2015-09-25T23:10:16 (Europe/London)
$ perl now.pl "London Canada"
London (Canada) 2015-09-25T18:10:22 (America/Toronto)
$ perl now.pl Paris
Paris (France) 2015-09-26T00:10:29 (Europe/Paris)
$ perl now.pl "New York"
New York (United States) 2015-09-25T18:10:41 (America/New_York)
$ perl now.pl Tokyo
Tokyo (Japan) 2015-09-26T07:10:50 (Asia/Tokyo)
$ perl now.pl "Mexico City"
Mexico City (Mexico) 2015-09-25T17:10:59 (America/Mexico_City)
$ perl now.pl "Kuala Lumpur"
Kuala Lumpur (Malaysia) 2015-09-26T06:11:09 (Asia/Kuala_Lumpur)
$ perl now.pl "São Paulo"
São Paulo (Brazil) 2015-09-25T19:11:29 (America/Sao_Paulo)
$ perl now.pl Maceio
Maceió (Brazil) 2015-09-25T19:11:39 (America/Maceio)
$ perl now.pl Maceió
Maceió (Brazil) 2015-09-25T19:11:48 (America/Maceio)
$ perl now.pl "Várzea Grande"
Várzea Grande (Brazil) 2015-09-25T18:12:04 (America/Cuiaba)
$ perl now.pl "Mos Eisley"
Unrecognized city 'Mos Eisley'

now.pl works by first using the Geo::GeoNames module to look up in the GeoNames database via the Internet the time zone for the town/city you have specified, then using the Date::Time module to look up the time in that time zone from the zoneinfo data in your installation, based on the time now in your installation’s system clock. In other words, if your system clock is, for example, 3 minutes ahead of actual time then the time returned by now.pl for the relevant time zone would also be 3 minutes fast. But if your system clock is correct, the script would return an accurate time for the requested town/city.

My interest in finding a command that returns the current time at any town or city around the Globe was because I wanted to create a keyboard shortcut to insert a signature in my e-mails, displaying my current location and the local time wherever I happened to be (I have to travel internationally frequently because of my work). In my next post I will explain how I created such an e-mail signature.

‘Waiting for 192.168.1.254…’ (Why I could not access a home hub’s management page)

I had not been able to access the Manager of the BT Home Hub 3 on my home network to view and configure the hub’s settings. All the network’s users could access the Internet, and I could ping the hub, but trying to access the BT Home Hub Manager from a Web browser resulted in the message ‘Waiting for 192.168.1.254…’. The same thing happened whatever the PC, OS, browser and method of connection (wired or wireless). Sometimes, after about ten minutes or so, an incomplete Manager page would appear, but usually the browser would just display ‘Waiting for 192.168.1.254…’ forever.

I should point out that my Ethernet wired connections use Powerline adapters (HomePlug) connected to the mains wiring of my semi-detached house.

Actually, I did find a temporary work-around to enable me to access the Home Hub Manager. If I switched off then on the power supply to the Home Hub I could access the Manager for a short period (the time varied, but typically was less than half an hour). Then I would be back in the same position of seeing ‘Waiting for 192.168.1.254…’ in a browser window if I tried later to access the Manager. Although I do not need to access the Home Hub Manager often, it was still a nuisance to have to cycle the power to the hub every time I needed to access the Manager.

Searching the Web, it seems this is quite a common problem and can occur irrespective of the manufacturer of the hub (or router) and its IP address. In some cases users have fixed the problem by upgrading the hub’s firmware or by performing a ‘factory reset’ of the hub, but some users never found a solution.

In my case, the BT Home Hub 3 has the latest available version of firmware installed. Not only did I check that via the Web, I also checked the firmware version of another BT Home Hub 3 in the house of someone I know who lives in another town. The curious thing was that he has no trouble accessing the BT Home Hub Manager (also IP address 192.168.1.254).

So I decided to perform a ‘factory reset’ of the Home Hub, but that made no difference.

Then, after many hours searching the Web, I found a thread about a similar problem with a different model of hub: Can’t access BT HomeHub 4? But I’m online ok?. A post by user troublegum in that thread made me sit up:

I still reckon it’s the homeplugs. Regardless of whether your PC is connected to it or not, If one of them is connected to your neighbour’s as well as your router, then it’s going to put 2 DHCP servers on your network.

Disconnect the homeplug from the router, renew your DHCP lease if necessary and try again.

Even before finding that thread I had wondered if the problem was somehow linked to my use of Powerline (HomePlug) adapters.

It seems that, if one PC on a home network is connected to the Home Hub via a Powerline adapter AND a neighbour also happens to be using Powerline adapters AND his single-phase mains house wiring is somehow linked to yours (which is unusual, as adjacent houses are normally connected to a different mains phase), there is the possibility that none of your PCs will be able to access the Home Hub Manager (even if they are connected directly to the Home Hub by Ethernet cable or Wi-Fi rather than via a Powerline adapter).

I have been using Powerline (HomePlug) adapters successfully for about nine years. In late December 2012 I changed from HomePlug 1.0 adapters (14 Mbps) to HomePlug AV adapters (200 Mbps). HomePlug 1.0 adapters and HomePlug AV adapters can operate concurrently over the same mains wiring but can only communicate with adapters of the same standard. The problem of not being able to access the Home Hub Manager started two or three years ago, so I assume that either my neighbour began using Powerline adapters at that time or, coincidentally, I changed to the same standard and manufacturer of Powerline adapter he uses.

Powerline adapters each have a non-volatile encryption key, intended to enable separate Powerline networks to co-exist on the same mains wiring by using a different encryption key for each network.

Since the end of December 2012 I have been using NETGEAR XAVB1301 200 Mbps Powerline adapters but had not bothered to change the encryption key in them (they all come configured with the factory default encryption key ‘HomePlugAV’). If my neighbour happens to be using Powerline adapters with the same default encryption key, and a hub with the same IP address as mine, we would both have two DHCP servers on the same network.

So I changed the encryption key on each of the four Powerline adapters I use:

  • Ethernet connection from the BT Home Hub to a mains socket in the Lounge.
  • Ethernet connection from a PC to a mains socket in the Lounge.
  • Ethernet connection from a laptop to a mains socket in my upstairs office.
  • Ethernet connection from a laptop to a mains socket in a bedroom.

It is supposed to be easy to set the encryption key in the model of Powerline adapter I use. You have to press a button on one adapter for 2 seconds, then a button on the next adapter for 2 seconds, and so on. You have to do them all within 2 minutes. The adapters only generate an encryption key once, so if you want to repeat the process you first have to press a recessed Factory Reset button on all the adapters.

However, despite following to the letter the instructions in the NETGEAR manual, I could not get all four adapters to connect to the network. So I downloaded the NETGEAR Powerline Universal Utility, installed it on the PC running Windows 10 in my lounge, connected the Ethernet port of that PC to one of the Powerline adapters and plugged it into a mains wall socket, plugged the other three Powerline adapters into a multi-socket mains adapter and plugged that into a mains wall socket in the lounge, launched the Powerline Universal Utility and I allocated all four adapters the same encryption key. Each adapter has its own MAC address, serial number and ‘Device Password’ (PWD) printed on it, and the NETGEAR utility program required me to enter the relevant PWD for each MAC address. Then I entered an encryption key (any string of characters of my choice) and clicked a button to set the adapters to use that encryption key. As that encryption key is different to the default key used by my neighbour, the two networks can now coexist without interfering with each other.

NETGEAR Powerline Utility showing my four Powerline adapters

NETGEAR Powerline Utility showing my four Powerline adapters.

The use of the NETGEAR Powerline utility program is explained in NETGEAR’s ‘How To’ Setting network encryption key on Powerline Adapters using the Config utility.

Problem finally solved! I can now access the Home Hub Manager without any trouble. And, as a bonus, Internet access seems a little quicker.

The problem of scanning using USB multi-function printers in Linux (continued)

My previous post discussed the inability of the Linux installation on my main laptop to use the scanner of my Canon PIXMA MP560 MFP (multi-function peripheral) when they are connected via USB. Linux sees the MP560 as a single USB device with multiple interfaces: Interface 0 (scanner), Interface 1 (printer) and Interface 2 (USB mass storage). The basic problem seems to be that the usb-storage driver — whether built into the kernel or as an external module — claims the USB device and blocks access by userspace’s libusb, which is what the SANE backend (‘pixma‘, in the case of the MP560) uses to access the USB device. However, scanning works fine when using a network connection instead of the USB connection.

Attempts such as unbinding the usb-storage driver from the USB device — either manually or using a UDEV rule — in order to try and allow libusb/SANE to access the scanner, did not solve the problem. Although I can scan by connecting to the MP560 via my home network, the inability of the OS to scan via the USB interface piqued my interest, so I continued my investigations and below I discuss my latest findings.

Disabling kernel auto-binding

I learned from the interesting blog post Controlling USB device access on Linux how to stop the kernel automatically binding a driver to a USB device in the first place, as distinct from unbinding a driver after the kernel has bound it to a device. I thought this approach could be used to stop the usb-storage driver from binding to the MP560 and thus allow libusb/SANE to access Interface 0. The method using sysfs to stop the kernel binding the driver is to disable kernel USB auto-probing before launching a scanner application, by using the following command:

# echo 0 > /sys/bus/usb/drivers_autoprobe

This did indeed stop the kernel from automatically binding USB drivers to USB devices, but unfortunately libusb/SANE would still not access the MP560 scanner via USB. When drivers_autoprobe contains zero, applications such as XSane can use the network-connected MP560 as before, but still hang if the USB-connected MP560 is selected.

Unloading the usb-storage module

According to various blog and forum posts, some people have been able to use MFP scanners via USB after manually unloading the usb-storage module. I decided to try this. As I had built the kernel with the usb-storage driver internally rather than an external module, I first had to rebuild the kernel with CONFIG_USB_STORAGE=m instead of CONFIG_USB_STORAGE=y. Then I unloaded manually the usb_storage module using the command ‘rmmod usb_storage‘ and launched a scanner application, but the application still hung.

Disabling the usb-storage driver using a ‘quirk’

Then I had a thought: Perhaps there is a kernel ‘quirk’ to disable the usb-storage driver from binding to a specific USB device. Indeed there is (see Kernel Parameters or /usr/src/linux-<version>/Documentation/kernel-parameters.txt).

If the usb-storage driver is built into the kernel (CONFIG_USB_STORAGE=y), I would need to add the following kernel boot parameter to the kernel boot line:

usb-storage.quirks=04a9:173e:i

’04a9′ is the Vendor ID and ‘173e’ is the Product ID of the MP560. The ‘i‘ stands for ‘ignore’.

If the usb-storage driver is built as a kernel module (CONFIG_USB_STORAGE=m), I would need to create a file with a name such as /etc/modprobe.d/usb-storage.conf containing the following line:

options usb-storage quirks=04a9:173e:i

So I set up the quirk. Upon rebooting my laptop, the dmesg command reported the following:

usb 1-1.2.2: new high-speed USB device number 8 using ehci-pci
usb 1-1.2.2: New USB device found, idVendor=04a9, idProduct=173e
usb 1-1.2.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
usb 1-1.2.2: Product: MP560 series
usb 1-1.2.2: Manufacturer: Canon
usb 1-1.2.2: SerialNumber: 1653C4
usb-storage 1-1.2.2:1.2: USB Mass Storage device detected
usb-storage 1-1.2.2:1.2: device ignored

Notice the final line. The quirk does indeed cause the usb-storage driver to ignore the MP560.

The lsusb command still shows the device, which is a good sign:

# lsusb
Bus 002 Device 005: ID 0bc2:3300 Seagate RSS LLC
Bus 002 Device 004: ID 0411:01d9 BUFFALO INC. (formerly MelCo., Inc.)
Bus 002 Device 003: ID 05e3:0606 Genesys Logic, Inc. USB 2.0 Hub / D-Link DUB-H4 USB 2.0 Hub
Bus 002 Device 002: ID 8087:8000 Intel Corp.
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 006: ID 5986:055c Acer, Inc
Bus 001 Device 004: ID 8087:07dc Intel Corp.
Bus 001 Device 007: ID 0603:00f2 Novatek Microelectronics Corp. Keyboard (Labtec Ultra Flat Keyboard)
Bus 001 Device 008: ID 04a9:173e Canon, Inc. MP560
Bus 001 Device 005: ID 045e:00d1 Microsoft Corp. Optical Mouse with Tilt Wheel
Bus 001 Device 003: ID 05e3:0606 Genesys Logic, Inc. USB 2.0 Hub / D-Link DUB-H4 USB 2.0 Hub
Bus 001 Device 002: ID 8087:8008 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

# lsusb -t
/:  Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M
    |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/8p, 480M
        |__ Port 2: Dev 3, If 0, Class=Hub, Driver=hub/4p, 480M
            |__ Port 1: Dev 4, If 0, Class=Mass Storage, Driver=usb-storage, 480M
            |__ Port 3: Dev 5, If 0, Class=Mass Storage, Driver=usb-storage, 480M
/:  Bus 01.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M
    |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/6p, 480M
        |__ Port 2: Dev 3, If 0, Class=Hub, Driver=hub/4p, 480M
            |__ Port 1: Dev 5, If 0, Class=Human Interface Device, Driver=usbhid, 1.5M
            |__ Port 2: Dev 8, If 0, Class=Vendor Specific Class, Driver=usbfs, 480M
            |__ Port 2: Dev 8, If 1, Class=Printer, Driver=, 480M
            |__ Port 2: Dev 8, If 2, Class=Mass Storage, Driver=, 480M
            |__ Port 4: Dev 7, If 0, Class=Human Interface Device, Driver=usbhid, 1.5M
            |__ Port 4: Dev 7, If 1, Class=Human Interface Device, Driver=usbhid, 1.5M
        |__ Port 3: Dev 4, If 0, Class=Wireless, Driver=btusb, 12M
        |__ Port 3: Dev 4, If 1, Class=Wireless, Driver=btusb, 12M
        |__ Port 4: Dev 6, If 0, Class=Video, Driver=uvcvideo, 480M
        |__ Port 4: Dev 6, If 1, Class=Video, Driver=uvcvideo, 480M

The output of the lsusb -v -d 04a9:173e command applicable to the MP560 is as follows:

Bus 001 Device 008: ID 04a9:173e Canon, Inc. MP560
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.00
  bDeviceClass            0 
  bDeviceSubClass         0 
  bDeviceProtocol         0 
  bMaxPacketSize0        64
  idVendor           0x04a9 Canon, Inc.
  idProduct          0x173e MP560
  bcdDevice            0.04
  iManufacturer           1 Canon
  iProduct                2 MP560 series
  iSerial                 3 1653C4
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           85
    bNumInterfaces          3
    bConfigurationValue     1
    iConfiguration          0 
    bmAttributes         0xc0
      Self Powered
    MaxPower                2mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           3
      bInterfaceClass       255 Vendor Specific Class
      bInterfaceSubClass      0 
      bInterfaceProtocol    255 
      iInterface              0 
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x07  EP 7 OUT
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x88  EP 8 IN
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x89  EP 9 IN
        bmAttributes            3
          Transfer Type            Interrupt
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0040  1x 64 bytes
        bInterval              11
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        1
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass         7 Printer
      bInterfaceSubClass      1 Printer
      bInterfaceProtocol      2 Bidirectional
      iInterface              0 
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x01  EP 1 OUT
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x82  EP 2 IN
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval               0
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        2
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass         8 Mass Storage
      bInterfaceSubClass      6 SCSI
      bInterfaceProtocol     80 Bulk-Only
      iInterface              0 
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x84  EP 4 IN
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x05  EP 5 OUT
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval               0
Device Qualifier (for other device speed):
  bLength                10
  bDescriptorType         6
  bcdUSB               2.00
  bDeviceClass            0 
  bDeviceSubClass         0 
  bDeviceProtocol         0 
  bMaxPacketSize0        64
  bNumConfigurations      1
can't get debug descriptor: Resource temporarily unavailable
Device Status:     0x0001
  Self Powered

The USB device created at boot was as follows:

# ls -la /dev/bus/usb/001/008
crw-rw-r--+ 1 root lp 189, 7 Jul 24 11:01 /dev/bus/usb/001/008

Whether run by the root user or under my user account, the SANE tools detected the MP560 scanner network and USB connections:

$ scanimage -L
device `pixma:MP560_192.168.1.78' is a CANON Canon PIXMA MP560 multi-function peripheral
device `pixma:04A9173E' is a CANON Canon PIXMA MP560 multi-function peripheral

$ sane-find-scanner

  # sane-find-scanner will now attempt to detect your scanner. If the
  # result is different from what you expected, first make sure your
  # scanner is powered up and properly connected to your computer.

  # No SCSI scanners found. If you expected something different, make sure that
  # you have loaded a kernel SCSI driver for your SCSI adapter.

found USB scanner (vendor=0x04a9 [Canon], product=0x173e [MP560 series]) at libusb:001:008
  # Your USB scanner was (probably) detected. It may or may not be supported by
  # SANE. Try scanimage -L and read the backend's manpage.

  # Not checking for parallel port scanners.

  # Most Scanners connected to the parallel port or other proprietary ports
  # can't be detected by this program.

But scanner applications still hung! This time the message displayed by the dmesg command was:

usb 1-1.2.2: usbfs: interface 0 claimed by usbfs while 'scanimage' sets config #1

I unplugged the USB cable and plugged it in again. The output of the dmesg command was:

usb 1-1.2.2: USB disconnect, device number 8
usb 1-1.2.2: new high-speed USB device number 9 using ehci-pci
usb 1-1.2.2: New USB device found, idVendor=04a9, idProduct=173e
usb 1-1.2.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
usb 1-1.2.2: Product: MP560 series
usb 1-1.2.2: Manufacturer: Canon
usb 1-1.2.2: SerialNumber: 1653C4
usb-storage 1-1.2.2:1.2: USB Mass Storage device detected
usb-storage 1-1.2.2:1.2: device ignored

I then launched XSane several times and each time I was able to select either the MP560 via my home network (pixma:MP560_192.168.1.78) or via the USB cable (pixma:04A9173E_1653C4) and scan successfully.

By the way, it is possible to scan via the command line instead of using a GUI scanner application. For example, tjhe following command will scan an A4 page via the MP560’s USB connection (see man scanimage for details of the options):

$ scanimage -d pixma:04A9173E_1653C4 -l 0 -t 0 -x 215 -y 297 --resolution 150 --mode Color | convert - scanned-page.png

So the problem is solved, right? Wrong! For whatever reason, scanning via the USB interface is not guaranteed to work every time I boot the laptop. Sometimes scanner applications (and the scanimage command) hang if I select the USB interface; at other times they don’t hang and scanning works fine. If scanning using the USB device is not working, if I unplug and re-insert the USB cable a few times it becomes possible to scan using the USB interface. And once scanning via the USB interface does work, from then onwards it works consistently during that session.

I had been using Version 1.0.24-r5 of the sane-backends package in Gentoo Linux, which is the latest stable version according to the Gentoo package manager. To check if that particular version of the SANE pixma backend might be the cause of the problem I installed the latest version available in the Gentoo package manager (currently 1.0.5_pre20150625). However it made no discernable difference.

To sum up, in my case the most successful approach so far has been to use a kernel ‘quirk’ to force the usb-storage driver to ignore the device and not bind to it. However, this approach does not result in libusb/SANE being able to access the scanner during every boot session, but, if access is successful, it remains successful during the current session. Even if access via the USB interface does not work initially, sometimes I can get it to work by unplugging and re-inserting the USB cable.

UPDATE (July 30, 2015): I have now managed to get scanning to work with almost 100% reliability when connected to the MP560 via USB — see my latest post for details.

Follow

Get every new post delivered to your Inbox.

Join 68 other followers