本文整理汇总了C++中pstrdup函数的典型用法代码示例。如果您正苦于以下问题:C++ pstrdup函数的具体用法?C++ pstrdup怎么用?C++ pstrdup使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了pstrdup函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: authfile_getgroups
MODRET authfile_getgroups(cmd_rec *cmd) {
struct passwd *pwd = NULL;
struct group *grp = NULL;
array_header *gids = NULL, *groups = NULL;
char *name = cmd->argv[0];
if (name == NULL) {
return PR_DECLINED(cmd);
}
if (af_setpwent(cmd->tmp_pool) < 0) {
return PR_DECLINED(cmd);
}
if (af_setgrent(cmd->tmp_pool) < 0) {
return PR_DECLINED(cmd);
}
/* Check for NULLs */
if (cmd->argv[1]) {
gids = (array_header *) cmd->argv[1];
}
if (cmd->argv[2]) {
groups = (array_header *) cmd->argv[2];
}
/* Retrieve the necessary info. */
pwd = af_getpwnam(cmd->tmp_pool, name);
if (pwd == NULL) {
return PR_DECLINED(cmd);
}
/* Populate the first group ID and name. */
if (gids) {
*((gid_t *) push_array(gids)) = pwd->pw_gid;
}
if (groups &&
(grp = af_getgrgid(cmd->tmp_pool, pwd->pw_gid)) != NULL) {
*((char **) push_array(groups)) = pstrdup(session.pool, grp->gr_name);
}
(void) af_setgrent(cmd->tmp_pool);
/* This is where things get slow, expensive, and ugly. Loop through
* everything, checking to make sure we haven't already added it.
*/
while ((grp = af_getgrent(cmd->tmp_pool)) != NULL &&
grp->gr_mem) {
char **gr_mems = NULL;
pr_signals_handle();
/* Loop through each member name listed */
for (gr_mems = grp->gr_mem; *gr_mems; gr_mems++) {
/* If it matches the given username... */
if (strcmp(*gr_mems, pwd->pw_name) == 0) {
/* ...add the GID and name */
if (gids) {
*((gid_t *) push_array(gids)) = grp->gr_gid;
}
if (groups) {
*((char **) push_array(groups)) = pstrdup(session.pool, grp->gr_name);
}
}
}
}
if (gids && gids->nelts > 0) {
return mod_create_data(cmd, (void *) &gids->nelts);
} else if (groups && groups->nelts > 0) {
return mod_create_data(cmd, (void *) &groups->nelts);
}
return PR_DECLINED(cmd);
}
示例2: main
int main(int argc, char *argv[]) {
unsigned char verbose = FALSE;
char **respargv = NULL;
const char *cmdopts = "hs:v";
register int i = 0;
char *socket_file = PR_RUN_DIR "/proftpd.sock";
int sockfd = -1, optc = 0, status = 0, respargc = 0;
unsigned int reqargc = 0;
pool *ctl_pool = NULL;
array_header *reqargv = NULL;
/* Make sure we were called with at least one argument. */
if (argc-1 < 1) {
fprintf(stdout, "%s: missing required arguments\n", program);
exit(1);
}
/* Set the POSIXLY_CORRECT environment variable, so that control handlers
* can themselves have optional flags.
*/
if (putenv("POSIXLY_CORRECT=1") < 0) {
fprintf(stderr, "%s: unable to set POSIXLY_CORRECT: %s\n", program,
strerror(errno));
exit(1);
}
opterr = 0;
while ((optc = getopt(argc, argv, cmdopts)) != -1) {
switch (optc) {
case 'h':
usage();
return 0;
case 's':
if (*optarg != '/') {
fprintf(stderr, "%s: alternate socket path must be an absolute "
"path\n", program);
return 1;
}
socket_file = optarg;
break;
case 'v':
verbose = TRUE;
break;
case '?':
fprintf(stdout, "%s: unknown option: %c\n", program, (char) optopt);
break;
}
}
signal(SIGPIPE, sig_pipe);
/* Allocate some memory for proftpd objects. */
ctl_pool = make_sub_pool(NULL);
reqargv = make_array(ctl_pool, 0, sizeof(char *));
/* Process the command-line args into an array_header. */
for (i = optind; i < argc; i++) {
if (verbose)
fprintf(stdout, "%s: adding \"%s\" to reqargv\n", program, argv[i]);
*((char **) push_array(reqargv)) = pstrdup(ctl_pool, argv[i]);
reqargc++;
}
/* Don't forget to NULL-terminate the array. */
*((char **) push_array(reqargv)) = NULL;
/* Open a connection to the socket maintained by mod_ctrls. */
if (verbose)
fprintf(stdout, "%s: contacting server using '%s'\n", program,
socket_file);
sockfd = pr_ctrls_connect(socket_file);
if (sockfd < 0) {
fprintf(stderr, "%s: error contacting server using '%s': %s\n", program,
socket_file, strerror(errno));
exit(1);
}
if (verbose)
fprintf(stdout, "%s: sending control request\n", program);
if (pr_ctrls_send_msg(sockfd, 0, reqargc, (char **) reqargv->elts) < 0) {
fprintf(stderr, "%s: error sending request: %s\n", program,
strerror(errno));
exit(1);
}
/* Read and display the responses. */
if (verbose)
fprintf(stdout, "%s: receiving control response\n", program);
/* Manually set errno to this value, so that if an error (like a segfault)
* occurs, the error string displayed to the user is more indicative of
//.........这里部分代码省略.........
示例3: datum_to_jsonb
//.........这里部分代码省略.........
if (!numeric_error)
{
jb.type = jbvNumeric;
jb.val.numeric = DatumGetNumeric(DirectFunctionCall3(numeric_in, CStringGetDatum(outputstr), 0, -1));
pfree(outputstr);
}
else
{
jb.type = jbvString;
jb.val.string.len = strlen(outputstr);
jb.val.string.val = outputstr;
}
}
break;
case JSONBTYPE_DATE:
{
DateADT date;
struct pg_tm tm;
char buf[MAXDATELEN + 1];
date = DatumGetDateADT(val);
/* Same as date_out(), but forcing DateStyle */
if (DATE_NOT_FINITE(date))
EncodeSpecialDate(date, buf);
else
{
j2date(date + POSTGRES_EPOCH_JDATE,
&(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
EncodeDateOnly(&tm, USE_XSD_DATES, buf);
}
jb.type = jbvString;
jb.val.string.len = strlen(buf);
jb.val.string.val = pstrdup(buf);
}
break;
case JSONBTYPE_TIMESTAMP:
{
Timestamp timestamp;
struct pg_tm tm;
fsec_t fsec;
char buf[MAXDATELEN + 1];
timestamp = DatumGetTimestamp(val);
/* Same as timestamp_out(), but forcing DateStyle */
if (TIMESTAMP_NOT_FINITE(timestamp))
EncodeSpecialTimestamp(timestamp, buf);
else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
else
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
jb.type = jbvString;
jb.val.string.len = strlen(buf);
jb.val.string.val = pstrdup(buf);
}
break;
case JSONBTYPE_TIMESTAMPTZ:
{
TimestampTz timestamp;
struct pg_tm tm;
int tz;
fsec_t fsec;
const char *tzn = NULL;
char buf[MAXDATELEN + 1];
示例4: regoperout
/*
* regoperout - converts operator OID to "opr_name"
*/
Datum
regoperout(PG_FUNCTION_ARGS)
{
Oid oprid = PG_GETARG_OID(0);
char *result;
HeapTuple opertup;
if (oprid == InvalidOid)
{
result = pstrdup("0");
PG_RETURN_CSTRING(result);
}
opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
if (HeapTupleIsValid(opertup))
{
Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
char *oprname = NameStr(operform->oprname);
/*
* In bootstrap mode, skip the fancy namespace stuff and just return
* the oper name. (This path is only needed for debugging output
* anyway.)
*/
if (IsBootstrapProcessingMode())
result = pstrdup(oprname);
else
{
FuncCandidateList clist;
/*
* Would this oper be found (uniquely!) by regoperin? If not,
* qualify it.
*/
clist = OpernameGetCandidates(list_make1(makeString(oprname)),
'\0');
if (clist != NULL && clist->next == NULL &&
clist->oid == oprid)
result = pstrdup(oprname);
else
{
const char *nspname;
nspname = get_namespace_name(operform->oprnamespace);
nspname = quote_identifier(nspname);
result = (char *) palloc(strlen(nspname) + strlen(oprname) + 2);
sprintf(result, "%s.%s", nspname, oprname);
}
}
ReleaseSysCache(opertup);
}
else
{
/*
* If OID doesn't match any pg_operator entry, return it numerically
*/
result = (char *) palloc(NAMEDATALEN);
snprintf(result, NAMEDATALEN, "%u", oprid);
}
PG_RETURN_CSTRING(result);
}
示例5: connect_pg_server
/*
* Connect to remote server using specified server and user mapping properties.
*/
static PGconn *
connect_pg_server(ForeignServer *server, UserMapping *user)
{
PGconn *volatile conn = NULL;
/*
* Use PG_TRY block to ensure closing connection on error.
*/
PG_TRY();
{
const char **keywords;
const char **values;
int n;
/*
* Construct connection params from generic options of ForeignServer
* and UserMapping. (Some of them might not be libpq options, in
* which case we'll just waste a few array slots.) Add 3 extra slots
* for fallback_application_name, client_encoding, end marker.
*/
n = list_length(server->options) + list_length(user->options) + 3;
keywords = (const char **) palloc(n * sizeof(char *));
values = (const char **) palloc(n * sizeof(char *));
n = 0;
n += ExtractConnectionOptions(server->options,
keywords + n, values + n);
n += ExtractConnectionOptions(user->options,
keywords + n, values + n);
/* Use "postgres_fdw" as fallback_application_name. */
keywords[n] = "fallback_application_name";
values[n] = "postgres_fdw";
n++;
/* Set client_encoding so that libpq can convert encoding properly. */
keywords[n] = "client_encoding";
values[n] = GetDatabaseEncodingName();
n++;
keywords[n] = values[n] = NULL;
/* verify connection parameters and make connection */
check_conn_params(keywords, values);
conn = PQconnectdbParams(keywords, values, false);
if (!conn || PQstatus(conn) != CONNECTION_OK)
{
char *connmessage;
int msglen;
/* libpq typically appends a newline, strip that */
connmessage = pstrdup(PQerrorMessage(conn));
msglen = strlen(connmessage);
if (msglen > 0 && connmessage[msglen - 1] == '\n')
connmessage[msglen - 1] = '\0';
ereport(ERROR,
(errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
errmsg("could not connect to server \"%s\"",
server->servername),
errdetail_internal("%s", connmessage)));
}
/*
* Check that non-superuser has used password to establish connection;
* otherwise, he's piggybacking on the postgres server's user
* identity. See also dblink_security_check() in contrib/dblink.
*/
if (!superuser() && !PQconnectionUsedPassword(conn))
ereport(ERROR,
(errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
errmsg("password is required"),
errdetail("Non-superuser cannot connect if the server does not request a password."),
errhint("Target server's authentication method must be changed.")));
/* Prepare new session for use */
configure_remote_session(conn);
pfree(keywords);
pfree(values);
}
PG_CATCH();
{
/* Release PGconn data structure if we managed to create one */
if (conn)
PQfinish(conn);
PG_RE_THROW();
}
PG_END_TRY();
return conn;
}
示例6: sepgsql_avc_compute
/*
* sepgsql_avc_compute
*
* A fallback path, when cache mishit. It asks SELinux its access control
* decision for the supplied pair of security context and object class.
*/
static avc_cache *
sepgsql_avc_compute(const char *scontext, const char *tcontext, uint16 tclass)
{
char *ucontext = NULL;
char *ncontext = NULL;
MemoryContext oldctx;
avc_cache *cache;
uint32 hash;
int index;
struct av_decision avd;
hash = sepgsql_avc_hash(scontext, tcontext, tclass);
index = hash % AVC_NUM_SLOTS;
/*
* Validation check of the supplied security context. Because it always
* invoke system-call, frequent check should be avoided. Unless security
* policy is reloaded, validation status shall be kept, so we also cache
* whether the supplied security context was valid, or not.
*/
if (security_check_context_raw((security_context_t) tcontext) != 0)
ucontext = sepgsql_avc_unlabeled();
/*
* Ask SELinux its access control decision
*/
if (!ucontext)
sepgsql_compute_avd(scontext, tcontext, tclass, &avd);
else
sepgsql_compute_avd(scontext, ucontext, tclass, &avd);
/*
* It also caches a security label to be switched when a client labeled as
* 'scontext' executes a procedure labeled as 'tcontext', not only access
* control decision on the procedure. The security label to be switched
* shall be computed uniquely on a pair of 'scontext' and 'tcontext',
* thus, it is reasonable to cache the new label on avc, and enables to
* reduce unnecessary system calls. It shall be referenced at
* sepgsql_needs_fmgr_hook to check whether the supplied function is a
* trusted procedure, or not.
*/
if (tclass == SEPG_CLASS_DB_PROCEDURE)
{
if (!ucontext)
ncontext = sepgsql_compute_create(scontext, tcontext,
SEPG_CLASS_PROCESS, NULL);
else
ncontext = sepgsql_compute_create(scontext, ucontext,
SEPG_CLASS_PROCESS, NULL);
if (strcmp(scontext, ncontext) == 0)
{
pfree(ncontext);
ncontext = NULL;
}
}
/*
* Set up an avc_cache object
*/
oldctx = MemoryContextSwitchTo(avc_mem_cxt);
cache = palloc0(sizeof(avc_cache));
cache->hash = hash;
cache->scontext = pstrdup(scontext);
cache->tcontext = pstrdup(tcontext);
cache->tclass = tclass;
cache->allowed = avd.allowed;
cache->auditallow = avd.auditallow;
cache->auditdeny = avd.auditdeny;
cache->hot_cache = true;
if (avd.flags & SELINUX_AVD_FLAGS_PERMISSIVE)
cache->permissive = true;
if (!ucontext)
cache->tcontext_is_valid = true;
if (ncontext)
cache->ncontext = pstrdup(ncontext);
avc_num_caches++;
if (avc_num_caches > avc_threshold)
sepgsql_avc_reclaim();
avc_slots[index] = lcons(cache, avc_slots[index]);
MemoryContextSwitchTo(oldctx);
return cache;
}
示例7: pr_var_set
int pr_var_set(pool *p, const char *name, const char *desc, int type,
void *val, void *data, size_t datasz) {
struct var *v;
if (var_tab == NULL) {
errno = EPERM;
return -1;
}
if (p == NULL ||
name == NULL ||
val == NULL) {
errno = EINVAL;
return -1;
}
/* The length of the key must be greater than 3 characters (for "%{}"). */
if (strlen(name) < 4) {
errno = EINVAL;
return -1;
}
/* Specifying data, but no length for that data, is an error. */
if (data != NULL &&
datasz == 0) {
errno = EINVAL;
return -1;
}
/* Specifying no data, but providing a non-zero length for that data, is an
* error.
*/
if (data == NULL &&
datasz > 0) {
errno = EINVAL;
return -1;
}
/* Variable names MUST start with '%{', and end in '}'. */
if (strncmp(name, "%{", 2) != 0 ||
name[strlen(name)-1] != '}') {
errno = EINVAL;
return -1;
}
/* Remove any previously registered value for this name. For names whose
* values change rapidly (e.g. session.xfer.total_bytes), a callback
* function should be used, rather than always setting the same name as an
* update; using a callback avoids the memory consumption that setting does
* (set always allocates a new struct var *).
*/
(void) pr_var_delete(name);
/* Note: if var_pool was used for allocating the struct var *, rather
* than the given pool, then deleting an entry would not necessarily
* lead to such memory consumption (assuming it would even be a problem).
* However, if this was the case, then a churn counter would be needed,
* and var_pool would need to be churned occasionally to limit memory
* growth.
*/
switch (type) {
case PR_VAR_TYPE_STR:
v = pcalloc(p, sizeof(struct var));
if (desc)
v->v_desc = (const char *) pstrdup(p, desc);
v->v_type = PR_VAR_TYPE_STR;
v->v_val = pstrdup(p, (char *) val);
v->v_datasz = strlen((char *) val);
break;
case PR_VAR_TYPE_FUNC:
v = pcalloc(p, sizeof(struct var));
if (desc)
v->v_desc = (const char *) pstrdup(p, desc);
v->v_type = PR_VAR_TYPE_FUNC;
v->v_val = val;
if (data) {
v->v_data = data;
v->v_datasz = datasz;
}
break;
default:
errno = EINVAL;
return -1;
}
return pr_table_add(var_tab, name, v, sizeof(struct var));
}
示例8: CreateTableSpace
/*
* Create a table space
*
* Only superusers can create a tablespace. This seems a reasonable restriction
* since we're determining the system layout and, anyway, we probably have
* root if we're doing this kind of activity
*/
Oid
CreateTableSpace(CreateTableSpaceStmt *stmt)
{
#ifdef HAVE_SYMLINK
Relation rel;
Datum values[Natts_pg_tablespace];
bool nulls[Natts_pg_tablespace];
HeapTuple tuple;
Oid tablespaceoid;
char *location;
Oid ownerId;
/* Must be super user */
if (!superuser())
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied to create tablespace \"%s\"",
stmt->tablespacename),
errhint("Must be superuser to create a tablespace.")));
/* However, the eventual owner of the tablespace need not be */
if (stmt->owner)
ownerId = get_role_oid(stmt->owner, false);
else
ownerId = GetUserId();
/* Unix-ify the offered path, and strip any trailing slashes */
location = pstrdup(stmt->location);
canonicalize_path(location);
/* disallow quotes, else CREATE DATABASE would be at risk */
if (strchr(location, '\''))
ereport(ERROR,
(errcode(ERRCODE_INVALID_NAME),
errmsg("tablespace location cannot contain single quotes")));
/*
* Allowing relative paths seems risky
*
* this also helps us ensure that location is not empty or whitespace
*/
if (!is_absolute_path(location))
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("tablespace location must be an absolute path")));
/*
* Check that location isn't too long. Remember that we're going to append
* 'PG_XXX/<dboid>/<relid>.<nnn>'. FYI, we never actually reference the
* whole path, but mkdir() uses the first two parts.
*/
if (strlen(location) + 1 + strlen(TABLESPACE_VERSION_DIRECTORY) + 1 +
OIDCHARS + 1 + OIDCHARS + 1 + OIDCHARS > MAXPGPATH)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("tablespace location \"%s\" is too long",
location)));
/*
* Disallow creation of tablespaces named "pg_xxx"; we reserve this
* namespace for system purposes.
*/
if (!allowSystemTableMods && IsReservedName(stmt->tablespacename))
ereport(ERROR,
(errcode(ERRCODE_RESERVED_NAME),
errmsg("unacceptable tablespace name \"%s\"",
stmt->tablespacename),
errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
/*
* Check that there is no other tablespace by this name. (The unique
* index would catch this anyway, but might as well give a friendlier
* message.)
*/
if (OidIsValid(get_tablespace_oid(stmt->tablespacename, true)))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("tablespace \"%s\" already exists",
stmt->tablespacename)));
/*
* Insert tuple into pg_tablespace. The purpose of doing this first is to
* lock the proposed tablename against other would-be creators. The
* insertion will roll back if we find problems below.
*/
rel = heap_open(TableSpaceRelationId, RowExclusiveLock);
MemSet(nulls, false, sizeof(nulls));
values[Anum_pg_tablespace_spcname - 1] =
DirectFunctionCall1(namein, CStringGetDatum(stmt->tablespacename));
values[Anum_pg_tablespace_spcowner - 1] =
ObjectIdGetDatum(ownerId);
//.........这里部分代码省略.........
示例9: destroy_tablespace_directories
//.........这里部分代码省略.........
if (dirdesc == NULL)
{
if (errno == ENOENT)
{
if (!redo)
ereport(WARNING,
(errcode_for_file_access(),
errmsg("could not open directory \"%s\": %m",
linkloc_with_version_dir)));
/* The symlink might still exist, so go try to remove it */
goto remove_symlink;
}
else if (redo)
{
/* in redo, just log other types of error */
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not open directory \"%s\": %m",
linkloc_with_version_dir)));
pfree(linkloc_with_version_dir);
return false;
}
/* else let ReadDir report the error */
}
while ((de = ReadDir(dirdesc, linkloc_with_version_dir)) != NULL)
{
if (strcmp(de->d_name, ".") == 0 ||
strcmp(de->d_name, "..") == 0)
continue;
subfile = psprintf("%s/%s", linkloc_with_version_dir, de->d_name);
/* This check is just to deliver a friendlier error message */
if (!redo && !directory_is_empty(subfile))
{
FreeDir(dirdesc);
pfree(subfile);
pfree(linkloc_with_version_dir);
return false;
}
/* remove empty directory */
if (rmdir(subfile) < 0)
ereport(redo ? LOG : ERROR,
(errcode_for_file_access(),
errmsg("could not remove directory \"%s\": %m",
subfile)));
pfree(subfile);
}
FreeDir(dirdesc);
/* remove version directory */
if (rmdir(linkloc_with_version_dir) < 0)
{
ereport(redo ? LOG : ERROR,
(errcode_for_file_access(),
errmsg("could not remove directory \"%s\": %m",
linkloc_with_version_dir)));
pfree(linkloc_with_version_dir);
return false;
}
/*
* Try to remove the symlink. We must however deal with the possibility
* that it's a directory instead of a symlink --- this could happen during
* WAL replay (see TablespaceCreateDbspace), and it is also the case on
* Windows where junction points lstat() as directories.
*
* Note: in the redo case, we'll return true if this final step fails;
* there's no point in retrying it. Also, ENOENT should provoke no more
* than a warning.
*/
remove_symlink:
linkloc = pstrdup(linkloc_with_version_dir);
get_parent_directory(linkloc);
if (lstat(linkloc, &st) == 0 && S_ISDIR(st.st_mode))
{
if (rmdir(linkloc) < 0)
ereport(redo ? LOG : ERROR,
(errcode_for_file_access(),
errmsg("could not remove directory \"%s\": %m",
linkloc)));
}
else
{
if (unlink(linkloc) < 0)
ereport(redo ? LOG : (errno == ENOENT ? WARNING : ERROR),
(errcode_for_file_access(),
errmsg("could not remove symbolic link \"%s\": %m",
linkloc)));
}
pfree(linkloc_with_version_dir);
pfree(linkloc);
return true;
}
示例10: check_temp_tablespaces
/* check_hook: validate new temp_tablespaces */
bool
check_temp_tablespaces(char **newval, void **extra, GucSource source)
{
char *rawname;
List *namelist;
/* Need a modifiable copy of string */
rawname = pstrdup(*newval);
/* Parse string into list of identifiers */
if (!SplitIdentifierString(rawname, ',', &namelist))
{
/* syntax error in name list */
GUC_check_errdetail("List syntax is invalid.");
pfree(rawname);
list_free(namelist);
return false;
}
/*
* If we aren't inside a transaction, we cannot do database access so
* cannot verify the individual names. Must accept the list on faith.
* Fortunately, there's then also no need to pass the data to fd.c.
*/
if (IsTransactionState())
{
temp_tablespaces_extra *myextra;
Oid *tblSpcs;
int numSpcs;
ListCell *l;
/* temporary workspace until we are done verifying the list */
tblSpcs = (Oid *) palloc(list_length(namelist) * sizeof(Oid));
numSpcs = 0;
foreach(l, namelist)
{
char *curname = (char *) lfirst(l);
Oid curoid;
AclResult aclresult;
/* Allow an empty string (signifying database default) */
if (curname[0] == '\0')
{
tblSpcs[numSpcs++] = InvalidOid;
continue;
}
/*
* In an interactive SET command, we ereport for bad info. When
* source == PGC_S_TEST, don't throw a hard error for a
* nonexistent tablespace, only a NOTICE. See comments in guc.h.
*/
curoid = get_tablespace_oid(curname, source <= PGC_S_TEST);
if (curoid == InvalidOid)
{
if (source == PGC_S_TEST)
ereport(NOTICE,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("tablespace \"%s\" does not exist",
curname)));
continue;
}
/*
* Allow explicit specification of database's default tablespace
* in temp_tablespaces without triggering permissions checks.
*/
if (curoid == MyDatabaseTableSpace)
{
tblSpcs[numSpcs++] = InvalidOid;
continue;
}
/* Check permissions, similarly complaining only if interactive */
aclresult = pg_tablespace_aclcheck(curoid, GetUserId(),
ACL_CREATE);
if (aclresult != ACLCHECK_OK)
{
if (source >= PGC_S_INTERACTIVE)
aclcheck_error(aclresult, ACL_KIND_TABLESPACE, curname);
continue;
}
tblSpcs[numSpcs++] = curoid;
}
/* Now prepare an "extra" struct for assign_temp_tablespaces */
myextra = malloc(offsetof(temp_tablespaces_extra, tblSpcs) +
numSpcs * sizeof(Oid));
if (!myextra)
return false;
myextra->numSpcs = numSpcs;
memcpy(myextra->tblSpcs, tblSpcs, numSpcs * sizeof(Oid));
*extra = (void *) myextra;
pfree(tblSpcs);
}
示例11: TablespaceCreateDbspace
/*
* Each database using a table space is isolated into its own name space
* by a subdirectory named for the database OID. On first creation of an
* object in the tablespace, create the subdirectory. If the subdirectory
* already exists, fall through quietly.
*
* isRedo indicates that we are creating an object during WAL replay.
* In this case we will cope with the possibility of the tablespace
* directory not being there either --- this could happen if we are
* replaying an operation on a table in a subsequently-dropped tablespace.
* We handle this by making a directory in the place where the tablespace
* symlink would normally be. This isn't an exact replay of course, but
* it's the best we can do given the available information.
*
* If tablespaces are not supported, we still need it in case we have to
* re-create a database subdirectory (of $PGDATA/base) during WAL replay.
*/
void
TablespaceCreateDbspace(Oid spcNode, Oid dbNode, bool isRedo)
{
struct stat st;
char *dir;
/*
* The global tablespace doesn't have per-database subdirectories, so
* nothing to do for it.
*/
if (spcNode == GLOBALTABLESPACE_OID)
return;
Assert(OidIsValid(spcNode));
Assert(OidIsValid(dbNode));
dir = GetDatabasePath(dbNode, spcNode);
if (stat(dir, &st) < 0)
{
/* Directory does not exist? */
if (errno == ENOENT)
{
/*
* Acquire TablespaceCreateLock to ensure that no DROP TABLESPACE
* or TablespaceCreateDbspace is running concurrently.
*/
LWLockAcquire(TablespaceCreateLock, LW_EXCLUSIVE);
/*
* Recheck to see if someone created the directory while we were
* waiting for lock.
*/
if (stat(dir, &st) == 0 && S_ISDIR(st.st_mode))
{
/* Directory was created */
}
else
{
/* Directory creation failed? */
if (mkdir(dir, S_IRWXU) < 0)
{
char *parentdir;
/* Failure other than not exists or not in WAL replay? */
if (errno != ENOENT || !isRedo)
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not create directory \"%s\": %m",
dir)));
/*
* Parent directories are missing during WAL replay, so
* continue by creating simple parent directories rather
* than a symlink.
*/
/* create two parents up if not exist */
parentdir = pstrdup(dir);
get_parent_directory(parentdir);
get_parent_directory(parentdir);
/* Can't create parent and it doesn't already exist? */
if (mkdir(parentdir, S_IRWXU) < 0 && errno != EEXIST)
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not create directory \"%s\": %m",
parentdir)));
pfree(parentdir);
/* create one parent up if not exist */
parentdir = pstrdup(dir);
get_parent_directory(parentdir);
/* Can't create parent and it doesn't already exist? */
if (mkdir(parentdir, S_IRWXU) < 0 && errno != EEXIST)
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not create directory \"%s\": %m",
parentdir)));
pfree(parentdir);
/* Create database directory */
if (mkdir(dir, S_IRWXU) < 0)
ereport(ERROR,
//.........这里部分代码省略.........
示例12: cash_out
//.........这里部分代码省略.........
int digit_pos;
int points,
mon_group;
char dsymbol;
const char *ssymbol,
*csymbol,
*nsymbol;
char convention;
struct lconv *lconvert = PGLC_localeconv();
/* see comments about frac_digits in cash_in() */
points = lconvert->frac_digits;
if (points < 0 || points > 10)
points = 2; /* best guess in this case, I think */
/*
* As with frac_digits, must apply a range check to mon_grouping to avoid
* being fooled by variant CHAR_MAX values.
*/
mon_group = *lconvert->mon_grouping;
if (mon_group <= 0 || mon_group > 6)
mon_group = 3;
convention = lconvert->n_sign_posn;
/* we restrict dsymbol to be a single byte, but not the other symbols */
if (*lconvert->mon_decimal_point != '\0' &&
lconvert->mon_decimal_point[1] == '\0')
dsymbol = *lconvert->mon_decimal_point;
else
dsymbol = '.';
if (*lconvert->mon_thousands_sep != '\0')
ssymbol = lconvert->mon_thousands_sep;
else /* ssymbol should not equal dsymbol */
ssymbol = (dsymbol != ',') ? "," : ".";
csymbol = (*lconvert->currency_symbol != '\0') ? lconvert->currency_symbol : "$";
nsymbol = (*lconvert->negative_sign != '\0') ? lconvert->negative_sign : "-";
/* we work with positive amounts and add the minus sign at the end */
if (value < 0)
{
minus = true;
value = -value;
}
/* we build the result string right-to-left in buf[] */
bufptr = buf + sizeof(buf) - 1;
*bufptr = '\0';
/*
* Generate digits till there are no non-zero digits left and we emitted
* at least one to the left of the decimal point. digit_pos is the
* current digit position, with zero as the digit just left of the decimal
* point, increasing to the right.
*/
digit_pos = points;
do
{
if (points && digit_pos == 0)
{
/* insert decimal point */
*(--bufptr) = dsymbol;
}
else if (digit_pos < points && (digit_pos % mon_group) == 0)
{
/* insert thousands sep */
bufptr -= strlen(ssymbol);
memcpy(bufptr, ssymbol, strlen(ssymbol));
}
*(--bufptr) = ((uint64) value % 10) + '0';
value = ((uint64) value) / 10;
digit_pos--;
} while (value || digit_pos >= 0);
/* prepend csymbol */
bufptr -= strlen(csymbol);
memcpy(bufptr, csymbol, strlen(csymbol));
/* see if we need to signify negative amount */
if (minus)
{
result = palloc(strlen(bufptr) + strlen(nsymbol) + 3);
/* Position code of 0 means use parens */
if (convention == 0)
sprintf(result, "(%s)", bufptr);
else if (convention == 2)
sprintf(result, "%s%s", bufptr, nsymbol);
else
sprintf(result, "%s%s", nsymbol, bufptr);
}
else
{
/* just emit what we have */
result = pstrdup(bufptr);
}
PG_RETURN_CSTRING(result);
}
示例13: newinput
//.........这里部分代码省略.........
if( Macro_depth != 0 ) {
/*
** in a macro, the 'current char' we want is kept as the
** first thing in the macro structure.
*/
pCurrC = (TEXT_TYPE)Macro_expansion[1].exp_string;
}
else {
pCurrC = (TEXT_TYPE)Current_char;
}
if(pCurrC >= p) {
/*
** p is the start of the child section.
** current char is past it. ie, we've already read some
** from the upper section.
** current char - p = # of characters used in upper section.
** numread = 0 implies there are no chars left from the parent.
** since, this is really the 'end' of the parent's buffer,
** we'll have to update the info so that the next read from the
** parent (after the child is finished) will be the terminator
** and we want the io_eob handler to refill the buffer.
** we reset the parent's cur char ptr to the beginning of its
** buffer, and put the terminator there.
*/
seek_posn += (pCurrC - pPrevF->fl_buffer);
pPrevF->fl_totalread += (pCurrC - pPrevF->fl_buffer);
pPrevF->fl_numread = 0;
if( Macro_depth != 0 ) {
Macro_expansion[1].exp_string = pPrevF->fl_buffer;
}
else {
Current_char = pPrevF->fl_buffer;
}
*(pPrevF->fl_buffer) = EOS_CHAR;
*(pPrevF->fl_pwchBuffer) = EOS_CHAR;
}
else {
/*
** the upper section has not been read from yet,
** but it has been read into.
** 'p' is pointing to the start of the child's buffer.
** we add the terminator to the new end of the parent's buffer.
*/
seek_posn += TWO_K;
pPrevF->fl_numread = TWO_K;
*(pPrevF->fl_buffer + TWO_K) = EOS_CHAR;
*(pPrevF->fl_pwchBuffer + TWO_K) = EOS_CHAR;
}
if (pPrevF->fl_fFileType == DFT_FILE_IS_8_BIT) {
fseek(pPrevF->fl_file, seek_posn, SEEK_SET);
} else {
fseek(pPrevF->fl_file, seek_posn * sizeof (WCHAR), SEEK_SET);
}
}
}
pF->fl_currc = Current_char;/* previous file's current char */
pF->fl_lineno = Linenumber; /* previous file's line number */
pF->fl_file = Fp; /* the new file descriptor */
pF->fl_buffer = p;
pF->fl_pwchBuffer = pwch;
pF->fl_numread = 0;
pF->fl_totalread = 0;
//- Added to support 16-bit files.
//- 8-2-91 David Marsyla.
pF->fl_fFileType = DetermineFileType (Fp);
//- The file type is unknown, warn them and then take a stab at an
//- 8-bit file. 8-2-91 David Marsyla.
if (pF->fl_fFileType == DFT_FILE_IS_UNKNOWN) {
Msg_Temp = GET_MSG (4413);
SET_MSG (Msg_Text, Msg_Temp, newname);
warning (4413);
pF->fl_fFileType = DFT_FILE_IS_8_BIT;
}
vfCurrFileType = pF->fl_fFileType;
Current_char = (ptext_t)p;
io_eob(); /* fill the buffer */
/*
* Note that include filenames will live the entire compiland. This
* puts the burden on the user with MANY include files. Any other
* scheme takes space out of static data.
* Notice also, that we save the previous filename in the new file's
* fl_name.
*/
pF->fl_name = pstrdup(Filename);
strncpy(Filebuff,newname,sizeof(Filebuff));
Linenumber = 0; /* do_newline() will increment to the first line */
if(Eflag) {
emit_line();
fwrite("\n", 1, 1, OUTPUTFILE); /* this line is inserted */
}
do_newline(); /* a new file may have preproc cmd as first line */
return(TRUE);
}
示例14: set_authgroupfile
/* usage: AuthGroupFile path [id <min-max>] [name <regex>] */
MODRET set_authgroupfile(cmd_rec *cmd) {
config_rec *c = NULL;
authfile_file_t *file = NULL;
int flags = 0;
char *path;
#ifdef PR_USE_REGEX
if (cmd->argc-1 < 1 ||
cmd->argc-1 > 5) {
#else
if (cmd->argc-1 < 1 ||
cmd->argc-1 > 2) {
#endif /* regex support */
CONF_ERROR(cmd, "wrong number of parameters");
}
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
path = cmd->argv[1];
if (*path != '/') {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
"unable to use relative path for ", (char *) cmd->argv[0], " '",
path, "'.", NULL));
}
/* Make sure the configured file has the correct permissions. Note that
* AuthGroupFiles, unlike AuthUserFiles, do not contain any sensitive
* information, and can thus be world-readable.
*/
flags = PR_AUTH_FILE_FL_ALLOW_WORLD_READABLE;
if (af_check_file(cmd->tmp_pool, cmd->argv[0], cmd->argv[1], flags) < 0) {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
"unable to use ", path, ": ", strerror(errno), NULL));
}
c = add_config_param(cmd->argv[0], 1, NULL);
file = pcalloc(c->pool, sizeof(authfile_file_t));
file->af_path = pstrdup(c->pool, path);
c->argv[0] = (void *) file;
/* Check for restrictions */
if (cmd->argc-1 != 1) {
register unsigned int i = 0;
for (i = 2; i < cmd->argc; i++) {
if (strncmp(cmd->argv[i], "id", 3) == 0) {
gid_t min, max;
char *sep = NULL, *tmp = NULL;
/* The range restriction parameter is of the form "min-max", where max
* must be >= min.
*/
sep = strchr(cmd->argv[++i], '-');
if (sep == NULL) {
CONF_ERROR(cmd, "badly formatted ID restriction parameter");
}
*sep = '\0';
min = strtol(cmd->argv[i], &tmp, 10);
if (tmp && *tmp) {
CONF_ERROR(cmd, "badly formatted minimum ID");
}
tmp = NULL;
max = strtol(sep+1, &tmp, 10);
if (tmp && *tmp) {
CONF_ERROR(cmd, "badly formatted maximum ID");
}
if (min > max) {
CONF_ERROR(cmd, "minimum cannot be larger than maximum");
}
file->af_min_id.gid = min;
file->af_max_id.gid = max;
file->af_restricted_ids = TRUE;
#ifdef PR_USE_REGEX
} else if (strncmp(cmd->argv[i], "name", 5) == 0) {
char *filter = cmd->argv[++i];
pr_regex_t *pre = NULL;
int res = 0;
pre = pr_regexp_alloc(&auth_file_module);
/* Check for a ! negation/inversion filter prefix. */
if (*filter == '!') {
filter++;
file->af_name_regex_inverted = TRUE;
}
res = pr_regexp_compile(pre, filter, REG_EXTENDED|REG_NOSUB);
if (res != 0) {
char errstr[200] = {'\0'};
//.........这里部分代码省略.........
示例15: pr_event_register
//.........这里部分代码省略.........
evh = pcalloc(event_pool, sizeof(struct event_handler));
evh->module = m;
evh->cb = cb;
evh->user_data = user_data;
/* Is this an untraced event? */
for (i = 0; untraced_events[i] != NULL; i++) {
if (strcmp(event, untraced_events[i]) == 0) {
flags = PR_EVENT_FL_UNTRACED;
break;
}
}
evh->flags = flags;
/* Scan the currently registered lists, looking for where to add this
* registration.
*/
for (evl = events; evl; evl = evl->next) {
if (strncmp(evl->event, event, evl->event_len + 1) == 0) {
struct event_handler *evhi, *evhl = NULL;
evhi = evl->handlers;
if (evhi) {
/* Make sure this event handler is added to the START of the list,
* in order to preserve module load order handling of events (i.e.
* last module loaded, first module handled). The exception to this
* rule are core callbacks (i.e. where m == NULL); these will always
* be invoked last.
*
* Before that, though, check for duplicate registration/subscription.
*/
while (evhi) {
pr_signals_handle();
if (evhi->cb == evh->cb) {
/* Duplicate callback */
errno = EEXIST;
return -1;
}
evhl = evhi;
if (evhi->next == NULL) {
break;
}
evhi = evhi->next;
}
if (evh->module != NULL) {
if (evl->handlers->next != NULL) {
evl->handlers->next->prev = evh;
}
evh->next = evl->handlers;
evl->handlers = evh;
} else {
/* Core event listeners go at the end. */
if (evhl != NULL) {
evhl->next = evh;
evh->prev = evhl;
} else {
evl->handlers = evh;
}
}
} else {
evl->handlers = evh;
}
/* All done */
return 0;
}
}
evl_pool = pr_pool_create_sz(event_pool, EVENT_POOL_SZ);
pr_pool_tag(evl_pool, "Event listener list pool");
evl = pcalloc(evl_pool, sizeof(struct event_list));
evl->pool = evl_pool;
evl->event = pstrdup(evl->pool, event);
evl->event_len = strlen(evl->event);
evl->handlers = evh;
evl->next = events;
events = evl;
/* Clear any cached data. */
curr_event = NULL;
curr_evl = NULL;
curr_evh = NULL;
return 0;
}