btrfs: Attempt to fix GCC2 build.
[haiku.git] / src / system / kernel / util / hostname.cpp
blob3a819733ee3443ae917d4295732ddb36159d2e23
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 */
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <string.h>
10 #include <unistd.h>
12 #include <FindDirectory.h>
13 #include <StorageDefs.h>
15 #include <errno_private.h>
16 #include <find_directory_private.h>
19 static status_t
20 get_path(char *path, bool create)
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;
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;
35 extern "C" int
36 sethostname(const char *hostName, size_t nameSize)
38 char path[B_PATH_NAME_LENGTH];
39 if (get_path(path, false) != B_OK) {
40 __set_errno(B_ERROR);
41 return -1;
44 int file = open(path, O_WRONLY | O_CREAT, 0644);
45 if (file < 0)
46 return -1;
48 nameSize = min_c(nameSize, MAXHOSTNAMELEN);
50 if (write(file, hostName, nameSize) != (ssize_t)nameSize
51 || write(file, "\n", 1) != 1) {
52 close(file);
53 return -1;
56 close(file);
57 return 0;
61 extern "C" int
62 gethostname(char *hostName, size_t nameSize)
64 // look up hostname from network settings hostname file
66 char path[B_PATH_NAME_LENGTH];
67 if (get_path(path, false) != B_OK) {
68 __set_errno(B_ERROR);
69 return -1;
72 int file = open(path, O_RDONLY);
73 if (file < 0)
74 return -1;
76 nameSize = min_c(nameSize, MAXHOSTNAMELEN);
78 int length = read(file, hostName, nameSize - 1);
79 close(file);
81 if (length < 0)
82 return -1;
84 hostName[length] = '\0';
86 char *end = strpbrk(hostName, "\r\n\t");
87 if (end != NULL)
88 end[0] = '\0';
90 return 0;