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#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 50 if (write(file, hostName, nameSize) != (ssize_t)nameSize 51 || write(file, "\n", 1) != 1) { 52 close(file); 53 return -1; 54 } 55 56 close(file); 57 return 0; 58} 59 60 61extern "C" int 62gethostname(char *hostName, size_t nameSize) 63{ 64 // look up hostname from network settings hostname file 65 66 char path[B_PATH_NAME_LENGTH]; 67 if (get_path(path, false) != B_OK) { 68 __set_errno(B_ERROR); 69 return -1; 70 } 71 72 int file = open(path, O_RDONLY); 73 if (file < 0) 74 return -1; 75 76 nameSize = min_c(nameSize, MAXHOSTNAMELEN); 77 78 int length = read(file, hostName, nameSize - 1); 79 close(file); 80 81 if (length < 0) 82 return -1; 83 84 hostName[length] = '\0'; 85 86 char *end = strpbrk(hostName, "\r\n\t"); 87 if (end != NULL) 88 end[0] = '\0'; 89 90 return 0; 91} 92 93