-
-/*
- * Retrieve the current NSM state
- */
-unsigned int
-nsm_get_state(int update)
-{
- char newfile[PATH_MAX];
- int fd, state;
-
- if ((fd = open(_SM_STATE_PATH, O_RDONLY)) < 0) {
- if (!opt_quiet) {
- nsm_log(LOG_WARNING, "%s: %m", _SM_STATE_PATH);
- nsm_log(LOG_WARNING, "Creating %s, set initial state 1",
- _SM_STATE_PATH);
- }
- state = 1;
- update = 1;
- } else {
- if (read(fd, &state, sizeof(state)) != sizeof(state)) {
- nsm_log(LOG_WARNING,
- "%s: bad file size, setting state = 1",
- _SM_STATE_PATH);
- state = 1;
- update = 1;
- } else {
- if (!(state & 1))
- state += 1;
- }
- close(fd);
- }
-
- if (update) {
- state += 2;
- snprintf(newfile, sizeof(newfile),
- "%s.new", _SM_STATE_PATH);
- if ((fd = open(newfile, O_CREAT|O_WRONLY, 0644)) < 0) {
- nsm_log(LOG_WARNING, "Cannot create %s: %m", newfile);
- exit(1);
- }
- if (write(fd, &state, sizeof(state)) != sizeof(state)) {
- nsm_log(LOG_WARNING,
- "Failed to write state to %s", newfile);
- exit(1);
- }
- close(fd);
- if (rename(newfile, _SM_STATE_PATH) < 0) {
- nsm_log(LOG_WARNING,
- "Cannot create %s: %m", _SM_STATE_PATH);
- exit(1);
- }
- sync();
- }
-
- return state;
-}
-
-/*
- * Address handling utilities
- */
-
-int
-addr_get_port(nsm_address *addr)
-{
- switch (((struct sockaddr *) addr)->sa_family) {
- case AF_INET:
- return ntohs(((struct sockaddr_in *) addr)->sin_port);
- case AF_INET6:
- return ntohs(((struct sockaddr_in6 *) addr)->sin6_port);
- }
- return 0;
-}
-
-static void
-addr_set_port(nsm_address *addr, int port)
-{
- switch (((struct sockaddr *) addr)->sa_family) {
- case AF_INET:
- ((struct sockaddr_in *) addr)->sin_port = htons(port);
- break;
- case AF_INET6:
- ((struct sockaddr_in6 *) addr)->sin6_port = htons(port);
- }
-}
-
-static int
-host_lookup(int af, const char *name, nsm_address *addr)
-{
- struct addrinfo hints, *ai;
- int okay = 0;
-
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = af;
-
- if (getaddrinfo(name, NULL, &hints, &ai) != 0)
- return 0;
-
- if (ai->ai_addrlen < sizeof(*addr)) {
- memcpy(addr, ai->ai_addr, ai->ai_addrlen);
- okay = 1;
- }
-
- freeaddrinfo(ai);
- return okay;
-}
-
-/*
- * Log a message
- */
-void
-nsm_log(int fac, const char *fmt, ...)
-{
- va_list ap;
-
- if (fac == LOG_DEBUG && !opt_debug)
- return;
-
- va_start(ap, fmt);
- if (log_syslog)
- vsyslog(fac, fmt, ap);
- else {
- vfprintf(stderr, fmt, ap);
- fputs("\n", stderr);
- }
- va_end(ap);
-}
-