Added SILC Thread Queue API
[silc.git] / lib / silcutil / unix / silcunixutil.c
1 /*
2
3   silcunixutil.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2007 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19
20 #include "silc.h"
21
22 /* Returns the username of the user. If the global variable LOGNAME
23    does not exists we will get the name from the password file. */
24
25 char *silc_get_username()
26 {
27   char *logname = NULL;
28
29   logname = getenv("LOGNAME");
30   if (!logname) {
31     logname = getlogin();
32     if (!logname) {
33       struct passwd *pw;
34
35       pw = getpwuid(getuid());
36       if (!pw)
37         return strdup("foo");
38
39       logname = pw->pw_name;
40     }
41   }
42
43   return strdup(logname);
44 }
45
46 /* Returns the real name of ther user. */
47
48 char *silc_get_real_name()
49 {
50   char *realname = NULL;
51   struct passwd *pw;
52
53   pw = getpwuid(getuid());
54   if (!pw)
55     return strdup("No Name");
56
57   if (strchr(pw->pw_gecos, ','))
58     *strchr(pw->pw_gecos, ',') = 0;
59
60   if (!strlen(pw->pw_gecos))
61     return strdup("No Name");
62
63   realname = strdup(pw->pw_gecos);
64
65   return realname;
66 }
67
68 /* Return current time to struct timeval. */
69
70 int silc_gettimeofday(struct timeval *p)
71 {
72 #if defined(HAVE_CLOCK_GETTIME)
73   struct timespec tp;
74   if (clock_gettime(CLOCK_REALTIME, &tp))
75     return -1;
76   p->tv_sec = tp.tv_sec;
77   p->tv_usec = tp.tv_nsec / 1000;
78   return 0;
79 #else
80   return gettimeofday(p, NULL);
81 #endif /* HAVE_CLOCK_GETTIME */
82 }
83
84 int silc_file_set_nonblock(int fd)
85 {
86   return fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
87 }