Search Results: "xam"

12 July 2010

Christine Spang: downloading a directory via HTTP with wget

From the department of things-that-I-know-are-possible-but-can-never-remember-how-to-do-so-hey-I-read-the-manpage-and-now-I'm-blogging-it, I bring you "downloading a directory of photos from a website":
 wget --recursive http://example.com/photos/some-event/ --no-directories --directory-prefix <local-folder-name> --accept JPG,RW2
I always remember wget --recursive (or wget -r for short), but that produces an annoying tree of directories starting with the website's domain and working its way up to the directory you actually want. In the command above, --no-directories removes the tree, and --directory-prefix tells wget to put the downloaded files somewhere that's not the current working directory. The --accept option tells wget to discard files with extensions other than those mentioned, so your downloaded directory is not cluttered with webserver-generated files like index.html if you don't want it to be. Here's the short version, since the long version is nice to remember but not so nice to type:
wget -r http://example.com/photos/some-event/ -nd -P <local-folder-name> -A JPG,RW2

Craig Small: Manually calculating process times

Most of the time you can trust the times you see in programs such as ps and top within Linux, but there are those other times where you just want to check what is going on.

First up, if you're using a FreeBSD system and the procps Linux tools, you're out of luck because a lot of the procfs is broken. You're almost guaranteed to get wierd results.

Jiffies and Hertz
The first thing to find is your jiffies. This is the number of clock ticks per second. There are two main ways of doing it.

The first, and more difficult way is to add up the cpu numbers in /proc/stat, divide it by the first number in /proc/uptime and divide it by the number of cpus.

My cpu line in /proc/stat looks like:
cpu 1267430 145826 552700 137029699 905086 8295 17885 0 0

and my /proc/uptime is:
695317.99 1370303.58

I've got 2 cpus on this system so the calculation is:

(1267430 + 145826 + 552700 + 137029699 + 905086 + 8295 + 17885 + 0 + 0 ) / 695317.99 / 2
which equals 100.

The second way is to use getconf, with the command "getconf CLK_TCK" which again on this system gives you 100.

We call this value "Hertz" and is usually 100 or 1024 though for some architectures it is other values.

Start Time
For each process the procfs has the start time, but it is expressed as the number of jiffes since the computer was booted. If we want to know the real "wall clock" time a process is started we have to start with number of seconds since epoch (for example using the time() function) subtract the number of seconds since the computer was booted and add the process start time from procfs.

The seconds since boot is the first value in /proc/uptime:
696141.85 1371857.53

The 22nd item in a procfs PID stat file is the number of jiffes since boot when the process started. We have to divide it by Hertz to calculate the number of seconds.
27139 (bash) S 11942 27139 27139 34821 5200 4202496 5500 25537 0 14 40 16 18 15 20 0 1 0 69446639 23433216 1378 18446744073709551615 4194304 5082140 14073724008 6512 140737240085456 140127945249678 0 65536 3686404 1266761467 0 0 0 17 1 0 0 0 0 0

To get the start time, take the current time, subtract the boot time and add the process start time.
perl -e '$nowstr = localtime(time() - 696141.85 + 69446639 / 100); print $nowstr, "\n";
Mon Jul 12 22:20:07 2010

Unless you are very quick, you will have to take a few seconds off because the time() function will be now, while the values from the proc files will be a few seconds earlier as it takes time for you to cut and paste.


<script defer="defer" src="http://static.zemanta.com/readside/loader.js" type="text/javascript"></script>
1

Russell Coker: Tracking down Write/Execute mmap() calls with LD_PRELOAD

One of the access controls in SE Linux is for execmem which is used to stop processes from creating memory regions that are writable and executable (as they make it easier to compromise programs and get them to execute supplied code). When the SE Linux audit log tells you that a program is attempting such access it s sometimes difficult to discover where in the code such an access occurs, for example if you have a large code base and mmap() is called in many places it can be difficult to determine which one is the culprit. Especially if you have a source package that contains multiple binaries that use a common shared library and you don t know which bits of library code are called by each executable. To solve this problem in the case of freshclam to provide extra information for Debian bug report #588599 [1] I wrote the following little shared object which can be compiled with gcc -shared -g -fPIC mmap.c -o mmap.so and used with LD_PRELOAD=./mmap.so whatever . Then when the program in question (or any non-SUID program it executes) calls mmap() with both PROT_EXEC and PROT_WRITE set the program will abort. If you run this through gdb then the program will break and you will get a back-trace of the function calls that led to the undesired mmap(). One thing to note is that this method only catches direct calls to a library function outside libc. When the libc code calls the library function (EG all the fwrite() etc code that calls mmap()) the LD_PRELOAD hack won t catch it. Thanks to Keith Owens for pointing this out. #include <dlfcn.h>
#include <stdio.h>
#include <sys/mman.h>
#include <stdlib.h>
#undef NDEBUG
#include <assert.h> void *libc6 = NULL; void *(*real_mmap)(void *, size_t, int, int, int, off_t); void do_init()

libc6 = dlopen("libc.so.6", RTLD_LAZY RTLD_GLOBAL);
if(!libc6)

printf("Aieee\n");
exit(1);

real_mmap = (void * (*)(void *, size_t, int, int, int, off_t))dlsym(libc6, "mmap");
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)

if(!real_mmap)
do_init();
assert(!(prot & PROT_EXEC) !(prot & PROT_WRITE));
return real_mmap(addr, length, prot, flags, fd, offset);

10 July 2010

John Goerzen: Radios

Those of you that follow me on twitter or identi.ca know that I ve been working on my amateur radio license. This started a few weeks ago when Jacob got excited about radios, and must have infected me too. I ve been studying and learning a bit. I had called a local ham (amateur radio operator) I know from church. He gave me one of his apparently newer radios, a 1981 2m Icom IC-22U 10W unit. That was great and got me all the more interested. Then last Friday, a couple of local hams came over to check out that radio and see what repeaters I could hit with it. They discovered a handheld 5W unit could hit at least one local repeater, and this 10W unit could too. One of them also had an HF rig in his pickup, and it was fun to stand out in the driveway and listen to conversations in Michigan and Utah. That evening erased any doubt in my mind about whether or not I would become a ham and it s a bit hard to believe it was only a week ago. I had been studying for the Technician-class amateur radio license, the lowest of three levels of licensing. One of the guys that came over Friday gave me a book to study for the General license, the intermediate level. It warned me to allow a month to prepare, and here I was planning to take the exams Tuesday. I picked it up Sunday, so really got 2 days of studying in. Tuesday I drove to Independence, KS, about 2.5 hours away for the exams. I went so far primarily because the Wichita exams weren t going to be offered until mid-August and I didn t want to wait that long. I found a fun group of people in Independence. I hadn t expected to have fun taking exams, but really, I did. We visited before the exams, and they wanted to know where I was from, of course. When it was time to take the exams, I guess I sort of surprised them by already having my FRN (FCC registration number) and photo copies of my IDs with me. One of them said, You re going to have no trouble with this, are you? I took the Technician exam, checked my work carefully, and turned it in to be graded. They checked it twice and had two people looking over it before they announced I passed with all 35 questions correct. I should note at this point that I was the only person taking the exams that night. Anyhow, on to the General exam. Same drill. It was harder, of course, and I turned it in to be graded. One of them looked at the test, looked at me, put on a grave face and said, Uh oh, not one right. I knew he was joking and they announced I passed THAT one with 100% correct as well. I hadn t expected that, and neither had they. That was what I planned to do, but they said that nobody had ever walked in, taken two tests, and had a score like that and pretty much insisted I try taking the Amateur Extra exam as well. I said I haven t studied for it at all and really doubt I could pass, but eventually went ahead and took that one too. I didn t pass, but I don t think they d have wanted to let me leave without trying. After the paperwork was done, they invited me to hang around and chat with their group that was meeting next door for a bit. I did, and drove home. Then was the frustrating part of the week: waiting for my license. I can t transmit until the FCC issues my license, even though I had passed the exam. My handheld radio arrived later in the week, and of course I still couldn t do much with it. Finally the FCC posted my license late yesterday so I was able to talk to people. It s been fun and I look forward to doing more. I was able to talk to people 55 miles away while driving, and with suitable equipment at home should be able to do much more than that. Several of the people I talked to were offering me tips. I ve never seen a group of people so eager to help out someone new. It s an amazing community and I think Jacob and Oliver will enjoy it one day too.

