Using xrdp Desktop for Everyday Life (Ubuntu Xenial)

Preface: I Need the Latest xrdp

During the holidays the keyboard of my laptop started to indicate that there is no eternity in the world. And especially not among the cheapo laptops. Since a new laptop with a decent screen and processor would const a fortune, I decided to try another approach. Why don’t I install a desktop Linux to my Xen server and use it for daily tasks? In this setup the laptop wouldn’t need to have a capable processor.

I wanted a setup where the connection would be direct without any servers between. I don’t want anyone to follow my mediocre node.js stumbles or follow my bank sessions. TeamViewer and similar helpdesk tools are no-go.

I did some testing with NoMachine NX, but it felt a bit clumsy although the setup was painless. Using X was not sufficient option since you want to hear the sounds when watching YLE Areena, right?

Finally I ended up working with xrdp, a Linux realisation of Microsoft’s Remote Desktop Protocol. The protocol supports sound and its performance should be enough for multimedia. Well, it quickly turned out that the pre-packaged version of xrdp (the server) did not have support for sound. It didn’t support mouse wheel either which is another “must”. Thus I needed to compile the latest version myself.

The Beef: Compiling xrdp With Sound

Compiling xrdp

Get the source from xrdp site. My version was 0.9.4. First compile xrdp. Make sure you have build-essential installed and give it a try:

cd xorg/
./configure
make
sudo make install

Compiling X11 with RDP support

It turns out that the pre-packaged Xorg does not have RDP support and we need to compile X11 with RDP support as well:

apt-get install xsltproc flex bison libxml2-dev python-libxml2
cd xorg/X11R7.6/
./buildx default

Install (copy) the binary to /usr/local/bin as root:

cp rdp/X11rdp /usr/local/bin

Now start (again, as root):

xrdp-sesman
xrdp

By default xrdp server supports multiple session types. Since I want to provide the RDP protocol only I have to edit /etc/xrdp/xrdp.ini. The session types are in the bottom (after [Channels] section).

Leave only X11rdp connection type:

[X11rdp]
name=X11rdp
lib=libxup.so
username=ask
password=ask
ip=127.0.0.1
port=-1
xserverbpp=24
code=10

Getting sound to work

Building Pulseaudio sound modules requires a bit extra work.

First, get the version of your Pulseaudio installation:

$ pulseaudio --version
pulseaudio 8.0

Get the pulseaudio source and unpack it somewhere. I used ~/src/pulseaudio and now I have ~/src/pulseaudio/pulseaudio-8.0. Now go to forementioned directory and compile your Pulseaudio:

apt-get install intltool libjson-c-dev libsndfile1-dev
./configure --without-caps
make

Now back to xrdp:

cd xrdp/sesman/chansrv/pulse

Edit PULSE_DIR (in xrdp/sesman/chansrv/pulse/Makefile) to point to the path you have your Pulseaudio source. In my example:

PULSE_DIR = /home/matti/src/pulseaudio/pulseaudio-8.0

Then simply:

make

Now you have module-xrdp-sink.so and module-xrdp-source.so. Copy them to Pulseaudio libs (as root)

cp *.so /usr/lib/pulse-8.0/modules/

Add following lines to your /etc/pulse/default.pa:

load-module module-xrdp-sink
load-module module-xrdp-source
set-default-sink xrdp-sink
set-default-source xrdp-source

Note! In my case pavucontrol crashed the RDP connection for whatever reason. If you encounter problems you can list sinks and sources with these commands:

$ pacmd list-sinks | grep -e 'name:' -e 'index'
 * index: 1
 name: <xrdp-sink>
$ pacmd list-sources | grep -e 'name:' -e 'index'
 index: 1
 name: <xrdp-sink.monitor>
 * index: 2
 name: <xrdp-source>

You can restart the xrdp server by restarting xrdp and xrdp-sesman.

Linux Client

At this point your Linux desktop can be connected using Windows Remote Desktop Client. Since none of the pre-packaged rdp clients did not work, had lag or did not support sound i decided to build latest FreeRDP. I personally decided latest nightly build offered from their CI at https://ci.freerdp.com/job/freerdp-nightly-binaries/.

