d1afa44a71dd44e1546f4e6a3a63efe2064e7968
[u/mdw/putty] / unix / uxmisc.c
1 /*
2 * PuTTY miscellaneous Unix stuff
3 */
4
5 #include <stdio.h>
6 #include <unistd.h>
7 #include <sys/time.h>
8 #include <sys/types.h>
9 #include <pwd.h>
10
11 #include "putty.h"
12
13 unsigned long getticks(void)
14 {
15 struct timeval tv;
16 gettimeofday(&tv, NULL);
17 /*
18 * This will wrap around approximately every 4000 seconds, i.e.
19 * just over an hour, which is more than enough.
20 */
21 return tv.tv_sec * 1000000 + tv.tv_usec;
22 }
23
24
25
26 Filename filename_from_str(const char *str)
27 {
28 Filename ret;
29 strncpy(ret.path, str, sizeof(ret.path));
30 ret.path[sizeof(ret.path)-1] = '\0';
31 return ret;
32 }
33
34 const char *filename_to_str(const Filename *fn)
35 {
36 return fn->path;
37 }
38
39 int filename_equal(Filename f1, Filename f2)
40 {
41 return !strcmp(f1.path, f2.path);
42 }
43
44 int filename_is_null(Filename fn)
45 {
46 return !*fn.path;
47 }
48
49 #ifdef DEBUG
50 static FILE *debug_fp = NULL;
51
52 void dputs(char *buf)
53 {
54 if (!debug_fp) {
55 debug_fp = fopen("debug.log", "w");
56 }
57
58 write(1, buf, strlen(buf));
59
60 fputs(buf, debug_fp);
61 fflush(debug_fp);
62 }
63 #endif
64
65 char *get_username(void)
66 {
67 struct passwd *p;
68 uid_t uid = getuid();
69 char *user, *ret = NULL;
70
71 /*
72 * First, find who we think we are using getlogin. If this
73 * agrees with our uid, we'll go along with it. This should
74 * allow sharing of uids between several login names whilst
75 * coping correctly with people who have su'ed.
76 */
77 user = getlogin();
78 setpwent();
79 if (user)
80 p = getpwnam(user);
81 else
82 p = NULL;
83 if (p && p->pw_uid == uid) {
84 /*
85 * The result of getlogin() really does correspond to
86 * our uid. Fine.
87 */
88 ret = user;
89 } else {
90 /*
91 * If that didn't work, for whatever reason, we'll do
92 * the simpler version: look up our uid in the password
93 * file and map it straight to a name.
94 */
95 p = getpwuid(uid);
96 if (!p)
97 return NULL;
98 ret = p->pw_name;
99 }
100 endpwent();
101
102 return dupstr(ret);
103 }