Enrico Zini: Importing OSM nodes into Spatialite

Importing OSM nodes into Spatialite Second step of my SoTM10 pet project: creating a searchable database with the points. What a fantastic opportunity to learn Spatialite. Learning Spatialite is easy. For example, you can use the two tutorials with catchy titles that assume your best wish in life is to create databases out of shapefiles using a pre-built, i386-only executable GUI binary downloaded over an insecure HTTP connection. To be fair, the second of those tutorials is called "An almost Idiot's Guide", thus expliciting the requirement of being an almost idiot in order to happily acquire and run software in that way. Alternatively, you can use A quick tutorial to SpatiaLite which is so quick it has examples that lead you to write SQL queries that trigger all sorts of vague exceptions at insert time. But at least it brought me a long way forward, at which point I could just cross reference things with PostGIS documentation to find out the right way of doing things. So, here's the importer script, which will probably become my reference example for how to get started with Spatialite, and how to use Spatialite from Python:
#!/usr/bin/python
#
# poiimport - import nodes from OSM into a spatialite DB
#
# Copyright (C) 2010  Enrico Zini <enrico@enricozini.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
import xml.sax
import xml.sax.handler
from pysqlite2 import dbapi2 as sqlite
import simplejson
import sys
import os
class OSMPOIReader(xml.sax.handler.ContentHandler):
    '''
    Filter SAX events in a OSM XML file to keep only nodes with names
    '''
    def __init__(self, consumer):
        self.consumer = consumer
    def startElement(self, name, attrs):
        if name == "node":
            self.attrs = attrs
            self.tags = dict()
        elif name == "tag":
            self.tags[attrs["k"]] = attrs["v"]
    def endElement(self, name):
        if name == "node":
            lat = float(self.attrs["lat"])
            lon = float(self.attrs["lon"])
            id = int(self.attrs["id"])
            #dt = parse(self.attrs["timestamp"])
            uid = self.attrs.get("uid", None)
            uid = int(uid) if uid is not None else None
            user = self.attrs.get("user", None)
            self.consumer(lat, lon, id, self.tags, user=user, uid=uid)
class Importer(object):
    '''
    Create the spatialite database and populate it
    '''
    TAG_WHITELIST = set(["amenity", "shop", "tourism", "place"])
    def __init__(self, filename):
        self.db = sqlite.connect(filename)
        self.db.enable_load_extension(True)
        self.db.execute("SELECT load_extension('libspatialite.so')")
        self.db.execute("SELECT InitSpatialMetaData()")
        self.db.execute("INSERT INTO spatial_ref_sys (srid, auth_name, auth_srid,"
                        " ref_sys_name, proj4text) VALUES (4326, 'epsg', 4326,"
                        " 'WGS 84', '+proj=longlat +ellps=WGS84 +datum=WGS84"
                        " +no_defs')")
        self.db.execute("CREATE TABLE poi (id int not null unique primary key,"
                        " name char, data text)")
        self.db.execute("SELECT AddGeometryColumn('poi', 'geom', 4326, 'POINT', 2)")
        self.db.execute("SELECT CreateSpatialIndex('poi', 'geom')")
        self.db.execute("CREATE TABLE tag (id integer primary key autoincrement,"
                        " name char, value char)")
        self.db.execute("CREATE UNIQUE INDEX tagidx ON tag (name, value)")
        self.db.execute("CREATE TABLE poitag (poi int not null, tag int not null)")
        self.db.execute("CREATE UNIQUE INDEX poitagidx ON poitag (poi, tag)")
        self.tagid_cache = dict()
    def tagid(self, k, v):
        key = (k, v)
        res = self.tagid_cache.get(key, None)
        if res is None:
            c = self.db.cursor()
            c.execute("SELECT id FROM tag WHERE name=? AND value=?", key)
            for row in c:
                self.tagid_cache[key] = row[0]
                return row[0]
            self.db.execute("INSERT INTO tag (id, name, value) VALUES (NULL, ?, ?)", key)
            c.execute("SELECT last_insert_rowid()")
            for row in c:
                res = row[0]
            self.tagid_cache[key] = res
        return res
    def __call__(self, lat, lon, id, tags, user=None, uid=None):
        # Acquire tag IDs
        tagids = []
        for k, v in tags.iteritems():
            if k not in self.TAG_WHITELIST: continue
            for val in v.split(";"):
                tagids.append(self.tagid(k, val))
        # Skip elements that don't have the tags we want
        if not tagids: return
        geom = "POINT(%f %f)" % (lon, lat)
        self.db.execute("INSERT INTO poi (id, geom, name, data)"
                        "     VALUES (?, GeomFromText(?, 4326), ?, ?)",
                (id, geom, tags["name"], simplejson.dumps(tags)))
        for tid in tagids:
            self.db.execute("INSERT INTO poitag (poi, tag) VALUES (?, ?)", (id, tid))
    def done(self):
        self.db.commit()
# Get the output file name
filename = sys.argv[1]
# Ensure we start from scratch
if os.path.exists(filename):
    print >>sys.stderr, filename, "already exists"
    sys.exit(1)
# Import
parser = xml.sax.make_parser()
importer = Importer(filename)
handler = OSMPOIReader(importer)
parser.setContentHandler(handler)
parser.parse(sys.stdin)
importer.done()
Let's run it:
$ ./poiimport pois.db < pois.osm 
SpatiaLite version ..: 2.4.0    Supported Extensions:
        - 'VirtualShape'        [direct Shapefile access]
        - 'VirtualDbf'          [direct Dbf access]
        - 'VirtualText'         [direct CSV/TXT access]
        - 'VirtualNetwork'      [Dijkstra shortest path]
        - 'RTree'               [Spatial Index - R*Tree]
        - 'MbrCache'            [Spatial Index - MBR cache]
        - 'VirtualFDO'          [FDO-OGR interoperability]
        - 'SpatiaLite'          [Spatial SQL - OGC]
PROJ.4 Rel. 4.7.1, 23 September 2009
GEOS version 3.2.0-CAPI-1.6.0
$ ls -l --si pois*
-rw-r--r-- 1 enrico enrico 17M Jul  9 23:44 pois.db
-rw-r--r-- 1 enrico enrico 37M Jul  9 16:20 pois.osm
$ spatialite pois.db
SpatiaLite version ..: 2.4.0    Supported Extensions:
        - 'VirtualShape'        [direct Shapefile access]
        - 'VirtualDbf'          [direct DBF access]
        - 'VirtualText'         [direct CSV/TXT access]
        - 'VirtualNetwork'      [Dijkstra shortest path]
        - 'RTree'               [Spatial Index - R*Tree]
        - 'MbrCache'            [Spatial Index - MBR cache]
        - 'VirtualFDO'          [FDO-OGR interoperability]
        - 'SpatiaLite'          [Spatial SQL - OGC]
PROJ.4 version ......: Rel. 4.7.1, 23 September 2009
GEOS version ........: 3.2.0-CAPI-1.6.0
SQLite version ......: 3.6.23.1
Enter ".help" for instructions
spatialite> select id from tag where name="amenity" and value="fountain";
24
spatialite> SELECT poi.name, poi.data, X(poi.geom), Y(poi.geom) FROM poi, poitag WHERE poi.rowid IN (SELECT pkid FROM idx_poi_geom WHERE (xmin >= 2.56 AND xmax <= 2.90 AND ymin >= 41.84 AND ymax <= 42.00) ) AND poitag.tag = 24 AND poitag.poi = poi.id;
Font Picant de la Cellera "amenity": "fountain", "name": "Font Picant de la Cellera" 2.616045 41.952449
Font de Can Pla "amenity": "fountain", "name": "Font de Can Pla" 2.622354 41.974724
Font de Can Ribes "amenity": "fountain", "name": "Font de Can Ribes" 2.62311 41.979193
It's impressive: I've got all sort of useful information for the whole of Spain in just 17Mb! Let's put it to practice: I'm thirsty, is there any water fountain nearby?
spatialite> SELECT count(1) FROM poi, poitag WHERE poi.rowid IN (SELECT pkid FROM idx_poi_geom WHERE (xmin >= 2.80 AND xmax <= 2.85 AND ymin >= 41.97 AND ymax <= 42.00) ) AND poitag.tag = 24 AND poitag.poi = poi.id;
0
Ouch! No water fountains mapped in Girona... yet. Problem 2 solved: now on to the next step, trying to show the results in some usable way.

