Категория: Компьютеры

Заметки о программировании и на околокомпьютерные темы

Вложенные категории: Игры, Delphi

Apache cannot serve files with unicode filenames

I've had a problem with my Apache setup where it couldn't serve images with unicode characters in file names:

 <a href="http://www.boku.ru/img/проверка.jpg">http://www.boku.ru/img/проверка.jpg</a> (really missing right now; just an example)

SCP client (WinSCP) clearly showed files were present, other files from the same folder could be accessed but those with cyrillic characters were returning 404.

Using Wireshark, I determined my browser sends urlencoded text (B0%D0…) instead of bare unicode, but that was, apparently, like it should be.

Studying Apache logs, I've found it complain about missing files, re-encoded in \x notation (\xb0\xd0…). For a while I thought this suggested a problem, but in the end it was unrelated and probably correct behavior.

Turns out, WinSCP does not use UTF-8 by default. Instead it sends file names to server in the local PC encoding, Win-1251 in my case. Looking through WinSCP everything seemed alright because it reads filenames back in the same encoding. But from the server point of view (as seen through SSH for example) those were not Russian characters but some Krakozyabry.

In other words, there really was no проверка.jpg.

To recongifure WinSCP, open Site manager, press Edit, Advanced, "UTF-8 encoding for file names: On", then reconnect. You'll have to rename all affected files.

WordPress not remembering name or email for anonymous commenters

Someone reported that WordPress at boku.ru hasn’t been remembering the name and email which you enter in comments. I vaguely remembered this working before. After some investigation, turns out it was W3 Total Cache plugin which uses comment_cookie_lifetime filter to drop standard WordPress cookie lifetime from half a year to 30 minutes. And since my site runs as GMT, this was eaten by the 4-hour time difference.

W3 Total Cache did that because for cookie-less visitors it serves fast static version of the page (which can not be tailored for each visitor and have their name pre-entered, the way names are handled now). As long as you have posted a comment, you receive a cookie and WordPress serves you slower, dynamic version of the page. So the longer the cookie lifetime is, the longer you’re going to be served dynamic pages (but the longer your settings are going to be preserved).

This setting can be changed at “Performance > Page Cache > Advanced > Comment cookie lifetime”.

If you’ve stumbled upon this post while solving a related problem, here’s some additional pointers:
1. WordPress stores commenter name/email/url in cookies:
comment_author_*
comment_author_email_*
comment_author_url_*

An example of how querying for these values should look like is in /wp-includes/comment-template.php/comments_template()

2. Your comment form is generated either by this, or by customization hook in your theme’s comments.php.

3. To debug cookies, add print_r($_COOKIES); to your theme’s header.php, don’t forget to remove it later. Use Wireshark or your browser’s request sniffer to track what’s being sent.

Всегда занят

Invisible – бесполезный режим в мессенджерах, поскольку всё, что он делает – это пытается забанить человека под благовидным предлогом, не портя с ним отношения, и длится это ровно до первого раза, когда вы спалитесь, ответив из инвиза.
Ну, конечно, есть умельцы, которые из принципа постоянно в инвизе, и это правильно, поскольку создаёт основания для plausible deniality, но тогда они вообще не пользуются статусом, получается.
Гораздо убедительней было бы “‘Занят/нет на месте’ для этого человека”. Во-первых, даже если вы заняты, вы можете отвлечься и ответить, когда захотите. Во-вторых, существует тысяча причин иметь такой статус постоянно (например, вы выставили его на мобильнике, т.к. оттуда общаться неудобно).

Чтобы действительно познакомиться с товаром перед покупкой, нужно искать в гугле “[товар] отстой”, “[товар] глючит”, “[товар] не покупайте”. А чтобы проверить, нельзя ли в программе случайно спалить свои личные данные, нужно погуглить “[программа] расшарить данные”. У вас и у этих людей дополняющие друг друга цели: вы хотите исключить любую лазейку, а они – какую-нибудь найти.

Can you repeat that?

Reading personal experiences on trimming the sizes of Delphi executables, I often encounter stories like this one:

I’ve moved from Delphi 2007 to Delphi XE3 and my executable went from 3Mb to 18Mb! I did this thing and that thing and disabled RTTI and set these flags and got the executable down to 16Mb. Nice, but not enough.
Then I discovered UPX and it reduced the size to 3.5Mb! UPX is magic!!

