(104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server

This error (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server started to appear in my apache error log whenever I tried to upload a file. Apache seemed to be working fine with static html pages, it was only when I tried to upload files that I had problems.

Searching for a solution suggested a whole series of possible causes all revolving around permission problems. Since I had not changed anything on the server for a few weeks, and everything looked fine permission wise, this did not look to be the cause. After checking everything I could think of I noticed that the disk quota allocated by Virtualmin was only 1 GB and that I had used nearly all of it. I upped the disk quota to 10 GB and the problem was fixed. I hope this helps someone.

setrlimit not raising a signal with SIGXCPU

I ran into a unusual linux bug of late using RLIMIT_CPU to kill zombie processes that ran for longer than 15 seconds. The basic code I was using was:

struct rlimit rl;
memset(&rl, 0, sizeof(rl));
/* Set a CPU limit of 15 second. */
rl.rlim_cur = 15;
setrlimit(RLIMIT_CPU, &rl);
/* CPU Time exceeded */
signal(SIGXCPU, catchSignal);

This worked fine when I original wrote it a few years ago, but I noticed of late that I was spawning a large number of zombie processes that were not being trapped by SIGXCPU. After tearing my hair out all day trying to work out why, I noticed that this was only occurring on my CentOS 6.5 development box (Linux version 2.6.32). It turns out that there was a bug in the implementation of setrlimit before 2.6.17 that led a RLIMIT_CPU limit of 0 to be wrongly treated as “no limit” (like RLIM_INFINITY). Since 2.6.17 this is now treated as a limit of 1 second. Since I was setting rlim_max to 0 via memset meant that I was now effectively setting rlim_max to less than rlim_cur.

The solution is really simple – just ensure that you set rlim_max (hard limit) as well as rlim_cur (soft limit).

struct rlimit rl;
/* Set a CPU soft limit of 15 second and hard limit of 20 seconds */
rl.rlim_cur = 15;
rl.rlim_max = 20;
setrlimit(RLIMIT_CPU, &rl);
/* CPU Time exceeded */
signal(SIGXCPU, catchSignal);

pear.php.net is using a unsupported protocol – This should never happen.

I ran into the error “pear.php.net is using a unsupported protocol – This should never happen.” when I tried to upgrade my pecl packages. I have to say errors like “this should never happen” shouldn’t happen, but since it obviously did what is the cause and more importantly the solution. Apparently this error is caused because PHP 5.2.9 and 5.2.10 were broken and it corrupted the .record folder. The solution to fix this is to upgrade pear first then pecl.

pear upgrade
pecl upgrade

So simple :)

Mount Langi Ghiran Cliff Edge Shiraz 2010

It has been a while since I have had a chance to post about a good value wine, but finally I have one. The 2010 Mount Langi Ghiran Cliff Edge Shiraz is certainly a nice secondary wine from a great winery. It has the typical cool climate peppery shiraz flavours without being washed out. This wine is a really elegant food wine and at $22 a bottle a total bargain. A wine that is well worth the price!

cliff_edge

Price $22
Value $40+

Update. I was able to get a couple of cases for under $20 a bottle from Winestar – even better value.

How to set cookies using PHP and get them via JavaScript

I had an application where I wanted to set a cookie value using the php setcookie function and then later pull out the value using JS. The problem is the php setcookie function url encodes the cookie values with ‘+’ symbols for any whitespace. When you later pull out the cookie value using the JS decodeURIComponent function the ‘+’ symbols remain, converting a string to like ‘abc cdf’ to ‘abc+cdf’. If you want to the cookie values to have ” ” rather than “+” then you need to str_replace all the “+” with “%20” after calling the php urlencode function and then save the encode string using setrawcookie. The basic call to do something this is:

setrawcookie("cookie", str_replace('+','%20',urlencode($string)), time() + 3600*24*7, "/path","www.yourwebsite.com");

Hopefully this will save someone some time. If you want to do the reverse it is very simple – just calling the php urldecode function on the server $_COOKIE variable.

$string = urldecode($_COOKIE['string']);

Of course all the usual warnings about not trusting user supplied data remain. Just because your script created the data does not mean you can trust what is actually there.

Letters to avoid in creating passwords for non-english keyboard layouts

I had an interesting issue arise where I sent a computer to a customer located in Germany. I had created a password for them, but they had problems logging in with it. It turns out that the password I had created contained the letters Z and Y. These two keys are swapped on German keyboards so when they plugged in their own German keyboard they ended up entering the wrong password as the computer was still set to the English keyboard layout.

I have looked into the most common keyboard layouts used in Europe (QWERTY, QWERTZ & AZERTY) and you can avoid key swapping problems like mine if you avoid using the letters Z, Y, A, Q, M & L in any password or user name.

Update. Here is a simple one liner to generate a random alpha numerical password of 8 characters that avoids these letters. You can of course change the password length by changing the -c switch on the head call. This should work on any *nix based system (including MacOS X) that has openssl installed. One warning is the password will visible at generation time to other local users on shared systems if the other users are watching for process list changes. This doesn’t matter to me too much as I generate the passwords on my Mac laptop, but it is something to keep in mind if you are on an shared system.

 openssl rand -base64 25 | tr -dc 'BCDEFGHIJKNOPRSTUVWXbcdefghijknoprstuvwx0123456789' | head -c8; echo ""

How to create a Windows program that works both as a GUI and console application

It would be very nice to be able to make Windows applications that can act as either a GUI or console application depending on how they are used (i.e. act as a GUI application if double clicked in Windows Explorer or as a console application if called from a cmd.exe window).

Unfortunately the way Windows work, each exe application has field in the PE header that specifies which subsystem it should run under. This is set in Visual Studio by using one of the linker SUBSYSTEM option (i.e. Windows or Console). The subsystem is used by the Windows kernel to set up the execution environment for the application. If the application is built using SUBSYSTEM/Console then the kernel will connect the application to the parent console and the application’s stdout, stderr and stdin will be redirected to the parent console. If the program is built as a GUI application then the application detaches from the parent console and all output to stdout and stderr are are lost – basically the program runs, but doesn’t output anything to the parent console window.

People have attempted various hacks over the years to solve this problem. One solution proposed was to compile the program as a Windows application and then edit the PE header to mark the program as using the Console subsystem. The downside of this approach is it flashes a Console window on the screen when run as a GUI application that looks pretty unprofessional. The second hack commonly used is to create two separate binaries, for example, a myuselessprogram.com and myuselessprogram.exe. The .com version is built as a Console application while the .exe is built as Windows application. When you run myuselessprogram the Windows probing rule runs the .com version first and if there is nothing on the command line then the .com version calls the .exe Windows version. While both these approaches work, they are to say less than ideal.

A better approach is use the WINAPI AttachConsole function to attach the application to the parent console and then redirect stdout, stdin and stderr back to the parent console. This actually works very well except that when the application exits the parent console can’t detect this and hence release the command prompt. The end result is the parent console just sits there until the user presses the “enter” key.

There is no really elegant solution to this problem, but as applications can simulate the keyboard being used, a simple solution is to call the SendInput API function with the “enter” key just before the application exits. This simulates the user pressing the enter key and hence releases the command prompt.

To show how this approach works I have written a small test application (see below). The main limitations is that AttachConsole is only available on Windows XP and above. It does works under Cygwin which is nice.

Update. I have added a check to make sure that the console window is in focus before sending the enter key. It is a good check to make if you are running your console program in a background script or else you will end up with lots of “enter” key presses in whatever application you actually have in focus – lots of fun if you are working on the documentation while a script runs in the background :)

