1/*
2 * Copyright 2002-2014, Axel Dörfler, axeld@pinc-software.de.
3 * Distributed under the terms of the MIT License.
4 */
5
6
7#include <errno.h>
8#include <fcntl.h>
9#include <string.h>
10#include <unistd.h>
11
12#include <FindDirectory.h>
13#include <StorageDefs.h>
14
15#include <errno_private.h>
16#include <find_directory_private.h>
17
18
19static status_t
20get_path(char *path, bool create)
21{
22	status_t status = __find_directory(B_SYSTEM_SETTINGS_DIRECTORY, -1, create,
23		path, B_PATH_NAME_LENGTH);
24	if (status != B_OK)
25		return status;
26
27	strlcat(path, "/network", B_PATH_NAME_LENGTH);
28	if (create)
29		mkdir(path, 0755);
30	strlcat(path, "/hostname", B_PATH_NAME_LENGTH);
31	return B_OK;
32}
33
34
35extern "C" int
36sethostname(const char *hostName, size_t nameSize)
37{
38	char path[B_PATH_NAME_LENGTH];
39	if (get_path(path, false) != B_OK) {
40		__set_errno(B_ERROR);
41		return -1;
42	}
43
44	int file = open(path, O_WRONLY | O_CREAT, 0644);
45	if (file < 0)
46		return -1;
47
48	nameSize = min_c(nameSize, MAXHOSTNAMELEN);
49	ftruncate(file, nameSize + 1);
50
51	if (write(file, hostName, nameSize) != (ssize_t)nameSize
52		|| write(file, "\n", 1) != 1) {
53		close(file);
54		return -1;
55	}
56
57	close(file);
58	return 0;
59}
60
61
62extern "C" int
63gethostname(char *hostName, size_t nameSize)
64{
65	// look up hostname from network settings hostname file
66
67	char path[B_PATH_NAME_LENGTH];
68	if (get_path(path, false) != B_OK) {
69		__set_errno(B_ERROR);
70		return -1;
71	}
72
73	int file = open(path, O_RDONLY);
74	if (file < 0)
75		return -1;
76
77	nameSize = min_c(nameSize, MAXHOSTNAMELEN);
78
79	int length = read(file, hostName, nameSize - 1);
80	close(file);
81
82	if (length < 0)
83		return -1;
84
85	hostName[length] = '\0';
86
87	char *end = strpbrk(hostName, "\r\n\t");
88	if (end != NULL)
89		end[0] = '\0';
90
91	return 0;
92}
93
94