PostgreSQL Source Code  git master
createuser.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * createuser
4  *
5  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
6  * Portions Copyright (c) 1994, Regents of the University of California
7  *
8  * src/bin/scripts/createuser.c
9  *
10  *-------------------------------------------------------------------------
11  */
12 
13 #include "postgres_fe.h"
14 #include "common.h"
15 #include "common/logging.h"
16 #include "fe_utils/simple_list.h"
17 #include "fe_utils/string_utils.h"
18 
19 
20 static void help(const char *progname);
21 
22 int
23 main(int argc, char *argv[])
24 {
25  static struct option long_options[] = {
26  {"host", required_argument, NULL, 'h'},
27  {"port", required_argument, NULL, 'p'},
28  {"username", required_argument, NULL, 'U'},
29  {"role", required_argument, NULL, 'g'},
30  {"no-password", no_argument, NULL, 'w'},
31  {"password", no_argument, NULL, 'W'},
32  {"echo", no_argument, NULL, 'e'},
33  {"createdb", no_argument, NULL, 'd'},
34  {"no-createdb", no_argument, NULL, 'D'},
35  {"superuser", no_argument, NULL, 's'},
36  {"no-superuser", no_argument, NULL, 'S'},
37  {"createrole", no_argument, NULL, 'r'},
38  {"no-createrole", no_argument, NULL, 'R'},
39  {"inherit", no_argument, NULL, 'i'},
40  {"no-inherit", no_argument, NULL, 'I'},
41  {"login", no_argument, NULL, 'l'},
42  {"no-login", no_argument, NULL, 'L'},
43  {"replication", no_argument, NULL, 1},
44  {"no-replication", no_argument, NULL, 2},
45  {"interactive", no_argument, NULL, 3},
46  {"connection-limit", required_argument, NULL, 'c'},
47  {"pwprompt", no_argument, NULL, 'P'},
48  {"encrypted", no_argument, NULL, 'E'},
49  {NULL, 0, NULL, 0}
50  };
51 
52  const char *progname;
53  int optindex;
54  int c;
55  const char *newuser = NULL;
56  char *host = NULL;
57  char *port = NULL;
58  char *username = NULL;
59  SimpleStringList roles = {NULL, NULL};
60  enum trivalue prompt_password = TRI_DEFAULT;
61  bool echo = false;
62  bool interactive = false;
63  int conn_limit = -2; /* less than minimum valid value */
64  bool pwprompt = false;
65  char *newpassword = NULL;
66  char newuser_buf[128];
67  char newpassword_buf[100];
68 
69  /* Tri-valued variables. */
72  createrole = TRI_DEFAULT,
73  inherit = TRI_DEFAULT,
75  replication = TRI_DEFAULT;
76 
77  PQExpBufferData sql;
78 
79  PGconn *conn;
80  PGresult *result;
81 
82  pg_logging_init(argv[0]);
83  progname = get_progname(argv[0]);
84  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pgscripts"));
85 
86  handle_help_version_opts(argc, argv, "createuser", help);
87 
88  while ((c = getopt_long(argc, argv, "h:p:U:g:wWedDsSrRiIlLc:PE",
89  long_options, &optindex)) != -1)
90  {
91  char *endptr;
92 
93  switch (c)
94  {
95  case 'h':
96  host = pg_strdup(optarg);
97  break;
98  case 'p':
99  port = pg_strdup(optarg);
100  break;
101  case 'U':
102  username = pg_strdup(optarg);
103  break;
104  case 'g':
106  break;
107  case 'w':
108  prompt_password = TRI_NO;
109  break;
110  case 'W':
111  prompt_password = TRI_YES;
112  break;
113  case 'e':
114  echo = true;
115  break;
116  case 'd':
117  createdb = TRI_YES;
118  break;
119  case 'D':
120  createdb = TRI_NO;
121  break;
122  case 's':
123  superuser = TRI_YES;
124  break;
125  case 'S':
126  superuser = TRI_NO;
127  break;
128  case 'r':
129  createrole = TRI_YES;
130  break;
131  case 'R':
132  createrole = TRI_NO;
133  break;
134  case 'i':
135  inherit = TRI_YES;
136  break;
137  case 'I':
138  inherit = TRI_NO;
139  break;
140  case 'l':
141  login = TRI_YES;
142  break;
143  case 'L':
144  login = TRI_NO;
145  break;
146  case 'c':
147  conn_limit = strtol(optarg, &endptr, 10);
148  if (*endptr != '\0' || conn_limit < -1) /* minimum valid value */
149  {
150  fprintf(stderr,
151  _("%s: invalid value for --connection-limit: %s\n"),
152  progname, optarg);
153  exit(1);
154  }
155  break;
156  case 'P':
157  pwprompt = true;
158  break;
159  case 'E':
160  /* no-op, accepted for backward compatibility */
161  break;
162  case 1:
163  replication = TRI_YES;
164  break;
165  case 2:
166  replication = TRI_NO;
167  break;
168  case 3:
169  interactive = true;
170  break;
171  default:
172  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
173  exit(1);
174  }
175  }
176 
177  switch (argc - optind)
178  {
179  case 0:
180  break;
181  case 1:
182  newuser = argv[optind];
183  break;
184  default:
185  pg_log_error("too many command-line arguments (first is \"%s\")",
186  argv[optind + 1]);
187  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
188  exit(1);
189  }
190 
191  if (newuser == NULL)
192  {
193  if (interactive)
194  {
195  simple_prompt("Enter name of role to add: ",
196  newuser_buf, sizeof(newuser_buf), true);
197  newuser = newuser_buf;
198  }
199  else
200  {
201  if (getenv("PGUSER"))
202  newuser = getenv("PGUSER");
203  else
204  newuser = get_user_name_or_exit(progname);
205  }
206  }
207 
208  if (pwprompt)
209  {
210  char pw2[100];
211 
212  simple_prompt("Enter password for new role: ",
213  newpassword_buf, sizeof(newpassword_buf), false);
214  simple_prompt("Enter it again: ", pw2, sizeof(pw2), false);
215  if (strcmp(newpassword_buf, pw2) != 0)
216  {
217  fprintf(stderr, _("Passwords didn't match.\n"));
218  exit(1);
219  }
220  newpassword = newpassword_buf;
221  }
222 
223  if (superuser == 0)
224  {
225  if (interactive && yesno_prompt("Shall the new role be a superuser?"))
226  superuser = TRI_YES;
227  else
228  superuser = TRI_NO;
229  }
230 
231  if (superuser == TRI_YES)
232  {
233  /* Not much point in trying to restrict a superuser */
234  createdb = TRI_YES;
235  createrole = TRI_YES;
236  }
237 
238  if (createdb == 0)
239  {
240  if (interactive && yesno_prompt("Shall the new role be allowed to create databases?"))
241  createdb = TRI_YES;
242  else
243  createdb = TRI_NO;
244  }
245 
246  if (createrole == 0)
247  {
248  if (interactive && yesno_prompt("Shall the new role be allowed to create more new roles?"))
249  createrole = TRI_YES;
250  else
251  createrole = TRI_NO;
252  }
253 
254  if (inherit == 0)
255  inherit = TRI_YES;
256 
257  if (login == 0)
258  login = TRI_YES;
259 
260  conn = connectDatabase("postgres", host, port, username, prompt_password,
261  progname, echo, false, false);
262 
263  initPQExpBuffer(&sql);
264 
265  printfPQExpBuffer(&sql, "CREATE ROLE %s", fmtId(newuser));
266  if (newpassword)
267  {
268  char *encrypted_password;
269 
270  appendPQExpBufferStr(&sql, " PASSWORD ");
271 
272  encrypted_password = PQencryptPasswordConn(conn,
273  newpassword,
274  newuser,
275  NULL);
276  if (!encrypted_password)
277  {
278  pg_log_error("password encryption failed: %s",
279  PQerrorMessage(conn));
280  exit(1);
281  }
282  appendStringLiteralConn(&sql, encrypted_password, conn);
283  PQfreemem(encrypted_password);
284  }
285  if (superuser == TRI_YES)
286  appendPQExpBufferStr(&sql, " SUPERUSER");
287  if (superuser == TRI_NO)
288  appendPQExpBufferStr(&sql, " NOSUPERUSER");
289  if (createdb == TRI_YES)
290  appendPQExpBufferStr(&sql, " CREATEDB");
291  if (createdb == TRI_NO)
292  appendPQExpBufferStr(&sql, " NOCREATEDB");
293  if (createrole == TRI_YES)
294  appendPQExpBufferStr(&sql, " CREATEROLE");
295  if (createrole == TRI_NO)
296  appendPQExpBufferStr(&sql, " NOCREATEROLE");
297  if (inherit == TRI_YES)
298  appendPQExpBufferStr(&sql, " INHERIT");
299  if (inherit == TRI_NO)
300  appendPQExpBufferStr(&sql, " NOINHERIT");
301  if (login == TRI_YES)
302  appendPQExpBufferStr(&sql, " LOGIN");
303  if (login == TRI_NO)
304  appendPQExpBufferStr(&sql, " NOLOGIN");
305  if (replication == TRI_YES)
306  appendPQExpBufferStr(&sql, " REPLICATION");
307  if (replication == TRI_NO)
308  appendPQExpBufferStr(&sql, " NOREPLICATION");
309  if (conn_limit >= -1)
310  appendPQExpBuffer(&sql, " CONNECTION LIMIT %d", conn_limit);
311  if (roles.head != NULL)
312  {
313  SimpleStringListCell *cell;
314 
315  appendPQExpBufferStr(&sql, " IN ROLE ");
316 
317  for (cell = roles.head; cell; cell = cell->next)
318  {
319  if (cell->next)
320  appendPQExpBuffer(&sql, "%s,", fmtId(cell->val));
321  else
322  appendPQExpBufferStr(&sql, fmtId(cell->val));
323  }
324  }
325  appendPQExpBufferChar(&sql, ';');
326 
327  if (echo)
328  printf("%s\n", sql.data);
329  result = PQexec(conn, sql.data);
330 
331  if (PQresultStatus(result) != PGRES_COMMAND_OK)
332  {
333  pg_log_error("creation of new role failed: %s", PQerrorMessage(conn));
334  PQfinish(conn);
335  exit(1);
336  }
337 
338  PQclear(result);
339  PQfinish(conn);
340  exit(0);
341 }
342 
343 
344 static void
345 help(const char *progname)
346 {
347  printf(_("%s creates a new PostgreSQL role.\n\n"), progname);
348  printf(_("Usage:\n"));
349  printf(_(" %s [OPTION]... [ROLENAME]\n"), progname);
350  printf(_("\nOptions:\n"));
351  printf(_(" -c, --connection-limit=N connection limit for role (default: no limit)\n"));
352  printf(_(" -d, --createdb role can create new databases\n"));
353  printf(_(" -D, --no-createdb role cannot create databases (default)\n"));
354  printf(_(" -e, --echo show the commands being sent to the server\n"));
355  printf(_(" -g, --role=ROLE new role will be a member of this role\n"));
356  printf(_(" -i, --inherit role inherits privileges of roles it is a\n"
357  " member of (default)\n"));
358  printf(_(" -I, --no-inherit role does not inherit privileges\n"));
359  printf(_(" -l, --login role can login (default)\n"));
360  printf(_(" -L, --no-login role cannot login\n"));
361  printf(_(" -P, --pwprompt assign a password to new role\n"));
362  printf(_(" -r, --createrole role can create new roles\n"));
363  printf(_(" -R, --no-createrole role cannot create roles (default)\n"));
364  printf(_(" -s, --superuser role will be superuser\n"));
365  printf(_(" -S, --no-superuser role will not be superuser (default)\n"));
366  printf(_(" -V, --version output version information, then exit\n"));
367  printf(_(" --interactive prompt for missing role name and attributes rather\n"
368  " than using defaults\n"));
369  printf(_(" --replication role can initiate replication\n"));
370  printf(_(" --no-replication role cannot initiate replication\n"));
371  printf(_(" -?, --help show this help, then exit\n"));
372  printf(_("\nConnection options:\n"));
373  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
374  printf(_(" -p, --port=PORT database server port\n"));
375  printf(_(" -U, --username=USERNAME user name to connect as (not the one to create)\n"));
376  printf(_(" -w, --no-password never prompt for password\n"));
377  printf(_(" -W, --password force password prompt\n"));
378  printf(_("\nReport bugs to <pgsql-bugs@lists.postgresql.org>.\n"));
379 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6684
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
bool yesno_prompt(const char *question)
Definition: common.c:435
const char * fmtId(const char *rawid)
Definition: string_utils.c:64
const char * get_progname(const char *argv0)
Definition: path.c:453
#define pg_log_error(...)
Definition: logging.h:79
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
void pg_logging_init(const char *argv0)
Definition: logging.c:39
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4182
bool superuser(void)
Definition: superuser.c:46
#define printf(...)
Definition: port.h:198
static bool pwprompt
Definition: initdb.c:134
const char * progname
Definition: pg_standby.c:36
#define fprintf
Definition: port.h:196
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
#define required_argument
Definition: getopt_long.h:25
int optind
Definition: getopt.c:50
PGconn * conn
Definition: streamutil.c:54
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
char * c
void simple_prompt(const char *prompt, char *destination, size_t destlen, bool echo)
Definition: sprompt.c:37
struct SimpleStringListCell * next
Definition: simple_list.h:34
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
int main(int argc, char *argv[])
Definition: createuser.c:23
static int port
Definition: pg_regress.c:90
void handle_help_version_opts(int argc, char *argv[], const char *fixed_progname, help_handler hlp)
Definition: common.c:33
trivalue
Definition: vacuumlo.c:33
#define no_argument
Definition: getopt_long.h:24
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1174
void simple_string_list_append(SimpleStringList *list, const char *val)
Definition: simple_list.c:63
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:380
static char * username
Definition: initdb.c:133
void PQclear(PGresult *res)
Definition: fe-exec.c:694
static PGconn * connectDatabase(const char *dbname, const char *connstr, const char *pghost, const char *pgport, const char *pguser, trivalue prompt_password, bool fail_on_error)
Definition: pg_dumpall.c:1634
SimpleStringListCell * head
Definition: simple_list.h:42
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1189
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
Oid createdb(ParseState *pstate, const CreatedbStmt *stmt)
Definition: dbcommands.c:100
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:435
char * optarg
Definition: getopt.c:52
char val[FLEXIBLE_ARRAY_MEMBER]
Definition: simple_list.h:37
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939
static void help(const char *progname)
Definition: createuser.c:345
#define _(x)
Definition: elog.c:87
void PQfreemem(void *ptr)
Definition: fe-exec.c:3296
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
char * login
Definition: pgbench.c:244
const char * get_user_name_or_exit(const char *progname)
Definition: username.c:74