Update 2. Contrary to what has been posted on Stack Overflow this approach works with STDIN too. I don’t have any need to capture STDIN with my application (just the command line parameters), but all you need to do to capture stdin is treat STDIN as is done for STDOUT (i.e just redirect STDIN to the console) in the attachOutputToConsole function.

Update 3. This is MIT licensed if this is important to you :)

Update 4. Microsoft has broken the old approach I was using in VS2015. I have updated the code to use a different way of attaching STDOUT and STRERR to the parent console. This code works with VS2015 and all earlier compliers I was able to test (VS2013, VS2008, VS2005).

/*

 Copyright (c) 2013, 2016 Daniel Tillett
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 
 1. Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#define WINVER 0x0501 // Allow use of features specific to Windows XP or later.
#define _WIN32_WINNT 0x0501
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#include "io.h"
#include "fcntl.h"
#include "stdio.h"
#include "stdlib.h"
#pragma comment(lib, "User32.lib")

// Attach output of application to parent console
static BOOL attachOutputToConsole(void) {
HANDLE consoleHandleOut, consoleHandleError;

if (AttachConsole(ATTACH_PARENT_PROCESS)) {
  // Redirect unbuffered STDOUT to the console
  consoleHandleOut = GetStdHandle(STD_OUTPUT_HANDLE);
  if (consoleHandleOut != INVALID_HANDLE_VALUE) {
    freopen("CONOUT$", "w", stdout);
    setvbuf(stdout, NULL, _IONBF, 0);
    }
  else {
    return FALSE;
    }
  // Redirect unbuffered STDERR to the console
  consoleHandleError = GetStdHandle(STD_ERROR_HANDLE);
  if (consoleHandleError != INVALID_HANDLE_VALUE) {
    freopen("CONOUT$", "w", stderr);
    setvbuf(stderr, NULL, _IONBF, 0);
    }
  else {
    return FALSE;
   }
  return TRUE;
  }
//Not a console application
return FALSE;
}

// Send the "enter" to the console to release the command prompt 
// on the parent console
static void sendEnterKey(void) {
 INPUT ip;
 // Set up a generic keyboard event.
 ip.type = INPUT_KEYBOARD;
 ip.ki.wScan = 0; // hardware scan code for key
 ip.ki.time = 0;
 ip.ki.dwExtraInfo = 0;

 // Send the "Enter" key
 ip.ki.wVk = 0x0D; // virtual-key code for the "Enter" key
 ip.ki.dwFlags = 0; // 0 for key press
 SendInput(1, &ip, sizeof(INPUT));

 // Release the "Enter" key
 ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
 SendInput(1, &ip, sizeof(INPUT));
}

int WINAPI WinMain(HINSTANCE hInstance, 
HINSTANCE hPrevInstance, 
PSTR lpCmdLine, 
INT nCmdShow) {
int argc = __argc;
char **argv = __argv;
UNREFERENCED_PARAMETER(hInstance);
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
BOOL console;
int i;

//Is the program running as console or GUI application
console = attachOutputToConsole();

if (console) {
    // Print to stdout
    printf("Program running as console application\n");
    for (i = 0; i < argc; i++) {
         printf("argv[%d] %s\n", i, argv[i]);
         }

    // Print to stderr
    fprintf(stderr, "Output to stderr\n");
    }
else {
    MessageBox(NULL, "Program running as Windows GUI application",
    "Windows GUI Application", MB_OK | MB_SETFOREGROUND);
}

// Send "enter" to release application from the console
// This is a hack, but if not used the console doesn't know the application has
// returned. The "enter" key only sent if the console window is in focus.
if (console && (GetConsoleWindow() == GetForegroundWindow())){
    sendEnterKey();
    }
return 0;
}

Solved: Problem with Skype number always engaged (busy)

I decided to get a skype number as a replacement for my landline number. I found that no matter what skype setting I used on my mac laptop the phone number was always engaged (busy). It turns out that the problem is due to the fact that I also had skype installed on my windows box. It seems that if you are logged in on two different machines skype will always take the settings from windows over osx. Any changes you make on the osx side are overridden by whatever settings you have on the windows box. As soon as I changed the settings on the windows box everything started working.

Now all I need to do is figure out how to get the 2 hours of my life back that I wasted on working this out :)

Voyager Estate Cabernet Sauvignon Merlot 2007

Over in Western Australia 2007 was the “vintage of the century” – I can’t say the same for Eastern Australia where 2007 was probably one of worst for at least 20 years. I managed to get (and drink) a couple of bottles of the 2007 Voyager Estate Shiraz and they were fantastic. I hadn’t had a chance to try the Cab Sav from the same year, but I noticed a few bottles of the 2007 Voyager Estate Cabernet Sauvignon Merlot for sale at my local Dan Murphys so I thought I would take a chance. At $50 a bottle this is a little above my normal limit, but given the year and maker I thought they might be worth the risk so I bought a couple of bottles. A good great decision as the wine is really outstanding. If you like WA cab savs then I think that you will not find better for the price right now. This wine is definitely worth the cost.

wine

Price $50
Value $90+

Update Nov 2013. I saw this for sale a week ago out of cellar release and they wanted $115 for it!

Install R on CentOS 5 x64 using yum

I recently had the fun of installing R on my development box. While you can install from source I wanted to be able to install using yum. R is not in the standard packages, but it is in the epel repository (Extra Packages for Enterprise Linux 5 – x86_64).

Steps for Installing R
1. Make sure that you have epel in your yum repositories (use yum listrepo to check). If not add epel to your yum repos (see here for instructions how to do this).
2. Install R and dependencies using yum install R-core R-2*
3. Enter R (just type R) and update all the default package using update.packages(). You will need to choose the nearest mirror to you.
4. Install the packages you need using install.packages(“package_name”, dependencies = TRUE)
5. Quit R using q()

Hope this saves someone a little time.

Update.
If you are behind a proxy server then use the following (change for your proxy setting) after starting R
 Sys.setenv(http_proxy=”http://url_to_proxy.com:8080″)
You can check if correct by
 Sys.getenv(“http_proxy”)
then update by
 update.packages()