To open a connection I enter:

/opt/freerdp-nightly/bin/xfreerdp /kbd:0x0000041D /sound /v:[MY SERVER NAME]

The /kbd value uses Swedish keyboard layout. You can get the possible values by entering:

/opt/freerdp-nightly/bin/xfreerdp /kbd-list

You don’t need to edit the keyboard settings in the target machine. Actually editing them made FreeRDP to segfault.

Epilogue: Was it Worth it?

The original goal was to use the remote desktop as a workstation for daily use: browsing the Net, reading emails and doing some garage programming. Was this setup good enough for this?

No.

There is slight lag with the display: when you close a window it can take 1-2 seconds before the screen updates. Changing the virtual desktop is sluggish. The mouse roller is inaccurate. I used this for one or two days and then destroyed the whole thing.

Acknowledgements

Reading PDF fields with Python/pdfminer

pdfminer is a PDF data extraction class written completely in Python. You can use it to extract data from PDF fields as well. However, doing so can be a headache since the form entries may have child objects which you should search as well. Most of the sample codes I found from the net did not do this properly or there were problems with the encoding of the strings.

Here is the sample code I wrote to demonstrate getting the data:

from argparse import ArgumentParser

from pdfminer.pdfparser import PDFParser 
from pdfminer.pdfdocument import PDFDocument

from pdfminer.pdftypes import resolve1, PDFObjRef

def load_form(filename):

    """Load pdf form contents into a nested list of name/value tuples"""

    with open(filename, 'rb') as file:
        parser = PDFParser(file)
        doc = PDFDocument(parser)
        return [load_fields(resolve1(f)) for f in
                   resolve1(doc.catalog['AcroForm'])['Fields']]
                   

def load_fields(field, parent_var=None):

    """Recursively load form fields"""

    def escape_utf16(param_str):
        if type(param_str).__name__ == "PSLiteral":
            param_str = str(param_str)
        if isinstance(param_str, basestring) and param_str[:2] == "\xfe\xff":
            # If we have string with UTF-16 BOM remove BOM and null characters
            param_str = param_str[2:].translate(None, "\x00")
        if isinstance(param_str, basestring):
            # Encode all strings to UTF-8 (PDF uses ISO-8859-15)
            return param_str.decode("iso-8859-15").encode("utf-8") 
        return param_str
        
    form = field.get('Kids', None)

    if form:
        # This is a child form, recurse into
        new_parent = field.get('T')
        if parent_var:
            new_parent = parent_var+"."+new_parent
        return [load_fields(resolve1(f), new_parent) for f in form]
    else:
        # Some field types, like signatures, need extra resolving
        if (parent_var):
             return (parent_var+"."+field.get('T'), escape_utf16(resolve1(field.get('V'))))
        else:
             return (field.get('T'), escape_utf16(resolve1(field.get('V'))))


def flatten_form (deep_form):
    """ Flatten given form (from load_form()) to a dictionary """

    dict_form = {}
    
    for this_item in deep_form:
        if isinstance(this_item, list):
            this_flat_item = flatten_form(this_item)
            for this_key in this_flat_item.keys():
               dict_form[this_key] = this_flat_item[this_key]
        else:
            dict_form[this_item[0]] = this_item[1]

    return dict_form
    
def parse_cli():
    """Load command line arguments"""

    parser = ArgumentParser(description='Dump the form contents of a PDF.')

    parser.add_argument('file', metavar='pdf_form',
                    help='PDF Form to dump the contents of')

    return parser.parse_args()



def main():
    args = parse_cli()

    # Read form
    form = load_form(args.file)
    # Make a "flat" dictionary from the form data given by load_form()
    form_flat = flatten_form(form)
    
    # Print form data
    form_keys = form_flat.keys()
    form_keys.sort()
    for this_key in form_keys:
        if isinstance(form_flat[this_key], basestring):
            print this_key+": "+form_flat[this_key]
        elif form_flat[this_key] == None:
            print this_key+": None"
        else:
            print this_key+": Unprintable"
    
if __name__ == '__main__':
    main()

