userhosts.c 2.45 KB
Newer Older
Vincent Pelletier's avatar
Vincent Pelletier committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
/* userhosts - redirect access to /etc/hosts to another file */
/*
 * Copyright (C) 2014 Vincent Pelletier <vincent@nexedi.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.

 * This library 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
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

/* Needed for RTLD_NEXT */
#define _GNU_SOURCE

#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <fcntl.h>

#define ORIGINAL_HOSTS_PATH "/etc/hosts"

static int (*original_open)(const char *, int, ...);
static FILE *(*original_fopen)(const char *, const char *);
static const char *replacement_hosts;

/* Call dlsym(RTLD_NEXT, name), abort()'ing with informative message to
 * stderr if it cannot be found. */
static inline void *dlsym_or_abort(const char *name) {
  char *error;
  void *symbol;
  dlerror(); /* Clear any previous error */
  if (NULL == (symbol = dlsym(RTLD_NEXT, name)) && (error = dlerror())) {
    fprintf(stderr, "Error loading '%s': %s\n", name, error);
    abort();
  }
  return symbol;
}

static void __attribute__ ((constructor)) init(void) {
50 51
  original_open = dlsym_or_abort("open");
  original_fopen = dlsym_or_abort("fopen");
Vincent Pelletier's avatar
Vincent Pelletier committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
  replacement_hosts = getenv("HOSTS");
  if (replacement_hosts == NULL)
    /* XXX: warn ? fallback on $HOME/???/hosts ? */
    replacement_hosts = ORIGINAL_HOSTS_PATH;
}

int open(const char *__file, int __oflag, ...) {
  if(strcmp(__file, ORIGINAL_HOSTS_PATH) == 0)
    __file = replacement_hosts;
  if (__oflag & (O_CREAT | O_TMPFILE)) {
    va_list ap;
    mode_t mode;

    va_start(ap, __oflag);
    mode = va_arg(ap, mode_t);
    va_end(ap);
    return (*original_open)(__file, __oflag, mode);
  }
  return (*original_open)(__file, __oflag);
}

FILE *fopen(const char *path, const char *mode) {
  if (strcmp(path, ORIGINAL_HOSTS_PATH) == 0)
    path = replacement_hosts;
  return (*original_fopen)(path, mode);
}