Skype for Linux doesn’t ring: How to fix it

I’ve been really annoyed at Skype for this weird behavior: When I was on a call, the audio worked fine. But when someone was calling me, I only got the small notification window but no ringing sound.

I couldn’t figure this out for a long time, but now I found a solution: Open the system-wide sound settings and unmute alerts/notification sounds. Now, you should get a ringing tone whenever somebody calls you.

This fixes one problem and creates a second one which I will fix below, but let me first give you some info on the origin of this behavior. When running on a system that uses PulseAudio, Skype doesn’t use the regular audio output methods for playing its notification sounds but plays the sounds through the audio notification channel. If you don’t like to hear system notifications such as log-in sounds et cetera and thus disable this channel in the audio settings, Skype doesn’t ring…

Fixing the original problem leaves us with a new one: If you’re like me and you don’t really appreciate the system notification sounds, you can configure the system to not play notification sounds without muting the notification channel. With Gnome 3, open the dconf-editor tool and go to org -> gnome -> desktop -> sound. Uncheck event-sounds. Done!

Now, you should hear a ringing sound if someone calls you, but no annoying system notification sounds.

Globally handling uncaught exceptions and signals in C++

If you have a sementation fault in your C++ program, the program crashes and this is printed to standard error:

Segmentation fault (core dumped)

It tells you that a core dump has been created if your system was configured to do so. You can use it to further debug the crash, but when you have a quick look at the error message, you learn near to nothing about the cause of the crash.

Similarly, when there is an uncaught exception in your code, the following is printed (again to standard error):

terminate called after throwing an instance of 'std::runtime_error'
what():  Hello, world!
Aborted (core dumped)

Again, you can use the core dump, but why not let the program print a stack trace to help you find the location where the segfault or exception occurred and the call chain that lead to it, just as many other languages do?

Environment

The following was tested with gcc 4.8.2 running under Fedora 19 and I’m not sure how portable this all is. Just try it on the platform(s) of your choice ;)

Printing a stack trace

gcc/glibc provides us with backtrace(), backtrace_symbols(), and backtrace_symbols_fd() from execinfo.h, which can be used to generate a binary stack trace (backtrace()) and convert it to a nicely formatted array of strings (backtrace_symbols()) or directly print it to a file descriptor, e.g. stderr (backtrace_symbols_fd()).

This is how you do it in code, with a maximum number of 20 entries in your stack trace:

void *array[20];
size_t size = backtrace(array, sizeof(array) / sizeof(array[0]));
backtrace_symbols_fd(array, size, STDERR_FILENO);

The result looks something like that:

./handlertest(_Z15printStacktracev+0x14)[0x401374]
./handlertest(_Z13signalHandleri+0x1e)[0x4013ae]
/lib64/libc.so.6[0x369c435a60]
./handlertest(main+0x36)[0x4011c6]
/lib64/libc.so.6(__libc_start_main+0xf5)[0x369c421b45]
./handlertest[0x401291]

You can see that the method names are mangled, but at least you can approximate the location of the error.

For this to work properly, you need to call g++ with -rdynamic, so that the linker exports all symbols. But how do we print the stack trace when our program crashes? Enter signal and terminate handlers…

Adding a signal handler

To catch segmentation faults, you can register a signal handler that is called when your programm receives a SIGSEGV signal (segmentation violation, code 11). This is done through signal() from signal.h:

void signalHandler(int sig) { /* print stacktrace */ }
...
signal(SIGSEGV, signalHandler);

Adding a terminate handler

When an exception in a C++ program is not caught by try-catch, std::terminate() is called before the program aborts. In fact, the default implementation simply calls abort(), but you can do something meaningful beforehand. This is how you register a terminate handler with std::set_terminate as defined by the exception header:

void terminateHandler() { /* print stacktrace */ }
...
std::set_terminate(terminateHandler);

Accessing the uncaught exception from the terminate handler