Configuring Chinese Ethernet-controllable 2-relay board

I bought some weeks ago a Ethernet-controllable 2-relay board. While my Chinese Top Seller could not provide any documentation for the item I had to find things myself.

The default IP for the device is 192.168.1.100. To control the device with my Linux device I found a nice Python script sr-201-relay. Since we know the IP of the board we can get rest of the configuration:

$ python sr-201-relay.py 192.168.1.100 config
ip=192.168.1.100
netmask=255.255.255.0
gateway=192.168.1.1
(unknown)=
power_persist=0
version=931
serial=XXXXX50E35000000
dns=192.168.1.1
cloud_server=connect.tutuuu.com
cloud_enabled=0
cloud_password=(not-sent)

Excellent! Now we can change the network settings to suit with my LAN:

$ python sr-201-relay.py 192.168.1.100 gateway=0.0.0.0
$ python sr-201-relay.py 192.168.1.100 dns=0.0.0.0
$ python sr-201-relay.py 192.168.1.100 ip=192.168.2.11
$ python sr-201-relay.py 192.168.1.100 reset

First I tried to make sure the device does not reach Internet and finally I set a static IP from the correct LAN.

The script offers methods to turn relays on (closed) and off (open):

$ python sr-201-relay.py 192.168.2.11 close:1
$ python sr-201-relay.py 192.168.2.11 status
relay status: 1-closed 2-open 3-open 4-open 5-open 6-open 7-open 8-open
$ python sr-201-relay.py 192.168.2.11 open:1
$ python sr-201-relay.py 192.168.2.11 status
relay status: 1-open 2-open 3-open 4-open 5-open 6-open 7-open 8-open

 

Installing PEAR modules in cPanel environment

My current webhotel does not provide pear client and it tool a while to figure out how to install Pear modules to this environment.

wget http://pear.php.net/go-pear.phar
php go-pear.phar

In my case the default paths were OK. Make sure all paths are writable by you (typically starting with /home/youraccount). Press enter to continue. After installing some packages I got a warning:

WARNING! The include_path defined in the currently used php.ini does not
contain the PEAR PHP directory you just specified:
</home/youraccount/pear/share/pear>
If the specified directory is also not in the include_path used by
your scripts, you will have problems getting any PEAR packages working.

Would you like to alter php.ini </usr/local/lib/php.ini>? [Y/n] :

Since this is not writable by you answer no. Now you’re given an important path:

Configured directory : /home/youraccount/pear/share/pear

You can add this to your php.ini but I decided to add this to my PHP script:

ini_set('include_path', '.'.PATH_SEPARATOR.'/home/youraccount/pear/share/pear');

Now you have the pear client at ~/pear/bin/pear and it can use used e.g. ~/pear/bin/pear install Auth

Merikartat ja peruskartat Androidiin (online)

Näillä ohjeilla voit tehdä Android-tabletille (tai puhelimelle) meri- ja peruskartat, joiden käyttö vaatii verkkoyhteyden. Sinun ei tarvitse ladata karttoja etukäteen. Voit halutessasi ladata kartat myös etukäteen.

Liikenneviraston karttapalvelusta ladattavat merikartat eivät sisällä saarien nimiä tai veneväyliä.

mobac_sample_seamap

  1. Lataa Androidille kartat näyttävä ohjelma OruxMaps.
  2. Käynnistä OruxMaps.
  3. Valitse kartat > Vaihda kartta.
    orux_wms_vaihdakartta
  4. Valitse yläreunasta WMS.
    orux_wms_muokkaawms
  5. Syötä haluamasi kartan URL (myös viimeinen kysymysmerkki) kohtaan “Syötä WMS URL”:
    1. Merikartta: https://julkinen.liikennevirasto.fi/s57/wms?
    2. Peruskartta: tiles.kartat.kapsi.fi/peruskartta?
    3. Taustakartta: tiles.kartat.kapsi.fi/taustakartta?
    4. Ortoilmakuvat: tiles.kartat.kapsi.fi/ortokuva?
  6. Napsauta OK.
  7. Valitse haluamasi karttatasot ja napsauta OK. Merikartassa valitse ainoastaan “Cell Layer”.
    orux_wms_merikartta_tasot
  8. Anna kohtaan “Syötä WMS ominaisuudet” Minimi zoomiksi 0 ja maksimi zoomiksi 20.
  9. Valitse “Välitallennus sallittu”.
  10. Anna kartan nimi -kohtaan lisäämäsi kartan nimi, esim. “Merikartta”. Tämä näkyy jatkossa karttavalikossasi.
  11. Napsauta “Luo”.

