xref: /haiku/src/system/libroot/posix/unistd/hostname.cpp (revision d9cebac2b77547b7064f22497514eecd2d047160)
1 /*
2  * Copyright 2002-2007, Axel Dörfler, axeld@pinc-software.de. All rights reserved.
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 
16 static status_t
17 get_path(char *path, bool create)
18 {
19 	status_t status = find_directory(B_COMMON_SETTINGS_DIRECTORY, -1, create,
20 		path, B_PATH_NAME_LENGTH);
21 	if (status != B_OK)
22 		return status;
23 
24 	strlcat(path, "/network", B_PATH_NAME_LENGTH);
25 	if (create)
26 		mkdir(path, 0755);
27 	strlcat(path, "/hostname", B_PATH_NAME_LENGTH);
28 	return B_OK;
29 }
30 
31 
32 extern "C" int
33 sethostname(const char *hostName, size_t nameSize)
34 {
35 	char path[B_PATH_NAME_LENGTH];
36 	if (get_path(path, false) != B_OK) {
37 		errno = B_ERROR;
38 		return -1;
39 	}
40 
41 	int file = open(path, O_WRONLY | O_CREAT, 0644);
42 	if (file < 0)
43 		return -1;
44 
45 	nameSize = min_c(nameSize, MAXHOSTNAMELEN);
46 
47 	if (write(file, hostName, nameSize) != (ssize_t)nameSize
48 		|| write(file, "\n", 1) != 1) {
49 		close(file);
50 		return -1;
51 	}
52 
53 	close(file);
54 	return 0;
55 }
56 
57 
58 extern "C" int
59 gethostname(char *hostName, size_t nameSize)
60 {
61 	// look up hostname from network settings hostname file
62 
63 	char path[B_PATH_NAME_LENGTH];
64 	if (get_path(path, false) != B_OK) {
65 		errno = B_ERROR;
66 		return -1;
67 	}
68 
69 	int file = open(path, O_RDONLY);
70 	if (file < 0)
71 		return -1;
72 
73 	nameSize = min_c(nameSize, MAXHOSTNAMELEN);
74 
75 	int length = read(file, hostName, nameSize - 1);
76 	close(file);
77 
78 	if (length < 0)
79 		return -1;
80 
81 	hostName[length] = '\0';
82 
83 	char *end = strpbrk(hostName, "\r\n\t");
84 	if (end != NULL)
85 		end[0] = '\0';
86 
87 	return 0;
88 }
89 
90