Now you get a chance to print a stack trace on termination, but you probably also want to print the exception that caused the crash. This caused some headache, but finally I got the following:

std::exception_ptr exptr = std::current_exception();
try {
    std::rethrow_exception(exptr);
}
catch (std::exception &ex) {
    std::fprintf(stderr, "Terminated due to exception: %s\n", ex.what());
}

The solution uses the std::current_exception() method introduced by C++11 (compile with -std=c++0x or -std=c++11). It returns an exception_ptr object that has only one meaningful use: It can be rethrown, which we do to finally catch and process it.

Putting it all together

I built a small demo project that first installs a signal handler and a terminate handler and then crashes the program randomly either by dereferencing a null pointer to cause a segfault, or by throwing an uncaught exception.

Hope I could help :) Please leave a comment if you want to add something I missed. If you like what you just read, you can also follow me on GitHub or star the demo project repo.

Refresh your SSD

Just like yourself, your SSD likes to have some rest from time to time to perform well on the long run. After some use, it gets slower and slower if it isn’t told which parts of it are still in use and which hold only garbage. This is due to the internal workings of the disk that I won’t go into here. If you’re interested in the gory details, please head on to Wikipedia: TRIM.

On Ubuntu, you can refresh your SSD with the fstrim command:

sudo fstrim -v /

This applies the optimizations to the root filesystem. If there are other filesystems that are mounted from an SSD, replace the single slash by the path to the mount point(s).

On my laptop, which is equipped with a 250 GB Samsung SSD 840 drive, you get the following results:

New SSD

Measurements taken directly after the initial OS installation on the new drive. The performance measurements were taken using the Gnome disk utility called “palimpsest” (sudo apt-get install gnome-disk-utility).

Used SSD

Measurements after 8 months of use.

SSD after trimming

Measurements after running fstrim.

After trimming, the SSD is not as fast as when it was new, but the average reading transfer rate improved by 15%.

Decreasing the pain of updating OwnCloud

OwnCloud is a file, calendar and address book storage service that you can run on your own PHP enabled web host. I use it for syncing my calendars (over CalDAV, with Lightning for Thunderbird and AnDal for Android) and my address book (over CardDAV, with Inverse SOGo Connector for Thunderbird and CardDAV-Sync for Android).

However, there’s one major pain point in using OwnCloud: Every few weeks, the project releases a security update that needs to be installed. However, they don’t have any means of notification: There’s neither an “announce” mailing list, nor an RSS feed for updates. I monitor the changelog with changedetection.com, so that I get an email when there’s a new version of OwnCloud.

When you know that there’s an update, you still need to install it. This isn’t done automatically with a single click like in WordPress, so you have to follow a procedure as outlined in the OwnCloud Administrators Manual. Previously, I needed to look it up every single time, so I wrote a shell script to automate some of it:

#!/bin/bash

if [ -z "$1" ]; then
        echo "usage: $0 owncloud-x.y.z.tar.bz2"
        exit 1
fi

tar xvf $1
sudo rsync --inplace -rtv owncloud/ public/owncloud/
rm -r owncloud $1

Prerequisite: The running owncloud instance is located in public/owncloud/, relative to the directory from which you run the script. Change the script as you need it.

You use like that:

$ wget http://download.owncloud.org/community/owncloud-x.y.z.tar.bz2
$ ./update-owncloud.sh

Afterwards, you need to open your OwnCloud instance in your browser to trigger the database upgrade.

That’s it!

Blue Screen with STOP 0x0000007F: What does it mean?

I recently got a blue screen on a Windows XP machine with the following error code:

STOP 0x0000007F (0x0000000D 0x00000000 0x00000000 0x00000000)

If you’re like me, you want to know what went wrong. This is what Microsoft has to say on the issue:

This error message can occur if either of the following conditions exists:
* Your computer has hardware or software problems (hardware failure is the most common cause).
* You try to over clock the speed of your computer’s processor (for example, you set a 150 MhZ processor to run at 187 MhZ).

