1 /* realname.c - query the user's real name
2  *
3  * Copyright 1999, 2000, 2006  Jochen Voss  */
4 
5 static const  char  rcsid[] = "$Id: realname.c 6825 2006-03-19 19:18:39Z voss $";
6 
7 #ifdef HAVE_CONFIG_H
8 #include <config.h>
9 #endif
10 
11 #ifdef _XOPEN_SOURCE
12 #define _XOPEN_SOURCE_EXTENDED 1
13 #endif
14 
15 #include <stdlib.h>
16 #include <string.h>
17 #include <ctype.h>
18 #include <sys/types.h>
19 #include <unistd.h>
20 #include <pwd.h>
21 #include <assert.h>
22 
23 #if defined(__hp9000s800)
24 #include <stdarg.h>
25 #endif
26 
27 #include "moon-buggy.h"
28 
29 
30 int
get_real_user_name(char * buffer,size_t size)31 get_real_user_name (char *buffer, size_t size)
32 /* Query the real user name.
33  * Store the result into BUFFER, but do not write more then SIZE
34  * characters.  */
35 {
36   int  res, start;
37   char *tmp;
38 
39   if (buffer[0] == '\0') {
40     uid_t me = geteuid ();
41     struct passwd *my_passwd = getpwuid (me);
42     if (my_passwd) {
43       int  i;
44       strncpy (buffer, my_passwd->pw_gecos, size);
45       for (i=0; i<size; ++i) {
46 	if (buffer[i] == ',') {
47 	  buffer[i] = '\0';
48 	  break;
49 	}
50       }
51     }
52   }
53 
54   werase (message);
55   if (buffer[0] == '\0') {
56     waddstr (message, "please enter your name: ");
57   } else {
58     char  tmpl [100];
59     int  def_size;
60 
61     def_size = (COLS
62 		- size
63 		- strlen("please enter your name (default: \"\"): "));
64     if (def_size >= (int)xstrnlen(buffer, size)) {
65       sprintf (tmpl, "please enter your name (default: \"%%.%ds\"): ", size);
66     } else {
67       def_size -= 2;
68       if (def_size < 6)  def_size = 6;
69       assert (size >= 8);
70       sprintf (tmpl, "please enter your name (default: \"%%.%ds..\"): ",
71 	       def_size);
72     }
73     wprintw (message, tmpl, buffer);
74   }
75 
76   tmp = xmalloc (size+1);
77 
78   show_cursor ();
79   echo ();
80   res = wgetnstr (message, tmp, size);
81   noecho ();
82   hide_cursor ();
83 
84   start = 0;
85   while (start < size && tmp[start] && isspace (tmp[start]))  ++start;
86   if (start<size && tmp[start]) {
87     strncpy (buffer, tmp+start, size-start);
88     if (start>0)  buffer[size-start] = '\0';
89   }
90   free (tmp);
91   return  res;
92 }
93