Kun olet lisännyt karttojen tiedot, saat ne käyttöön seuraavasti:

  1. Valitse kartat > Vaihda kartta.
    orux_wms_vaihdakartta
  2. Valitse WMS-hakemisto (voit tarvittaessa sulkea KERROKSET ja MULTIMAPS napsauttamalla niitä).
  3. Napsauta lisäämääsi karttaa, esim. WMS:Merikartta.
    orux_wms_valitsemerikartta
  4. Nyt käytössäsi on valitsemasi kartta.
    orux_wms_merikarttatoimii

 

HST-kortin käyttöönotto: Ubuntu Trusty

Tässä ohjeessa kerrotaan miten HST kortti otetaan käyttöön niin, että sillä voi kirjautua Firefoxilla viranomaisten sähköisiin verkkopalveluihin.

  1. sudo apt-get install opensc
  2. Käynnistä Firefox (esimerkissä 40.0.3)
  3. Edit > Preferences > Advanced > Certificates > Security Devices > Load > Module Filename
    • 32-bittisessä anna: /usr/lib/i386-linux-gnu/opensc-pkcs11.so
    • 64-bittisessä anna: /usr/lib/x86_64-linux-gnu/opensc-pkcs11.so
  4. OK

Lähde: http://www.linux.fi/wiki/HST

Paketista asennettuna opensc kysyy kirjautumisen yhteydessä molemmat PIN-koodit. OpenSC sisältää kirjaston onepin-opensc-pkcs11, joka kysyy vain PIN1:n. Tämän saa vain kääntämällä OpenSC:n uudelleen. Onneksi homma on helppo ja ohjeet ovat hyvät. OpenSC on asennettava ohjeiden mukaisesti /usr -haaraan. /usr/local ei toimi.

 

Merikartat ja peruskartat Androidiin (offline)

Näillä ohjeilla voit tehdä Android-tabletille (tai puhelimelle) meri- ja peruskartat, joiden käyttö ei vaadi verkkoyhteyttä. Valitsemasi kartat ladataan maksuttomista karttapalveluista tietokoneella ja siirretään tablettiin. Voit siis ladata vain ne alueet, joita oikeasti tulet käyttämään. Jos et halua ladata karttoja etukäteen, katso toinen ohje.

Karttaselaimena käytetään erinomaista OruxMaps-ohjelmistoa, joka on maksullinen.

Liikenneviraston karttapalvelusta ladattavat merikartat eivät sisällä saarien nimiä tai veneväyliä, mutta alla oleva asetustiedosto lataa ne Maanmittauslaitoksen rajapinnasta.

mobac_sample_seamap

Jos resepti tuntii työläältä, kokeile vaikka Maastokarttoja.

A) Valmistelevat toimenpiteet

Kartat ladataan maksuttomalla MOBAC-ohjelmalla. Se on kirjoitettu karttatiedostojen lataukseen ja pakkaukseen eri ohjelmille.

  1. MOBAC tarvitsee Javan.
    • Windows: Lataa Java. Se on maksuton.
    • Linux: Tarvitset Javan. OpenJDK käy, esim. Ubuntussa asenna paketti “openjdk-7-jre”.
  2. Lataa MOBAC. Tuloksena on ZIP-tiedosto.
    • Windows: Pura ZIP-tiedosto esim. työpöydälle.
    • Linux: Pura ZIP-tiedosto esim. kotihakemistoosi.
  3. Tarvitset vielä meri- ja peruskarttojen määrittelytiedostot. Löydät ne tästä tiedostosta. Pura tiedostot MOBAC-ohjelman hakemistoon “mapsources”:
    mobac_mapsources1 mobac_mapsources2