[…]

The most important parameter is the first one (0x0000000X) which may have several different values. The cause of this trap can vary, depending on the value of this parameter. All traps that cause a STOP 0x7F can be found in any Intel x86 microprocessor reference manual as they are specific to the x86 platform.

Then follows a short list of common error codes, but 0x0000000D (decimal 13) is not on the list. As mentioned by the document, the full list can be found in the document called Intel® 64 and IA-32 Architectures Software Developer’s Manual, more specifically in the first volume of this 3000+ page behemoth. In Section 6.4.1 on Page 140, you can find the table “Exceptions and Interrupts” with the full list.

So, what is 0xD?

Description: General Protection
Source: Any memory reference and other protection checks.

Ah, it’s the classic General Protection Fault.

Django: Prevent email notification on SuspiciousOperation

Django 1.4.4 introduced the ALLOWED_HOSTS setting as implemented in django/http/__init__.py:

A list of strings representing the host/domain names that this Django site can serve. This is a security measure to prevent an attacker from poisoning caches and password reset emails with links to malicious hosts by submitting requests with a fake HTTP Host header, which is possible even under many seemingly-safe webserver configurations.

If the host header holds an unknown host and DEBUG is set to False, a SuspiciousOperation exception is raised. This results in an HTTP 500 (Internal Server Error) error code which is returned to the client. I believe this was chosen over the HTTP 4xy-class error (Client Error) so that the admins are notified via email (see the Error Reporting docs). This is a good thing if you have misconfigured the ALLOWED_HOSTS setting and forgot to include some host name that should be usable with the site.

If, however, you are constantly spammed by Django error messages because someone is scanning your website and tries to set a fake Host header, things get annoying. I posted a bug report on the Django bug tracker, and it looks like this will be handled either in 1.5.1 or at least in 1.6. (I wish to note at this place that I’m very grateful that Django has such a responsive dev team. The first response came in in less than 3 hours after the bug, and the first proposed patch was posted on the same day. Thank you!)

Until Django is properly fixed, I need some workaround that I implemented as a logging filter that prevents SuspiciousOperation exceptions from being sent via email (it does not change the HTTP 500 into an HTTP 400):

from django.core.exceptions import SuspiciousOperation

def skip_suspicious_operations(record):
  if record.exc_info:
    exc_value = record.exc_info[1]
    if isinstance(exc_value, SuspiciousOperation):
      return False
  return True

To activate this filter, it must be included in your settings.py file just like in the logging docs, where I also got the blueprint for the code that is listed above.

I prepared a minimal example project for your convenience. It comes with the filter enabled.

If you’d like to verify that the filter works, do the following:

  • Check out the example project and make sure that Django is installed (either globally or in a virtualenv).
  • Run the dev server:
    python manage.py runserver
  • On a second terminal, run the SMTP debugging server built into Python:
    sudo python -m smtpd -n -c DebuggingServer localhost:25
    

    (sudo is necessary because port 25 (SMTP default) can only be used by root)

  • On a third terminal, check that the main page works:
    curl http://localhost:8000/

    (should print “Hello, world” to the console)

  • Check that changing the Host name leads to an error message, but that no email is sent (look at the terminal that runs the SMTP server, nothing should be printed there):
    curl -H "Host: asdfasdf" http://localhost:8000/
  • Check that other server errors are sent out as an email (the SMTP debugging server should print the lenghty message):
    curl http://localhost:8000/500

Building the Botan library for Android

Botan is a C++ crypto library with a wide range of supported cryptographic algorithms. In this article, I’ll walk you through building Botan for Android, so that it can be used in applications that are built with the Android NDK.

Preparations

In the following, I use Ubuntu 12.04 LTS (x86_64) with Eclipse as my development platform. If you use another operating system, the commands may differ.

First, we pull in the Java Development Kit (here: OpenJDK 6), some essential build tools and Python which is needed for the configure script:

sudo apt-get install openjdk-6-jdk build-essential python

We need to have the Android SDK and Eclipse with the Android Development Tools (ADT) installed. The easiest way to get both the SDK and Eclipse with ADT preinstalled is to get the ADT Bundle, extract it somewhere (I used /opt/adt-bundle) and run the eclipse/eclipse program from the resulting folder.

Next, we need to get the Android Native Development Kit (NDK) so that we can compile programs written in C or C++ for Android. I extracted it to /opt/android-ndk, but you can freely choose the location.

Generating the botan_all.* files

First, we download and extract the Botan sources. I recommend to get the Stable Series package, which is version 1.10 at the time of writing.

The configure script of Botan offers to put all of the code into one pair of .h/.cpp files, the botan_all.h and botan_all.cpp. This is called amalgamation and makes it easier to build Botan using the NDK, so we open a terminal, change to the Botan directory, and execute the configure script:

./configure.py --gen-amalgamation --cpu=armv5te --os=linux --cc=gcc --with-tr1=none

This works fine if we target ARM-based Android devices, which covers almost all devices out there. If you need to build for x86/Atom- or MIPS-based devices, you will likely need to adjust the argument to the –cpu parameter. The –with-tr1=none parameter seems to be necessary when using STLport instead of GNU STL (see below).

When the configure script is done, you should see the files botan_all.h and botan_all.cpp in the Botan folder.

Including Botan in an Android project

If you have not already started an Android project which should include Botan, create one now: In Eclipse/ADT, choose File -> New -> Android Application Project and follow the instructions.

Now that you created a project, create a subfolder named “jni” in the project folder which will hold the native code. Inside, create “Android.mk” and “Application.mk” files:

# jni/Android.mk:
include $(call all-subdir-makefiles)

# jni/Application.mk:
APP_ABI := armeabi
APP_CPPFLAGS += -fexceptions -frtti
APP_STL := stlport_shared

If you want to know more about these files, you can look it up in the docs folder of the Android NDK (files ANDROID-MK.html and APPLICATION-MK.html, or use the index in documentation.html in the NDK main directory). Basically, Android.mk tells the Android build system to look for makefiles in the subdirectories, while Application.mk introduces some settings that are used for all modules from the subfolders (ARM instruction set, allow C++ exceptions and RTTI, use STLport instead of the extremely restricted default Android STL).

When you have done this, it is time to create the directory “jni/botan”. Put the botan_all.* files in there and create another Android.mk file:

# jni/botan/Android.mk:
LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := botan
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)
LOCAL_SRC_FILES := botan_all.cpp
LOCAL_CPPFLAGS := -DBOTAN_USE_GCC_INLINE_ASM=0

include $(BUILD_SHARED_LIBRARY)

Again, detailed information can be found in ANDROID-MK.html. The LOCAL_CPPFLAGS line was necessary because, later on, the compiler complained about wrong assembler syntax when inline assembler was used.

Creating some native code that uses Botan

Now we need to build an interface so that our Java app can talk to our native code which will talk to Botan. We do this by creating a Native class which loads the necessary libraries in its static initializer, and which declares the methods that we intend to implement in C++, for example:

// src/de/tiwoc/botandemo/Native.java
package de.tiwoc.botandemo;

public class Native {
    static {
        System.loadLibrary("stlport_shared");
        System.loadLibrary("botan");
        System.loadLibrary("botandemo");
    }

    public static native String pbkdf2Demo(int iterations);
}

The order of the loadLibrary statements is significant: botandemo uses botan, which uses stlport_shared, so stlport_shared must be loaded first, then botan, then botandemo.

botandemo will hold our glue code, so we need to create the folder “jni/botandemo” and create an Android.mk for this module:

# jni/botandemo/Android.mk
LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := botandemo
LOCAL_SRC_FILES := botandemo.cpp
LOCAL_SHARED_LIBRARIES := botan

include $(BUILD_SHARED_LIBRARY)

