view src/lib/hostpid.c @ 14682:d0d7b810646b

Make sure we check all the functions' return values. Minor API changes to simplify this. Checked using a patched clang that adds attribute(warn_unused_result) to all functions. This commit fixes several error handling mistakes.
author Timo Sirainen <tss@iki.fi>
date Mon, 25 Jun 2012 01:14:03 +0300
parents ba770cba5598
children a446d8bc2be5
line wrap: on
line source

/* Copyright (c) 2002-2012 Dovecot authors, see the included COPYING file */

#include "lib.h"
#include "hostpid.h"

#include <unistd.h>
#include <netdb.h>

const char *my_hostname = NULL;
const char *my_pid = NULL;

static char *my_domain = NULL;

void hostpid_init(void)
{
	static char hostname[256], pid[MAX_INT_STRLEN];

	if (gethostname(hostname, sizeof(hostname)-1) == -1) {
		if (i_strocpy(hostname, "unknown", sizeof(hostname)) < 0)
			i_unreached();
	}
	hostname[sizeof(hostname)-1] = '\0';
	my_hostname = hostname;

	if (strchr(hostname, '/') != NULL)
		i_fatal("Invalid system hostname: %s", hostname);

	/* allow calling hostpid_init() multiple times to reset hostname */
	i_free_and_null(my_domain);

	if (i_strocpy(pid, dec2str(getpid()), sizeof(pid)) < 0)
		i_unreached();
	my_pid = pid;
}

const char *my_hostdomain(void)
{
	struct hostent *hent;
	const char *name;

	if (my_domain == NULL) {
		hent = gethostbyname(my_hostname);
		name = hent != NULL ? hent->h_name : NULL;
		if (name == NULL) {
			/* failed, use just the hostname */
			name = my_hostname;
		}
		my_domain = i_strdup(name);
	}
	return my_domain;
}