B) Valitse ja lataa kartat

MOBAC-ohjelman toimintaperiaate on yksinkertainen. Sen avulla voit tehdä atlaksia (karttakokoelmia), jotka sisältävät yhden tai useampia suorakaiteen muotoisia karttoja.

  1. Käynnistä MOBAC:
    • Windows: Kaksoisnapsauta MOBAC-ohjelman hakemistosta löytyvää tiedostoa “Mobile Atlas Creator.exe”
    • Linux: Aja “start.sh”, esim. terminaalissa “sh start.sh”.
  2. Anna ensimmäiselle atlakselle jokin kuvaava nimi tai esim. “Testi”. Valitse formaatiksi “OruxMaps Sqlite”.
    mobac_name_atlas
  3. Oletuksena sinulle näytetään karttaa “OpenStreetMap MapQuest” (ks. vasemman ylänurkan Map Source -valinta). Siirry tämän kartan avulla haluamallesi alueelle (esim. Suomenlahdelle).
    • Liikuta karttaa pitämällä hiiren kakkosnappia alhaalla.
    • Zoomaa hiiren rullalla tai näytön yläreunassa näkyvällä zoom-valitsijalla.
      mobac_goto_finland
  4. Kun olet oikealla alueella ja zoom levelillä 10, valitse Map Source -valinnalla “Merikartta Liikennevirasto S57”.
  5. Rajaa haluamasi alueet (hiiren vasen näppäin), valitse zoom levelit ja valinta atlakseen (valinnan jälkeen vasemmalta Add selection).
    • Valitut alueet (selection) vastaavat ikään kuin karttalehtiä, kun taas atlakset ovat kartastoja.
    • Tabletin ohjelma osaa valita automaattisesti oikean karttalehden.
    • Mitä isomman zoom levelin (vasen ylänurkka, 0-18) otat mukaan, sen enemmän tilaa kartta-aineisto vie (ja kartan tekeminen kestää). Kannattaa kokeilla jättää levelit 15-18 pois, niin säästyy tabletilta levytilaa.
      mobac_select_layer
  6. Kun olet tyytyväinen atlakseen napsauta “Create atlas”. Se lataa valitsemasi kartat . Tämä kestää kauan, koska karttatiilet (kartan palaset) haetaan yksitellen palvelimelta. Mitä isompia zoom leveleitä olet valinnut selectioneihin, sen enemmän ladattavaa on.
  7. Valmis tavara tulee mobac-ohjelman hakemistoon “atlases”, jossa on alihakemisto kaikille tehdyille atlaksille.

C) Kartat Androidiin

Tässä vaiheessa olet tehnyt tietokoneella haluamasi kartat. Viimeisessä vaiheessa näytät kartat tabletissa.

  1. Lataa Androidille kartat näyttävä ohjelma OruxMaps.
  2. Käynnistä OruxMaps, jotta se tekee karttahakemistot tabletille. Voit sulkea OruxMapsin saman tien.
  3. Seuraavaksi voit siirtää valmiit kartat MOBAC-ohjelman hakemistosta “atlases” tabletille.
    • Näet tabletin hakemiston seuraavasti: Asetukset (kolme pistettä näytön ylänurkassa) > Kaikki asetukset > Kartat > Kartat hakemisto: esim. “/storage/emulated/0/oruxmaps/mapfiles/”.
    • Voit tehdä siirron esim. muistikortin tai Google Driven avulla. Kätevä apuväline tässä on Cheetah Mobilen File Manager.
  4. OruxMapsissa karttavalikko (karttaikoni) > Switch map > Offline > oma Atlaksesi jokin layer. Jos karttasi ei näy, paina yläreunan reload-painiketta.

D) OruxMapsin käyttö

OruxMapsissa on tärkeä säätää karttojen zoom-tasot oman päätelaitteen näytölle sopivaksi. Zoom-tasot näkyvät näytön oikeassa alanurkassa:

oruxmaps_zoomlevel

