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