+ return 0;
+}
+
+static int init_named_socket(char *name, char **path_out)
+{
+ int result;
+ int fd;
+
+ struct sockaddr_un addr;
+
+ result = fd = socket(PF_UNIX, SOCK_DGRAM, 0);
+ if(result == -1) {
+ PERROR("socket");
+ return -1;
+ }
+
+ addr.sun_family = AF_UNIX;
+
+ strncpy(addr.sun_path, name, UNIX_PATH_MAX);
+ addr.sun_path[UNIX_PATH_MAX-1] = '\0';
+
+ result = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
+ if(result == -1) {
+ PERROR("bind");
+ goto close_sock;
+ }
+
+ if(path_out)
+ *path_out = strdupa(addr.sun_path);
+
+ return fd;
+
+ close_sock:
+ close(fd);
+
+ return -1;
+}
+
+int ustcomm_init_app(pid_t pid, struct ustcomm_app *handle)
+{
+ int result;
+ char *name;
+
+ result = asprintf(&name, "%s/%d", SOCK_DIR, (int)pid);
+ if(result >= UNIX_PATH_MAX) {
+ ERR("string overflow allocating socket name");
+ return -1;
+ }
+
+ handle->fd = init_named_socket(name, &handle->socketpath);
+ if(handle->fd < 0) {
+ goto free_name;
+ }
+ free(name);
+
+ return 0;
+
+free_name:
+ free(name);
+ return -1;
+}
+
+int ustcomm_init_ustd(struct ustcomm_ustd *handle)
+{
+ handle->fd = init_named_socket("ustd", &handle->socketpath);
+ if(handle->fd < 0)
+ return handle->fd;
+
+ return 0;
+}