PostgreSQL Source Code  git master
createuser.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * createuser
4  *
5  * Portions Copyright (c) 1996-2021, 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 
15 #include <limits.h>
16 
17 #include "common.h"
18 #include "common/logging.h"
19 #include "common/string.h"
20 #include "fe_utils/option_utils.h"
21 #include "fe_utils/simple_list.h"
22 #include "fe_utils/string_utils.h"
23 
24 
25 static void help(const char *progname);
26 
27 int
28 main(int argc, char *argv[])
29 {
30  static struct option long_options[] = {
31  {"host", required_argument, NULL, 'h'},
32  {"port", required_argument, NULL, 'p'},
33  {"username", required_argument, NULL, 'U'},
34  {"role", required_argument, NULL, 'g'},
35  {"no-password", no_argument, NULL, 'w'},
36  {"password", no_argument, NULL, 'W'},
37  {"echo", no_argument, NULL, 'e'},
38  {"createdb", no_argument, NULL, 'd'},
39  {"no-createdb", no_argument, NULL, 'D'},
40  {"superuser", no_argument, NULL, 's'},
41  {"no-superuser", no_argument, NULL, 'S'},
42  {"createrole", no_argument, NULL, 'r'},
43  {"no-createrole", no_argument, NULL, 'R'},
44  {"inherit", no_argument, NULL, 'i'},
45  {"no-inherit", no_argument, NULL, 'I'},
46  {"login", no_argument, NULL, 'l'},
47  {"no-login", no_argument, NULL, 'L'},
48  {"replication", no_argument, NULL, 1},
49  {"no-replication", no_argument, NULL, 2},
50  {"interactive", no_argument, NULL, 3},
51  {"connection-limit", required_argument, NULL, 'c'},
52  {"pwprompt", no_argument, NULL, 'P'},
53  {"encrypted", no_argument, NULL, 'E'},
54  {NULL, 0, NULL, 0}
55  };
56 
57  const char *progname;
58  int optindex;
59  int c;
60  const char *newuser = NULL;
61  char *host = NULL;
62  char *port = NULL;
63  char *username = NULL;
64  SimpleStringList roles = {NULL, NULL};
65  enum trivalue prompt_password = TRI_DEFAULT;
66  ConnParams cparams;
67  bool echo = false;
68  bool interactive = false;
69  int conn_limit = -2; /* less than minimum valid value */
70  bool pwprompt = false;
71  char *newpassword = NULL;
72 
73  /* Tri-valued variables. */
76  createrole = TRI_DEFAULT,
77  inherit = TRI_DEFAULT,
78  login = TRI_DEFAULT,
79  replication = TRI_DEFAULT;
80 
81  PQExpBufferData sql;
82 
83  PGconn *conn;
84  PGresult *result;
85 
86  pg_logging_init(argv[0]);
87  progname = get_progname(argv[0]);
88  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pgscripts"));
89 
90  handle_help_version_opts(argc, argv, "createuser", help);
91 
92  while ((c = getopt_long(argc, argv, "h:p:U:g:wWedDsSrRiIlLc:PE",
93  long_options, &optindex)) != -1)
94  {
95  switch (c)
96  {
97  case 'h':
98  host = pg_strdup(optarg);
99  break;
100  case 'p':
101  port = pg_strdup(optarg);
102  break;
103  case 'U':
104  username = pg_strdup(optarg);
105  break;
106  case 'g':
108  break;
109  case 'w':
110  prompt_password = TRI_NO;
111  break;
112  case 'W':
113  prompt_password = TRI_YES;
114  break;
115  case 'e':
116  echo = true;
117  break;
118  case 'd':
119  createdb = TRI_YES;
120  break;
121  case 'D':
122  createdb = TRI_NO;
123  break;
124  case 's':
125  superuser = TRI_YES;
126  break;
127  case 'S':
128  superuser = TRI_NO;
129  break;
130  case 'r':
131  createrole = TRI_YES;
132  break;
133  case 'R':
134  createrole = TRI_NO;
135  break;
136  case 'i':
137  inherit = TRI_YES;
138  break;
139  case 'I':
140  inherit = TRI_NO;
141  break;
142  case 'l':
143  login = TRI_YES;
144  break;
145  case 'L':
146  login = TRI_NO;
147  break;
148  case 'c':
149  if (!option_parse_int(optarg, "-c/--connection-limit",
150  -1, INT_MAX, &conn_limit))
151  exit(1);
152  break;
153  case 'P':
154  pwprompt = true;
155  break;
156  case 'E':
157  /* no-op, accepted for backward compatibility */
158  break;
159  case 1:
160  replication = TRI_YES;
161  break;
162  case 2:
163  replication = TRI_NO;
164  break;
165  case 3:
166  interactive = true;
167  break;
168  default:
169  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
170  exit(1);
171  }
172  }
173 
174  switch (argc - optind)
175  {
176  case 0:
177  break;
178  case 1:
179  newuser = argv[optind];
180  break;
181  default:
182  pg_log_error("too many command-line arguments (first is \"%s\")",
183  argv[optind + 1]);
184  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
185  exit(1);
186  }
187 
188  if (newuser == NULL)
189  {
190  if (interactive)
191  {
192  newuser = simple_prompt("Enter name of role to add: ", true);
193  }
194  else
195  {
196  if (getenv("PGUSER"))
197  newuser = getenv("PGUSER");
198  else
199  newuser = get_user_name_or_exit(progname);
200  }
201  }
202 
203  if (pwprompt)
204  {
205  char *pw2;
206 
207  newpassword = simple_prompt("Enter password for new role: ", false);
208  pw2 = simple_prompt("Enter it again: ", false);
209  if (strcmp(newpassword, pw2) != 0)
210  {
211  fprintf(stderr, _("Passwords didn't match.\n"));
212  exit(1);
213  }
214  free(pw2);
215  }
216 
217  if (superuser == 0)
218  {
219  if (interactive && yesno_prompt("Shall the new role be a superuser?"))
220  superuser = TRI_YES;
221  else
222  superuser = TRI_NO;
223  }
224 
225  if (superuser == TRI_YES)
226  {
227  /* Not much point in trying to restrict a superuser */
228  createdb = TRI_YES;
229  createrole = TRI_YES;
230  }
231 
232  if (createdb == 0)
233  {
234  if (interactive && yesno_prompt("Shall the new role be allowed to create databases?"))
235  createdb = TRI_YES;
236  else
237  createdb = TRI_NO;
238  }
239 
240  if (createrole == 0)
241  {
242  if (interactive && yesno_prompt("Shall the new role be allowed to create more new roles?"))
243  createrole = TRI_YES;
244  else
245  createrole = TRI_NO;
246  }
247 
248  if (inherit == 0)
249  inherit = TRI_YES;
250 
251  if (login == 0)
252  login = TRI_YES;
253 
254  cparams.dbname = NULL; /* this program lacks any dbname option... */
255  cparams.pghost = host;
256  cparams.pgport = port;
257  cparams.pguser = username;
258  cparams.prompt_password = prompt_password;
259  cparams.override_dbname = NULL;
260 
261  conn = connectMaintenanceDatabase(&cparams, progname, echo);
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 <%s>.\n"), PACKAGE_BUGREPORT);
379  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
380 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6744
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
bool yesno_prompt(const char *question)
Definition: common.c:136
const char * progname
Definition: main.c:46
char * pgport
Definition: pg_backup.h:66
const char * fmtId(const char *rawid)
Definition: string_utils.c:64
bool option_parse_int(const char *optarg, const char *optname, int min_range, int max_range, int *result)
Definition: option_utils.c:50
const char * get_progname(const char *argv0)
Definition: path.c:453
#define pg_log_error(...)
Definition: logging.h:80
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:81
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4231
bool superuser(void)
Definition: superuser.c:46
#define printf(...)
Definition: port.h:222
char * simple_prompt(const char *prompt, bool echo)
Definition: sprompt.c:38
static bool pwprompt
Definition: initdb.c:135
#define fprintf
Definition: port.h:220
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3178
char * dbname
Definition: pg_backup.h:65
#define required_argument
Definition: getopt_long.h:25
int optind
Definition: getopt.c:50
void handle_help_version_opts(int argc, char *argv[], const char *fixed_progname, help_handler hlp)
Definition: option_utils.c:24
PGconn * conn
Definition: streamutil.c:54
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
char * c
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:28
const char * username
Definition: pgbench.c:282
char * override_dbname
Definition: pg_backup.h:72
static int port
Definition: pg_regress.c:92
char * pghost
Definition: pg_backup.h:67
enum trivalue prompt_password
Definition: connect_utils.h:32
trivalue
Definition: vacuumlo.c:34
#define no_argument
Definition: getopt_long.h:24
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1215
void simple_string_list_append(SimpleStringList *list, const char *val)
Definition: simple_list.c:63
PGconn * connectMaintenanceDatabase(ConnParams *cparams, const char *progname, bool echo)
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:380
void PQclear(PGresult *res)
Definition: fe-exec.c:694
#define free(a)
Definition: header.h:65
SimpleStringListCell * head
Definition: simple_list.h:42
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1217
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:433
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:2193
static void help(const char *progname)
Definition: createuser.c:345
#define _(x)
Definition: elog.c:89
void PQfreemem(void *ptr)
Definition: fe-exec.c:3796
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
const char * pguser
Definition: connect_utils.h:31
const char * get_user_name_or_exit(const char *progname)
Definition: username.c:74