The one new line in here is the LOCAL_SHARED_LIBRARIES statement which holds a list of the other modules which botandemo will use.

As a next step, we generate a header file corresponding to the Native class. To do this, we use a terminal to change to the bin/classes folder of the app and issue the javah command from the JDK:

javah -o ../../jni/botandemo/native.h de.tiwoc.botandemo.Native

Now, we can write a .cpp file which implements the definitions from the header. The following method will invoke the PBKDF2 key derivation algorithm with some test data:

// snippet from jni/botandemo/botandemo.cpp
JNIEXPORT jstring JNICALL Java_de_tiwoc_botandemo_Native_pbkdf2Demo
    (JNIEnv * env, jclass cls, jint iterations)
{
    try {
        PBKDF* pbkdf = get_pbkdf("PBKDF2(SHA-256)");
        AutoSeeded_RNG rng;

        SecureVector<byte> salt = rng.random_vec(16);
        OctetString aes256_key = pbkdf->derive_key(
                32, "this_is_a_weak_password",
                &salt[0], salt.size(), iterations);
        return env->NewStringUTF(aes256_key.as_string().c_str());

    } catch (...) {
        std::string empty_str = "";
        return env->NewStringUTF(empty_str.c_str());
    }
}

This does nothing particularly useful, but it shows how to bridge the gap between a Java app and the Botan library. A full and working example of this file is part of the example project that can be found on GitHub.

Building the library and testing the app

At this time, all of the native code can be built. We open a terminal, change to the main folder of our project (in this case: BotanDemo) and invoke the Android build system:

# $(NDK) denotes the main folder of the NDK
$(NDK)/ndk-build

This will put all of the native files in the right place inside the project folder, so that the ADT packages all of it into the .apk when building the app.

For the test project on GitHub, I added an Activity that invokes the pbkdf2Demo method:

botan-demo-1

After touching the button:

botan-demo-2

We’re done!

Get the demo project sources from Github!

Resources

The following web sites helped me a lot while I figured out how to do this:

Backup-Erinnerung für Windows

Vor einiger Zeit habe ich ja bereits über eine einfache Backuplösung für Windows mit RdiffBackup (jetzt HardlinkBackup) geschrieben. Diese funktioniert für mehrere Rechner meiner Familie ganz hervorragend. Das verbleibende Problem war jedoch, dass der Benutzer regelmäßig daran erinnert werden sollte, ein Backup anzufertigen. Unter Linux habe ich dafür schon länger eine Lösung: eine Erinnerung nach dem Login mit direkter Möglichkeit, ein Backup zu starten. Ein Artikel dazu, der meinen leicht angestaubten Artikel zu Backup unter Linux aktualisiert, folgt demnächst. Hier widme ich mich zunächst der Windows-Variante (Download am Ende des Artikels).

  • Nach Windows-Systemstart / Login erscheint, wenn das letzte Backup zu alt ist (z.B. nach 7 Tagen), die Bitte, die USB-Backup-Festplatte anzuschließen.
  • Wenn der Benutzer das Laufwerk anschließt und die Meldung bestätigt, startet das Backup-Programm.
  • Wenn allerdings das Backup abgelehnt wird, erscheint die Meldung beim nächsten Login wieder.

Dies wird durch ein in JScript geschriebenes Programm für den Windows Script Host (WSH) erreicht. Das Skript wird zur “Installation” zunächst im Kopfbereich konfiguriert; konkret muss das gewünschte Backup-Intervall und der auszuführende Befehl eingetragen werden. Anschließend kann es einfach im Autostart-Ordner des Startmenüs abgelegt werden, so dass es nach dem Login gestartet wird.

Download:
backup_erinnerung.js

Reporting plagiarism to publishers of Computer Science papers

So you have found plagiarized papers and don’t know who to contact to report your findings? Here are pointers for some of the relevant publishers of Computer Science literature:

If you have anything to add, feel free to add a comment or drop me a message. Thank you!