This is obviously wrong, it should make anyone with half a pint of a sense cringe – but why is it wrong? They got their size down. That’s what they wanted.

And then I figured:
Well, you got it down to 3Mb. Can you repeat that?

If Delphi XE8 comes out and your executable is suddenly 17Mb again, what are you going to do to trim it back? If you had spent several hours more and actually understood what happened and how to unhappen that, then you’d still be on a fair footing with the circumstances. Your trump card of using UPX and being excited would still be with you. And now it isn’t.

Right-click to copy web path for the file

Everybody who uses Dropbox have probably seen that you can right-click the file and “Copy shared path”, under which it is accessible in the internet.

I thought it would be nice to have similar functionality for BTSync and wrote the following sсript.

Code on pastebin.

Usage: put the code into “Copy links.cmd”, drop the shorcut to it into “C:\Users\[your username]\AppData\Roaming\Microsoft\Windows\SendTo” or wherever Sent To folder is in your versions of Windows.

Now suppose you have a folder C:\Download\images which is BTSync-ed to your server as http://example.org/lib/img. Create a file C:\Download\images\path.txt and write the above web base path to it.

Now select some files, right-click them and press “Send To -> Copy Links”. Web links for all the selected images are copied into your clipboard:

C:\Download\images\test\file.png --> http://example.org/lib/img/test/file.png

The sсript can also be used if you have a web server running at home which presents some of the files on your PC to the outside world, or even if you share some files and want to copy those as “\\mypc\share\path”. Since the sсript looks for the first available path.txt in the parent directories, you can link different folders to different addresses, or even copy and modify the sсript so that the same folder is linked to several base paths (“Copy as web address”, “Copy as local \\share”).

Как работать с двумя аккаунтами SpiderOak одновременно

Так же, как несколько аккаунтов в Picasa, можно сделать несколько аккаунтов SpiderOak.

Зачем? На SpiderOak удобно бэкапить сервер, но использовать для этого домашний аккаунт не рекомендую. Лучше завести отдельный, тогда если сервер взломают, то получат доступ только к его данным.

В принципе, достаточно зарегистрироваться, настроить сервер и забыть о нём – бэкапы сами будут сбрасываться. Но иногда SpiderOak нужно администрировать – например, удалять старые версии удалённых файлов, это удобнее делать из графической оболочки. А переключаться между аккаунтами неудобно.

Заведите ещё один аккаунт Windows и настройте под ним SpiderOak на тот аккаунт, который используете для бэкапа на сервере. Теперь SpiderOak можно запускать из обычного аккаунта по Shift+правой клавише – “Запуск от имени другого пользователя”.

У многих сайтов есть очень удобные “мобильные версии”:

Вконтакте: m.vk.com
Твиттер: mobile.twitter.com
Гугл+: plus.google.com/app/basic/

Gmail: вариант 1, варианта 2
Google Calendar: google.com/calendar/m
Google Tasks: mail.google.com/tasks/ (и ещё такая вот версия для планшетов)

Diary: m.diary.ru

Обычно они 1. компактнее, 2. без графического мусора, 3. без javasсript, 4. используют мало трафика. Особенно удобно добавлять их как панели в Оперу – тогда все ленты постоянно под рукой.

Другие сайты, которые я не пробовал использовать:
Facebook: m.facebook.com
Evernote: evernote.com/mobile
Яндекс: m.yandex.ru и op.yandex.ru
Dropbox: dropbox.com/m
box.com: m.app.box.com

Скачка youtube-видео из командной строки

Чтобы спать спокойно, нужно скачивать всё, в том числе видео с ютюба, потому, что если тот ролик с котёнком удалят, и главное, вас не предупредят, то вы о нём так никогда и не вспомните и не узнаете, что его нужно заново найти и добавить. Короче говоря, есть утилита:

youtube-dl

Которая написана на питоне и умеет всё. Любая функция, которая приходит в голову, там сделана. Скачать канал? Favorites? Likes? С сабами? Вшить их в видео? Описание положить рядом? Она даже устанавливает дату создания файла такой, какая она на ютюбе. И работает из коробки.

В качестве бонуса: адрес канала Liked Videos можно получить из адреса Favorites для того же пользователя, заменив первую букву в параметре list c “F” на “L”. Каналы открыты, пароль указывать не надо, но в канале Liked хранятся последние 100 лайков, так что скачивать лайкнутое нужно регулярно.

