/* Public domain. */

#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/un.h>
#include "error.h"
#include "byte.h"
#include "str.h"
#include "socket_unix.h"

int socket_unix_bind(int s, const char* path) {
  struct sockaddr_un sa;
  int size;

  byte_zero(&sa, sizeof sa);
  sa.sun_family = AF_UNIX;

  size = str_len(path) + 1;
  if(size > sizeof(sa.sun_path)) {
    errno = error_nomem;
    return -1;
  }

  byte_copy(sa.sun_path, size, path);

  if(bind(s, (struct sockaddr *)&sa, sizeof sa) == 0)
    return 0;
  if(errno != EADDRINUSE)
    return -1;
  unlink(path);
  return bind(s, (struct sockaddr *)&sa, sizeof sa);
}