Zoom level on 16, joka on suurennettu digitaalisella zoomilla 136%:iin. Tässä näkyvät zoom levelit ovat samoja, jotka näkyvät MOBAC-karttoja tehdessä.

  • Zoom leveliä voi vaihtaa nipistämällä karttaa kahdella sormella.
  • Digital zoomia voi säätää äänenvoimakkuusnäppäimillä.

Pieni digital zoom auttaa, jotta karttamerkit näkyy sujuvasti. Zoom-asetuksia voi säätää: Asetukset (kolme pistettä näytön ylänurkassa) > Kaikki asetukset > Kartat > Zoom asetukset:

  • Pyöritys ele: Ota tämä pois päältä, jos et halua kääntää karttoja.
  • Äänenv. näppäimet: Valitse tämä, niin voit säätää digitaalisia zoomeja äänenvoimakkuuksilla.
  • Viimeistele nipistys zoom: Valitse tämä, niin zoom level vaihtuu loogisesti.

 

Getting Rid of Black Borders in Titanfall

After installing the Titanfall FPS game our gamer soon noticed a great annoyance: the screen was aligned in somewhat peculiar way. The screen had a large black border on the left while the screen was missing an equal part on the right.

We tried to change the video settings but none of the presets was functional. However, this solved the problem:

  1. Right click on the desktop > Screen Resolution > Get your current screen resolution (e.g. “1680 x 1050”).
  2. Open up Windows Explorer, and navigate to “C:\users\yourusernamehere\Documents\Respawn” and open the Titanfall folder.
  3. Go into the local folder and open the file titled “videoconfig.txt”.
  4. Set the variables “setting.defaultres” and “setting.defaultresheight” to correct values. In our example they should be

    “setting.defaultres”  “1680”
    “setting.defaultresheight”  “1050”

  5. To full screen you may want to set

    “setting.fullscreen”  “1”
    “setting.nowindowborder”  “0”

Reinstalling GRUB After Windows Update (non-EFI)

This post explains how to revert the GRUB after your Linux (Ubuntu 14.10)/Windows (7) dual-boot workstation boots directly to Windows the Windows update. This procedure is valid for non-EFI (legacy) workstations. For EFI workstations see another post.

  1. Get a sysresccd boot image and boot the workstation from it.
    • Note that you cannot make an bootable USB stick using dd but executing an installation script as explained in the documentation.
    • This recipe was tested on 4.5.3.
  2. Find your Linux root partiton using fdisk:
    1. fdisk /dev/sda (sdb, sdc…)
    2. p (prints the partiton table)
  3. In this example we found the suspected root partition from /dev/sdb2. It has the boot flag on and the partition type is “Linux”.
  4. mkdir /tmp/root
  5. mount /dev/sdb2 /tmp/root
  6. ls /tmp/root (make sure that this contains the root partition)
  7. grub2-install –root-directory=/mnt /dev/sda
  8. reboot
  9. As soon as you get your Ubuntu up and running re-instal grub:
  10. sudo grub-install /dev/sda

kernel-qemu for running RaspBi on QEMU

Some days ago I was in desperate need to run Raspberry Pi on my Ubuntu. As you might expect, there has been several others with similar need and i quickly ran to a number of blog posts explaining how to do this with QEMU. Maybe the best I could find is at http://paulscott.co.za/blog/full-raspberry-pi-raspbian-emulation-with-qemu/.

However, all these documents had a similar drawback. For some reason you cannot just make QEMU to boot from the Raspbian image file but you need a kernel file (often referred as kernel-qemu) which is given with -kernel parameter to QEMU. All these blogs pointed at currently no-existing blog at xecdesign.com and did not explain where this magical kernel file came from.

It appears that you have to do apply a number of patches (armhf? qemu?) to stock kernel to make it boot in QEMU. Of yourse, you have to cross-compile the kernel to ARM.

Finally I found the kernel-qemu inside the pre-packaged QEMU+Raspbian Windows installation at sourceforge. If you just need the kernel-qemu, go ahead and download it. This is probably the one that origins from xecdesign.com. There is another alternative (http://elinux.org/File:ZImage.7z) which gives you 3.6.1 kernel (download).

However, both the two have same drawback. You don’t get modules and they lack some important modules. For example the USB stack does not work.