Silk Road demise

Так вот, к чему я вспомнил. Пока в телевизоре закончился один Breaking Bad, другой Брейкин Бэд закончился в реальной жизни. Преступный супермаркет Silk Road закрыли американские спецслужбы, а его хозяина Dreaded Pirate Roberts арестовали. Случилось это не потому что NSA вскрыло Tor, как все думали после недавнего ареста The Freedom Hosting, а просто DPR спалился.

The silk road was basically made from the shroomery.com, it was the first place he visited. They traced him by finding his old posts on various forums where he advertised it, not as the owner, just saying “I found this site, what do you think about it?”

комментарий на реддите с кучей интересной инфы

Рекламировал Silk Road под тем же ником, под которым в другом месте постил свой email – этого стало достаточно, чтобы его заподозрили. Владельцем оказался Росс Ульбрихт, молодой образованный парень, физик и экономист из какого-то там университета. Имея до 800 000 биткоинов (3.5 миллиарда рублей по текущему курсу), жил под фальшивым именем в коммуналке со студентотой, а серверами Silk Road управлял из ближайшего кафе с ноутбука. Когда человек под ником friendly chemist стал его шантажировать, по-джентельменски вежливо заказал его убийство:

DPR sent a message to “readandwhite,” stating that “friendly chemist” is “causing me problems,” and adding: “I would like to put a bounty on his head if it’s not too much trouble for you. What would be an adequate amount to motivate you to find him?

readandwhite sent DPR a message quoting him a price of $150k to $300 “depending on how you want it done”

DPR responded: “Don’t want to be a pain here, but the price seems high. Not long ago, I had a clean hit done for $80k.”

DPR and readandwhite agreed upon a price of 1,670 Bitcoin – approximately $150k – for the job.

Several hours later on March 31, 2013, readandwhite wrote back: “I received the payment… We know where he is. He’ll be grabbed tonight.”

Subsequent messages reflect, at DPR’s request, readandwhite sent DPR a picture of the victim after the job was done…DPR wrote readandwhite “I’ve received the picture and deleted it. Thank you for your swift action.”

Ho. Lee. Shit.

комментарий на реддите

Правда, Reddit уже сомневается, что этот случай так прост. Friendly chemist требовал за краденые аккаунты пользователей 500 килобаксов, которые должен был кредитору. Ульбрихт попросил связать его с кредитором и заказал химика именно ему. Но это же глупо. Что, если химик и кредитор его обманут? Ульбрихт мог просто пугать химика, рассчитывая, что тот струсит, увидев, что Ульбрихт правда его заказал. Во всех отношениях удобно, и химику остаётся только притвориться мёртвым и уйти на дно, иначе в следующий раз Ульбрихт закажет его кому-нибудь другому (и тот уже по правде его убьёт).

Всплывают и другие истории, в одной из которых DPR якобы заказал пытки и казнь работника, пошедшего на сделку с полицией. Неожиданный поступок для идеалиста-либертарианца, по его собственным словам, выступавшего не за наркотики, а за принцип, и запрещавшего на своём сайте торговлю ЦП, оружием и контрактами на убийство:

“What we’re doing isn’t about scoring drugs or ‘sticking it to the man.’ It’s about standing up for our rights as human beings and refusing to submit when we’ve done no wrong.”
“Silk Road is a vehicle for that message,” he writes to me from somewhere in the Internet’s encrypted void. “All else is secondary.”

Интервью DPR в Forbes

Понятно, что Росс Ульбрихт попался на ерунде, но вообще он шифровался круто: сервер держал в другой стране, секретную жизнь тщательно скрывал. Прямо Волтер Вайт/Гейзенберг на самом деле. Я потерял ссылку, но в каком-то из интервью DPR спросили, страшно ли ему, и он сказал, что очень страшно. Он уже тысячу раз пережил все ошибки, арест, а теперь уже свыкся с мыслью, что рано или поздно его поймают и он проведёт в тюрьме всю жизнь – однако идея стоит того. Ну вот, теперь ему действительно грозит пожизненное заключение, и вряд ли он получит что-то меньшее. Не знаю, “увы” тут, или “ура”, или что.

Bonus reading: Родители Ульбрихта говорят, что тот не мог никого убить. Да может и не убивал, на самом деле – пока непонятно.