How Not To Name Files

:date: 2022-03-05 07:39 :tags:

I was doing some quick operations on a couple of images in /tmp/ and I ran this simple ImageMagick command to quickly see exactly what their dimensions were.

$ identify /tmp/*jpg

Simple, right? I was pretty surprised to get this output.

/tmp/image1.jpg JPEG 520x473 520x473+0+0 8-bit sRGB 28564B 0.000u 0:00.000
/tmp/image2.jpg JPEG 446x307 446x307+0+0 8-bit sRGB 43772B 0.000u 0:00.000
identify-im6.q16: unable to open image
`/tmp/systemd-private-dc07b3ba0d8d4a5bb3f871d462a4c015-systemd-logind.service-9rFjpg':
Permission denied @ error/blob.c/OpenBlob/2924.

What's going on there? Well, it seems that this is a flaw in Systemd, the double edged sword of Damocles which tries to make Linux less Linuxy (unfortunately).

In its internal housekeeping, Systemd has created a temporary file in a public temporary file location that ends in a random string. And in this case, luck runs out and today's file's random string is 9rFjpg, which of course ends in jpg, just like the well known photography file format.

Although Systemd is both irritating and useful, I don't mean to single it out. This is really a problem with the unix mktemp command which uses the C mkstemp() function from stdlib.h. So this is a pretty deep problem.

You could argue that I should have done what DOS people were trained to do and specify my shell glob as *.jpg. But why? If we're going to have extensions be a thing at all (and trigger all kinds of automatic responses), surely we should respect them and not write random strings to the end of filenames. (Especially if we're delimiting parts of the filename with dashes instead of periods!) That's certainly my opinion and I'm posting this to encourage others  —  and my future self  —  to consider this a mistake and not make it. But given this problem, when doing serious scripting it probably does make sense to be defensive when specifying files by extension and insist on the period too if possible. That may not actually solve all problems of this type but it should cure most issues with default mkstemp() filenames.