9 July 2010

Tim Retout: Toggle fullscreen in Emacs

Today I improved the function I was using to toggle full screen in GNU Emacs.
(defun toggle-fullscreen (&optional f)
  (interactive)
  (let ((current-value (frame-parameter nil 'fullscreen)))
       (set-frame-parameter nil 'fullscreen
                            (if (equal 'fullboth current-value)
                                (if (boundp 'old-fullscreen) old-fullscreen nil)
                                (progn (setq old-fullscreen current-value)
                                       'fullboth)))))
(global-set-key [f11] 'toggle-fullscreen)
The previous function would always restore the frame to "normal" state, even if Emacs was previously maximized. This one makes it behave more like, say, Epiphany or Totem. Apparently using GNOME Keyboard Shortcuts to set this to F11 globally would override custom behaviour from some programs. I've not found any examples of this, though. This would be easily extensible to disable the Emacs toolbar when fullscreen, for instance.

Enrico Zini: Filtering nodes out of OSM files

Filtering nodes out of OSM files I have a pet project here at SoTM10: create a tool for searching nearby POIs while offline. The idea is to have something in my pocket (FreeRunner or N900), which doesn't require an internet connection, and which can point me at the nearest fountains, post offices, atm machines, bars and so on. The first step is to obtain a list of POIs. In theory one can use Xapi but all the known Xapi servers appear to be down at the moment. Another attempt is to obtain it by filtering all nodes with the tags we want out of a planet OSM extract. I downloaded the Spanish one and set to work. First I tried with xmlstarlet, but it ate all the RAM and crashed my laptop, because for some reason, on my laptop the Linux kernels up to 2.6.32 (don't now about later ones) like to swap out ALL running apps to cache I/O operations, which mean that heavy I/O operations swap out the very programs performing them, so the system gets caught in some infinite I/O loop and dies. Or at least this is what I've figured out so far. So, we need SAX. I put together this prototype in Python, which can process a nice 8MB/s of OSM data for quite some time with a constant, low RAM usage:
#!/usr/bin/python
#
# poifilter - extract interesting nodes from OSM XML files
#
# Copyright (C) 2010  Enrico Zini <enrico@enricozini.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
import xml.sax
import xml.sax.handler
import xml.sax.saxutils
import sys
class XMLSAXFilter(xml.sax.handler.ContentHandler):
    '''
    A SAX filter that is a ContentHandler.

    There is xml.sax.saxutils.XMLFilterBase in the standard library but it is
    undocumented, and most of the examples using it you find online are wrong.
    You can look at its source code, and at that point you find out that it is
    an offensive practical joke.
    '''
    def __init__(self, downstream):
        self.downstream = downstream
    # ContentHandler methods
    def setDocumentLocator(self, locator):
        self.downstream.setDocumentLocator(locator)
    def startDocument(self):
        self.downstream.startDocument()
    def endDocument(self):
        self.downstream.endDocument()
    def startPrefixMapping(self, prefix, uri):
        self.downstream.startPrefixMapping(prefix, uri)
    def endPrefixMapping(self, prefix):
        self.downstream.endPrefixMapping(prefix)
    def startElement(self, name, attrs):
        self.downstream.startElement(name, attrs)
    def endElement(self, name):
        self.downstream.endElement(name)
    def startElementNS(self, name, qname, attrs):
        self.downstream.startElementNS(name, qname, attrs)
    def endElementNS(self, name, qname):
        self.downstream.endElementNS(name, qname)
    def characters(self, content):
        self.downstream.characters(content)
    def ignorableWhitespace(self, chars):
        self.downstream.ignorableWhitespace(chars)
    def processingInstruction(self, target, data):
        self.downstream.processingInstruction(target, data)
    def skippedEntity(self, name):
        self.downstream.skippedEntity(name)
class OSMPOIHandler(XMLSAXFilter):
    '''
    Filter SAX events in a OSM XML file to keep only nodes with names
    '''
    PASSTHROUGH = ["osm", "bound"]
    TAG_WHITELIST = set(["amenity", "shop", "tourism", "place"])
    def startElement(self, name, attrs):
        if name in self.PASSTHROUGH:
            self.downstream.startElement(name, attrs)
        elif name == "node":
            self.attrs = attrs
            self.tags = []
            self.propagate = False
        elif name == "tag":
            if self.tags is not None:
                self.tags.append(attrs)
                if attrs["k"] in self.TAG_WHITELIST:
                    self.propagate = True
        else:
            self.tags = None
            self.attrs = None
    def endElement(self, name):
        if name in self.PASSTHROUGH:
            self.downstream.endElement(name)
        elif name == "node":
            if self.propagate:
                self.downstream.startElement("node", self.attrs)
                for attrs in self.tags:
                    self.downstream.startElement("tag", attrs)
                    self.downstream.endElement("tag")
                self.downstream.endElement("node")
    def ignorableWhitespace(self, chars):
        pass
    def characters(self, content):
        pass
# Simple stdin->stdout XMl filter
parser = xml.sax.make_parser()
handler = OSMPOIHandler(xml.sax.saxutils.XMLGenerator(sys.stdout, "utf-8"))
parser.setContentHandler(handler)
parser.parse(sys.stdin)
Let's run it:
$ bzcat /store/osm/spain.osm.bz2   pv   ./poifilter > pois.osm
[...]
$ ls -l --si pois.osm
-rw-r--r-- 1 enrico enrico 19M Jul 10 23:56 pois.osm
$ xmlstarlet val pois.osm 
pois.osm - valid
Problem 1 solved: now on to the next step: importing the nodes in a database.

Francois Marier: Restoring lost RT tickets

Request Tracker (also know as RT), the defacto Open Source ticket tracking software, has a special status value to get rid of spam tickets: deleted. It does exactly what it's supposed to do, that is get rid of these tickets quickly.

Unfortunately, it's very easy to accidentally delete a bunch of non-spam tickets via the bulk update interface. Restoring these deleted tickets is not straightforward.

Good news: none of the lost tickets were removed from the database.
Bad news: you can't search for deleted tickets.

Finding the lost ticketsIf you have a copy of the page before you did the bulk update (perhaps in your browser cache?) then you've got all you need. Otherwise, you'll need to access the database directly to get a list of ticket IDs.

First of all, find the user ID of the person who marked of all these tickets as deleted (42 in this example), then issue the following query:
 SELECT id, lastupdated, subject
FROM tickets
WHERE status = 'deleted' AND
lastupdatedby = 42
ORDER BY lastupdated;
You may want to filter some more using the lastupdated timestamp if you know roughly when the deletion occurred.

Restoring deleted ticketsSince all of the tickets are still in the database, all you need to do is to go to each of them directly (e.g. http://www.example.com/Ticket/Display.html?id=12345 for Ticket #12345) and change the status back to "open".

Francois Marier: Improving the performance of Request Tracker by reducing latency

Request Tracker is a really neat support tool, but one of the common complaints I heard from people using it during a previous project was that it was pretty slow.

There wasn't much we could do about the (overloaded) server it was running on, but I found that enabling mod_deflate really helped.

After watching this great video though, I was inspired to look into it a bit more, focussing this time on latency.

Description of tests
Also note that I was looking for the "best case" for each of the different configurations and so each screenshot was taken after reloading the homepage 10-20 times to maximize cache hits (thanks in large part to mod_expires).

(Is there a nice automated way of measuring average latency?)

Stock RT 3.6Using the default apache2-modperl2 config file (as supplied by RT), here's what the homepage (logged in as root) looked like before I changed anything:



The purple section here indicates the time spent waiting for the server. This shows that the server (running Mason inside mod_perl) is doing quite a bit of processing, including a lot more work than you'd expect while serving static files. It's quite impressive to see how fast the images are being served (directly by Apache) in comparison with the Javascript and the CSS files (which go through Mason).

The reason while Javascript and CSS files have to be served by mod_perl is that they are in fact templates. They contain a few Mason variables which must be substituted before being served.

Looking into it further though, all of these replacements have to do with variables defined in RT_SiteConfig.pm (mostly the install path). Here's an example:
var path = "" ? "" : "/";
which gets turned into:
var path = "/rt" ? "/rt" : "/";
So as long as these paths don't change, then there is no need to re-generate these files.

Static Javascript and CSSThis next diagram was produced after configuring Apache to serve all Javascript and CSS files directly from Apache:



The way I did that (without modifying any of the original files) was by saving the Javascript/CSS sent to the browser and using mod_rewrite rules to serve these files instead of the original templated ones:

# Serve static files directly
RewriteRule ^/usr/share/request-tracker3.6/html/NoAuth/js/ahah.js$ /var/www/rt/ahah.js
RewriteRule ^/usr/share/request-tracker3.6/html/NoAuth/js/cascaded.js$ /var/www/rt/cascaded.js
RewriteRule ^/usr/share/request-tracker3.6/html/NoAuth/js/class.js$ /var/www/rt/class.js
RewriteRule ^/usr/share/request-tracker3.6/html/NoAuth/js/combobox.js$ /var/www/rt/combobox.js
RewriteRule ^/usr/share/request-tracker3.6/html/NoAuth/js/list.js$ /var/www/rt/list.js
RewriteRule ^/usr/share/request-tracker3.6/html/NoAuth/js/titlebox-state.js$ /var/www/rt/titlebox-state.js
RewriteRule ^/usr/share/request-tracker3.6/html/NoAuth/js/util.js$ /var/www/rt/util.js
RewriteRule ^/usr/share/request-tracker3.6/html/NoAuth/css/3.5-default/main-squished.css$ /var/www/rt/main-squished.css
RewriteRule ^/usr/share/request-tracker3.6/html/NoAuth/css/print.css$ /var/www/rt/print.css
RewriteRule ^/usr/share/request-tracker3.6/html/NoAuth/webrtfm.css$ /var/www/rt/webrtfm.css

Removing unnecessary images

Finally, one thing I noticed from this last graph is that the rounded corners in the theme require a number of small images. While these don't take a whole lot of bandwidth, they do require quite a bit of back and forth between the browser and the server.

So I replaced all of the "rounded corner" images in the main-squished.css file with the following CSS attributes:

-moz-border-radius-topleft: 8px;
-moz-border-radius-topright: 8px;
-moz-border-radius-bottomleft: 8px;
-moz-border-radius-bottomright: 8px;
-webkit-border-top-left-radius: 8px;
-webkit-border-top-right-radius: 8px;
-webkit-border-bottom-left-radius: 8px;
-webkit-border-bottom-right-radius: 8px;

(yes, Internet Explorer users probably don't get the rounded corners... oh well)

This eliminated a number of roundtrips and shaved off a few more milliseconds:



Merging CSS and Javascript filesBy this stage, the pages are pretty snappy so there is not much to be gained anymore, but I figured I'd try to reduce the latency a bit more by combining all Javascript files into one (and doing the same for CSS files with the exception of print.css). This is what I got:



(Note that I also took the opportunity to minify both squished files to reduce the filesize.)

Not a huge improvement and I unfortunately had to copy quite a few Mason templates from /usr/share/request-tracker3.6/html/ to /usr/local/share/request-tracker3.6/html/ and then replace all of the script tags with a single one in html/Elements/Header.

Others things to look intoI've stopped here, but there might be ways to further reduce the processing time on the server (hence the latency) by tuning mod_perl/Mason or Postgres. The RT wiki also has a few pointers.

Replacing Apache with Nginx (which means moving to FastCGI) was something I considered, but after trying it out, it turned out that it would add about 100ms of extra latency.

Feel free to leave a comment if you've found something else that makes a big difference on your site.

8 July 2010

Eugene V. Lyubimkin: bits about cupt

1.5.x branch

This is the branch of Cupt I intend to put into Squeeze, I fix rare bugs from time to time there. Today I uploaded the version with the support of the architecture wildcards in source packages, defined in recently released Debian Policy 3.9.0.

2.0 branch
In the same time, I started a rewrite of the whole thing to C++ to make Cupt not only (as possible) feature-rich and bug-free, but also fast, following the example of Git DVCS. I have a significant chance to finish this task before Squeeze+1 release.

Aigars Mahinovs: Phoning it in

Currently I own and use an iPhone 3G. I bought it almost two years ago, when the local phone provider LMT started offering the iPhone legally. I had a pretty good experience with it most of the time, but now it is showing its age: I will try to send my iPhone in for repair hoping to extend its usefulness, but frankly it looks that I might have to get a new phone at or before Debconf. So I am considering my options for a new phone and so far I have 3 main options each with some sub-options. The main options are: iPhone 4, MeeGo and Android. Each choice has its benefits and drawbacks and each also has several sub-options related either to specific phone models or to purchase methods. What I need is a phone with: calling function, contact information synchronised to Google, support for Google Mail/Contacts/Calendar simultaneously with one Exchange account also providing mail/contacts/calendars, music, audiobooks saving my place in the audio book and in the list of books, fully featured Twitter client with Twitpic and location support, encrypted password storage application (preferably open source), GPS with maps, ability to download maps for offline use, Geocaching support with offline cache info and logging, Skype client, ability to write in Latvian, English and Russian in all applications, reliable backup and restore of phones data including settings and data of installed apps. Optional features: last.fm streaming and reporting support, ebook applications with purchasable ebooks, high quality video and photo recording (for a phone), ability for me to write applications on the phone, ssh client, wireless data upload to the phone, ability to change the phones battery without loosing data in the phone (on the go), compass, physical keyboard, confidence in getting software upgrades and developer interest for the next 2 years. I ll try to describe all of the options here to organise my thoughts and maybe also help someone else make the choice. Option 1: iPhone 4 To get the iPhone 4 I have two options: LMT and unlocked. The official arrival of iPhone 4 to Latvia is expected in September and it will likely be sold by LMT for the same prices as iPhone 3GS is now. If I choose this scenario, I will need to survive with my semi-broken iPhone for 2-3 more months. Total price over 2 years (LVL): 131 (purchase price) + 24 * 8 (surcharge) = 323 LVL. Note: the surcharge is the extra cost of the iPhone call plan compared to a comparable regular plan (Vien dais 7 + Internets telefon 5). If I go and purchase an unlocked iPhone 4 in a country where such units are sold (UK is the most easily accessible choice, because a few of my workmates travel weekly to and from UK) then the total price over 2 years would be the purchase price: 499 GBP + 65 GBP (2 year warranty extension) = 505 LVL Now lets go over the general benefits and downsides of the iPhone 4, first the positives: Drawbacks: Option 2: Maemo/MeeGo Some of my colleagues at work (in the Riga office of Accenture) have N900 phones and I have been exposed to people with raw enthusiasm towards the Maemo platform ever since the Debconf in Helsinki, where we saw the first N700 devices in the hands of some lucky Debian/Nokia people using it as an Internet tablet. N900 has been a strong leap forward for the platform, before its head was teleported sideways by the whole MeeGo merger/debackle. Again I have two options here: Get a N900 either here in Latvia for 325 LVL (that would be the total cost over 2 years) or get it from USA during Debconf for 399 USD (+129 USD for 2 year warranty) = 317 LVL. And additional option would be to wait until October/November and then buy the new Nokia MeeGo device, rumoured to be N9-00 and likely to be around the same price as N900 was when it was introduced (around 500 LVL). Benefits: Drawbacks: Option 3 Android After looking trough the options for Android phones, I ve narrowed the selection to the ones that are either available from local carriers or can be easily gotten unlocked also the phones need to have announced plans to have at least Android 2.2 version. Currently the choice is limited to HTC Desire (from carrier or unlocked) and Samsung Galaxy S (unlocked). The prices over 2 years break down as follows: HTC Desire (locked to LMT): 69 + 9*24 = 285 LVL
HTC Desire (locked to Bite): 199 + 2*24 = 247 LVL (Note: only 500Mb of data per month available)
HTC Desire (locked to Tele2): 179 + 6*24 = 323 LVL
Note: all the above options would also require me to pay a 45 LVL early termination fee on my current iPhone contract if I choose to do this before September.
HTC Desire (unlocked): 311 LVL
Samsung Galaxy S (unlocked): 350 LVL (import from Germany) Benefits: Drawbacks: Please correct me if I am wrong with something!!! And also it would be cool if you expressed your own opinions in the comments. Currently I am very undecided about what I am going to do, but after completing this entry I am leaning towards an unlocked HTC Desire. Update:
Olivier Cr te shares a N900 vs. Nexus One experience Edit 01-07-2010: Handed my iPhone in for a warranty repair, got a dumbphone Nokia as a loaner during repairs. Very surprised about how long a battery can last on a low powered and cheap phone. In the mean time from all the comments here and elsewhere I am starting to see that I am too annoyed with the iPhone platform (mostly iTunes) to stay there and that I am also not convinced in the direction MeeGo is going (a lot of community developers are annoyed and are jumping ship), so N900 is also out. I will need to see 2-3 MeeGo smartphones and also see how Nokia will treat their smartphone users and developers on this platform, in the long term, before I ll be ready to trust them with my money. Therefore, my choice is becoming pretty clear look for the best Android phone (after my iPhone dies). We have this thing at Accenture, where we can get company phones at a discount and HTC Desire is on that list. If I can get that, it would slash 100 LVL (almost a third of the price!) off it, but to get there I either need to get a promotion (rather rare after just one year with the company) or prove the necessity of the phone for the needs of my project (kinda hard currently). Well, the situation will be a bit clearer next week when I get my iPhone back. (Apparently the Latvia s largest holiday Midsummer Festivities or J i/L go with tons of traditional outdoor activities, caused a lot of phones to become broken and there is a backlog of warranty service :) ) So at this point my plan is: get my iPhone repaired and get a promotion or a project where I can justify a company-paid HTC Desire and then hope that Nokia/Intel really get their stuff together and make MeeGo a great smartphone platform over the next year or two. Update: Got my iPhone 3G back from the warranty . It is in quotes because they just gave me a new iPhone 3G. The battery lasts for 3 days of minimal use and it has not crashed yet. The recovery process was a pain again caused by iTunes: iTunes refused to restore my backup onto the new phone, because my backup was made on a iOS 4.0, while the new phone I got from the warranty has 3.1.3 on it. So I had to set this phone as a new phone, initialise it, make a backup, upgrade to 4.0, restore from the (empty) backup, then reset the phone to factory settings again and only then I could start restoring data from my original (pre-warranty) backup and start copying my data on to the device. All in all it took nearly 3 hours if iTunes doing something and almost a dozen reboots of the phone. Almost half of that time was spent doing completely unnecessary steps to work around the fact that iTunes is braindead. I ll continue using my iPhone for now, keeping my eyes on the newest Android phones and also waiting for the long-promised first MeeGo phone from Nokia.

7 July 2010

James Morrison: A speech that didn't happen

I have a lot of papers lying around. I now try to keep them organized, but I haven't got through the back log of when I didn't organize them. Sometimes I come across stuff that I'm happy I had in the pile. The following was my attempt at a valedictorian speech for the 2005 Math class at the University of Waterloo. I was not the valedictorian, but I tried, and thus have a speech.

Ladies, Gentlemen, Doctors and children of all ages. Thank you for spending our last day at Waterloo, here with us. I am one of those people who won't be staying here after day, but somehow I was still chosen to be the valedictorian. So, when I was asked to be the valedictorian by some friends of mine, I was thrilled. I also though I could do a good job, heck, I got my degree in CS, therefore, I can do anything. So, I accepted the nomination. I looked at the nomination form and didn't find any hints on what to talk about. At this point I realized that this speech may be a little underspecified. In fact, there was no specification at all.

I gathered what I could from the form, i.e. a speech had to be written by, and performed on the 18th of June 2005. Skip forward a few weeks, I'd accomplished nothing more than vague thoughts on what to talk about, then I got an email. All potential speeches had to be presented on the 6th of April 2005 (the deadline had moved up, and still no specification). However, a performance objective was given in that email -- each speech must be completed in 5 minutes. Given that I don't have a spec, I can only hope no one else has one.

What follows is my implementation of this unknown specification.

Another cycle in our lives is over. We are finished our latest round of education. This time from the University of Waterloo, in some Math program. Many of us have changed significantly while we've been here, but we are still the same people. We know we are older, we can guess that we are wiser, and we are certainly more educated. So, here is a quick tour of my cycle through Waterloo.

When I got here back in September 2000, I was amazed at how many smart people could be put together in one small place. I am actually still amazed by all the smart people here. I simply happen to know a bit more about some of these people and the amazing things they have done. With all these smart people here, I even had to do homework to keep up.

Skip forward to second year. Second year is when the university decided there is no more room for me in residence. In fact, they do that to almost all second year students. So, I found a sleezy place to live off-campus and started discovering what life is like outside the university bubble. For example, there are stores not in the plaza. There are a couple malls, a bus station, and a train station.

By third year Waterloo had become home despite working in two other cities and growing up on the other side of Toronto. I no longer had to fear being kicked out of CS since I had enough courses with good marks racked up that my cumulative average wouldn't drop too low unless I started failing, which would have been a bad thing to do.

In fourth year, I could see the end in sight. Grad school applications needed to be done pronto and some interesting job prospects lured me away from yet more years of school. Co-op didn't help keep me in school, I enjoyed the working world. I know there are others that used co-op to find that the working world wasn't for them. I expect those people to be in some school for a good long time.

Now we are at the end, and the cycle is complete. I've been across the country, lived over in sunny California, and biked through Scotland, but no where has compared to Waterloo, or the great people that make it such a wonderful place to be. I'm sad to go, as I'm sure many of you are, but I hope you are excited about the next step at the same time.

That was my 5 years, in a non-chronologically accurate order. But it's been even better to help and see people do amazing things. Small things, like getting a group of friends together to go get pints of Bubbletea. To large things like running frosh week for thousands of first year students.

Now that we have looked at the past, what about the future? One of the things I didn't wan to say during this speech is that "We are the future". What does that even mean? Are we useless now? I don't know what it means, it could even be partially true, but we are not useless. In fact our time is now! Among this graduating class are those who are doing cutting edge research. There are those we are already running their own companies. There are those who are already half-way through there plan to rule the world. There are even those of us who are simply going to help others do those things. So, we are not "the future", we are "the now".

Being "the now", (don't I sound like Dubya?) is one thing, but we should always be "the now". We can always make now be our time. We should do this because if we aren't the ones living happily and making the world a better place, in our own ways, then who is going to do it?

If nothing else, I really hope everyone lives happily. For me, I found if I can keep my hat then I can be happy. Well, I can be happy promoting "No Pants Day"!

DOWN WITH PANTS!!

At the end, I finally figured out the specification for this speech. It's simple: Remind people of the awesome things they have done here, the amazing people they shouldn't forget. Lastly, to convince people to keep doing the awesome things despite what might happen or what obstacles appear.

Thank you, I enjoyed being your VD today.

6 July 2010

Matt Zimmerman: We ve packaged all of the free software what now?

Today, virtually all of the free software available can be found in packaged form in distributions like Debian and Ubuntu. Users of these distributions have access to a library of thousands of applications, ranging from trivial to highly sophisticated software systems. Developers can find a vast array of programming languages, tools and libraries for constructing new applications. This is possible because we have a mature system for turning free software components into standardized modules (packages). Some software is more difficult to package and maintain, and I m occasionally surprised to find something very useful which isn t packaged yet, but in general, the software I want is packaged and ready before I realize I need it. Even the long tail of niche software is generally packaged very effectively. Thanks to coherent standards, sophisticated management tools, and the principles of software freedom, these packages can be mixed and matched to create complete software stacks for a wide range of devices, from netbooks to supercomputing clusters. These stacks are tightly integrated, and can be tested, released, maintained and upgraded as a unit. The Debian system is unparalleled for this purpose, which is why Ubuntu is based on it. The vision, for a free software operating system which is highly modular and customizable, has been achieved. Rough edges This is a momentous achievement, and the Debian packaging system fulfills its intended purpose very well. However, there are a number of areas where it introduces friction, because the package model doesn t quite fit some new problems. Most of these are becoming more common over time as technology evolves and changes shape. Why are we stuck?
I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail.
Abraham Maslow
The packaging ecosystem is very strong. Not only do we have powerful tools for working with packages, we also benefit from packages being a well-understood concept, and having established processes for developing, exchanging and talking about them. Once something is packaged, we know what it is and how to work with it, and it fits into everything else. So, it is tempting to package everything in sight, as we already know how to make sense of packages. However, this may not always be the right tool for the job. Various attempts have been made to extend the packaging concept to make it more general, for example: Other package managers aim to solve a specific problem, such as providing lightweight package management for embedded systems, or lazy dependency installation, or fixing the filesystem hierarchy. There is a long list of package managers of various levels which solve different problems. Most of these systems suffer from an important fundamental tradeoff: they are designed to manage the entire system, from the kernel through applications, and so they must be used wholesale in order to reap their full benefit. In other words, in their world, everything is a package, and anything which is not a package is out of scope. Therefore, each of these systems requires a separate collection of packages, and each time we invent a new one, its adherents set about packaging everything in the new format. It takes a very long time to do this, and most of them lose momentum before a mature ecosystem can form around them. This lock-in effect makes it difficult for new packaging technologies to succeed. Divide and Conquer No single package management framework is flexible enough to accommodate all of the needs we have today. Even more importantly, a generic solution won t account for the needs we will have tomorrow. I propose that in order to move forward, we must make it possible to solve packaging problems separately, rather than attempting to solve them all within a single system. But I like things how they are! We don t have a choice. The world is changing around us, and distributions need to evolve with it. If we don t adapt, we will eventually give way to systems which do solve these problems. Take, for example, modern web browsers like Firefox and Chromium. Arguably the most vital application for users, the browser is coming under increasing pressure to keep up with the breakneck pace of innovation on the web. The next wave of real-time collaboration and multimedia applications relies on the rapid development of new capabilities in web browsers. Browser makers are responding by accelerating deployment in the field: both aggressively push new releases to their users. A report from Google found that Chrome upgrades 97% of their users within 21 days of a new release, and Firefox 85% (both impressive numbers). Mozilla recently changed their maintenance policies, discontinuing maintenance of stable releases and forcing Ubuntu to ship new upstream releases to users. These applications are just the leading edge of the curve, and the pressure will only increase. Equally powerful trends are pressing server applications, embedded systems, and data to adapt as well. The ideas I ve presented here are only one possible way forward, and I m sure there are more and better ideas brewing in distribution communities. I m sure that I m not the only one thinking about these problems. Whatever it looks like in the end, I have no doubt that change is ahead.

4 July 2010

Torsten Landschoff: Postprocessing conference videos

I was planning to attend DebConf New York this year, but for a number of reasons I decided not to go. Fortunately, Ferdinand Thommes organized a MiniDebConf in Berlin at LinuxTag and I managed to attend. Thanks, Ferdinand! There were a number of interesting Talks. I especially liked the talk of our DPL, and those about piuparts and git-buildpackage. In contrast to the other LinuxTag talks, we had a livestream of our talks and recorded (most) of them. The kudos for setting this up goes to Alexander Wirt, who spent quite a few hours to get it up and running. I have to apologize for being late in bringing my Notebook, which was intended to do the theora encoding of the livestream. This was a misunderstanding on my part, I should have known that this is not going to be setup in the night before show time So to compensate the extra hours he had to put in for me, I offered to do the post processing of the videos. Basic approach for post processing The main goal of post processing the videos was (of course) to compress them to a usable size from the original 143 GB. I also wanted to have a title on each video, and show the sponsors at the end of the video. My basic idea to implement that consisted of the following steps:
  1. Create a title animation template.
  2. Generate title animations from template for all talks.
  3. Use a video editor to create a playlist of the parts title talk epilogue.
  4. Run the video editor in batch mode to generate the combined video.
  5. Encode the resulting video as ogg theora.
As always with technology, it turned out that the original plan needed a few modifications. Title animations
<video controls="controls" height="288" src="http://www.landschoff.net/blog/uploads/2010/07/mdc2010_title_anim1.ogv" width="360 "></video>
Originally I wanted to use Blender for the title animation, but I knew it is quite a complicated bit of software. So I looked for something simpler, and stumbled across an article that pointed me towards Synfig Studio for 2D animation. This is also in Debian, so I gave it a try. I was delighted that Synfig Studio has a command line renderer which is just called synfig and that the file format is XML, which would make it simple to batch-create the title animations. My title template can be found in this git repository. Batch creation of title animations I used a combination of make and a simple python script to replace the author name and the title of the talk into the synfig XML file. The data for all talks is another XML file talks.xml. Basically, I used a simple XPath expression to find the relevant text node and change the data using the ElementTree API of lxml python module. The same could be done using XSLT of course (for a constant replacement, see this file) but I found it easier to combine two XML files in python. Note that I create PNG files with synfig and use ffmpeg to generate a DV file from those. Originally, I had synfig create DV files directly but those turned out quite gray for some reason. I am now unable to reproduce this problem. Combining the title animation with the talk For joining the title animation with the talk, I originally went with OpenShot, which somebody of the video team had running at the conference. My idea was to mix a single video manually and just replace the underlying data files for each talk. I expected that this would be easy using the openshot-render command, which renders the output video from the input clips and the OpenShot project file. However, OpenShot stores the video lengths in the project file and will take those literally, so this did not work for talks of different play times I considered working with Kino or Kdenlive but they did not look more appropriate for this use case. I noticed that OpenShot and Kdenlive both use the Media Lovin Toolkit under the hood, and OpenShot actually serializes the MLT configuration to $HOME/.openshot/sequence.xml when rendering. I first tried to read that XML file from python (using the mlt python bindings from the python-mlt2 package) but did not find an API function to do that. So I just hard coded the video sequence in python. I ran into a few gotchas on the way: Things to improve While the results look quite okay for me now, there is a lot of room for improvement. Availability

1 July 2010

Kees Cook: reporting all execs

I recently learned about the process event connector, and went looking for an example program that could report all the exec()s that happen on my system to help with debugging things like AC plug/unplug scripts, etc. After cleaning it up and adding some features to do a simple best-effort cmdline reporting, I ve now got a tool that will report every program run on a system:
$ sudo ./cn_proc
sending proc connector: PROC_CN_MCAST_LISTEN... sent
Reading process events from proc connector.
Hit Ctrl-C to exit
event: exec 17514 17514: ls -AF --color=auto (unconfined)
event: exec 17516 17516: date +%H:%M (unconfined)
event: exec 17518 17518: whoami (unconfined)
Change the values show_event, show_seq, show_cpu, show_security_context to set the reporting defaults. Or, if someone is feeling bored, it would rock to add getopt support instead. It seems strange to me that only CAP_NET_ADMIN is needed to get access to this information.

Petter Reinholdtsen: Caching password, user and group on a roaming Debian laptop

For a laptop, centralized user directories and password checking is a bit troubling. Laptops are typically used also when not connected to the network, and it is vital for a user to be able to log in or unlock the screen saver also when a central server is unavailable. This is possible by caching passwords and directory information (user and group attributes) locally, and the packages to do so are available in Debian. Here follow two recipes to set this up in Debian/Squeeze. It is also possible to set up in Debian/Lenny, but require more manual setup there because pam-auth-update is missing in Lenny. LDAP/Kerberos + nscd + libpam-ccreds + libpam-mklocaluser/pam_mkhomedir This is the traditional method with a twist. The password caching is provided by libpam-ccreds (version 10-4 or later is needed on Squeeze), and the directory caching is done by nscd. The directory lookup and password checking is done using LDAP. If one want to use Kerberos for password checking the libpam-ldapd package can be replaced with libpam-krb5 or libpam-heimdal. If one is happy having a local home directory with the path listed in LDAP, one can use the pam_mkhomedir module from pam-modules to make this happen instead of using libpam-mklocaluser. A setup for pam-auth-update to enable pam_mkhomedir will have to be written until a fix for bug #568577 is in the archive. Because I believe it is a bad idea to have local home directories using misleading paths like /site/server/partition/, I prefer to create a local user with the home directory in /home/. This is done using the libpam-mklocaluser package. These packages need to be installed and configured
libnss-ldapd libpam-ldapd nscd libpam-ccreds libpam-mklocaluser
The ldapd packages will ask for LDAP connection information, and one have to fill in the values that fits ones own site. Make sure the PAM part uses encrypted connections, to make sure the password is not sent in clear text to the LDAP server. I've been unable to get TLS certificate checking for a self signed certificate working, which make LDAP authentication unsafe for Debian Edu (nslcd is not checking if it is talking to the correct LDAP server), and very much welcome feedback on how to get this working. Because nscd do not have a default configuration fit for offline caching until bug #485282 is fixed, this configuration should be used instead of the one currently in /etc/nscd.conf. The changes are in the fields reload-count and positive-time-to-live, and is based on the instructions I found in the LDAP for Mobile Laptops instructions by Flyn Computing.
	debug-level		0
	reload-count		unlimited
	paranoia		no
	enable-cache		passwd		yes
	positive-time-to-live	passwd		2592000
	negative-time-to-live	passwd		20
	suggested-size		passwd		211
	check-files		passwd		yes
	persistent		passwd		yes
	shared			passwd		yes
	max-db-size		passwd		33554432
	auto-propagate		passwd		yes
	enable-cache		group		yes
	positive-time-to-live	group		2592000
	negative-time-to-live	group		20
	suggested-size		group		211
	check-files		group		yes
	persistent		group		yes
	shared			group		yes
	max-db-size		group		33554432
	auto-propagate		group		yes
	enable-cache		hosts		no
	positive-time-to-live	hosts		2592000
	negative-time-to-live	hosts		20
	suggested-size		hosts		211
	check-files		hosts		yes
	persistent		hosts		yes
	shared			hosts		yes
	max-db-size		hosts		33554432
	enable-cache		services	yes
	positive-time-to-live	services	2592000
	negative-time-to-live	services	20
	suggested-size		services	211
	check-files		services	yes
	persistent		services	yes
	shared			services	yes
	max-db-size		services	33554432
While we wait for a mechanism to update /etc/nsswitch.conf automatically like the one provided in bug #496915, the file content need to be manually replaced to ensure LDAP is used as the directory service on the machine. /etc/nsswitch.conf should normally look like this:
passwd:         files ldap
group:          files ldap
shadow:         files ldap
hosts:          files mdns4_minimal [NOTFOUND=return] dns mdns4
networks:       files
protocols:      files
services:       files
ethers:         files
rpc:            files
netgroup:       files ldap
The important parts are that ldap is listed last for passwd, group, shadow and netgroup. With these changes in place, any user in LDAP will be able to log in locally on the machine using for example kdm, get a local home directory created and have the password as well as user and group attributes cached. LDAP/Kerberos + nss-updatedb + libpam-ccreds + libpam-mklocaluser/pam_mkhomedir Because nscd have had its share of problems, and seem to have problems doing proper caching, I've seen suggestions and recipes to use nss-updatedb to copy parts of the LDAP database locally when the LDAP database is available. I have not tested such setup, because I discovered sssd. LDAP/Kerberos + sssd + libpam-mklocaluser A more flexible and robust setup than the nscd combination mentioned earlier that has shown up recently, is the sssd package from Redhat. It is part of the FreeIPA project to provide a Active Directory like directory service for Linux machines. The sssd system combines the caching of passwords and user information into one package, and remove the need for nscd and libpam-ccreds. It support LDAP and Kerberos, but not NIS. Version 1.2 do not support netgroups, but it is said that it will support this in version 1.5 expected to show up later in 2010. Because the sssd package was missing in Debian, I ended up co-maintaining it with Werner, and version 1.2 is now in testing. These packages need to be installed and configured to get the roaming setup I want
libpam-sss libnss-sss libpam-mklocaluser
The complete setup of sssd is done by editing/creating /etc/sssd/sssd.conf.
[sssd]
config_file_version = 2
reconnection_retries = 3
sbus_timeout = 30
services = nss, pam
domains = INTERN
[nss]
filter_groups = root
filter_users = root
reconnection_retries = 3
[pam]
reconnection_retries = 3
[domain/INTERN]
enumerate = false
cache_credentials = true
id_provider = ldap
auth_provider = ldap
chpass_provider = ldap
ldap_uri = ldap://ldap
ldap_search_base = dc=skole,dc=skolelinux,dc=no
ldap_tls_reqcert = never
ldap_tls_cacert = /etc/ssl/certs/ca-certificates.crt
I got the same problem here with certificate checking. Had to set "ldap_tls_reqcert = never" to get it working. With the libnss-sss package in testing at the moment, the nsswitch.conf file is update automatically, so there is no need to modify it manually. If you want to help out with implementing this for Debian Edu, please contact us on debian-edu@lists.debian.org.

30 June 2010

Vincent Sanders: Programmers are suckers for a meme

Many Open Source projects have and IRC # for developers. The NetSurf project is no different. During a discussion someone jokingly suggested that one contributor should be asked to take the FizzBuzz test. Can you guess what happened next?

Ten minutes later Michael Drake posted this solid example in C which is where it all ought to have ended.

<iframe src="http://pastebin.com/embed_iframe.php?i=MesmvSjk" style="border:none;width:100%;height:200px;"></iframe>

Being programmers, of course this had a predictable result. The original question, the reason for asking it and any the serious point being made in the original article were discarded. Just so everyone (including myself) could play silly buggers over our lunch break. Coders, it would seem, simply like to produce a solution even if it is only for fun.

None of these programs took more than ten minutes (except the JAVA monstrosity), are reproduced with permission and I am to blame for none of them (ok maybe just the one ;-).

First up was Rob Kendrick with the classic solution in C (his day job is as a support team lead which seems to make those programmers who cannot do this seem even more scary bad.)

<iframe src="http://pastebin.com/embed_iframe.php?i=EaQ2414U" style="border:none;width:100%;height:200px;"></iframe>

Next was Daniel Silverstone who turned this Lua solution out very quickly and berated the rest of us for not following the rules ;-)

<iframe src="http://pastebin.com/embed_iframe.php?i=cYY0YDYM" style="border:none;width:100%;height:220px;"></iframe>

The final C solution was my own uber silly sieve implementation

<iframe src="http://pastebin.com/embed_iframe.php?i=5w5BhKt3" style="border:none;width:100%;height:200px;"></iframe>

Peter Howkins decided the world required a solution in PHP

<iframe src="http://pastebin.com/embed_iframe.php?i=h2aQ5eXM" style="border:none;width:100%;height:200px;"></iframe>

When pointed out that his solution stopped at 50 he presented this vastly superior and obviously idiomatic solution

<iframe src="http://pastebin.com/embed_iframe.php?i=k8T6VtJu" style="border:none;width:100%;height:200px;"></iframe>

Finally after a long time James Shaw caused mental anguish and wailing with this abomination unto Nuggin.

<iframe src="http://pastebin.com/embed_iframe.php?i=GFeHdJdr" style="border:none;width:100%;height:200px;"></iframe>

With Luck everyone has now got it out of their system and we will never have to put up with this again (yeah right). And now you also know why Open Source projects sometimes take ages to release ;-)

Ingo Juergensmann: Getting hit by a spammer with Exim

Yesterday I was warned by Nagios that something is going on with my server. The number of processes has been gone beyond the limit. The reason for this were a bunch of Exim processes trying to deliver a lot of mails. Apparently a spammer made it happen to send spams via my server. How could this happen? I was seeing a lot of those log entries:
2010-06-28 16:29:25 1OTFKt-0004cZ-1R <= vsvc@euhu.com H=(qknlvj.com) [58.212.194.230] P=esmtpa A=cram_md5:inna S=1455 id=0ec5ff00b06c43369e2582fc4269839e@e12c17c51ec546bf9e7a23e6f9875941
2010-06-28 16:29:27 1OTFKw-0004cZ-KZ <= ebms@ylmdbm.com H=(qknlvj.com) [58.212.194.230] P=esmtpa A=cram_md5:inna S=1520 id=58913c34bde64e908310db7e1280eff5@2dc8ed5998b64e8485c472cae5ef98c3
2010-06-28 16:29:28 1OTFKy-0004cZ-1p <= wiyscy@hegyogz.com H=(qknlvj.com) [58.212.194.230] P=esmtpa A=cram_md5:inna S=1436 id=814a7bdcbe85447a9283d4a0a074830b@0ada3cde4a4c41c38c65bc912639afb6
Apparently the spammer has successfully found a way to bypass the authenticators in Exim. By default only authenticated users can send mails via my mailserver, of course. But this spammer found a way around that problem. A user "inna" is not known, so the spammer shouldn't be able to send mails at all. But he can. Something is broken apparently. The spammer sent an empty password ('') and the database didn't find an user by this name and returned an empty resultset (''). Both sides of the comparison matches and the mail is allowed in. Let's have a look at my Exim config:
cram_md5:
server_debug_print = "running smtp auth $1 $2"
driver = cram_md5
public_name = CRAM-MD5
server_secret = $ lookup pgsql select clear from passwd where passwd.usr='$1' limit 1 $value
server_set_id = $1
On #exim@freenode there was just another user with the very same problem with exactly the same spammer. Apparently the lookup is true for empty passwords or users. The solution is to add a "fail" in the lookup statement:
server_secret = $ lookup pgsql select clear from passwd where passwd.usr='$1' limit 1 $value fail
That's pretty all to do to prevent the spamming. But how could this happen at all? Back then when I was configuring my mailserver (around 2003 or so) I can remember that I tried a "fail" statement in the server_secret as it is described in the Exim documentation, but it didn't work as expected. So I ended up with no "fail". This worked fairly well over the years and I remember that I tested this lookup by trying to send with user/password combinations of all different sorts. So it went into "production". Apparently it doesn't work anymore today. The other guy on the #exim channel said that he found no database lookup example with "fail" at all. Even the example in one of his books was without "fail". So I believe that something changed either in Exim or in PostgreSQL to make submitting an empty password string a positive match for bypassing authentication nowadays. For the records: the spammer send approx. >10.000 mails. Another bunch of 8000 mails were rejected, but this is just slightly over the daily average.

Dirk Eddelbuettel: Rcpp 0.8.3

A new version 0.8.3 of Rcpp is now CRAN and in Debian. It comes about three weeks after the 0.8.2 release. And even though we promised to concentrate on documentation, it contains a raft of new features: The main thing here is Rcpp sugar for which we also have a new (seventh !!) vignette Rcpp-sugar. As a quick example, consider this simple C++ function that takes two vectors from R and creates a new one conditional on the relative values:
export "C" SEXP foo( SEXP xs, SEXP ys)  
    Rcpp::NumericVector x(xs), y(ys);
    int n = x.size();
    Rcpp::NumericVector res( n );
    double xd = 0.0, yd = 0.0 ;
    for( int i=0; i<n; i++) 
        xd = x[i];
        yd = y[i];
        if( xd < yd ) 
            res[i] = xd * xd ;
          else  
            res[i] = -( yd * yd);
         
     
    return res ;
 
Now, if you use R, you really want to writes this more compactly. And now you can, thanks to Rcpp sugar:
extern "C" SEXP foo( SEXP xs, SEXP ys) 
    Rcpp::NumericVector x(xs), y(xs);
    return ifelse( x < y, x*x, -(y*y));
 
Same great taste, but much less filling! More details are in the Rcpp-sugar vignette. Doug Bates is already a fan of this and is employing it in the lme4a development version of the well-known lme4 package. The full NEWS entry for this release follows below:
0.8.3   2010-06-27
    o	This release adds Rcpp sugar which brings (a subset of) the R syntax
        into C++. This supports : 
         - binary operators : <,>,<=,>=,==,!= between R vectors
         - arithmetic operators: +,-,*,/ between compatible R vectors
         - several functions that are similar to the R function of the same name:
        abs, all, any, ceiling, diff, exp, ifelse, is_na, lapply, pmin, pmax, 
        pow, sapply, seq_along, seq_len, sign
        
        Simple examples :
        
          // two numeric vector of the same size
          NumericVector x ;
          NumericVector y ;
          NumericVector res = ifelse( x < y, x*x, -(y*y) ) ;
        
          // sapply'ing a C++ function
          double square( double x )  return x*x ;  
          NumericVector res = sapply( x, square ) ;
        
        Rcpp sugar uses the technique of expression templates, pioneered by the 
        Blitz++ library and used in many libraries (Boost::uBlas, Armadillo). 
        Expression templates allow lazy evaluation of expressions, which 
        coupled with inlining generates very efficient code, very closely 
        approaching the performance of hand written loop code, and often
        much more efficient than the equivalent (vectorized) R code.
        
        Rcpp sugar is curently limited to vectors, future releases will 
        include support for matrices with sugar functions such as outer, etc ...
        
        Rcpp sugar is documented in the Rcpp-sugar vignette, which contains
        implementation details.
    o   New helper function so that "Rcpp?something" brings up Rcpp help
    o   Rcpp Modules can now expose public data members
    o   New classes Date, Datetime, DateVector and DatetimeVector with proper
        'new' API integration such as as(), wrap(), iterators, ...
    o   The so-called classic API headers have been moved to a subdirectory
        classic/ This should not affect client-code as only Rcpp.h was ever
        included.
    o   RcppDate now has a constructor from SEXP as well
    o   RcppDateVector and RcppDatetimeVector get constructors from int
        and both const / non-const operator(int i) functions
        
    o   New API class Rcpp::InternalFunction that can expose C++ functions
    	to R without modules. The function is exposed as an S4 object of 
    	class C++Function
As always, even fuller details are in Rcpp Changelog page and the Rcpp page which also leads to the downloads, the browseable doxygen docs and zip files of doxygen output for the standard formats. A local directory has source and documentation too. Questions, comments etc should go to the rcpp-devel mailing list off the R-Forge page

27 June 2010

Filippo Giunchedi: using git-svn with rsync

From time to time I find myself using git-svn with projects using subversion, this is all nice and fine but it takes quite some time to do the ''initial import'' if you are doing it over a remote transport such as ssh+svn. One trick to speed things up is to use rsync to copy the svn repo locally and then ''git-svn'' it from your harddisk. The idea is originally documented at the allegro wiki For example a typical sourceforge project will be done like this:
DESTDIR=/your/dest
PROJECTNAME=vde
PROJECTURL=https://$PROJECTNAME.svn.sourceforge.net/svnroot/$PROJECTNAME
SVN_COPY=$(mktemp -d)
rsync -c -av $PROJECTNAME.svn.sourceforge.net::svn/$PROJECTNAME/'*' $SVN_COPY
mkdir -p $DESTDIR
cd $DESTDIR
git svn init file://$SVN_COPY --rewrite-root=$PROJECTURL --stdlayout
git svn fetch
# ... git svn imports the repo ...
sed -i 's@url =.*@url = $PROJECTURL' .git/config
rm -rf $SVN_COPY
The important bit is to remember to update the url key after updating otherwise subsequent commits will go to your rsync-ed repo and not the original one!

Next.

Previous.