unique_id
int64 13
189k
| target
int64 0
1
| code
stringlengths 20
241k
| __index_level_0__
int64 0
18.9k
|
---|---|---|---|
147,114 | 0 | void DocumentLoader::AppendRedirect(const KURL& url) {
redirect_chain_.push_back(url);
}
| 16,100 |
188,601 | 1 | static void TearDownTestCase() {
vpx_free(source_data_);
source_data_ = NULL;
vpx_free(reference_data_);
reference_data_ = NULL;
}
| 16,101 |
43,648 | 0 | static void drop_links(struct nameidata *nd)
{
int i = nd->depth;
while (i--) {
struct saved *last = nd->stack + i;
struct inode *inode = last->inode;
if (last->cookie && inode->i_op->put_link) {
inode->i_op->put_link(inode, last->cookie);
last->cookie = NULL;
}
}
}
| 16,102 |
76,063 | 0 | vrrp_vscript_user_handler(vector_t *strvec)
{
vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script);
if (set_script_uid_gid(strvec, 1, &vscript->script.uid, &vscript->script.gid)) {
report_config_error(CONFIG_GENERAL_ERROR, "Unable to set uid/gid for script %s", cmd_str(&vscript->script));
remove_script = true;
}
else {
remove_script = false;
script_user_set = true;
}
}
| 16,103 |
125,392 | 0 | void GDataFileSystem::OnCommitDirtyInCacheCompleteForCloseFile(
const FileOperationCallback& callback,
GDataFileError error,
const std::string& resource_id,
const std::string& md5) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!callback.is_null())
callback.Run(error);
}
| 16,104 |
175,418 | 0 | static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
{
struct audio_device *adev = (struct audio_device *)dev;
*state = adev->mic_mute;
return 0;
}
| 16,105 |
89,780 | 0 | parse_args_recurse (int *argcp,
const char ***argvp,
bool in_file,
int *total_parsed_argc_p)
{
SetupOp *op;
int argc = *argcp;
const char **argv = *argvp;
/* I can't imagine a case where someone wants more than this.
* If you do...you should be able to pass multiple files
* via a single tmpfs and linking them there, etc.
*
* We're adding this hardening due to precedent from
* http://googleprojectzero.blogspot.com/2014/08/the-poisoned-nul-byte-2014-edition.html
*
* I picked 9000 because the Internet told me to and it was hard to
* resist.
*/
static const uint32_t MAX_ARGS = 9000;
if (*total_parsed_argc_p > MAX_ARGS)
die ("Exceeded maximum number of arguments %u", MAX_ARGS);
while (argc > 0)
{
const char *arg = argv[0];
if (strcmp (arg, "--help") == 0)
{
usage (EXIT_SUCCESS, stdout);
}
else if (strcmp (arg, "--version") == 0)
{
print_version_and_exit ();
}
else if (strcmp (arg, "--args") == 0)
{
int the_fd;
char *endptr;
const char *p, *data_end;
size_t data_len;
cleanup_free const char **data_argv = NULL;
const char **data_argv_copy;
int data_argc;
int i;
if (in_file)
die ("--args not supported in arguments file");
if (argc < 2)
die ("--args takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
/* opt_args_data is essentially a recursive argv array, which we must
* keep allocated until exit time, since its argv entries get used
* by the other cases in parse_args_recurse() when we recurse. */
opt_args_data = load_file_data (the_fd, &data_len);
if (opt_args_data == NULL)
die_with_error ("Can't read --args data");
(void) close (the_fd);
data_end = opt_args_data + data_len;
data_argc = 0;
p = opt_args_data;
while (p != NULL && p < data_end)
{
data_argc++;
(*total_parsed_argc_p)++;
if (*total_parsed_argc_p > MAX_ARGS)
die ("Exceeded maximum number of arguments %u", MAX_ARGS);
p = memchr (p, 0, data_end - p);
if (p != NULL)
p++;
}
data_argv = xcalloc (sizeof (char *) * (data_argc + 1));
i = 0;
p = opt_args_data;
while (p != NULL && p < data_end)
{
/* Note: load_file_data always adds a nul terminator, so this is safe
* even for the last string. */
data_argv[i++] = p;
p = memchr (p, 0, data_end - p);
if (p != NULL)
p++;
}
data_argv_copy = data_argv; /* Don't change data_argv, we need to free it */
parse_args_recurse (&data_argc, &data_argv_copy, TRUE, total_parsed_argc_p);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--unshare-all") == 0)
{
/* Keep this in order with the older (legacy) --unshare arguments,
* we use the --try variants of user and cgroup, since we want
* to support systems/kernels without support for those.
*/
opt_unshare_user_try = opt_unshare_ipc = opt_unshare_pid =
opt_unshare_uts = opt_unshare_cgroup_try =
opt_unshare_net = TRUE;
}
/* Begin here the older individual --unshare variants */
else if (strcmp (arg, "--unshare-user") == 0)
{
opt_unshare_user = TRUE;
}
else if (strcmp (arg, "--unshare-user-try") == 0)
{
opt_unshare_user_try = TRUE;
}
else if (strcmp (arg, "--unshare-ipc") == 0)
{
opt_unshare_ipc = TRUE;
}
else if (strcmp (arg, "--unshare-pid") == 0)
{
opt_unshare_pid = TRUE;
}
else if (strcmp (arg, "--unshare-net") == 0)
{
opt_unshare_net = TRUE;
}
else if (strcmp (arg, "--unshare-uts") == 0)
{
opt_unshare_uts = TRUE;
}
else if (strcmp (arg, "--unshare-cgroup") == 0)
{
opt_unshare_cgroup = TRUE;
}
else if (strcmp (arg, "--unshare-cgroup-try") == 0)
{
opt_unshare_cgroup_try = TRUE;
}
/* Begin here the newer --share variants */
else if (strcmp (arg, "--share-net") == 0)
{
opt_unshare_net = FALSE;
}
/* End --share variants, other arguments begin */
else if (strcmp (arg, "--chdir") == 0)
{
if (argc < 2)
die ("--chdir takes one argument");
opt_chdir_path = argv[1];
argv++;
argc--;
}
else if (strcmp (arg, "--remount-ro") == 0)
{
if (argc < 2)
die ("--remount-ro takes one argument");
SetupOp *op = setup_op_new (SETUP_REMOUNT_RO_NO_RECURSIVE);
op->dest = argv[1];
argv++;
argc--;
}
else if (strcmp(arg, "--bind") == 0 ||
strcmp(arg, "--bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp(arg, "--ro-bind") == 0 ||
strcmp(arg, "--ro-bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_RO_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--ro-bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--dev-bind") == 0 ||
strcmp (arg, "--dev-bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_DEV_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--dev-bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--proc") == 0)
{
if (argc < 2)
die ("--proc takes an argument");
op = setup_op_new (SETUP_MOUNT_PROC);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--exec-label") == 0)
{
if (argc < 2)
die ("--exec-label takes an argument");
opt_exec_label = argv[1];
die_unless_label_valid (opt_exec_label);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--file-label") == 0)
{
if (argc < 2)
die ("--file-label takes an argument");
opt_file_label = argv[1];
die_unless_label_valid (opt_file_label);
if (label_create_file (opt_file_label))
die_with_error ("--file-label setup failed");
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--dev") == 0)
{
if (argc < 2)
die ("--dev takes an argument");
op = setup_op_new (SETUP_MOUNT_DEV);
op->dest = argv[1];
opt_needs_devpts = TRUE;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--tmpfs") == 0)
{
if (argc < 2)
die ("--tmpfs takes an argument");
op = setup_op_new (SETUP_MOUNT_TMPFS);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--mqueue") == 0)
{
if (argc < 2)
die ("--mqueue takes an argument");
op = setup_op_new (SETUP_MOUNT_MQUEUE);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--dir") == 0)
{
if (argc < 2)
die ("--dir takes an argument");
op = setup_op_new (SETUP_MAKE_DIR);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--file") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--file takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--bind-data") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--bind-data takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_BIND_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--ro-bind-data") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--ro-bind-data takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_RO_BIND_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--symlink") == 0)
{
if (argc < 3)
die ("--symlink takes two arguments");
op = setup_op_new (SETUP_MAKE_SYMLINK);
op->source = argv[1];
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--lock-file") == 0)
{
if (argc < 2)
die ("--lock-file takes an argument");
(void) lock_file_new (argv[1]);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--sync-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--sync-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_sync_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--block-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--block-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_block_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--userns-block-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--userns-block-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_userns_block_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--info-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--info-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_info_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--json-status-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--json-status-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_json_status_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--seccomp") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--seccomp takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_seccomp_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--setenv") == 0)
{
if (argc < 3)
die ("--setenv takes two arguments");
xsetenv (argv[1], argv[2], 1);
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--unsetenv") == 0)
{
if (argc < 2)
die ("--unsetenv takes an argument");
xunsetenv (argv[1]);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--uid") == 0)
{
int the_uid;
char *endptr;
if (argc < 2)
die ("--uid takes an argument");
the_uid = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_uid < 0)
die ("Invalid uid: %s", argv[1]);
opt_sandbox_uid = the_uid;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--gid") == 0)
{
int the_gid;
char *endptr;
if (argc < 2)
die ("--gid takes an argument");
the_gid = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_gid < 0)
die ("Invalid gid: %s", argv[1]);
opt_sandbox_gid = the_gid;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--hostname") == 0)
{
if (argc < 2)
die ("--hostname takes an argument");
op = setup_op_new (SETUP_SET_HOSTNAME);
op->dest = argv[1];
op->flags = NO_CREATE_DEST;
opt_sandbox_hostname = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--new-session") == 0)
{
opt_new_session = TRUE;
}
else if (strcmp (arg, "--die-with-parent") == 0)
{
opt_die_with_parent = TRUE;
}
else if (strcmp (arg, "--as-pid-1") == 0)
{
opt_as_pid_1 = TRUE;
}
else if (strcmp (arg, "--cap-add") == 0)
{
cap_value_t cap;
if (argc < 2)
die ("--cap-add takes an argument");
opt_cap_add_or_drop_used = TRUE;
if (strcasecmp (argv[1], "ALL") == 0)
{
requested_caps[0] = requested_caps[1] = 0xFFFFFFFF;
}
else
{
if (cap_from_name (argv[1], &cap) < 0)
die ("unknown cap: %s", argv[1]);
if (cap < 32)
requested_caps[0] |= CAP_TO_MASK_0 (cap);
else
requested_caps[1] |= CAP_TO_MASK_1 (cap - 32);
}
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--cap-drop") == 0)
{
cap_value_t cap;
if (argc < 2)
die ("--cap-drop takes an argument");
opt_cap_add_or_drop_used = TRUE;
if (strcasecmp (argv[1], "ALL") == 0)
{
requested_caps[0] = requested_caps[1] = 0;
}
else
{
if (cap_from_name (argv[1], &cap) < 0)
die ("unknown cap: %s", argv[1]);
if (cap < 32)
requested_caps[0] &= ~CAP_TO_MASK_0 (cap);
else
requested_caps[1] &= ~CAP_TO_MASK_1 (cap - 32);
}
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--") == 0)
{
argv += 1;
argc -= 1;
break;
}
else if (*arg == '-')
{
die ("Unknown option %s", arg);
}
else
{
break;
}
argv++;
argc--;
}
*argcp = argc;
*argvp = argv;
}
| 16,106 |
2,568 | 0 | each_array_start(void *state)
{
EachState *_state = (EachState *) state;
/* json structure check */
if (_state->lex->lex_level == 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("cannot deconstruct an array as an object")));
}
| 16,107 |
161,506 | 0 | void RenderFrameDevToolsAgentHost::InspectElement(
DevToolsSession* session,
int x,
int y) {
if (frame_tree_node_) {
if (auto* main_view =
frame_tree_node_->frame_tree()->GetMainFrame()->GetView()) {
gfx::Point transformed_point = gfx::ToRoundedPoint(
main_view->TransformRootPointToViewCoordSpace(gfx::PointF(x, y)));
x = transformed_point.x();
y = transformed_point.y();
}
}
session->InspectElement(gfx::Point(x, y));
}
| 16,108 |
63,406 | 0 | static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
{
int32_t *decoded0 = ctx->decoded[0];
while (blockstodecode--)
*decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
}
| 16,109 |
37,555 | 0 | static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
{
}
| 16,110 |
151,451 | 0 | void FrameFetchContext::SetFirstPartyCookieAndRequestorOrigin(
ResourceRequest& request) {
if (request.SiteForCookies().IsNull()) {
if (request.GetFrameType() == WebURLRequest::kFrameTypeTopLevel) {
request.SetSiteForCookies(request.Url());
} else {
request.SetSiteForCookies(GetSiteForCookies());
}
}
if (!request.RequestorOrigin()) {
if (request.GetFrameType() == WebURLRequest::kFrameTypeNone) {
request.SetRequestorOrigin(GetRequestorOrigin());
} else {
request.SetRequestorOrigin(GetRequestorOriginForFrameLoading());
}
}
}
| 16,111 |
21,749 | 0 | static int em_idiv_ex(struct x86_emulate_ctxt *ctxt)
{
u8 de = 0;
emulate_1op_rax_rdx(ctxt, "idiv", de);
if (de)
return emulate_de(ctxt);
return X86EMUL_CONTINUE;
}
| 16,112 |
51,523 | 0 | void tcp_clear_retrans(struct tcp_sock *tp)
{
tp->retrans_out = 0;
tp->lost_out = 0;
tp->undo_marker = 0;
tp->undo_retrans = -1;
tp->fackets_out = 0;
tp->sacked_out = 0;
}
| 16,113 |
164,151 | 0 | void BasicFindMainFallbackResponse(bool drop_from_working_set) {
PushNextTask(base::BindOnce(
&AppCacheStorageImplTest::Verify_BasicFindMainFallbackResponse,
base::Unretained(this)));
MakeCacheAndGroup(kManifestUrl, 2, 1, true);
cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::FALLBACK, 1));
cache_->AddEntry(kEntryUrl2, AppCacheEntry(AppCacheEntry::FALLBACK, 2));
cache_->fallback_namespaces_.push_back(AppCacheNamespace(
APPCACHE_FALLBACK_NAMESPACE, kFallbackNamespace2, kEntryUrl2, false));
cache_->fallback_namespaces_.push_back(AppCacheNamespace(
APPCACHE_FALLBACK_NAMESPACE, kFallbackNamespace, kEntryUrl, false));
AppCacheDatabase::CacheRecord cache_record;
std::vector<AppCacheDatabase::EntryRecord> entries;
std::vector<AppCacheDatabase::NamespaceRecord> intercepts;
std::vector<AppCacheDatabase::NamespaceRecord> fallbacks;
std::vector<AppCacheDatabase::OnlineWhiteListRecord> whitelists;
cache_->ToDatabaseRecords(group_.get(), &cache_record, &entries,
&intercepts, &fallbacks, &whitelists);
for (const auto& entry : entries) {
if (entry.url != kDefaultEntryUrl)
EXPECT_TRUE(database()->InsertEntry(&entry));
}
EXPECT_TRUE(database()->InsertNamespaceRecords(fallbacks));
EXPECT_TRUE(database()->InsertOnlineWhiteListRecords(whitelists));
if (drop_from_working_set) {
EXPECT_TRUE(cache_->HasOneRef());
cache_ = nullptr;
EXPECT_TRUE(group_->HasOneRef());
group_ = nullptr;
}
storage()->FindResponseForMainRequest(kFallbackTestUrl, GURL(), delegate());
EXPECT_NE(kFallbackTestUrl, delegate()->found_url_);
}
| 16,114 |
185,125 | 1 | void LocalFileSystem::fileSystemNotAllowedInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
PassRefPtr<CallbackWrapper> callbacks)
{
context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR));
}
| 16,115 |
173,854 | 0 | virtual status_t getParameter(
node_id node, OMX_INDEXTYPE index,
void *params, size_t size) {
Parcel data, reply;
data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
data.writeInt32((int32_t)node);
data.writeInt32(index);
data.writeInt64(size);
data.write(params, size);
remote()->transact(GET_PARAMETER, data, &reply);
status_t err = reply.readInt32();
if (err != OK) {
return err;
}
reply.read(params, size);
return OK;
}
| 16,116 |
4,818 | 0 | DeliverOneEvent(InternalEvent *event, DeviceIntPtr dev, enum InputLevel level,
WindowPtr win, Window child, GrabPtr grab)
{
xEvent *xE = NULL;
int count = 0;
int deliveries = 0;
int rc;
switch (level) {
case XI2:
rc = EventToXI2(event, &xE);
count = 1;
break;
case XI:
rc = EventToXI(event, &xE, &count);
break;
case CORE:
rc = EventToCore(event, &xE, &count);
break;
default:
rc = BadImplementation;
break;
}
if (rc == Success) {
deliveries = DeliverEvent(dev, xE, count, win, child, grab);
free(xE);
}
else
BUG_WARN_MSG(rc != BadMatch,
"%s: conversion to level %d failed with rc %d\n",
dev->name, level, rc);
return deliveries;
}
| 16,117 |
94 | 0 | static int ssl3_read_internal(SSL *s, void *buf, int len, int peek)
{
int ret;
clear_sys_error();
if (s->s3->renegotiate) ssl3_renegotiate_check(s);
s->s3->in_read_app_data=1;
ret=s->method->ssl_read_bytes(s,SSL3_RT_APPLICATION_DATA,buf,len,peek);
if ((ret == -1) && (s->s3->in_read_app_data == 2))
{
/* ssl3_read_bytes decided to call s->handshake_func, which
* called ssl3_read_bytes to read handshake data.
* However, ssl3_read_bytes actually found application data
* and thinks that application data makes sense here; so disable
* handshake processing and try to read application data again. */
s->in_handshake++;
ret=s->method->ssl_read_bytes(s,SSL3_RT_APPLICATION_DATA,buf,len,peek);
s->in_handshake--;
}
else
s->s3->in_read_app_data=0;
return(ret);
}
| 16,118 |
17,470 | 0 | ProcXvQueryExtension(ClientPtr client)
{
xvQueryExtensionReply rep = {
.type = X_Reply,
.sequenceNumber = client->sequence,
.length = 0,
.version = XvVersion,
.revision = XvRevision
};
/* REQUEST(xvQueryExtensionReq); */
REQUEST_SIZE_MATCH(xvQueryExtensionReq);
_WriteQueryExtensionReply(client, &rep);
return Success;
}
| 16,119 |
163,568 | 0 | htmlAttrAllowed(const htmlElemDesc* elt, const xmlChar* attr, int legacy) {
const char** p ;
if ( !elt || ! attr )
return HTML_INVALID ;
if ( elt->attrs_req )
for ( p = elt->attrs_req; *p; ++p)
if ( !xmlStrcmp((const xmlChar*)*p, attr) )
return HTML_REQUIRED ;
if ( elt->attrs_opt )
for ( p = elt->attrs_opt; *p; ++p)
if ( !xmlStrcmp((const xmlChar*)*p, attr) )
return HTML_VALID ;
if ( legacy && elt->attrs_depr )
for ( p = elt->attrs_depr; *p; ++p)
if ( !xmlStrcmp((const xmlChar*)*p, attr) )
return HTML_DEPRECATED ;
return HTML_INVALID ;
}
| 16,120 |
160,093 | 0 | void BackendImpl::StoreStats() {
int size = stats_.StorageSize();
std::unique_ptr<char[]> data(new char[size]);
Addr address;
size = stats_.SerializeStats(data.get(), size, &address);
DCHECK(size);
if (!address.is_initialized())
return;
MappedFile* file = File(address);
if (!file)
return;
size_t offset = address.start_block() * address.BlockSize() +
kBlockHeaderSize;
file->Write(data.get(), size, offset); // ignore result.
}
| 16,121 |
134,602 | 0 | void OSExchangeData::SetString(const base::string16& data) {
provider_->SetString(data);
}
| 16,122 |
19,470 | 0 | static int efx_fill_loopback_test(struct efx_nic *efx,
struct efx_loopback_self_tests *lb_tests,
enum efx_loopback_mode mode,
unsigned int test_index,
struct ethtool_string *strings, u64 *data)
{
struct efx_channel *channel = efx_get_channel(efx, 0);
struct efx_tx_queue *tx_queue;
efx_for_each_channel_tx_queue(tx_queue, channel) {
efx_fill_test(test_index++, strings, data,
&lb_tests->tx_sent[tx_queue->queue],
EFX_TX_QUEUE_NAME(tx_queue),
EFX_LOOPBACK_NAME(mode, "tx_sent"));
efx_fill_test(test_index++, strings, data,
&lb_tests->tx_done[tx_queue->queue],
EFX_TX_QUEUE_NAME(tx_queue),
EFX_LOOPBACK_NAME(mode, "tx_done"));
}
efx_fill_test(test_index++, strings, data,
&lb_tests->rx_good,
"rx", 0,
EFX_LOOPBACK_NAME(mode, "rx_good"));
efx_fill_test(test_index++, strings, data,
&lb_tests->rx_bad,
"rx", 0,
EFX_LOOPBACK_NAME(mode, "rx_bad"));
return test_index;
}
| 16,123 |
20,223 | 0 | static struct inode *hugetlbfs_get_inode(struct super_block *sb,
struct inode *dir,
umode_t mode, dev_t dev)
{
struct inode *inode;
inode = new_inode(sb);
if (inode) {
struct hugetlbfs_inode_info *info;
inode->i_ino = get_next_ino();
inode_init_owner(inode, dir, mode);
inode->i_mapping->a_ops = &hugetlbfs_aops;
inode->i_mapping->backing_dev_info =&hugetlbfs_backing_dev_info;
inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
INIT_LIST_HEAD(&inode->i_mapping->private_list);
info = HUGETLBFS_I(inode);
/*
* The policy is initialized here even if we are creating a
* private inode because initialization simply creates an
* an empty rb tree and calls spin_lock_init(), later when we
* call mpol_free_shared_policy() it will just return because
* the rb tree will still be empty.
*/
mpol_shared_policy_init(&info->policy, NULL);
switch (mode & S_IFMT) {
default:
init_special_inode(inode, mode, dev);
break;
case S_IFREG:
inode->i_op = &hugetlbfs_inode_operations;
inode->i_fop = &hugetlbfs_file_operations;
break;
case S_IFDIR:
inode->i_op = &hugetlbfs_dir_inode_operations;
inode->i_fop = &simple_dir_operations;
/* directory inodes start off with i_nlink == 2 (for "." entry) */
inc_nlink(inode);
break;
case S_IFLNK:
inode->i_op = &page_symlink_inode_operations;
break;
}
lockdep_annotate_inode_mutex_key(inode);
}
return inode;
}
| 16,124 |
104,697 | 0 | static v8::Handle<v8::Value> StartRequest(const v8::Arguments& args) {
std::string str_args = *v8::String::Utf8Value(args[1]);
base::JSONReader reader;
scoped_ptr<Value> value_args;
value_args.reset(reader.JsonToValue(str_args, false, false));
if (!value_args.get() || !value_args->IsType(Value::TYPE_LIST)) {
NOTREACHED() << "Invalid JSON passed to StartRequest.";
return v8::Undefined();
}
return StartRequestCommon(args, static_cast<ListValue*>(value_args.get()));
}
| 16,125 |
4,681 | 0 | static EVP_PKEY * php_openssl_evp_from_zval(zval ** val, int public_key, char * passphrase, int makeresource, long * resourceval TSRMLS_DC)
{
EVP_PKEY * key = NULL;
X509 * cert = NULL;
int free_cert = 0;
long cert_res = -1;
char * filename = NULL;
zval tmp;
Z_TYPE(tmp) = IS_NULL;
#define TMP_CLEAN \
if (Z_TYPE(tmp) == IS_STRING) {\
zval_dtor(&tmp); \
} \
return NULL;
if (resourceval) {
*resourceval = -1;
}
if (Z_TYPE_PP(val) == IS_ARRAY) {
zval ** zphrase;
/* get passphrase */
if (zend_hash_index_find(HASH_OF(*val), 1, (void **)&zphrase) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "key array must be of the form array(0 => key, 1 => phrase)");
return NULL;
}
if (Z_TYPE_PP(zphrase) == IS_STRING) {
passphrase = Z_STRVAL_PP(zphrase);
} else {
tmp = **zphrase;
zval_copy_ctor(&tmp);
convert_to_string(&tmp);
passphrase = Z_STRVAL(tmp);
}
/* now set val to be the key param and continue */
if (zend_hash_index_find(HASH_OF(*val), 0, (void **)&val) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "key array must be of the form array(0 => key, 1 => phrase)");
TMP_CLEAN;
}
}
if (Z_TYPE_PP(val) == IS_RESOURCE) {
void * what;
int type;
what = zend_fetch_resource(val TSRMLS_CC, -1, "OpenSSL X.509/key", &type, 2, le_x509, le_key);
if (!what) {
TMP_CLEAN;
}
if (resourceval) {
*resourceval = Z_LVAL_PP(val);
}
if (type == le_x509) {
/* extract key from cert, depending on public_key param */
cert = (X509*)what;
free_cert = 0;
} else if (type == le_key) {
int is_priv;
is_priv = php_openssl_is_private_key((EVP_PKEY*)what TSRMLS_CC);
/* check whether it is actually a private key if requested */
if (!public_key && !is_priv) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "supplied key param is a public key");
TMP_CLEAN;
}
if (public_key && is_priv) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Don't know how to get public key from this private key");
TMP_CLEAN;
} else {
if (Z_TYPE(tmp) == IS_STRING) {
zval_dtor(&tmp);
}
/* got the key - return it */
return (EVP_PKEY*)what;
}
} else {
/* other types could be used here - eg: file pointers and read in the data from them */
TMP_CLEAN;
}
} else {
/* force it to be a string and check if it refers to a file */
/* passing non string values leaks, object uses toString, it returns NULL
* See bug38255.phpt
*/
if (!(Z_TYPE_PP(val) == IS_STRING || Z_TYPE_PP(val) == IS_OBJECT)) {
TMP_CLEAN;
}
convert_to_string_ex(val);
if (Z_STRLEN_PP(val) > 7 && memcmp(Z_STRVAL_PP(val), "file://", sizeof("file://") - 1) == 0) {
filename = Z_STRVAL_PP(val) + (sizeof("file://") - 1);
}
/* it's an X509 file/cert of some kind, and we need to extract the data from that */
if (public_key) {
cert = php_openssl_x509_from_zval(val, 0, &cert_res TSRMLS_CC);
free_cert = (cert_res == -1);
/* actual extraction done later */
if (!cert) {
/* not a X509 certificate, try to retrieve public key */
BIO* in;
if (filename) {
in = BIO_new_file(filename, "r");
} else {
in = BIO_new_mem_buf(Z_STRVAL_PP(val), Z_STRLEN_PP(val));
}
if (in == NULL) {
TMP_CLEAN;
}
key = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL);
BIO_free(in);
}
} else {
/* we want the private key */
BIO *in;
if (filename) {
if (php_openssl_open_base_dir_chk(filename TSRMLS_CC)) {
TMP_CLEAN;
}
in = BIO_new_file(filename, "r");
} else {
in = BIO_new_mem_buf(Z_STRVAL_PP(val), Z_STRLEN_PP(val));
}
if (in == NULL) {
TMP_CLEAN;
}
key = PEM_read_bio_PrivateKey(in, NULL,NULL, passphrase);
BIO_free(in);
}
}
if (public_key && cert && key == NULL) {
/* extract public key from X509 cert */
key = (EVP_PKEY *) X509_get_pubkey(cert);
}
if (free_cert && cert) {
X509_free(cert);
}
if (key && makeresource && resourceval) {
*resourceval = ZEND_REGISTER_RESOURCE(NULL, key, le_key);
}
if (Z_TYPE(tmp) == IS_STRING) {
zval_dtor(&tmp);
}
return key;
}
| 16,126 |
92,251 | 0 | XML_GetFeatureList(void)
{
static const XML_Feature features[] = {
{XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"),
sizeof(XML_Char)},
{XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"),
sizeof(XML_LChar)},
#ifdef XML_UNICODE
{XML_FEATURE_UNICODE, XML_L("XML_UNICODE"), 0},
#endif
#ifdef XML_UNICODE_WCHAR_T
{XML_FEATURE_UNICODE_WCHAR_T, XML_L("XML_UNICODE_WCHAR_T"), 0},
#endif
#ifdef XML_DTD
{XML_FEATURE_DTD, XML_L("XML_DTD"), 0},
#endif
#ifdef XML_CONTEXT_BYTES
{XML_FEATURE_CONTEXT_BYTES, XML_L("XML_CONTEXT_BYTES"),
XML_CONTEXT_BYTES},
#endif
#ifdef XML_MIN_SIZE
{XML_FEATURE_MIN_SIZE, XML_L("XML_MIN_SIZE"), 0},
#endif
#ifdef XML_NS
{XML_FEATURE_NS, XML_L("XML_NS"), 0},
#endif
#ifdef XML_LARGE_SIZE
{XML_FEATURE_LARGE_SIZE, XML_L("XML_LARGE_SIZE"), 0},
#endif
#ifdef XML_ATTR_INFO
{XML_FEATURE_ATTR_INFO, XML_L("XML_ATTR_INFO"), 0},
#endif
{XML_FEATURE_END, NULL, 0}
};
return features;
}
| 16,127 |
2,204 | 0 | void FoFiType1C::convertToType1(char *psName, const char **newEncoding, GBool ascii,
FoFiOutputFunc outputFunc,
void *outputStream) {
int psNameLen;
Type1CEexecBuf eb;
Type1CIndex subrIdx;
Type1CIndexVal val;
GooString *buf;
char buf2[256];
const char **enc;
GBool ok;
int i;
if (psName) {
psNameLen = strlen(psName);
} else {
psName = name->getCString();
psNameLen = name->getLength();
}
ok = gTrue;
(*outputFunc)(outputStream, "%!FontType1-1.0: ", 17);
(*outputFunc)(outputStream, psName, psNameLen);
if (topDict.versionSID != 0) {
getString(topDict.versionSID, buf2, &ok);
(*outputFunc)(outputStream, buf2, strlen(buf2));
}
(*outputFunc)(outputStream, "\n", 1);
(*outputFunc)(outputStream, "12 dict begin\n", 14);
(*outputFunc)(outputStream, "/FontInfo 10 dict dup begin\n", 28);
if (topDict.versionSID != 0) {
(*outputFunc)(outputStream, "/version ", 9);
writePSString(buf2, outputFunc, outputStream);
(*outputFunc)(outputStream, " readonly def\n", 14);
}
if (topDict.noticeSID != 0) {
getString(topDict.noticeSID, buf2, &ok);
(*outputFunc)(outputStream, "/Notice ", 8);
writePSString(buf2, outputFunc, outputStream);
(*outputFunc)(outputStream, " readonly def\n", 14);
}
if (topDict.copyrightSID != 0) {
getString(topDict.copyrightSID, buf2, &ok);
(*outputFunc)(outputStream, "/Copyright ", 11);
writePSString(buf2, outputFunc, outputStream);
(*outputFunc)(outputStream, " readonly def\n", 14);
}
if (topDict.fullNameSID != 0) {
getString(topDict.fullNameSID, buf2, &ok);
(*outputFunc)(outputStream, "/FullName ", 10);
writePSString(buf2, outputFunc, outputStream);
(*outputFunc)(outputStream, " readonly def\n", 14);
}
if (topDict.familyNameSID != 0) {
getString(topDict.familyNameSID, buf2, &ok);
(*outputFunc)(outputStream, "/FamilyName ", 12);
writePSString(buf2, outputFunc, outputStream);
(*outputFunc)(outputStream, " readonly def\n", 14);
}
if (topDict.weightSID != 0) {
getString(topDict.weightSID, buf2, &ok);
(*outputFunc)(outputStream, "/Weight ", 8);
writePSString(buf2, outputFunc, outputStream);
(*outputFunc)(outputStream, " readonly def\n", 14);
}
if (topDict.isFixedPitch) {
(*outputFunc)(outputStream, "/isFixedPitch true def\n", 23);
} else {
(*outputFunc)(outputStream, "/isFixedPitch false def\n", 24);
}
buf = GooString::format("/ItalicAngle {0:.4g} def\n", topDict.italicAngle);
(*outputFunc)(outputStream, buf->getCString(), buf->getLength());
delete buf;
buf = GooString::format("/UnderlinePosition {0:.4g} def\n",
topDict.underlinePosition);
(*outputFunc)(outputStream, buf->getCString(), buf->getLength());
delete buf;
buf = GooString::format("/UnderlineThickness {0:.4g} def\n",
topDict.underlineThickness);
(*outputFunc)(outputStream, buf->getCString(), buf->getLength());
delete buf;
(*outputFunc)(outputStream, "end readonly def\n", 17);
(*outputFunc)(outputStream, "/FontName /", 11);
(*outputFunc)(outputStream, psName, psNameLen);
(*outputFunc)(outputStream, " def\n", 5);
buf = GooString::format("/PaintType {0:d} def\n", topDict.paintType);
(*outputFunc)(outputStream, buf->getCString(), buf->getLength());
delete buf;
(*outputFunc)(outputStream, "/FontType 1 def\n", 16);
buf = GooString::format("/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] readonly def\n",
topDict.fontMatrix[0], topDict.fontMatrix[1],
topDict.fontMatrix[2], topDict.fontMatrix[3],
topDict.fontMatrix[4], topDict.fontMatrix[5]);
(*outputFunc)(outputStream, buf->getCString(), buf->getLength());
delete buf;
buf = GooString::format("/FontBBox [{0:.4g} {1:.4g} {2:.4g} {3:.4g}] readonly def\n",
topDict.fontBBox[0], topDict.fontBBox[1],
topDict.fontBBox[2], topDict.fontBBox[3]);
(*outputFunc)(outputStream, buf->getCString(), buf->getLength());
delete buf;
buf = GooString::format("/StrokeWidth {0:.4g} def\n", topDict.strokeWidth);
(*outputFunc)(outputStream, buf->getCString(), buf->getLength());
delete buf;
if (topDict.uniqueID != 0) {
buf = GooString::format("/UniqueID {0:d} def\n", topDict.uniqueID);
(*outputFunc)(outputStream, buf->getCString(), buf->getLength());
delete buf;
}
(*outputFunc)(outputStream, "/Encoding ", 10);
if (!newEncoding && encoding == fofiType1StandardEncoding) {
(*outputFunc)(outputStream, "StandardEncoding def\n", 21);
} else {
(*outputFunc)(outputStream, "256 array\n", 10);
(*outputFunc)(outputStream,
"0 1 255 {1 index exch /.notdef put} for\n", 40);
enc = newEncoding ? newEncoding : (const char **)encoding;
for (i = 0; i < 256; ++i) {
if (enc[i]) {
buf = GooString::format("dup {0:d} /{1:s} put\n", i, enc[i]);
(*outputFunc)(outputStream, buf->getCString(), buf->getLength());
delete buf;
}
}
(*outputFunc)(outputStream, "readonly def\n", 13);
}
(*outputFunc)(outputStream, "currentdict end\n", 16);
(*outputFunc)(outputStream, "currentfile eexec\n", 18);
eb.outputFunc = outputFunc;
eb.outputStream = outputStream;
eb.ascii = ascii;
eb.r1 = 55665;
eb.line = 0;
eexecWrite(&eb, "\x83\xca\x73\xd5");
eexecWrite(&eb, "dup /Private 32 dict dup begin\n");
eexecWrite(&eb, "/RD {string currentfile exch readstring pop}"
" executeonly def\n");
eexecWrite(&eb, "/ND {noaccess def} executeonly def\n");
eexecWrite(&eb, "/NP {noaccess put} executeonly def\n");
eexecWrite(&eb, "/MinFeature {16 16} def\n");
eexecWrite(&eb, "/password 5839 def\n");
if (privateDicts[0].nBlueValues) {
eexecWrite(&eb, "/BlueValues [");
for (i = 0; i < privateDicts[0].nBlueValues; ++i) {
buf = GooString::format("{0:s}{1:d}",
i > 0 ? " " : "", privateDicts[0].blueValues[i]);
eexecWrite(&eb, buf->getCString());
delete buf;
}
eexecWrite(&eb, "] def\n");
}
if (privateDicts[0].nOtherBlues) {
eexecWrite(&eb, "/OtherBlues [");
for (i = 0; i < privateDicts[0].nOtherBlues; ++i) {
buf = GooString::format("{0:s}{1:d}",
i > 0 ? " " : "", privateDicts[0].otherBlues[i]);
eexecWrite(&eb, buf->getCString());
delete buf;
}
eexecWrite(&eb, "] def\n");
}
if (privateDicts[0].nFamilyBlues) {
eexecWrite(&eb, "/FamilyBlues [");
for (i = 0; i < privateDicts[0].nFamilyBlues; ++i) {
buf = GooString::format("{0:s}{1:d}",
i > 0 ? " " : "", privateDicts[0].familyBlues[i]);
eexecWrite(&eb, buf->getCString());
delete buf;
}
eexecWrite(&eb, "] def\n");
}
if (privateDicts[0].nFamilyOtherBlues) {
eexecWrite(&eb, "/FamilyOtherBlues [");
for (i = 0; i < privateDicts[0].nFamilyOtherBlues; ++i) {
buf = GooString::format("{0:s}{1:d}", i > 0 ? " " : "",
privateDicts[0].familyOtherBlues[i]);
eexecWrite(&eb, buf->getCString());
delete buf;
}
eexecWrite(&eb, "] def\n");
}
if (privateDicts[0].blueScale != 0.039625) {
buf = GooString::format("/BlueScale {0:.4g} def\n",
privateDicts[0].blueScale);
eexecWrite(&eb, buf->getCString());
delete buf;
}
if (privateDicts[0].blueShift != 7) {
buf = GooString::format("/BlueShift {0:d} def\n", privateDicts[0].blueShift);
eexecWrite(&eb, buf->getCString());
delete buf;
}
if (privateDicts[0].blueFuzz != 1) {
buf = GooString::format("/BlueFuzz {0:d} def\n", privateDicts[0].blueFuzz);
eexecWrite(&eb, buf->getCString());
delete buf;
}
if (privateDicts[0].hasStdHW) {
buf = GooString::format("/StdHW [{0:.4g}] def\n", privateDicts[0].stdHW);
eexecWrite(&eb, buf->getCString());
delete buf;
}
if (privateDicts[0].hasStdVW) {
buf = GooString::format("/StdVW [{0:.4g}] def\n", privateDicts[0].stdVW);
eexecWrite(&eb, buf->getCString());
delete buf;
}
if (privateDicts[0].nStemSnapH) {
eexecWrite(&eb, "/StemSnapH [");
for (i = 0; i < privateDicts[0].nStemSnapH; ++i) {
buf = GooString::format("{0:s}{1:.4g}",
i > 0 ? " " : "", privateDicts[0].stemSnapH[i]);
eexecWrite(&eb, buf->getCString());
delete buf;
}
eexecWrite(&eb, "] def\n");
}
if (privateDicts[0].nStemSnapV) {
eexecWrite(&eb, "/StemSnapV [");
for (i = 0; i < privateDicts[0].nStemSnapV; ++i) {
buf = GooString::format("{0:s}{1:.4g}",
i > 0 ? " " : "", privateDicts[0].stemSnapV[i]);
eexecWrite(&eb, buf->getCString());
delete buf;
}
eexecWrite(&eb, "] def\n");
}
if (privateDicts[0].hasForceBold) {
buf = GooString::format("/ForceBold {0:s} def\n",
privateDicts[0].forceBold ? "true" : "false");
eexecWrite(&eb, buf->getCString());
delete buf;
}
if (privateDicts[0].forceBoldThreshold != 0) {
buf = GooString::format("/ForceBoldThreshold {0:.4g} def\n",
privateDicts[0].forceBoldThreshold);
eexecWrite(&eb, buf->getCString());
delete buf;
}
if (privateDicts[0].languageGroup != 0) {
buf = GooString::format("/LanguageGroup {0:d} def\n",
privateDicts[0].languageGroup);
eexecWrite(&eb, buf->getCString());
delete buf;
}
if (privateDicts[0].expansionFactor != 0.06) {
buf = GooString::format("/ExpansionFactor {0:.4g} def\n",
privateDicts[0].expansionFactor);
eexecWrite(&eb, buf->getCString());
delete buf;
}
ok = gTrue;
getIndex(privateDicts[0].subrsOffset, &subrIdx, &ok);
if (!ok) {
subrIdx.pos = -1;
}
buf = GooString::format("2 index /CharStrings {0:d} dict dup begin\n",
nGlyphs);
eexecWrite(&eb, buf->getCString());
delete buf;
for (i = 0; i < nGlyphs; ++i) {
ok = gTrue;
getIndexVal(&charStringsIdx, i, &val, &ok);
if (ok && i < charsetLength) {
getString(charset[i], buf2, &ok);
if (ok) {
eexecCvtGlyph(&eb, buf2, val.pos, val.len, &subrIdx, &privateDicts[0]);
}
}
}
eexecWrite(&eb, "end\n");
eexecWrite(&eb, "end\n");
eexecWrite(&eb, "readonly put\n");
eexecWrite(&eb, "noaccess put\n");
eexecWrite(&eb, "dup /FontName get exch definefont pop\n");
eexecWrite(&eb, "mark currentfile closefile\n");
if (ascii && eb.line > 0) {
(*outputFunc)(outputStream, "\n", 1);
}
for (i = 0; i < 8; ++i) {
(*outputFunc)(outputStream, "0000000000000000000000000000000000000000000000000000000000000000\n", 65);
}
(*outputFunc)(outputStream, "cleartomark\n", 12);
}
| 16,128 |
129,799 | 0 | bool SystemClipboard::IsValidBufferType(mojom::ClipboardBuffer buffer) {
switch (buffer) {
case mojom::ClipboardBuffer::kStandard:
return true;
case mojom::ClipboardBuffer::kSelection:
#if defined(USE_X11)
return true;
#else
return false;
#endif
}
return true;
}
| 16,129 |
98,633 | 0 | RenderWidget* RenderWidget::Create(int32 opener_id,
RenderThreadBase* render_thread,
WebKit::WebPopupType popup_type) {
DCHECK(opener_id != MSG_ROUTING_NONE);
scoped_refptr<RenderWidget> widget = new RenderWidget(render_thread,
popup_type);
widget->Init(opener_id); // adds reference
return widget;
}
| 16,130 |
162,905 | 0 | void CoordinatorImpl::OnOSMemoryDumpResponse(uint64_t dump_guid,
mojom::ClientProcess* client,
bool success,
OSMemDumpMap os_dumps) {
using ResponseType = QueuedRequest::PendingResponse::Type;
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
QueuedRequest* request = GetCurrentRequest();
if (request == nullptr || request->dump_guid != dump_guid) {
return;
}
RemovePendingResponse(client, ResponseType::kOSDump);
if (!clients_.count(client)) {
VLOG(1) << "Received a memory dump response from an unregistered client";
return;
}
request->responses[client].os_dumps = std::move(os_dumps);
if (!success) {
request->failed_memory_dump_count++;
VLOG(1) << "RequestGlobalMemoryDump() FAIL: NACK from client process";
}
FinalizeGlobalMemoryDumpIfAllManagersReplied();
}
| 16,131 |
57,973 | 0 | static int nf_tables_getrule(struct sock *nlsk, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const nla[])
{
const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
const struct nft_af_info *afi;
const struct nft_table *table;
const struct nft_chain *chain;
const struct nft_rule *rule;
struct sk_buff *skb2;
struct net *net = sock_net(skb->sk);
int family = nfmsg->nfgen_family;
int err;
if (nlh->nlmsg_flags & NLM_F_DUMP) {
struct netlink_dump_control c = {
.dump = nf_tables_dump_rules,
};
return netlink_dump_start(nlsk, skb, nlh, &c);
}
afi = nf_tables_afinfo_lookup(net, family, false);
if (IS_ERR(afi))
return PTR_ERR(afi);
table = nf_tables_table_lookup(afi, nla[NFTA_RULE_TABLE]);
if (IS_ERR(table))
return PTR_ERR(table);
if (table->flags & NFT_TABLE_INACTIVE)
return -ENOENT;
chain = nf_tables_chain_lookup(table, nla[NFTA_RULE_CHAIN]);
if (IS_ERR(chain))
return PTR_ERR(chain);
if (chain->flags & NFT_CHAIN_INACTIVE)
return -ENOENT;
rule = nf_tables_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
if (IS_ERR(rule))
return PTR_ERR(rule);
skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb2)
return -ENOMEM;
err = nf_tables_fill_rule_info(skb2, net, NETLINK_CB(skb).portid,
nlh->nlmsg_seq, NFT_MSG_NEWRULE, 0,
family, table, chain, rule);
if (err < 0)
goto err;
return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
err:
kfree_skb(skb2);
return err;
}
| 16,132 |
54,285 | 0 | SPL_METHOD(SplDoublyLinkedList, setIteratorMode)
{
zend_long value;
spl_dllist_object *intern;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &value) == FAILURE) {
return;
}
intern = Z_SPLDLLIST_P(getThis());
if (intern->flags & SPL_DLLIST_IT_FIX
&& (intern->flags & SPL_DLLIST_IT_LIFO) != (value & SPL_DLLIST_IT_LIFO)) {
zend_throw_exception(spl_ce_RuntimeException, "Iterators' LIFO/FIFO modes for SplStack/SplQueue objects are frozen", 0);
return;
}
intern->flags = value & SPL_DLLIST_IT_MASK;
RETURN_LONG(intern->flags);
}
| 16,133 |
102,415 | 0 | string16 IDNToUnicode(const std::string& host,
const std::string& languages) {
return IDNToUnicodeWithOffsets(host, languages, NULL);
}
| 16,134 |
135,864 | 0 | const AtomicString& TextTrack::CaptionsKeyword() {
DEFINE_STATIC_LOCAL(const AtomicString, captions, ("captions"));
return captions;
}
| 16,135 |
45,823 | 0 | static void mcryptd_fini_queue(struct mcryptd_queue *queue)
{
int cpu;
struct mcryptd_cpu_queue *cpu_queue;
for_each_possible_cpu(cpu) {
cpu_queue = per_cpu_ptr(queue->cpu_queue, cpu);
BUG_ON(cpu_queue->queue.qlen);
}
free_percpu(queue->cpu_queue);
}
| 16,136 |
147,851 | 0 | void V8TestObject::SizeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_size_Getter");
test_object_v8_internal::SizeAttributeGetter(info);
}
| 16,137 |
22,915 | 0 | static int nfs4_wait_clnt_recover(struct nfs_client *clp)
{
int res;
might_sleep();
res = wait_on_bit(&clp->cl_state, NFS4CLNT_MANAGER_RUNNING,
nfs4_wait_bit_killable, TASK_KILLABLE);
return res;
}
| 16,138 |
38,345 | 0 | static int cm_alloc_msg(struct cm_id_private *cm_id_priv,
struct ib_mad_send_buf **msg)
{
struct ib_mad_agent *mad_agent;
struct ib_mad_send_buf *m;
struct ib_ah *ah;
mad_agent = cm_id_priv->av.port->mad_agent;
ah = ib_create_ah(mad_agent->qp->pd, &cm_id_priv->av.ah_attr);
if (IS_ERR(ah))
return PTR_ERR(ah);
m = ib_create_send_mad(mad_agent, cm_id_priv->id.remote_cm_qpn,
cm_id_priv->av.pkey_index,
0, IB_MGMT_MAD_HDR, IB_MGMT_MAD_DATA,
GFP_ATOMIC);
if (IS_ERR(m)) {
ib_destroy_ah(ah);
return PTR_ERR(m);
}
/* Timeout set by caller if response is expected. */
m->ah = ah;
m->retries = cm_id_priv->max_cm_retries;
atomic_inc(&cm_id_priv->refcount);
m->context[0] = cm_id_priv;
*msg = m;
return 0;
}
| 16,139 |
154,412 | 0 | ScopedPixelUnpackState::~ScopedPixelUnpackState() {
state_->RestoreUnpackState();
}
| 16,140 |
32,478 | 0 | static void __tg3_set_rx_mode(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
u32 rx_mode;
rx_mode = tp->rx_mode & ~(RX_MODE_PROMISC |
RX_MODE_KEEP_VLAN_TAG);
#if !defined(CONFIG_VLAN_8021Q) && !defined(CONFIG_VLAN_8021Q_MODULE)
/* When ASF is in use, we always keep the RX_MODE_KEEP_VLAN_TAG
* flag clear.
*/
if (!tg3_flag(tp, ENABLE_ASF))
rx_mode |= RX_MODE_KEEP_VLAN_TAG;
#endif
if (dev->flags & IFF_PROMISC) {
/* Promiscuous mode. */
rx_mode |= RX_MODE_PROMISC;
} else if (dev->flags & IFF_ALLMULTI) {
/* Accept all multicast. */
tg3_set_multi(tp, 1);
} else if (netdev_mc_empty(dev)) {
/* Reject all multicast. */
tg3_set_multi(tp, 0);
} else {
/* Accept one or more multicast(s). */
struct netdev_hw_addr *ha;
u32 mc_filter[4] = { 0, };
u32 regidx;
u32 bit;
u32 crc;
netdev_for_each_mc_addr(ha, dev) {
crc = calc_crc(ha->addr, ETH_ALEN);
bit = ~crc & 0x7f;
regidx = (bit & 0x60) >> 5;
bit &= 0x1f;
mc_filter[regidx] |= (1 << bit);
}
tw32(MAC_HASH_REG_0, mc_filter[0]);
tw32(MAC_HASH_REG_1, mc_filter[1]);
tw32(MAC_HASH_REG_2, mc_filter[2]);
tw32(MAC_HASH_REG_3, mc_filter[3]);
}
if (rx_mode != tp->rx_mode) {
tp->rx_mode = rx_mode;
tw32_f(MAC_RX_MODE, rx_mode);
udelay(10);
}
}
| 16,141 |
19,271 | 0 | static inline struct hlist_head *nl_pid_hashfn(struct nl_pid_hash *hash, u32 pid)
{
return &hash->table[jhash_1word(pid, hash->rnd) & hash->mask];
}
| 16,142 |
36,157 | 0 | static inline void mk_request_init(struct session_request *request)
{
request->status = MK_TRUE;
request->method = MK_HTTP_METHOD_UNKNOWN;
request->file_info.size = -1;
request->bytes_to_send = -1;
request->fd_file = -1;
/* Response Headers */
mk_header_response_reset(&request->headers);
}
| 16,143 |
120,529 | 0 | PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
{
if (!elementData())
return 0;
QualifiedName qName(nullAtom, localName, namespaceURI);
synchronizeAttribute(qName);
const Attribute* attribute = elementData()->getAttributeItem(qName);
if (!attribute)
return 0;
return ensureAttr(attribute->name());
}
| 16,144 |
47,459 | 0 | static int padlock_sha256_update_nano(struct shash_desc *desc, const u8 *data,
unsigned int len)
{
struct sha256_state *sctx = shash_desc_ctx(desc);
unsigned int partial, done;
const u8 *src;
/*The PHE require the out buffer must 128 bytes and 16-bytes aligned*/
u8 buf[128 + PADLOCK_ALIGNMENT - STACK_ALIGN] __attribute__
((aligned(STACK_ALIGN)));
u8 *dst = PTR_ALIGN(&buf[0], PADLOCK_ALIGNMENT);
int ts_state;
partial = sctx->count & 0x3f;
sctx->count += len;
done = 0;
src = data;
memcpy(dst, (u8 *)(sctx->state), SHA256_DIGEST_SIZE);
if ((partial + len) >= SHA256_BLOCK_SIZE) {
/* Append the bytes in state's buffer to a block to handle */
if (partial) {
done = -partial;
memcpy(sctx->buf + partial, data,
done + SHA256_BLOCK_SIZE);
src = sctx->buf;
ts_state = irq_ts_save();
asm volatile (".byte 0xf3,0x0f,0xa6,0xd0"
: "+S"(src), "+D"(dst)
: "a"((long)-1), "c"((unsigned long)1));
irq_ts_restore(ts_state);
done += SHA256_BLOCK_SIZE;
src = data + done;
}
/* Process the left bytes from input data*/
if (len - done >= SHA256_BLOCK_SIZE) {
ts_state = irq_ts_save();
asm volatile (".byte 0xf3,0x0f,0xa6,0xd0"
: "+S"(src), "+D"(dst)
: "a"((long)-1),
"c"((unsigned long)((len - done) / 64)));
irq_ts_restore(ts_state);
done += ((len - done) - (len - done) % 64);
src = data + done;
}
partial = 0;
}
memcpy((u8 *)(sctx->state), dst, SHA256_DIGEST_SIZE);
memcpy(sctx->buf + partial, src, len - done);
return 0;
}
| 16,145 |
125,540 | 0 | GDataEntry::~GDataEntry() {
}
| 16,146 |
57,759 | 0 | static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
{
#ifdef CONFIG_X86_64
bool vcpus_matched;
struct kvm_arch *ka = &vcpu->kvm->arch;
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
atomic_read(&vcpu->kvm->online_vcpus));
/*
* Once the masterclock is enabled, always perform request in
* order to update it.
*
* In order to enable masterclock, the host clocksource must be TSC
* and the vcpus need to have matched TSCs. When that happens,
* perform request to enable masterclock.
*/
if (ka->use_master_clock ||
(gtod->clock.vclock_mode == VCLOCK_TSC && vcpus_matched))
kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
atomic_read(&vcpu->kvm->online_vcpus),
ka->use_master_clock, gtod->clock.vclock_mode);
#endif
}
| 16,147 |
142,935 | 0 | void HTMLMediaElement::UpdateControlsVisibility() {
if (!isConnected())
return;
bool native_controls = ShouldShowControls(RecordMetricsBehavior::kDoRecord);
if (!RuntimeEnabledFeatures::LazyInitializeMediaControlsEnabled() ||
RuntimeEnabledFeatures::MediaCastOverlayButtonEnabled() ||
native_controls) {
EnsureMediaControls();
GetMediaControls()->Reset();
}
if (native_controls)
GetMediaControls()->MaybeShow();
else if (GetMediaControls())
GetMediaControls()->Hide();
if (web_media_player_)
web_media_player_->OnHasNativeControlsChanged(native_controls);
}
| 16,148 |
117,694 | 0 | virtual void CreateNewWidget(int route_id,
WebKit::WebPopupType popup_type) {}
| 16,149 |
143,518 | 0 | void CompositorImpl::OnGpuChannelEstablished(
scoped_refptr<gpu::GpuChannelHost> gpu_channel_host) {
CompositorDependencies::Get().TryEstablishVizConnectionIfNeeded();
if (!layer_tree_frame_sink_request_pending_)
return;
if (!gpu_channel_host) {
HandlePendingLayerTreeFrameSinkRequest();
return;
}
if (!host_->IsVisible()) {
return;
}
DCHECK(window_);
DCHECK_NE(surface_handle_, gpu::kNullSurfaceHandle);
gpu::GpuChannelEstablishFactory* factory =
BrowserMainLoop::GetInstance()->gpu_channel_establish_factory();
int32_t stream_id = kGpuStreamIdDefault;
gpu::SchedulingPriority stream_priority = kGpuStreamPriorityUI;
constexpr bool support_locking = false;
constexpr bool automatic_flushes = false;
constexpr bool support_grcontext = true;
display_color_space_ = display::Screen::GetScreen()
->GetDisplayNearestWindow(root_window_)
.color_space();
gpu::SurfaceHandle surface_handle =
enable_viz_ ? gpu::kNullSurfaceHandle : surface_handle_;
auto context_provider =
base::MakeRefCounted<ws::ContextProviderCommandBuffer>(
std::move(gpu_channel_host), factory->GetGpuMemoryBufferManager(),
stream_id, stream_priority, surface_handle,
GURL(std::string("chrome://gpu/CompositorImpl::") +
std::string("CompositorContextProvider")),
automatic_flushes, support_locking, support_grcontext,
GetCompositorContextSharedMemoryLimits(root_window_),
GetCompositorContextAttributes(display_color_space_,
requires_alpha_channel_),
ws::command_buffer_metrics::ContextType::BROWSER_COMPOSITOR);
auto result = context_provider->BindToCurrentThread();
if (result != gpu::ContextResult::kSuccess) {
if (gpu::IsFatalOrSurfaceFailure(result))
OnFatalOrSurfaceContextCreationFailure(result);
HandlePendingLayerTreeFrameSinkRequest();
return;
}
if (enable_viz_) {
InitializeVizLayerTreeFrameSink(std::move(context_provider));
} else {
auto display_output_surface = std::make_unique<AndroidOutputSurface>(
context_provider, base::BindRepeating(&CompositorImpl::DidSwapBuffers,
base::Unretained(this)));
InitializeDisplay(std::move(display_output_surface),
std::move(context_provider));
}
}
| 16,150 |
177,637 | 0 | void CheckTMPrediction() const {
for (int p = 0; p < num_planes_; p++)
for (int y = 0; y < block_size_; y++)
for (int x = 0; x < block_size_; x++) {
const int expected = ClipByte(data_ptr_[p][x - stride_]
+ data_ptr_[p][stride_ * y - 1]
- data_ptr_[p][-1 - stride_]);
ASSERT_EQ(expected, data_ptr_[p][y * stride_ + x]);
}
}
| 16,151 |
59,254 | 0 | SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
{
struct fs_struct *fs, *new_fs = NULL;
struct files_struct *fd, *new_fd = NULL;
struct cred *new_cred = NULL;
struct nsproxy *new_nsproxy = NULL;
int do_sysvsem = 0;
int err;
/*
* If unsharing a user namespace must also unshare the thread group
* and unshare the filesystem root and working directories.
*/
if (unshare_flags & CLONE_NEWUSER)
unshare_flags |= CLONE_THREAD | CLONE_FS;
/*
* If unsharing vm, must also unshare signal handlers.
*/
if (unshare_flags & CLONE_VM)
unshare_flags |= CLONE_SIGHAND;
/*
* If unsharing a signal handlers, must also unshare the signal queues.
*/
if (unshare_flags & CLONE_SIGHAND)
unshare_flags |= CLONE_THREAD;
/*
* If unsharing namespace, must also unshare filesystem information.
*/
if (unshare_flags & CLONE_NEWNS)
unshare_flags |= CLONE_FS;
err = check_unshare_flags(unshare_flags);
if (err)
goto bad_unshare_out;
/*
* CLONE_NEWIPC must also detach from the undolist: after switching
* to a new ipc namespace, the semaphore arrays from the old
* namespace are unreachable.
*/
if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
do_sysvsem = 1;
err = unshare_fs(unshare_flags, &new_fs);
if (err)
goto bad_unshare_out;
err = unshare_fd(unshare_flags, &new_fd);
if (err)
goto bad_unshare_cleanup_fs;
err = unshare_userns(unshare_flags, &new_cred);
if (err)
goto bad_unshare_cleanup_fd;
err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
new_cred, new_fs);
if (err)
goto bad_unshare_cleanup_cred;
if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
if (do_sysvsem) {
/*
* CLONE_SYSVSEM is equivalent to sys_exit().
*/
exit_sem(current);
}
if (unshare_flags & CLONE_NEWIPC) {
/* Orphan segments in old ns (see sem above). */
exit_shm(current);
shm_init_task(current);
}
if (new_nsproxy)
switch_task_namespaces(current, new_nsproxy);
task_lock(current);
if (new_fs) {
fs = current->fs;
spin_lock(&fs->lock);
current->fs = new_fs;
if (--fs->users)
new_fs = NULL;
else
new_fs = fs;
spin_unlock(&fs->lock);
}
if (new_fd) {
fd = current->files;
current->files = new_fd;
new_fd = fd;
}
task_unlock(current);
if (new_cred) {
/* Install the new user namespace */
commit_creds(new_cred);
new_cred = NULL;
}
}
perf_event_namespaces(current);
bad_unshare_cleanup_cred:
if (new_cred)
put_cred(new_cred);
bad_unshare_cleanup_fd:
if (new_fd)
put_files_struct(new_fd);
bad_unshare_cleanup_fs:
if (new_fs)
free_fs_struct(new_fs);
bad_unshare_out:
return err;
}
| 16,152 |
139,372 | 0 | void Editor::RevealSelectionAfterEditingOperation(
const ScrollAlignment& alignment,
RevealExtentOption reveal_extent_option) {
if (prevent_reveal_selection_)
return;
if (!GetFrame().Selection().IsAvailable())
return;
GetFrame().Selection().RevealSelection(alignment, reveal_extent_option);
}
| 16,153 |
178,364 | 1 | expand_string_internal(uschar *string, BOOL ket_ends, uschar **left,
BOOL skipping, BOOL honour_dollar, BOOL *resetok_p)
{
int ptr = 0;
int size = Ustrlen(string)+ 64;
int item_type;
uschar *yield = store_get(size);
uschar *s = string;
uschar *save_expand_nstring[EXPAND_MAXN+1];
int save_expand_nlength[EXPAND_MAXN+1];
BOOL resetok = TRUE;
expand_string_forcedfail = FALSE;
expand_string_message = US"";
while (*s != 0)
{
uschar *value;
uschar name[256];
/* \ escapes the next character, which must exist, or else
the expansion fails. There's a special escape, \N, which causes
copying of the subject verbatim up to the next \N. Otherwise,
the escapes are the standard set. */
if (*s == '\\')
{
if (s[1] == 0)
{
expand_string_message = US"\\ at end of string";
goto EXPAND_FAILED;
}
if (s[1] == 'N')
{
uschar *t = s + 2;
for (s = t; *s != 0; s++) if (*s == '\\' && s[1] == 'N') break;
yield = string_cat(yield, &size, &ptr, t, s - t);
if (*s != 0) s += 2;
}
else
{
uschar ch[1];
ch[0] = string_interpret_escape(&s);
s++;
yield = string_cat(yield, &size, &ptr, ch, 1);
}
continue;
}
/*{*/
/* Anything other than $ is just copied verbatim, unless we are
looking for a terminating } character. */
/*{*/
if (ket_ends && *s == '}') break;
if (*s != '$' || !honour_dollar)
{
yield = string_cat(yield, &size, &ptr, s++, 1);
continue;
}
/* No { after the $ - must be a plain name or a number for string
match variable. There has to be a fudge for variables that are the
names of header fields preceded by "$header_" because header field
names can contain any printing characters except space and colon.
For those that don't like typing this much, "$h_" is a synonym for
"$header_". A non-existent header yields a NULL value; nothing is
inserted. */ /*}*/
if (isalpha((*(++s))))
{
int len;
int newsize = 0;
s = read_name(name, sizeof(name), s, US"_");
/* If this is the first thing to be expanded, release the pre-allocated
buffer. */
if (ptr == 0 && yield != NULL)
{
if (resetok) store_reset(yield);
yield = NULL;
size = 0;
}
/* Header */
if (Ustrncmp(name, "h_", 2) == 0 ||
Ustrncmp(name, "rh_", 3) == 0 ||
Ustrncmp(name, "bh_", 3) == 0 ||
Ustrncmp(name, "header_", 7) == 0 ||
Ustrncmp(name, "rheader_", 8) == 0 ||
Ustrncmp(name, "bheader_", 8) == 0)
{
BOOL want_raw = (name[0] == 'r')? TRUE : FALSE;
uschar *charset = (name[0] == 'b')? NULL : headers_charset;
s = read_header_name(name, sizeof(name), s);
value = find_header(name, FALSE, &newsize, want_raw, charset);
/* If we didn't find the header, and the header contains a closing brace
character, this may be a user error where the terminating colon
has been omitted. Set a flag to adjust the error message in this case.
But there is no error here - nothing gets inserted. */
if (value == NULL)
{
if (Ustrchr(name, '}') != NULL) malformed_header = TRUE;
continue;
}
}
/* Variable */
else
{
value = find_variable(name, FALSE, skipping, &newsize);
if (value == NULL)
{
expand_string_message =
string_sprintf("unknown variable name \"%s\"", name);
check_variable_error_message(name);
goto EXPAND_FAILED;
}
}
/* If the data is known to be in a new buffer, newsize will be set to the
size of that buffer. If this is the first thing in an expansion string,
yield will be NULL; just point it at the new store instead of copying. Many
expansion strings contain just one reference, so this is a useful
optimization, especially for humungous headers. */
len = Ustrlen(value);
if (yield == NULL && newsize != 0)
{
yield = value;
size = newsize;
ptr = len;
}
else yield = string_cat(yield, &size, &ptr, value, len);
continue;
}
if (isdigit(*s))
{
int n;
s = read_number(&n, s);
if (n >= 0 && n <= expand_nmax)
yield = string_cat(yield, &size, &ptr, expand_nstring[n],
expand_nlength[n]);
continue;
}
/* Otherwise, if there's no '{' after $ it's an error. */ /*}*/
if (*s != '{') /*}*/
{
expand_string_message = US"$ not followed by letter, digit, or {"; /*}*/
goto EXPAND_FAILED;
}
/* After { there can be various things, but they all start with
an initial word, except for a number for a string match variable. */
if (isdigit((*(++s))))
{
int n;
s = read_number(&n, s); /*{*/
if (*s++ != '}')
{ /*{*/
expand_string_message = US"} expected after number";
goto EXPAND_FAILED;
}
if (n >= 0 && n <= expand_nmax)
yield = string_cat(yield, &size, &ptr, expand_nstring[n],
expand_nlength[n]);
continue;
}
if (!isalpha(*s))
{
expand_string_message = US"letter or digit expected after ${"; /*}*/
goto EXPAND_FAILED;
}
/* Allow "-" in names to cater for substrings with negative
arguments. Since we are checking for known names after { this is
OK. */
s = read_name(name, sizeof(name), s, US"_-");
item_type = chop_match(name, item_table, sizeof(item_table)/sizeof(uschar *));
switch(item_type)
{
/* Call an ACL from an expansion. We feed data in via $acl_arg1 - $acl_arg9.
If the ACL returns accept or reject we return content set by "message ="
There is currently no limit on recursion; this would have us call
acl_check_internal() directly and get a current level from somewhere.
See also the acl expansion condition ECOND_ACL and the traditional
acl modifier ACLC_ACL.
Assume that the function has side-effects on the store that must be preserved.
*/
case EITEM_ACL:
/* ${acl {name} {arg1}{arg2}...} */
{
uschar *sub[10]; /* name + arg1-arg9 (which must match number of acl_arg[]) */
uschar *user_msg;
switch(read_subs(sub, 10, 1, &s, skipping, TRUE, US"acl", &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
if (skipping) continue;
resetok = FALSE;
switch(eval_acl(sub, sizeof(sub)/sizeof(*sub), &user_msg))
{
case OK:
case FAIL:
DEBUG(D_expand)
debug_printf("acl expansion yield: %s\n", user_msg);
if (user_msg)
yield = string_cat(yield, &size, &ptr, user_msg, Ustrlen(user_msg));
continue;
case DEFER:
expand_string_forcedfail = TRUE;
default:
expand_string_message = string_sprintf("error from acl \"%s\"", sub[0]);
goto EXPAND_FAILED;
}
}
/* Handle conditionals - preserve the values of the numerical expansion
variables in case they get changed by a regular expression match in the
condition. If not, they retain their external settings. At the end
of this "if" section, they get restored to their previous values. */
case EITEM_IF:
{
BOOL cond = FALSE;
uschar *next_s;
int save_expand_nmax =
save_expand_strings(save_expand_nstring, save_expand_nlength);
while (isspace(*s)) s++;
next_s = eval_condition(s, &resetok, skipping? NULL : &cond);
if (next_s == NULL) goto EXPAND_FAILED; /* message already set */
DEBUG(D_expand)
debug_printf("condition: %.*s\n result: %s\n", (int)(next_s - s), s,
cond? "true" : "false");
s = next_s;
/* The handling of "yes" and "no" result strings is now in a separate
function that is also used by ${lookup} and ${extract} and ${run}. */
switch(process_yesno(
skipping, /* were previously skipping */
cond, /* success/failure indicator */
lookup_value, /* value to reset for string2 */
&s, /* input pointer */
&yield, /* output pointer */
&size, /* output size */
&ptr, /* output current point */
US"if", /* condition type */
&resetok))
{
case 1: goto EXPAND_FAILED; /* when all is well, the */
case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */
}
/* Restore external setting of expansion variables for continuation
at this level. */
restore_expand_strings(save_expand_nmax, save_expand_nstring,
save_expand_nlength);
continue;
}
/* Handle database lookups unless locked out. If "skipping" is TRUE, we are
expanding an internal string that isn't actually going to be used. All we
need to do is check the syntax, so don't do a lookup at all. Preserve the
values of the numerical expansion variables in case they get changed by a
partial lookup. If not, they retain their external settings. At the end
of this "lookup" section, they get restored to their previous values. */
case EITEM_LOOKUP:
{
int stype, partial, affixlen, starflags;
int expand_setup = 0;
int nameptr = 0;
uschar *key, *filename, *affix;
uschar *save_lookup_value = lookup_value;
int save_expand_nmax =
save_expand_strings(save_expand_nstring, save_expand_nlength);
if ((expand_forbid & RDO_LOOKUP) != 0)
{
expand_string_message = US"lookup expansions are not permitted";
goto EXPAND_FAILED;
}
/* Get the key we are to look up for single-key+file style lookups.
Otherwise set the key NULL pro-tem. */
while (isspace(*s)) s++;
if (*s == '{') /*}*/
{
key = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);
if (key == NULL) goto EXPAND_FAILED; /*{*/
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
while (isspace(*s)) s++;
}
else key = NULL;
/* Find out the type of database */
if (!isalpha(*s))
{
expand_string_message = US"missing lookup type";
goto EXPAND_FAILED;
}
/* The type is a string that may contain special characters of various
kinds. Allow everything except space or { to appear; the actual content
is checked by search_findtype_partial. */ /*}*/
while (*s != 0 && *s != '{' && !isspace(*s)) /*}*/
{
if (nameptr < sizeof(name) - 1) name[nameptr++] = *s;
s++;
}
name[nameptr] = 0;
while (isspace(*s)) s++;
/* Now check for the individual search type and any partial or default
options. Only those types that are actually in the binary are valid. */
stype = search_findtype_partial(name, &partial, &affix, &affixlen,
&starflags);
if (stype < 0)
{
expand_string_message = search_error_message;
goto EXPAND_FAILED;
}
/* Check that a key was provided for those lookup types that need it,
and was not supplied for those that use the query style. */
if (!mac_islookup(stype, lookup_querystyle|lookup_absfilequery))
{
if (key == NULL)
{
expand_string_message = string_sprintf("missing {key} for single-"
"key \"%s\" lookup", name);
goto EXPAND_FAILED;
}
}
else
{
if (key != NULL)
{
expand_string_message = string_sprintf("a single key was given for "
"lookup type \"%s\", which is not a single-key lookup type", name);
goto EXPAND_FAILED;
}
}
/* Get the next string in brackets and expand it. It is the file name for
single-key+file lookups, and the whole query otherwise. In the case of
queries that also require a file name (e.g. sqlite), the file name comes
first. */
if (*s != '{') goto EXPAND_FAILED_CURLY;
filename = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);
if (filename == NULL) goto EXPAND_FAILED;
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
while (isspace(*s)) s++;
/* If this isn't a single-key+file lookup, re-arrange the variables
to be appropriate for the search_ functions. For query-style lookups,
there is just a "key", and no file name. For the special query-style +
file types, the query (i.e. "key") starts with a file name. */
if (key == NULL)
{
while (isspace(*filename)) filename++;
key = filename;
if (mac_islookup(stype, lookup_querystyle))
{
filename = NULL;
}
else
{
if (*filename != '/')
{
expand_string_message = string_sprintf(
"absolute file name expected for \"%s\" lookup", name);
goto EXPAND_FAILED;
}
while (*key != 0 && !isspace(*key)) key++;
if (*key != 0) *key++ = 0;
}
}
/* If skipping, don't do the next bit - just lookup_value == NULL, as if
the entry was not found. Note that there is no search_close() function.
Files are left open in case of re-use. At suitable places in higher logic,
search_tidyup() is called to tidy all open files. This can save opening
the same file several times. However, files may also get closed when
others are opened, if too many are open at once. The rule is that a
handle should not be used after a second search_open().
Request that a partial search sets up $1 and maybe $2 by passing
expand_setup containing zero. If its value changes, reset expand_nmax,
since new variables will have been set. Note that at the end of this
"lookup" section, the old numeric variables are restored. */
if (skipping)
lookup_value = NULL;
else
{
void *handle = search_open(filename, stype, 0, NULL, NULL);
if (handle == NULL)
{
expand_string_message = search_error_message;
goto EXPAND_FAILED;
}
lookup_value = search_find(handle, filename, key, partial, affix,
affixlen, starflags, &expand_setup);
if (search_find_defer)
{
expand_string_message =
string_sprintf("lookup of \"%s\" gave DEFER: %s",
string_printing2(key, FALSE), search_error_message);
goto EXPAND_FAILED;
}
if (expand_setup > 0) expand_nmax = expand_setup;
}
/* The handling of "yes" and "no" result strings is now in a separate
function that is also used by ${if} and ${extract}. */
switch(process_yesno(
skipping, /* were previously skipping */
lookup_value != NULL, /* success/failure indicator */
save_lookup_value, /* value to reset for string2 */
&s, /* input pointer */
&yield, /* output pointer */
&size, /* output size */
&ptr, /* output current point */
US"lookup", /* condition type */
&resetok))
{
case 1: goto EXPAND_FAILED; /* when all is well, the */
case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */
}
/* Restore external setting of expansion variables for carrying on
at this level, and continue. */
restore_expand_strings(save_expand_nmax, save_expand_nstring,
save_expand_nlength);
continue;
}
/* If Perl support is configured, handle calling embedded perl subroutines,
unless locked out at this time. Syntax is ${perl{sub}} or ${perl{sub}{arg}}
or ${perl{sub}{arg1}{arg2}} or up to a maximum of EXIM_PERL_MAX_ARGS
arguments (defined below). */
#define EXIM_PERL_MAX_ARGS 8
case EITEM_PERL:
#ifndef EXIM_PERL
expand_string_message = US"\"${perl\" encountered, but this facility " /*}*/
"is not included in this binary";
goto EXPAND_FAILED;
#else /* EXIM_PERL */
{
uschar *sub_arg[EXIM_PERL_MAX_ARGS + 2];
uschar *new_yield;
if ((expand_forbid & RDO_PERL) != 0)
{
expand_string_message = US"Perl calls are not permitted";
goto EXPAND_FAILED;
}
switch(read_subs(sub_arg, EXIM_PERL_MAX_ARGS + 1, 1, &s, skipping, TRUE,
US"perl", &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
/* If skipping, we don't actually do anything */
if (skipping) continue;
/* Start the interpreter if necessary */
if (!opt_perl_started)
{
uschar *initerror;
if (opt_perl_startup == NULL)
{
expand_string_message = US"A setting of perl_startup is needed when "
"using the Perl interpreter";
goto EXPAND_FAILED;
}
DEBUG(D_any) debug_printf("Starting Perl interpreter\n");
initerror = init_perl(opt_perl_startup);
if (initerror != NULL)
{
expand_string_message =
string_sprintf("error in perl_startup code: %s\n", initerror);
goto EXPAND_FAILED;
}
opt_perl_started = TRUE;
}
/* Call the function */
sub_arg[EXIM_PERL_MAX_ARGS + 1] = NULL;
new_yield = call_perl_cat(yield, &size, &ptr, &expand_string_message,
sub_arg[0], sub_arg + 1);
/* NULL yield indicates failure; if the message pointer has been set to
NULL, the yield was undef, indicating a forced failure. Otherwise the
message will indicate some kind of Perl error. */
if (new_yield == NULL)
{
if (expand_string_message == NULL)
{
expand_string_message =
string_sprintf("Perl subroutine \"%s\" returned undef to force "
"failure", sub_arg[0]);
expand_string_forcedfail = TRUE;
}
goto EXPAND_FAILED;
}
/* Yield succeeded. Ensure forcedfail is unset, just in case it got
set during a callback from Perl. */
expand_string_forcedfail = FALSE;
yield = new_yield;
continue;
}
#endif /* EXIM_PERL */
/* Transform email address to "prvs" scheme to use
as BATV-signed return path */
case EITEM_PRVS:
{
uschar *sub_arg[3];
uschar *p,*domain;
switch(read_subs(sub_arg, 3, 2, &s, skipping, TRUE, US"prvs", &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
/* If skipping, we don't actually do anything */
if (skipping) continue;
/* sub_arg[0] is the address */
domain = Ustrrchr(sub_arg[0],'@');
if ( (domain == NULL) || (domain == sub_arg[0]) || (Ustrlen(domain) == 1) )
{
expand_string_message = US"prvs first argument must be a qualified email address";
goto EXPAND_FAILED;
}
/* Calculate the hash. The second argument must be a single-digit
key number, or unset. */
if (sub_arg[2] != NULL &&
(!isdigit(sub_arg[2][0]) || sub_arg[2][1] != 0))
{
expand_string_message = US"prvs second argument must be a single digit";
goto EXPAND_FAILED;
}
p = prvs_hmac_sha1(sub_arg[0],sub_arg[1],sub_arg[2],prvs_daystamp(7));
if (p == NULL)
{
expand_string_message = US"prvs hmac-sha1 conversion failed";
goto EXPAND_FAILED;
}
/* Now separate the domain from the local part */
*domain++ = '\0';
yield = string_cat(yield,&size,&ptr,US"prvs=",5);
string_cat(yield,&size,&ptr,(sub_arg[2] != NULL) ? sub_arg[2] : US"0", 1);
string_cat(yield,&size,&ptr,prvs_daystamp(7),3);
string_cat(yield,&size,&ptr,p,6);
string_cat(yield,&size,&ptr,US"=",1);
string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0]));
string_cat(yield,&size,&ptr,US"@",1);
string_cat(yield,&size,&ptr,domain,Ustrlen(domain));
continue;
}
/* Check a prvs-encoded address for validity */
case EITEM_PRVSCHECK:
{
uschar *sub_arg[3];
int mysize = 0, myptr = 0;
const pcre *re;
uschar *p;
/* TF: Ugliness: We want to expand parameter 1 first, then set
up expansion variables that are used in the expansion of
parameter 2. So we clone the string for the first
expansion, where we only expand parameter 1.
PH: Actually, that isn't necessary. The read_subs() function is
designed to work this way for the ${if and ${lookup expansions. I've
tidied the code.
*/
/* Reset expansion variables */
prvscheck_result = NULL;
prvscheck_address = NULL;
prvscheck_keynum = NULL;
switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
re = regex_must_compile(US"^prvs\\=([0-9])([0-9]{3})([A-F0-9]{6})\\=(.+)\\@(.+)$",
TRUE,FALSE);
if (regex_match_and_setup(re,sub_arg[0],0,-1))
{
uschar *local_part = string_copyn(expand_nstring[4],expand_nlength[4]);
uschar *key_num = string_copyn(expand_nstring[1],expand_nlength[1]);
uschar *daystamp = string_copyn(expand_nstring[2],expand_nlength[2]);
uschar *hash = string_copyn(expand_nstring[3],expand_nlength[3]);
uschar *domain = string_copyn(expand_nstring[5],expand_nlength[5]);
DEBUG(D_expand) debug_printf("prvscheck localpart: %s\n", local_part);
DEBUG(D_expand) debug_printf("prvscheck key number: %s\n", key_num);
DEBUG(D_expand) debug_printf("prvscheck daystamp: %s\n", daystamp);
DEBUG(D_expand) debug_printf("prvscheck hash: %s\n", hash);
DEBUG(D_expand) debug_printf("prvscheck domain: %s\n", domain);
/* Set up expansion variables */
prvscheck_address = string_cat(NULL, &mysize, &myptr, local_part, Ustrlen(local_part));
string_cat(prvscheck_address,&mysize,&myptr,US"@",1);
string_cat(prvscheck_address,&mysize,&myptr,domain,Ustrlen(domain));
prvscheck_address[myptr] = '\0';
prvscheck_keynum = string_copy(key_num);
/* Now expand the second argument */
switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
/* Now we have the key and can check the address. */
p = prvs_hmac_sha1(prvscheck_address, sub_arg[0], prvscheck_keynum,
daystamp);
if (p == NULL)
{
expand_string_message = US"hmac-sha1 conversion failed";
goto EXPAND_FAILED;
}
DEBUG(D_expand) debug_printf("prvscheck: received hash is %s\n", hash);
DEBUG(D_expand) debug_printf("prvscheck: own hash is %s\n", p);
if (Ustrcmp(p,hash) == 0)
{
/* Success, valid BATV address. Now check the expiry date. */
uschar *now = prvs_daystamp(0);
unsigned int inow = 0,iexpire = 1;
(void)sscanf(CS now,"%u",&inow);
(void)sscanf(CS daystamp,"%u",&iexpire);
/* When "iexpire" is < 7, a "flip" has occured.
Adjust "inow" accordingly. */
if ( (iexpire < 7) && (inow >= 993) ) inow = 0;
if (iexpire >= inow)
{
prvscheck_result = US"1";
DEBUG(D_expand) debug_printf("prvscheck: success, $pvrs_result set to 1\n");
}
else
{
prvscheck_result = NULL;
DEBUG(D_expand) debug_printf("prvscheck: signature expired, $pvrs_result unset\n");
}
}
else
{
prvscheck_result = NULL;
DEBUG(D_expand) debug_printf("prvscheck: hash failure, $pvrs_result unset\n");
}
/* Now expand the final argument. We leave this till now so that
it can include $prvscheck_result. */
switch(read_subs(sub_arg, 1, 0, &s, skipping, TRUE, US"prvs", &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
if (sub_arg[0] == NULL || *sub_arg[0] == '\0')
yield = string_cat(yield,&size,&ptr,prvscheck_address,Ustrlen(prvscheck_address));
else
yield = string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0]));
/* Reset the "internal" variables afterwards, because they are in
dynamic store that will be reclaimed if the expansion succeeded. */
prvscheck_address = NULL;
prvscheck_keynum = NULL;
}
else
{
/* Does not look like a prvs encoded address, return the empty string.
We need to make sure all subs are expanded first, so as to skip over
the entire item. */
switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"prvs", &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
}
continue;
}
/* Handle "readfile" to insert an entire file */
case EITEM_READFILE:
{
FILE *f;
uschar *sub_arg[2];
if ((expand_forbid & RDO_READFILE) != 0)
{
expand_string_message = US"file insertions are not permitted";
goto EXPAND_FAILED;
}
switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"readfile", &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
/* If skipping, we don't actually do anything */
if (skipping) continue;
/* Open the file and read it */
f = Ufopen(sub_arg[0], "rb");
if (f == NULL)
{
expand_string_message = string_open_failed(errno, "%s", sub_arg[0]);
goto EXPAND_FAILED;
}
yield = cat_file(f, yield, &size, &ptr, sub_arg[1]);
(void)fclose(f);
continue;
}
/* Handle "readsocket" to insert data from a Unix domain socket */
case EITEM_READSOCK:
{
int fd;
int timeout = 5;
int save_ptr = ptr;
FILE *f;
struct sockaddr_un sockun; /* don't call this "sun" ! */
uschar *arg;
uschar *sub_arg[4];
if ((expand_forbid & RDO_READSOCK) != 0)
{
expand_string_message = US"socket insertions are not permitted";
goto EXPAND_FAILED;
}
/* Read up to 4 arguments, but don't do the end of item check afterwards,
because there may be a string for expansion on failure. */
switch(read_subs(sub_arg, 4, 2, &s, skipping, FALSE, US"readsocket", &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2: /* Won't occur: no end check */
case 3: goto EXPAND_FAILED;
}
/* Sort out timeout, if given */
if (sub_arg[2] != NULL)
{
timeout = readconf_readtime(sub_arg[2], 0, FALSE);
if (timeout < 0)
{
expand_string_message = string_sprintf("bad time value %s",
sub_arg[2]);
goto EXPAND_FAILED;
}
}
else sub_arg[3] = NULL; /* No eol if no timeout */
/* If skipping, we don't actually do anything. Otherwise, arrange to
connect to either an IP or a Unix socket. */
if (!skipping)
{
/* Handle an IP (internet) domain */
if (Ustrncmp(sub_arg[0], "inet:", 5) == 0)
{
int port;
uschar *server_name = sub_arg[0] + 5;
uschar *port_name = Ustrrchr(server_name, ':');
/* Sort out the port */
if (port_name == NULL)
{
expand_string_message =
string_sprintf("missing port for readsocket %s", sub_arg[0]);
goto EXPAND_FAILED;
}
*port_name++ = 0; /* Terminate server name */
if (isdigit(*port_name))
{
uschar *end;
port = Ustrtol(port_name, &end, 0);
if (end != port_name + Ustrlen(port_name))
{
expand_string_message =
string_sprintf("invalid port number %s", port_name);
goto EXPAND_FAILED;
}
}
else
{
struct servent *service_info = getservbyname(CS port_name, "tcp");
if (service_info == NULL)
{
expand_string_message = string_sprintf("unknown port \"%s\"",
port_name);
goto EXPAND_FAILED;
}
port = ntohs(service_info->s_port);
}
if ((fd = ip_connectedsocket(SOCK_STREAM, server_name, port, port,
timeout, NULL, &expand_string_message)) < 0)
goto SOCK_FAIL;
}
/* Handle a Unix domain socket */
else
{
int rc;
if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
{
expand_string_message = string_sprintf("failed to create socket: %s",
strerror(errno));
goto SOCK_FAIL;
}
sockun.sun_family = AF_UNIX;
sprintf(sockun.sun_path, "%.*s", (int)(sizeof(sockun.sun_path)-1),
sub_arg[0]);
sigalrm_seen = FALSE;
alarm(timeout);
rc = connect(fd, (struct sockaddr *)(&sockun), sizeof(sockun));
alarm(0);
if (sigalrm_seen)
{
expand_string_message = US "socket connect timed out";
goto SOCK_FAIL;
}
if (rc < 0)
{
expand_string_message = string_sprintf("failed to connect to socket "
"%s: %s", sub_arg[0], strerror(errno));
goto SOCK_FAIL;
}
}
DEBUG(D_expand) debug_printf("connected to socket %s\n", sub_arg[0]);
/* Allow sequencing of test actions */
if (running_in_test_harness) millisleep(100);
/* Write the request string, if not empty */
if (sub_arg[1][0] != 0)
{
int len = Ustrlen(sub_arg[1]);
DEBUG(D_expand) debug_printf("writing \"%s\" to socket\n",
sub_arg[1]);
if (write(fd, sub_arg[1], len) != len)
{
expand_string_message = string_sprintf("request write to socket "
"failed: %s", strerror(errno));
goto SOCK_FAIL;
}
}
/* Shut down the sending side of the socket. This helps some servers to
recognise that it is their turn to do some work. Just in case some
system doesn't have this function, make it conditional. */
#ifdef SHUT_WR
shutdown(fd, SHUT_WR);
#endif
if (running_in_test_harness) millisleep(100);
/* Now we need to read from the socket, under a timeout. The function
that reads a file can be used. */
f = fdopen(fd, "rb");
sigalrm_seen = FALSE;
alarm(timeout);
yield = cat_file(f, yield, &size, &ptr, sub_arg[3]);
alarm(0);
(void)fclose(f);
/* After a timeout, we restore the pointer in the result, that is,
make sure we add nothing from the socket. */
if (sigalrm_seen)
{
ptr = save_ptr;
expand_string_message = US "socket read timed out";
goto SOCK_FAIL;
}
}
/* The whole thing has worked (or we were skipping). If there is a
failure string following, we need to skip it. */
if (*s == '{')
{
if (expand_string_internal(s+1, TRUE, &s, TRUE, TRUE, &resetok) == NULL)
goto EXPAND_FAILED;
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
while (isspace(*s)) s++;
}
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
continue;
/* Come here on failure to create socket, connect socket, write to the
socket, or timeout on reading. If another substring follows, expand and
use it. Otherwise, those conditions give expand errors. */
SOCK_FAIL:
if (*s != '{') goto EXPAND_FAILED;
DEBUG(D_any) debug_printf("%s\n", expand_string_message);
arg = expand_string_internal(s+1, TRUE, &s, FALSE, TRUE, &resetok);
if (arg == NULL) goto EXPAND_FAILED;
yield = string_cat(yield, &size, &ptr, arg, Ustrlen(arg));
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
while (isspace(*s)) s++;
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
continue;
}
/* Handle "run" to execute a program. */
case EITEM_RUN:
{
FILE *f;
uschar *arg;
uschar **argv;
pid_t pid;
int fd_in, fd_out;
int lsize = 0;
int lptr = 0;
if ((expand_forbid & RDO_RUN) != 0)
{
expand_string_message = US"running a command is not permitted";
goto EXPAND_FAILED;
}
while (isspace(*s)) s++;
if (*s != '{') goto EXPAND_FAILED_CURLY;
arg = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);
if (arg == NULL) goto EXPAND_FAILED;
while (isspace(*s)) s++;
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
if (skipping) /* Just pretend it worked when we're skipping */
{
runrc = 0;
}
else
{
if (!transport_set_up_command(&argv, /* anchor for arg list */
arg, /* raw command */
FALSE, /* don't expand the arguments */
0, /* not relevant when... */
NULL, /* no transporting address */
US"${run} expansion", /* for error messages */
&expand_string_message)) /* where to put error message */
{
goto EXPAND_FAILED;
}
/* Create the child process, making it a group leader. */
pid = child_open(argv, NULL, 0077, &fd_in, &fd_out, TRUE);
if (pid < 0)
{
expand_string_message =
string_sprintf("couldn't create child process: %s", strerror(errno));
goto EXPAND_FAILED;
}
/* Nothing is written to the standard input. */
(void)close(fd_in);
/* Read the pipe to get the command's output into $value (which is kept
in lookup_value). Read during execution, so that if the output exceeds
the OS pipe buffer limit, we don't block forever. */
f = fdopen(fd_out, "rb");
sigalrm_seen = FALSE;
alarm(60);
lookup_value = cat_file(f, lookup_value, &lsize, &lptr, NULL);
alarm(0);
(void)fclose(f);
/* Wait for the process to finish, applying the timeout, and inspect its
return code for serious disasters. Simple non-zero returns are passed on.
*/
if (sigalrm_seen == TRUE || (runrc = child_close(pid, 30)) < 0)
{
if (sigalrm_seen == TRUE || runrc == -256)
{
expand_string_message = string_sprintf("command timed out");
killpg(pid, SIGKILL); /* Kill the whole process group */
}
else if (runrc == -257)
expand_string_message = string_sprintf("wait() failed: %s",
strerror(errno));
else
expand_string_message = string_sprintf("command killed by signal %d",
-runrc);
goto EXPAND_FAILED;
}
}
/* Process the yes/no strings; $value may be useful in both cases */
switch(process_yesno(
skipping, /* were previously skipping */
runrc == 0, /* success/failure indicator */
lookup_value, /* value to reset for string2 */
&s, /* input pointer */
&yield, /* output pointer */
&size, /* output size */
&ptr, /* output current point */
US"run", /* condition type */
&resetok))
{
case 1: goto EXPAND_FAILED; /* when all is well, the */
case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */
}
continue;
}
/* Handle character translation for "tr" */
case EITEM_TR:
{
int oldptr = ptr;
int o2m;
uschar *sub[3];
switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"tr", &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
yield = string_cat(yield, &size, &ptr, sub[0], Ustrlen(sub[0]));
o2m = Ustrlen(sub[2]) - 1;
if (o2m >= 0) for (; oldptr < ptr; oldptr++)
{
uschar *m = Ustrrchr(sub[1], yield[oldptr]);
if (m != NULL)
{
int o = m - sub[1];
yield[oldptr] = sub[2][(o < o2m)? o : o2m];
}
}
continue;
}
/* Handle "hash", "length", "nhash", and "substr" when they are given with
expanded arguments. */
case EITEM_HASH:
case EITEM_LENGTH:
case EITEM_NHASH:
case EITEM_SUBSTR:
{
int i;
int len;
uschar *ret;
int val[2] = { 0, -1 };
uschar *sub[3];
/* "length" takes only 2 arguments whereas the others take 2 or 3.
Ensure that sub[2] is set in the ${length } case. */
sub[2] = NULL;
switch(read_subs(sub, (item_type == EITEM_LENGTH)? 2:3, 2, &s, skipping,
TRUE, name, &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
/* Juggle the arguments if there are only two of them: always move the
string to the last position and make ${length{n}{str}} equivalent to
${substr{0}{n}{str}}. See the defaults for val[] above. */
if (sub[2] == NULL)
{
sub[2] = sub[1];
sub[1] = NULL;
if (item_type == EITEM_LENGTH)
{
sub[1] = sub[0];
sub[0] = NULL;
}
}
for (i = 0; i < 2; i++)
{
if (sub[i] == NULL) continue;
val[i] = (int)Ustrtol(sub[i], &ret, 10);
if (*ret != 0 || (i != 0 && val[i] < 0))
{
expand_string_message = string_sprintf("\"%s\" is not a%s number "
"(in \"%s\" expansion)", sub[i], (i != 0)? " positive" : "", name);
goto EXPAND_FAILED;
}
}
ret =
(item_type == EITEM_HASH)?
compute_hash(sub[2], val[0], val[1], &len) :
(item_type == EITEM_NHASH)?
compute_nhash(sub[2], val[0], val[1], &len) :
extract_substr(sub[2], val[0], val[1], &len);
if (ret == NULL) goto EXPAND_FAILED;
yield = string_cat(yield, &size, &ptr, ret, len);
continue;
}
/* Handle HMAC computation: ${hmac{<algorithm>}{<secret>}{<text>}}
This code originally contributed by Steve Haslam. It currently supports
the use of MD5 and SHA-1 hashes.
We need some workspace that is large enough to handle all the supported
hash types. Use macros to set the sizes rather than be too elaborate. */
#define MAX_HASHLEN 20
#define MAX_HASHBLOCKLEN 64
case EITEM_HMAC:
{
uschar *sub[3];
md5 md5_base;
sha1 sha1_base;
void *use_base;
int type, i;
int hashlen; /* Number of octets for the hash algorithm's output */
int hashblocklen; /* Number of octets the hash algorithm processes */
uschar *keyptr, *p;
unsigned int keylen;
uschar keyhash[MAX_HASHLEN];
uschar innerhash[MAX_HASHLEN];
uschar finalhash[MAX_HASHLEN];
uschar finalhash_hex[2*MAX_HASHLEN];
uschar innerkey[MAX_HASHBLOCKLEN];
uschar outerkey[MAX_HASHBLOCKLEN];
switch (read_subs(sub, 3, 3, &s, skipping, TRUE, name, &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
if (Ustrcmp(sub[0], "md5") == 0)
{
type = HMAC_MD5;
use_base = &md5_base;
hashlen = 16;
hashblocklen = 64;
}
else if (Ustrcmp(sub[0], "sha1") == 0)
{
type = HMAC_SHA1;
use_base = &sha1_base;
hashlen = 20;
hashblocklen = 64;
}
else
{
expand_string_message =
string_sprintf("hmac algorithm \"%s\" is not recognised", sub[0]);
goto EXPAND_FAILED;
}
keyptr = sub[1];
keylen = Ustrlen(keyptr);
/* If the key is longer than the hash block length, then hash the key
first */
if (keylen > hashblocklen)
{
chash_start(type, use_base);
chash_end(type, use_base, keyptr, keylen, keyhash);
keyptr = keyhash;
keylen = hashlen;
}
/* Now make the inner and outer key values */
memset(innerkey, 0x36, hashblocklen);
memset(outerkey, 0x5c, hashblocklen);
for (i = 0; i < keylen; i++)
{
innerkey[i] ^= keyptr[i];
outerkey[i] ^= keyptr[i];
}
/* Now do the hashes */
chash_start(type, use_base);
chash_mid(type, use_base, innerkey);
chash_end(type, use_base, sub[2], Ustrlen(sub[2]), innerhash);
chash_start(type, use_base);
chash_mid(type, use_base, outerkey);
chash_end(type, use_base, innerhash, hashlen, finalhash);
/* Encode the final hash as a hex string */
p = finalhash_hex;
for (i = 0; i < hashlen; i++)
{
*p++ = hex_digits[(finalhash[i] & 0xf0) >> 4];
*p++ = hex_digits[finalhash[i] & 0x0f];
}
DEBUG(D_any) debug_printf("HMAC[%s](%.*s,%.*s)=%.*s\n", sub[0],
(int)keylen, keyptr, Ustrlen(sub[2]), sub[2], hashlen*2, finalhash_hex);
yield = string_cat(yield, &size, &ptr, finalhash_hex, hashlen*2);
}
continue;
/* Handle global substitution for "sg" - like Perl's s/xxx/yyy/g operator.
We have to save the numerical variables and restore them afterwards. */
case EITEM_SG:
{
const pcre *re;
int moffset, moffsetextra, slen;
int roffset;
int emptyopt;
const uschar *rerror;
uschar *subject;
uschar *sub[3];
int save_expand_nmax =
save_expand_strings(save_expand_nstring, save_expand_nlength);
switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"sg", &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
/* Compile the regular expression */
re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset,
NULL);
if (re == NULL)
{
expand_string_message = string_sprintf("regular expression error in "
"\"%s\": %s at offset %d", sub[1], rerror, roffset);
goto EXPAND_FAILED;
}
/* Now run a loop to do the substitutions as often as necessary. It ends
when there are no more matches. Take care over matches of the null string;
do the same thing as Perl does. */
subject = sub[0];
slen = Ustrlen(sub[0]);
moffset = moffsetextra = 0;
emptyopt = 0;
for (;;)
{
int ovector[3*(EXPAND_MAXN+1)];
int n = pcre_exec(re, NULL, CS subject, slen, moffset + moffsetextra,
PCRE_EOPT | emptyopt, ovector, sizeof(ovector)/sizeof(int));
int nn;
uschar *insert;
/* No match - if we previously set PCRE_NOTEMPTY after a null match, this
is not necessarily the end. We want to repeat the match from one
character further along, but leaving the basic offset the same (for
copying below). We can't be at the end of the string - that was checked
before setting PCRE_NOTEMPTY. If PCRE_NOTEMPTY is not set, we are
finished; copy the remaining string and end the loop. */
if (n < 0)
{
if (emptyopt != 0)
{
moffsetextra = 1;
emptyopt = 0;
continue;
}
yield = string_cat(yield, &size, &ptr, subject+moffset, slen-moffset);
break;
}
/* Match - set up for expanding the replacement. */
if (n == 0) n = EXPAND_MAXN + 1;
expand_nmax = 0;
for (nn = 0; nn < n*2; nn += 2)
{
expand_nstring[expand_nmax] = subject + ovector[nn];
expand_nlength[expand_nmax++] = ovector[nn+1] - ovector[nn];
}
expand_nmax--;
/* Copy the characters before the match, plus the expanded insertion. */
yield = string_cat(yield, &size, &ptr, subject + moffset,
ovector[0] - moffset);
insert = expand_string(sub[2]);
if (insert == NULL) goto EXPAND_FAILED;
yield = string_cat(yield, &size, &ptr, insert, Ustrlen(insert));
moffset = ovector[1];
moffsetextra = 0;
emptyopt = 0;
/* If we have matched an empty string, first check to see if we are at
the end of the subject. If so, the loop is over. Otherwise, mimic
what Perl's /g options does. This turns out to be rather cunning. First
we set PCRE_NOTEMPTY and PCRE_ANCHORED and try the match a non-empty
string at the same point. If this fails (picked up above) we advance to
the next character. */
if (ovector[0] == ovector[1])
{
if (ovector[0] == slen) break;
emptyopt = PCRE_NOTEMPTY | PCRE_ANCHORED;
}
}
/* All done - restore numerical variables. */
restore_expand_strings(save_expand_nmax, save_expand_nstring,
save_expand_nlength);
continue;
}
/* Handle keyed and numbered substring extraction. If the first argument
consists entirely of digits, then a numerical extraction is assumed. */
case EITEM_EXTRACT:
{
int i;
int j = 2;
int field_number = 1;
BOOL field_number_set = FALSE;
uschar *save_lookup_value = lookup_value;
uschar *sub[3];
int save_expand_nmax =
save_expand_strings(save_expand_nstring, save_expand_nlength);
/* Read the arguments */
for (i = 0; i < j; i++)
{
while (isspace(*s)) s++;
if (*s == '{') /*}*/
{
sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);
if (sub[i] == NULL) goto EXPAND_FAILED; /*{*/
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
/* After removal of leading and trailing white space, the first
argument must not be empty; if it consists entirely of digits
(optionally preceded by a minus sign), this is a numerical
extraction, and we expect 3 arguments. */
if (i == 0)
{
int len;
int x = 0;
uschar *p = sub[0];
while (isspace(*p)) p++;
sub[0] = p;
len = Ustrlen(p);
while (len > 0 && isspace(p[len-1])) len--;
p[len] = 0;
if (*p == 0 && !skipping)
{
expand_string_message = US"first argument of \"extract\" must "
"not be empty";
goto EXPAND_FAILED;
}
if (*p == '-')
{
field_number = -1;
p++;
}
while (*p != 0 && isdigit(*p)) x = x * 10 + *p++ - '0';
if (*p == 0)
{
field_number *= x;
j = 3; /* Need 3 args */
field_number_set = TRUE;
}
}
}
else goto EXPAND_FAILED_CURLY;
}
/* Extract either the numbered or the keyed substring into $value. If
skipping, just pretend the extraction failed. */
lookup_value = skipping? NULL : field_number_set?
expand_gettokened(field_number, sub[1], sub[2]) :
expand_getkeyed(sub[0], sub[1]);
/* If no string follows, $value gets substituted; otherwise there can
be yes/no strings, as for lookup or if. */
switch(process_yesno(
skipping, /* were previously skipping */
lookup_value != NULL, /* success/failure indicator */
save_lookup_value, /* value to reset for string2 */
&s, /* input pointer */
&yield, /* output pointer */
&size, /* output size */
&ptr, /* output current point */
US"extract", /* condition type */
&resetok))
{
case 1: goto EXPAND_FAILED; /* when all is well, the */
case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */
}
/* All done - restore numerical variables. */
restore_expand_strings(save_expand_nmax, save_expand_nstring,
save_expand_nlength);
continue;
}
/* return the Nth item from a list */
case EITEM_LISTEXTRACT:
{
int i;
int field_number = 1;
uschar *save_lookup_value = lookup_value;
uschar *sub[2];
int save_expand_nmax =
save_expand_strings(save_expand_nstring, save_expand_nlength);
/* Read the field & list arguments */
for (i = 0; i < 2; i++)
{
while (isspace(*s)) s++;
if (*s != '{') /*}*/
goto EXPAND_FAILED_CURLY;
sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);
if (!sub[i]) goto EXPAND_FAILED; /*{*/
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
/* After removal of leading and trailing white space, the first
argument must be numeric and nonempty. */
if (i == 0)
{
int len;
int x = 0;
uschar *p = sub[0];
while (isspace(*p)) p++;
sub[0] = p;
len = Ustrlen(p);
while (len > 0 && isspace(p[len-1])) len--;
p[len] = 0;
if (!*p && !skipping)
{
expand_string_message = US"first argument of \"listextract\" must "
"not be empty";
goto EXPAND_FAILED;
}
if (*p == '-')
{
field_number = -1;
p++;
}
while (*p && isdigit(*p)) x = x * 10 + *p++ - '0';
if (*p)
{
expand_string_message = US"first argument of \"listextract\" must "
"be numeric";
goto EXPAND_FAILED;
}
field_number *= x;
}
}
/* Extract the numbered element into $value. If
skipping, just pretend the extraction failed. */
lookup_value = skipping? NULL : expand_getlistele(field_number, sub[1]);
/* If no string follows, $value gets substituted; otherwise there can
be yes/no strings, as for lookup or if. */
switch(process_yesno(
skipping, /* were previously skipping */
lookup_value != NULL, /* success/failure indicator */
save_lookup_value, /* value to reset for string2 */
&s, /* input pointer */
&yield, /* output pointer */
&size, /* output size */
&ptr, /* output current point */
US"extract", /* condition type */
&resetok))
{
case 1: goto EXPAND_FAILED; /* when all is well, the */
case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */
}
/* All done - restore numerical variables. */
restore_expand_strings(save_expand_nmax, save_expand_nstring,
save_expand_nlength);
continue;
}
#ifdef SUPPORT_TLS
case EITEM_CERTEXTRACT:
{
uschar *save_lookup_value = lookup_value;
uschar *sub[2];
int save_expand_nmax =
save_expand_strings(save_expand_nstring, save_expand_nlength);
/* Read the field argument */
while (isspace(*s)) s++;
if (*s != '{') /*}*/
goto EXPAND_FAILED_CURLY;
sub[0] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);
if (!sub[0]) goto EXPAND_FAILED; /*{*/
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
/* strip spaces fore & aft */
{
int len;
uschar *p = sub[0];
while (isspace(*p)) p++;
sub[0] = p;
len = Ustrlen(p);
while (len > 0 && isspace(p[len-1])) len--;
p[len] = 0;
}
/* inspect the cert argument */
while (isspace(*s)) s++;
if (*s != '{') /*}*/
goto EXPAND_FAILED_CURLY;
if (*++s != '$')
{
expand_string_message = US"second argument of \"certextract\" must "
"be a certificate variable";
goto EXPAND_FAILED;
}
sub[1] = expand_string_internal(s+1, TRUE, &s, skipping, FALSE, &resetok);
if (!sub[1]) goto EXPAND_FAILED; /*{*/
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
if (skipping)
lookup_value = NULL;
else
{
lookup_value = expand_getcertele(sub[0], sub[1]);
if (*expand_string_message) goto EXPAND_FAILED;
}
switch(process_yesno(
skipping, /* were previously skipping */
lookup_value != NULL, /* success/failure indicator */
save_lookup_value, /* value to reset for string2 */
&s, /* input pointer */
&yield, /* output pointer */
&size, /* output size */
&ptr, /* output current point */
US"extract", /* condition type */
&resetok))
{
case 1: goto EXPAND_FAILED; /* when all is well, the */
case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */
}
restore_expand_strings(save_expand_nmax, save_expand_nstring,
save_expand_nlength);
continue;
}
#endif /*SUPPORT_TLS*/
/* Handle list operations */
case EITEM_FILTER:
case EITEM_MAP:
case EITEM_REDUCE:
{
int sep = 0;
int save_ptr = ptr;
uschar outsep[2] = { '\0', '\0' };
uschar *list, *expr, *temp;
uschar *save_iterate_item = iterate_item;
uschar *save_lookup_value = lookup_value;
while (isspace(*s)) s++;
if (*s++ != '{') goto EXPAND_FAILED_CURLY;
list = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok);
if (list == NULL) goto EXPAND_FAILED;
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
if (item_type == EITEM_REDUCE)
{
while (isspace(*s)) s++;
if (*s++ != '{') goto EXPAND_FAILED_CURLY;
temp = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok);
if (temp == NULL) goto EXPAND_FAILED;
lookup_value = temp;
if (*s++ != '}') goto EXPAND_FAILED_CURLY;
}
while (isspace(*s)) s++;
if (*s++ != '{') goto EXPAND_FAILED_CURLY;
expr = s;
/* For EITEM_FILTER, call eval_condition once, with result discarded (as
if scanning a "false" part). This allows us to find the end of the
condition, because if the list is empty, we won't actually evaluate the
condition for real. For EITEM_MAP and EITEM_REDUCE, do the same, using
the normal internal expansion function. */
if (item_type == EITEM_FILTER)
{
temp = eval_condition(expr, &resetok, NULL);
if (temp != NULL) s = temp;
}
else
{
temp = expand_string_internal(s, TRUE, &s, TRUE, TRUE, &resetok);
}
if (temp == NULL)
{
expand_string_message = string_sprintf("%s inside \"%s\" item",
expand_string_message, name);
goto EXPAND_FAILED;
}
while (isspace(*s)) s++;
if (*s++ != '}')
{ /*{*/
expand_string_message = string_sprintf("missing } at end of condition "
"or expression inside \"%s\"", name);
goto EXPAND_FAILED;
}
while (isspace(*s)) s++; /*{*/
if (*s++ != '}')
{ /*{*/
expand_string_message = string_sprintf("missing } at end of \"%s\"",
name);
goto EXPAND_FAILED;
}
/* If we are skipping, we can now just move on to the next item. When
processing for real, we perform the iteration. */
if (skipping) continue;
while ((iterate_item = string_nextinlist(&list, &sep, NULL, 0)) != NULL)
{
*outsep = (uschar)sep; /* Separator as a string */
DEBUG(D_expand) debug_printf("%s: $item = \"%s\"\n", name, iterate_item);
if (item_type == EITEM_FILTER)
{
BOOL condresult;
if (eval_condition(expr, &resetok, &condresult) == NULL)
{
iterate_item = save_iterate_item;
lookup_value = save_lookup_value;
expand_string_message = string_sprintf("%s inside \"%s\" condition",
expand_string_message, name);
goto EXPAND_FAILED;
}
DEBUG(D_expand) debug_printf("%s: condition is %s\n", name,
condresult? "true":"false");
if (condresult)
temp = iterate_item; /* TRUE => include this item */
else
continue; /* FALSE => skip this item */
}
/* EITEM_MAP and EITEM_REDUCE */
else
{
temp = expand_string_internal(expr, TRUE, NULL, skipping, TRUE, &resetok);
if (temp == NULL)
{
iterate_item = save_iterate_item;
expand_string_message = string_sprintf("%s inside \"%s\" item",
expand_string_message, name);
goto EXPAND_FAILED;
}
if (item_type == EITEM_REDUCE)
{
lookup_value = temp; /* Update the value of $value */
continue; /* and continue the iteration */
}
}
/* We reach here for FILTER if the condition is true, always for MAP,
and never for REDUCE. The value in "temp" is to be added to the output
list that is being created, ensuring that any occurrences of the
separator character are doubled. Unless we are dealing with the first
item of the output list, add in a space if the new item begins with the
separator character, or is an empty string. */
if (ptr != save_ptr && (temp[0] == *outsep || temp[0] == 0))
yield = string_cat(yield, &size, &ptr, US" ", 1);
/* Add the string in "temp" to the output list that we are building,
This is done in chunks by searching for the separator character. */
for (;;)
{
size_t seglen = Ustrcspn(temp, outsep);
yield = string_cat(yield, &size, &ptr, temp, seglen + 1);
/* If we got to the end of the string we output one character
too many; backup and end the loop. Otherwise arrange to double the
separator. */
if (temp[seglen] == '\0') { ptr--; break; }
yield = string_cat(yield, &size, &ptr, outsep, 1);
temp += seglen + 1;
}
/* Output a separator after the string: we will remove the redundant
final one at the end. */
yield = string_cat(yield, &size, &ptr, outsep, 1);
} /* End of iteration over the list loop */
/* REDUCE has generated no output above: output the final value of
$value. */
if (item_type == EITEM_REDUCE)
{
yield = string_cat(yield, &size, &ptr, lookup_value,
Ustrlen(lookup_value));
lookup_value = save_lookup_value; /* Restore $value */
}
/* FILTER and MAP generate lists: if they have generated anything, remove
the redundant final separator. Even though an empty item at the end of a
list does not count, this is tidier. */
else if (ptr != save_ptr) ptr--;
/* Restore preserved $item */
iterate_item = save_iterate_item;
continue;
}
/* If ${dlfunc } support is configured, handle calling dynamically-loaded
functions, unless locked out at this time. Syntax is ${dlfunc{file}{func}}
or ${dlfunc{file}{func}{arg}} or ${dlfunc{file}{func}{arg1}{arg2}} or up to
a maximum of EXPAND_DLFUNC_MAX_ARGS arguments (defined below). */
#define EXPAND_DLFUNC_MAX_ARGS 8
case EITEM_DLFUNC:
#ifndef EXPAND_DLFUNC
expand_string_message = US"\"${dlfunc\" encountered, but this facility " /*}*/
"is not included in this binary";
goto EXPAND_FAILED;
#else /* EXPAND_DLFUNC */
{
tree_node *t;
exim_dlfunc_t *func;
uschar *result;
int status, argc;
uschar *argv[EXPAND_DLFUNC_MAX_ARGS + 3];
if ((expand_forbid & RDO_DLFUNC) != 0)
{
expand_string_message =
US"dynamically-loaded functions are not permitted";
goto EXPAND_FAILED;
}
switch(read_subs(argv, EXPAND_DLFUNC_MAX_ARGS + 2, 2, &s, skipping,
TRUE, US"dlfunc", &resetok))
{
case 1: goto EXPAND_FAILED_CURLY;
case 2:
case 3: goto EXPAND_FAILED;
}
/* If skipping, we don't actually do anything */
if (skipping) continue;
/* Look up the dynamically loaded object handle in the tree. If it isn't
found, dlopen() the file and put the handle in the tree for next time. */
t = tree_search(dlobj_anchor, argv[0]);
if (t == NULL)
{
void *handle = dlopen(CS argv[0], RTLD_LAZY);
if (handle == NULL)
{
expand_string_message = string_sprintf("dlopen \"%s\" failed: %s",
argv[0], dlerror());
log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message);
goto EXPAND_FAILED;
}
t = store_get_perm(sizeof(tree_node) + Ustrlen(argv[0]));
Ustrcpy(t->name, argv[0]);
t->data.ptr = handle;
(void)tree_insertnode(&dlobj_anchor, t);
}
/* Having obtained the dynamically loaded object handle, look up the
function pointer. */
func = (exim_dlfunc_t *)dlsym(t->data.ptr, CS argv[1]);
if (func == NULL)
{
expand_string_message = string_sprintf("dlsym \"%s\" in \"%s\" failed: "
"%s", argv[1], argv[0], dlerror());
log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message);
goto EXPAND_FAILED;
}
/* Call the function and work out what to do with the result. If it
returns OK, we have a replacement string; if it returns DEFER then
expansion has failed in a non-forced manner; if it returns FAIL then
failure was forced; if it returns ERROR or any other value there's a
problem, so panic slightly. In any case, assume that the function has
side-effects on the store that must be preserved. */
resetok = FALSE;
result = NULL;
for (argc = 0; argv[argc] != NULL; argc++);
status = func(&result, argc - 2, &argv[2]);
if(status == OK)
{
if (result == NULL) result = US"";
yield = string_cat(yield, &size, &ptr, result, Ustrlen(result));
continue;
}
else
{
expand_string_message = result == NULL ? US"(no message)" : result;
if(status == FAIL_FORCED) expand_string_forcedfail = TRUE;
else if(status != FAIL)
log_write(0, LOG_MAIN|LOG_PANIC, "dlfunc{%s}{%s} failed (%d): %s",
argv[0], argv[1], status, expand_string_message);
goto EXPAND_FAILED;
}
}
#endif /* EXPAND_DLFUNC */
} /* EITEM_* switch */
/* Control reaches here if the name is not recognized as one of the more
complicated expansion items. Check for the "operator" syntax (name terminated
by a colon). Some of the operators have arguments, separated by _ from the
name. */
if (*s == ':')
{
int c;
uschar *arg = NULL;
uschar *sub;
var_entry *vp = NULL;
/* Owing to an historical mis-design, an underscore may be part of the
operator name, or it may introduce arguments. We therefore first scan the
table of names that contain underscores. If there is no match, we cut off
the arguments and then scan the main table. */
if ((c = chop_match(name, op_table_underscore,
sizeof(op_table_underscore)/sizeof(uschar *))) < 0)
{
arg = Ustrchr(name, '_');
if (arg != NULL) *arg = 0;
c = chop_match(name, op_table_main,
sizeof(op_table_main)/sizeof(uschar *));
if (c >= 0) c += sizeof(op_table_underscore)/sizeof(uschar *);
if (arg != NULL) *arg++ = '_'; /* Put back for error messages */
}
/* Deal specially with operators that might take a certificate variable
as we do not want to do the usual expansion. For most, expand the string.*/
switch(c)
{
#ifdef SUPPORT_TLS
case EOP_MD5:
case EOP_SHA1:
case EOP_SHA256:
if (s[1] == '$')
{
uschar * s1 = s;
sub = expand_string_internal(s+2, TRUE, &s1, skipping,
FALSE, &resetok);
if (!sub) goto EXPAND_FAILED; /*{*/
if (*s1 != '}') goto EXPAND_FAILED_CURLY;
if ((vp = find_var_ent(sub)) && vp->type == vtype_cert)
{
s = s1+1;
break;
}
vp = NULL;
}
/*FALLTHROUGH*/
#endif
default:
sub = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);
if (!sub) goto EXPAND_FAILED;
s++;
break;
}
/* If we are skipping, we don't need to perform the operation at all.
This matters for operations like "mask", because the data may not be
in the correct format when skipping. For example, the expression may test
for the existence of $sender_host_address before trying to mask it. For
other operations, doing them may not fail, but it is a waste of time. */
if (skipping && c >= 0) continue;
/* Otherwise, switch on the operator type */
switch(c)
{
case EOP_BASE62:
{
uschar *t;
unsigned long int n = Ustrtoul(sub, &t, 10);
if (*t != 0)
{
expand_string_message = string_sprintf("argument for base62 "
"operator is \"%s\", which is not a decimal number", sub);
goto EXPAND_FAILED;
}
t = string_base62(n);
yield = string_cat(yield, &size, &ptr, t, Ustrlen(t));
continue;
}
/* Note that for Darwin and Cygwin, BASE_62 actually has the value 36 */
case EOP_BASE62D:
{
uschar buf[16];
uschar *tt = sub;
unsigned long int n = 0;
while (*tt != 0)
{
uschar *t = Ustrchr(base62_chars, *tt++);
if (t == NULL)
{
expand_string_message = string_sprintf("argument for base62d "
"operator is \"%s\", which is not a base %d number", sub,
BASE_62);
goto EXPAND_FAILED;
}
n = n * BASE_62 + (t - base62_chars);
}
(void)sprintf(CS buf, "%ld", n);
yield = string_cat(yield, &size, &ptr, buf, Ustrlen(buf));
continue;
}
case EOP_EXPAND:
{
uschar *expanded = expand_string_internal(sub, FALSE, NULL, skipping, TRUE, &resetok);
if (expanded == NULL)
{
expand_string_message =
string_sprintf("internal expansion of \"%s\" failed: %s", sub,
expand_string_message);
goto EXPAND_FAILED;
}
yield = string_cat(yield, &size, &ptr, expanded, Ustrlen(expanded));
continue;
}
case EOP_LC:
{
int count = 0;
uschar *t = sub - 1;
while (*(++t) != 0) { *t = tolower(*t); count++; }
yield = string_cat(yield, &size, &ptr, sub, count);
continue;
}
case EOP_UC:
{
int count = 0;
uschar *t = sub - 1;
while (*(++t) != 0) { *t = toupper(*t); count++; }
yield = string_cat(yield, &size, &ptr, sub, count);
continue;
}
case EOP_MD5:
#ifdef SUPPORT_TLS
if (vp && *(void **)vp->value)
{
uschar * cp = tls_cert_fprt_md5(*(void **)vp->value);
yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp));
}
else
#endif
{
md5 base;
uschar digest[16];
int j;
char st[33];
md5_start(&base);
md5_end(&base, sub, Ustrlen(sub), digest);
for(j = 0; j < 16; j++) sprintf(st+2*j, "%02x", digest[j]);
yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st));
}
continue;
case EOP_SHA1:
#ifdef SUPPORT_TLS
if (vp && *(void **)vp->value)
{
uschar * cp = tls_cert_fprt_sha1(*(void **)vp->value);
yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp));
}
else
#endif
{
sha1 base;
uschar digest[20];
int j;
char st[41];
sha1_start(&base);
sha1_end(&base, sub, Ustrlen(sub), digest);
for(j = 0; j < 20; j++) sprintf(st+2*j, "%02X", digest[j]);
yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st));
}
continue;
case EOP_SHA256:
#ifdef SUPPORT_TLS
if (vp && *(void **)vp->value)
{
uschar * cp = tls_cert_fprt_sha256(*(void **)vp->value);
yield = string_cat(yield, &size, &ptr, cp, (int)Ustrlen(cp));
}
else
#endif
expand_string_message = US"sha256 only supported for certificates";
continue;
/* Convert hex encoding to base64 encoding */
case EOP_HEX2B64:
{
int c = 0;
int b = -1;
uschar *in = sub;
uschar *out = sub;
uschar *enc;
for (enc = sub; *enc != 0; enc++)
{
if (!isxdigit(*enc))
{
expand_string_message = string_sprintf("\"%s\" is not a hex "
"string", sub);
goto EXPAND_FAILED;
}
c++;
}
if ((c & 1) != 0)
{
expand_string_message = string_sprintf("\"%s\" contains an odd "
"number of characters", sub);
goto EXPAND_FAILED;
}
while ((c = *in++) != 0)
{
if (isdigit(c)) c -= '0';
else c = toupper(c) - 'A' + 10;
if (b == -1)
{
b = c << 4;
}
else
{
*out++ = b | c;
b = -1;
}
}
enc = auth_b64encode(sub, out - sub);
yield = string_cat(yield, &size, &ptr, enc, Ustrlen(enc));
continue;
}
/* Convert octets outside 0x21..0x7E to \xXX form */
case EOP_HEXQUOTE:
{
uschar *t = sub - 1;
while (*(++t) != 0)
{
if (*t < 0x21 || 0x7E < *t)
yield = string_cat(yield, &size, &ptr,
string_sprintf("\\x%02x", *t), 4);
else
yield = string_cat(yield, &size, &ptr, t, 1);
}
continue;
}
/* count the number of list elements */
case EOP_LISTCOUNT:
{
int cnt = 0;
int sep = 0;
uschar * cp;
uschar buffer[256];
while (string_nextinlist(&sub, &sep, buffer, sizeof(buffer)) != NULL) cnt++;
cp = string_sprintf("%d", cnt);
yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp));
continue;
}
/* expand a named list given the name */
/* handles nested named lists; requotes as colon-sep list */
case EOP_LISTNAMED:
{
tree_node *t = NULL;
uschar * list;
int sep = 0;
uschar * item;
uschar * suffix = US"";
BOOL needsep = FALSE;
uschar buffer[256];
if (*sub == '+') sub++;
if (arg == NULL) /* no-argument version */
{
if (!(t = tree_search(addresslist_anchor, sub)) &&
!(t = tree_search(domainlist_anchor, sub)) &&
!(t = tree_search(hostlist_anchor, sub)))
t = tree_search(localpartlist_anchor, sub);
}
else switch(*arg) /* specific list-type version */
{
case 'a': t = tree_search(addresslist_anchor, sub); suffix = US"_a"; break;
case 'd': t = tree_search(domainlist_anchor, sub); suffix = US"_d"; break;
case 'h': t = tree_search(hostlist_anchor, sub); suffix = US"_h"; break;
case 'l': t = tree_search(localpartlist_anchor, sub); suffix = US"_l"; break;
default:
expand_string_message = string_sprintf("bad suffix on \"list\" operator");
goto EXPAND_FAILED;
}
if(!t)
{
expand_string_message = string_sprintf("\"%s\" is not a %snamed list",
sub, !arg?""
: *arg=='a'?"address "
: *arg=='d'?"domain "
: *arg=='h'?"host "
: *arg=='l'?"localpart "
: 0);
goto EXPAND_FAILED;
}
list = ((namedlist_block *)(t->data.ptr))->string;
while ((item = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL)
{
uschar * buf = US" : ";
if (needsep)
yield = string_cat(yield, &size, &ptr, buf, 3);
else
needsep = TRUE;
if (*item == '+') /* list item is itself a named list */
{
uschar * sub = string_sprintf("${listnamed%s:%s}", suffix, item);
item = expand_string_internal(sub, FALSE, NULL, FALSE, TRUE, &resetok);
}
else if (sep != ':') /* item from non-colon-sep list, re-quote for colon list-separator */
{
char * cp;
char tok[3];
tok[0] = sep; tok[1] = ':'; tok[2] = 0;
while ((cp= strpbrk((const char *)item, tok)))
{
yield = string_cat(yield, &size, &ptr, item, cp-(char *)item);
if (*cp++ == ':') /* colon in a non-colon-sep list item, needs doubling */
{
yield = string_cat(yield, &size, &ptr, US"::", 2);
item = (uschar *)cp;
}
else /* sep in item; should already be doubled; emit once */
{
yield = string_cat(yield, &size, &ptr, (uschar *)tok, 1);
if (*cp == sep) cp++;
item = (uschar *)cp;
}
}
}
yield = string_cat(yield, &size, &ptr, item, Ustrlen(item));
}
continue;
}
/* mask applies a mask to an IP address; for example the result of
${mask:131.111.10.206/28} is 131.111.10.192/28. */
case EOP_MASK:
{
int count;
uschar *endptr;
int binary[4];
int mask, maskoffset;
int type = string_is_ip_address(sub, &maskoffset);
uschar buffer[64];
if (type == 0)
{
expand_string_message = string_sprintf("\"%s\" is not an IP address",
sub);
goto EXPAND_FAILED;
}
if (maskoffset == 0)
{
expand_string_message = string_sprintf("missing mask value in \"%s\"",
sub);
goto EXPAND_FAILED;
}
mask = Ustrtol(sub + maskoffset + 1, &endptr, 10);
if (*endptr != 0 || mask < 0 || mask > ((type == 4)? 32 : 128))
{
expand_string_message = string_sprintf("mask value too big in \"%s\"",
sub);
goto EXPAND_FAILED;
}
/* Convert the address to binary integer(s) and apply the mask */
sub[maskoffset] = 0;
count = host_aton(sub, binary);
host_mask(count, binary, mask);
/* Convert to masked textual format and add to output. */
yield = string_cat(yield, &size, &ptr, buffer,
host_nmtoa(count, binary, mask, buffer, '.'));
continue;
}
case EOP_ADDRESS:
case EOP_LOCAL_PART:
case EOP_DOMAIN:
{
uschar *error;
int start, end, domain;
uschar *t = parse_extract_address(sub, &error, &start, &end, &domain,
FALSE);
if (t != NULL)
{
if (c != EOP_DOMAIN)
{
if (c == EOP_LOCAL_PART && domain != 0) end = start + domain - 1;
yield = string_cat(yield, &size, &ptr, sub+start, end-start);
}
else if (domain != 0)
{
domain += start;
yield = string_cat(yield, &size, &ptr, sub+domain, end-domain);
}
}
continue;
}
case EOP_ADDRESSES:
{
uschar outsep[2] = { ':', '\0' };
uschar *address, *error;
int save_ptr = ptr;
int start, end, domain; /* Not really used */
while (isspace(*sub)) sub++;
if (*sub == '>') { *outsep = *++sub; ++sub; }
parse_allow_group = TRUE;
for (;;)
{
uschar *p = parse_find_address_end(sub, FALSE);
uschar saveend = *p;
*p = '\0';
address = parse_extract_address(sub, &error, &start, &end, &domain,
FALSE);
*p = saveend;
/* Add the address to the output list that we are building. This is
done in chunks by searching for the separator character. At the
start, unless we are dealing with the first address of the output
list, add in a space if the new address begins with the separator
character, or is an empty string. */
if (address != NULL)
{
if (ptr != save_ptr && address[0] == *outsep)
yield = string_cat(yield, &size, &ptr, US" ", 1);
for (;;)
{
size_t seglen = Ustrcspn(address, outsep);
yield = string_cat(yield, &size, &ptr, address, seglen + 1);
/* If we got to the end of the string we output one character
too many. */
if (address[seglen] == '\0') { ptr--; break; }
yield = string_cat(yield, &size, &ptr, outsep, 1);
address += seglen + 1;
}
/* Output a separator after the string: we will remove the
redundant final one at the end. */
yield = string_cat(yield, &size, &ptr, outsep, 1);
}
if (saveend == '\0') break;
sub = p + 1;
}
/* If we have generated anything, remove the redundant final
separator. */
if (ptr != save_ptr) ptr--;
parse_allow_group = FALSE;
continue;
}
/* quote puts a string in quotes if it is empty or contains anything
other than alphamerics, underscore, dot, or hyphen.
quote_local_part puts a string in quotes if RFC 2821/2822 requires it to
be quoted in order to be a valid local part.
In both cases, newlines and carriage returns are converted into \n and \r
respectively */
case EOP_QUOTE:
case EOP_QUOTE_LOCAL_PART:
if (arg == NULL)
{
BOOL needs_quote = (*sub == 0); /* TRUE for empty string */
uschar *t = sub - 1;
if (c == EOP_QUOTE)
{
while (!needs_quote && *(++t) != 0)
needs_quote = !isalnum(*t) && !strchr("_-.", *t);
}
else /* EOP_QUOTE_LOCAL_PART */
{
while (!needs_quote && *(++t) != 0)
needs_quote = !isalnum(*t) &&
strchr("!#$%&'*+-/=?^_`{|}~", *t) == NULL &&
(*t != '.' || t == sub || t[1] == 0);
}
if (needs_quote)
{
yield = string_cat(yield, &size, &ptr, US"\"", 1);
t = sub - 1;
while (*(++t) != 0)
{
if (*t == '\n')
yield = string_cat(yield, &size, &ptr, US"\\n", 2);
else if (*t == '\r')
yield = string_cat(yield, &size, &ptr, US"\\r", 2);
else
{
if (*t == '\\' || *t == '"')
yield = string_cat(yield, &size, &ptr, US"\\", 1);
yield = string_cat(yield, &size, &ptr, t, 1);
}
}
yield = string_cat(yield, &size, &ptr, US"\"", 1);
}
else yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub));
continue;
}
/* quote_lookuptype does lookup-specific quoting */
else
{
int n;
uschar *opt = Ustrchr(arg, '_');
if (opt != NULL) *opt++ = 0;
n = search_findtype(arg, Ustrlen(arg));
if (n < 0)
{
expand_string_message = search_error_message;
goto EXPAND_FAILED;
}
if (lookup_list[n]->quote != NULL)
sub = (lookup_list[n]->quote)(sub, opt);
else if (opt != NULL) sub = NULL;
if (sub == NULL)
{
expand_string_message = string_sprintf(
"\"%s\" unrecognized after \"${quote_%s\"",
opt, arg);
goto EXPAND_FAILED;
}
yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub));
continue;
}
/* rx quote sticks in \ before any non-alphameric character so that
the insertion works in a regular expression. */
case EOP_RXQUOTE:
{
uschar *t = sub - 1;
while (*(++t) != 0)
{
if (!isalnum(*t))
yield = string_cat(yield, &size, &ptr, US"\\", 1);
yield = string_cat(yield, &size, &ptr, t, 1);
}
continue;
}
/* RFC 2047 encodes, assuming headers_charset (default ISO 8859-1) as
prescribed by the RFC, if there are characters that need to be encoded */
case EOP_RFC2047:
{
uschar buffer[2048];
uschar *string = parse_quote_2047(sub, Ustrlen(sub), headers_charset,
buffer, sizeof(buffer), FALSE);
yield = string_cat(yield, &size, &ptr, string, Ustrlen(string));
continue;
}
/* RFC 2047 decode */
case EOP_RFC2047D:
{
int len;
uschar *error;
uschar *decoded = rfc2047_decode(sub, check_rfc2047_length,
headers_charset, '?', &len, &error);
if (error != NULL)
{
expand_string_message = error;
goto EXPAND_FAILED;
}
yield = string_cat(yield, &size, &ptr, decoded, len);
continue;
}
/* from_utf8 converts UTF-8 to 8859-1, turning non-existent chars into
underscores */
case EOP_FROM_UTF8:
{
while (*sub != 0)
{
int c;
uschar buff[4];
GETUTF8INC(c, sub);
if (c > 255) c = '_';
buff[0] = c;
yield = string_cat(yield, &size, &ptr, buff, 1);
}
continue;
}
/* replace illegal UTF-8 sequences by replacement character */
#define UTF8_REPLACEMENT_CHAR US"?"
case EOP_UTF8CLEAN:
{
int seq_len, index = 0;
int bytes_left = 0;
uschar seq_buff[4]; /* accumulate utf-8 here */
while (*sub != 0)
{
int complete;
long codepoint;
uschar c;
complete = 0;
c = *sub++;
if (bytes_left)
{
if ((c & 0xc0) != 0x80)
{
/* wrong continuation byte; invalidate all bytes */
complete = 1; /* error */
}
else
{
codepoint = (codepoint << 6) | (c & 0x3f);
seq_buff[index++] = c;
if (--bytes_left == 0) /* codepoint complete */
{
if(codepoint > 0x10FFFF) /* is it too large? */
complete = -1; /* error */
else
{ /* finished; output utf-8 sequence */
yield = string_cat(yield, &size, &ptr, seq_buff, seq_len);
index = 0;
}
}
}
}
else /* no bytes left: new sequence */
{
if((c & 0x80) == 0) /* 1-byte sequence, US-ASCII, keep it */
{
yield = string_cat(yield, &size, &ptr, &c, 1);
continue;
}
if((c & 0xe0) == 0xc0) /* 2-byte sequence */
{
if(c == 0xc0 || c == 0xc1) /* 0xc0 and 0xc1 are illegal */
complete = -1;
else
{
bytes_left = 1;
codepoint = c & 0x1f;
}
}
else if((c & 0xf0) == 0xe0) /* 3-byte sequence */
{
bytes_left = 2;
codepoint = c & 0x0f;
}
else if((c & 0xf8) == 0xf0) /* 4-byte sequence */
{
bytes_left = 3;
codepoint = c & 0x07;
}
else /* invalid or too long (RFC3629 allows only 4 bytes) */
complete = -1;
seq_buff[index++] = c;
seq_len = bytes_left + 1;
} /* if(bytes_left) */
if (complete != 0)
{
bytes_left = index = 0;
yield = string_cat(yield, &size, &ptr, UTF8_REPLACEMENT_CHAR, 1);
}
if ((complete == 1) && ((c & 0x80) == 0))
{ /* ASCII character follows incomplete sequence */
yield = string_cat(yield, &size, &ptr, &c, 1);
}
}
continue;
}
/* escape turns all non-printing characters into escape sequences. */
case EOP_ESCAPE:
{
uschar *t = string_printing(sub);
yield = string_cat(yield, &size, &ptr, t, Ustrlen(t));
continue;
}
/* Handle numeric expression evaluation */
case EOP_EVAL:
case EOP_EVAL10:
{
uschar *save_sub = sub;
uschar *error = NULL;
int_eximarith_t n = eval_expr(&sub, (c == EOP_EVAL10), &error, FALSE);
if (error != NULL)
{
expand_string_message = string_sprintf("error in expression "
"evaluation: %s (after processing \"%.*s\")", error, sub-save_sub,
save_sub);
goto EXPAND_FAILED;
}
sprintf(CS var_buffer, PR_EXIM_ARITH, n);
yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer));
continue;
}
/* Handle time period formating */
case EOP_TIME_EVAL:
{
int n = readconf_readtime(sub, 0, FALSE);
if (n < 0)
{
expand_string_message = string_sprintf("string \"%s\" is not an "
"Exim time interval in \"%s\" operator", sub, name);
goto EXPAND_FAILED;
}
sprintf(CS var_buffer, "%d", n);
yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer));
continue;
}
case EOP_TIME_INTERVAL:
{
int n;
uschar *t = read_number(&n, sub);
if (*t != 0) /* Not A Number*/
{
expand_string_message = string_sprintf("string \"%s\" is not a "
"positive number in \"%s\" operator", sub, name);
goto EXPAND_FAILED;
}
t = readconf_printtime(n);
yield = string_cat(yield, &size, &ptr, t, Ustrlen(t));
continue;
}
/* Convert string to base64 encoding */
case EOP_STR2B64:
{
uschar *encstr = auth_b64encode(sub, Ustrlen(sub));
yield = string_cat(yield, &size, &ptr, encstr, Ustrlen(encstr));
continue;
}
/* strlen returns the length of the string */
case EOP_STRLEN:
{
uschar buff[24];
(void)sprintf(CS buff, "%d", Ustrlen(sub));
yield = string_cat(yield, &size, &ptr, buff, Ustrlen(buff));
continue;
}
/* length_n or l_n takes just the first n characters or the whole string,
whichever is the shorter;
substr_m_n, and s_m_n take n characters from offset m; negative m take
from the end; l_n is synonymous with s_0_n. If n is omitted in substr it
takes the rest, either to the right or to the left.
hash_n or h_n makes a hash of length n from the string, yielding n
characters from the set a-z; hash_n_m makes a hash of length n, but
uses m characters from the set a-zA-Z0-9.
nhash_n returns a single number between 0 and n-1 (in text form), while
nhash_n_m returns a div/mod hash as two numbers "a/b". The first lies
between 0 and n-1 and the second between 0 and m-1. */
case EOP_LENGTH:
case EOP_L:
case EOP_SUBSTR:
case EOP_S:
case EOP_HASH:
case EOP_H:
case EOP_NHASH:
case EOP_NH:
{
int sign = 1;
int value1 = 0;
int value2 = -1;
int *pn;
int len;
uschar *ret;
if (arg == NULL)
{
expand_string_message = string_sprintf("missing values after %s",
name);
goto EXPAND_FAILED;
}
/* "length" has only one argument, effectively being synonymous with
substr_0_n. */
if (c == EOP_LENGTH || c == EOP_L)
{
pn = &value2;
value2 = 0;
}
/* The others have one or two arguments; for "substr" the first may be
negative. The second being negative means "not supplied". */
else
{
pn = &value1;
if (name[0] == 's' && *arg == '-') { sign = -1; arg++; }
}
/* Read up to two numbers, separated by underscores */
ret = arg;
while (*arg != 0)
{
if (arg != ret && *arg == '_' && pn == &value1)
{
pn = &value2;
value2 = 0;
if (arg[1] != 0) arg++;
}
else if (!isdigit(*arg))
{
expand_string_message =
string_sprintf("non-digit after underscore in \"%s\"", name);
goto EXPAND_FAILED;
}
else *pn = (*pn)*10 + *arg++ - '0';
}
value1 *= sign;
/* Perform the required operation */
ret =
(c == EOP_HASH || c == EOP_H)?
compute_hash(sub, value1, value2, &len) :
(c == EOP_NHASH || c == EOP_NH)?
compute_nhash(sub, value1, value2, &len) :
extract_substr(sub, value1, value2, &len);
if (ret == NULL) goto EXPAND_FAILED;
yield = string_cat(yield, &size, &ptr, ret, len);
continue;
}
/* Stat a path */
case EOP_STAT:
{
uschar *s;
uschar smode[12];
uschar **modetable[3];
int i;
mode_t mode;
struct stat st;
if ((expand_forbid & RDO_EXISTS) != 0)
{
expand_string_message = US"Use of the stat() expansion is not permitted";
goto EXPAND_FAILED;
}
if (stat(CS sub, &st) < 0)
{
expand_string_message = string_sprintf("stat(%s) failed: %s",
sub, strerror(errno));
goto EXPAND_FAILED;
}
mode = st.st_mode;
switch (mode & S_IFMT)
{
case S_IFIFO: smode[0] = 'p'; break;
case S_IFCHR: smode[0] = 'c'; break;
case S_IFDIR: smode[0] = 'd'; break;
case S_IFBLK: smode[0] = 'b'; break;
case S_IFREG: smode[0] = '-'; break;
default: smode[0] = '?'; break;
}
modetable[0] = ((mode & 01000) == 0)? mtable_normal : mtable_sticky;
modetable[1] = ((mode & 02000) == 0)? mtable_normal : mtable_setid;
modetable[2] = ((mode & 04000) == 0)? mtable_normal : mtable_setid;
for (i = 0; i < 3; i++)
{
memcpy(CS(smode + 7 - i*3), CS(modetable[i][mode & 7]), 3);
mode >>= 3;
}
smode[10] = 0;
s = string_sprintf("mode=%04lo smode=%s inode=%ld device=%ld links=%ld "
"uid=%ld gid=%ld size=" OFF_T_FMT " atime=%ld mtime=%ld ctime=%ld",
(long)(st.st_mode & 077777), smode, (long)st.st_ino,
(long)st.st_dev, (long)st.st_nlink, (long)st.st_uid,
(long)st.st_gid, st.st_size, (long)st.st_atime,
(long)st.st_mtime, (long)st.st_ctime);
yield = string_cat(yield, &size, &ptr, s, Ustrlen(s));
continue;
}
/* vaguely random number less than N */
case EOP_RANDINT:
{
int_eximarith_t max;
uschar *s;
max = expand_string_integer(sub, TRUE);
if (expand_string_message != NULL)
goto EXPAND_FAILED;
s = string_sprintf("%d", vaguely_random_number((int)max));
yield = string_cat(yield, &size, &ptr, s, Ustrlen(s));
continue;
}
/* Reverse IP, including IPv6 to dotted-nibble */
case EOP_REVERSE_IP:
{
int family, maskptr;
uschar reversed[128];
family = string_is_ip_address(sub, &maskptr);
if (family == 0)
{
expand_string_message = string_sprintf(
"reverse_ip() not given an IP address [%s]", sub);
goto EXPAND_FAILED;
}
invert_address(reversed, sub);
yield = string_cat(yield, &size, &ptr, reversed, Ustrlen(reversed));
continue;
}
/* Unknown operator */
default:
expand_string_message =
string_sprintf("unknown expansion operator \"%s\"", name);
goto EXPAND_FAILED;
}
}
/* Handle a plain name. If this is the first thing in the expansion, release
the pre-allocated buffer. If the result data is known to be in a new buffer,
newsize will be set to the size of that buffer, and we can just point at that
store instead of copying. Many expansion strings contain just one reference,
so this is a useful optimization, especially for humungous headers
($message_headers). */
/*{*/
if (*s++ == '}')
{
int len;
int newsize = 0;
if (ptr == 0)
{
if (resetok) store_reset(yield);
yield = NULL;
size = 0;
}
value = find_variable(name, FALSE, skipping, &newsize);
if (value == NULL)
{
expand_string_message =
string_sprintf("unknown variable in \"${%s}\"", name);
check_variable_error_message(name);
goto EXPAND_FAILED;
}
len = Ustrlen(value);
if (yield == NULL && newsize != 0)
{
yield = value;
size = newsize;
ptr = len;
}
else yield = string_cat(yield, &size, &ptr, value, len);
continue;
}
/* Else there's something wrong */
expand_string_message =
string_sprintf("\"${%s\" is not a known operator (or a } is missing "
"in a variable reference)", name);
goto EXPAND_FAILED;
}
/* If we hit the end of the string when ket_ends is set, there is a missing
terminating brace. */
if (ket_ends && *s == 0)
{
expand_string_message = malformed_header?
US"missing } at end of string - could be header name not terminated by colon"
:
US"missing } at end of string";
goto EXPAND_FAILED;
}
/* Expansion succeeded; yield may still be NULL here if nothing was actually
added to the string. If so, set up an empty string. Add a terminating zero. If
left != NULL, return a pointer to the terminator. */
if (yield == NULL) yield = store_get(1);
yield[ptr] = 0;
if (left != NULL) *left = s;
/* Any stacking store that was used above the final string is no longer needed.
In many cases the final string will be the first one that was got and so there
will be optimal store usage. */
if (resetok) store_reset(yield + ptr + 1);
else if (resetok_p) *resetok_p = FALSE;
DEBUG(D_expand)
{
debug_printf("expanding: %.*s\n result: %s\n", (int)(s - string), string,
yield);
if (skipping) debug_printf("skipping: result is not used\n");
}
return yield;
/* This is the failure exit: easiest to program with a goto. We still need
to update the pointer to the terminator, for cases of nested calls with "fail".
*/
EXPAND_FAILED_CURLY:
expand_string_message = malformed_header?
US"missing or misplaced { or } - could be header name not terminated by colon"
:
US"missing or misplaced { or }";
/* At one point, Exim reset the store to yield (if yield was not NULL), but
that is a bad idea, because expand_string_message is in dynamic store. */
EXPAND_FAILED:
if (left != NULL) *left = s;
DEBUG(D_expand)
{
debug_printf("failed to expand: %s\n", string);
debug_printf(" error message: %s\n", expand_string_message);
if (expand_string_forcedfail) debug_printf("failure was forced\n");
}
if (resetok_p) *resetok_p = resetok;
return NULL;
}
| 16,154 |
37,987 | 0 | mdebug(uint32_t offset, const char *str, size_t len)
{
(void) fprintf(stderr, "mget/%zu @%d: ", len, offset);
file_showstr(stderr, str, len);
(void) fputc('\n', stderr);
(void) fputc('\n', stderr);
}
| 16,155 |
187,926 | 1 | static int sysMapFD(int fd, MemMapping* pMap)
{
off_t start;
size_t length;
void* memPtr;
assert(pMap != NULL);
if (getFileStartAndLength(fd, &start, &length) < 0)
return -1;
memPtr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, start);
if (memPtr == MAP_FAILED) {
LOGW("mmap(%d, R, PRIVATE, %d, %d) failed: %s\n", (int) length,
fd, (int) start, strerror(errno));
return -1;
}
pMap->addr = memPtr;
pMap->length = length;
pMap->range_count = 1;
pMap->ranges = malloc(sizeof(MappedRange));
pMap->ranges[0].addr = memPtr;
pMap->ranges[0].length = length;
return 0;
}
| 16,156 |
100,092 | 0 | void SetExemplarSetForLang(const std::string& lang,
icu::UnicodeSet* lang_set) {
LangToExemplarSetMap& map = Singleton<LangToExemplarSet>()->map;
map.insert(std::make_pair(lang, lang_set));
}
| 16,157 |
72,049 | 0 | static int _bcast_find_in_list(void *x, void *y)
{
file_bcast_info_t *info = (file_bcast_info_t *)x;
file_bcast_info_t *key = (file_bcast_info_t *)y;
/* uid, job_id, and fname must match */
return ((info->uid == key->uid)
&& (info->job_id == key->job_id)
&& (!xstrcmp(info->fname, key->fname)));
}
| 16,158 |
88,751 | 0 | int modbus_set_response_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec)
{
if (ctx == NULL ||
(to_sec == 0 && to_usec == 0) || to_usec > 999999) {
errno = EINVAL;
return -1;
}
ctx->response_timeout.tv_sec = to_sec;
ctx->response_timeout.tv_usec = to_usec;
return 0;
}
| 16,159 |
33,857 | 0 | cib_ipc_accept(qb_ipcs_connection_t *c, uid_t uid, gid_t gid)
{
cib_client_t *new_client = NULL;
#if ENABLE_ACL
struct group *crm_grp = NULL;
#endif
crm_trace("Connecting %p for uid=%d gid=%d pid=%d", c, uid, gid, crm_ipcs_client_pid(c));
if (cib_shutdown_flag) {
crm_info("Ignoring new client [%d] during shutdown", crm_ipcs_client_pid(c));
return -EPERM;
}
new_client = calloc(1, sizeof(cib_client_t));
new_client->ipc = c;
CRM_CHECK(new_client->id == NULL, free(new_client->id));
new_client->id = crm_generate_uuid();
#if ENABLE_ACL
crm_grp = getgrnam(CRM_DAEMON_GROUP);
if (crm_grp) {
qb_ipcs_connection_auth_set(c, -1, crm_grp->gr_gid, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
}
new_client->user = uid2username(uid);
#endif
/* make sure we can find ourselves later for sync calls
* redirected to the master instance
*/
g_hash_table_insert(client_list, new_client->id, new_client);
qb_ipcs_context_set(c, new_client);
return 0;
}
| 16,160 |
128,568 | 0 | pp::Var Instance::GetInstanceObject() {
if (instance_object_.is_undefined()) {
PDFScriptableObject* object = new PDFScriptableObject(this);
instance_object_ = pp::VarPrivate(this, object);
}
return instance_object_;
}
| 16,161 |
159,606 | 0 | Event* Document::createEvent(ScriptState* script_state,
const String& event_type,
ExceptionState& exception_state) {
Event* event = nullptr;
ExecutionContext* execution_context = ExecutionContext::From(script_state);
for (const auto& factory : EventFactories()) {
event = factory->Create(execution_context, event_type);
if (event) {
if (DeprecatedEqualIgnoringCase(event_type, "TouchEvent") &&
!OriginTrials::touchEventFeatureDetectionEnabled(execution_context))
break;
return event;
}
}
exception_state.ThrowDOMException(
kNotSupportedError,
"The provided event type ('" + event_type + "') is invalid.");
return nullptr;
}
| 16,162 |
121,678 | 0 | void ChangeListLoader::LoadChangeListFromServerAfterUpdate(
ChangeListProcessor* change_list_processor,
bool should_notify_changed_directories,
const base::Time& start_time,
FileError error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
const base::TimeDelta elapsed = base::Time::Now() - start_time;
util::Log(logging::LOG_INFO,
"Change lists applied (elapsed time: %sms)",
base::Int64ToString(elapsed.InMilliseconds()).c_str());
if (should_notify_changed_directories) {
for (std::set<base::FilePath>::iterator dir_iter =
change_list_processor->changed_dirs().begin();
dir_iter != change_list_processor->changed_dirs().end();
++dir_iter) {
FOR_EACH_OBSERVER(ChangeListLoaderObserver, observers_,
OnDirectoryChanged(*dir_iter));
}
}
OnChangeListLoadComplete(error);
FOR_EACH_OBSERVER(ChangeListLoaderObserver,
observers_,
OnLoadFromServerComplete());
}
| 16,163 |
103,148 | 0 | void Browser::OpenCreateShortcutsDialog() {
UserMetrics::RecordAction(UserMetricsAction("CreateShortcut"), profile_);
#if defined(OS_WIN) || defined(OS_LINUX)
TabContentsWrapper* current_tab = GetSelectedTabContentsWrapper();
DCHECK(current_tab &&
web_app::IsValidUrl(current_tab->tab_contents()->GetURL())) <<
"Menu item should be disabled.";
NavigationEntry* entry = current_tab->controller().GetLastCommittedEntry();
if (!entry)
return;
DCHECK(pending_web_app_action_ == NONE);
pending_web_app_action_ = CREATE_SHORTCUT;
current_tab->extension_tab_helper()->GetApplicationInfo(entry->page_id());
#else
NOTIMPLEMENTED();
#endif
}
| 16,164 |
149,153 | 0 | static int decodeFlags(MemPage *pPage, int flagByte){
BtShared *pBt; /* A copy of pPage->pBt */
assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
assert( sqlite3_mutex_held(pPage->pBt->mutex) );
pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
flagByte &= ~PTF_LEAF;
pPage->childPtrSize = 4-4*pPage->leaf;
pPage->xCellSize = cellSizePtr;
pBt = pPage->pBt;
if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
/* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
** interior table b-tree page. */
assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
/* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
** leaf table b-tree page. */
assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
pPage->intKey = 1;
if( pPage->leaf ){
pPage->intKeyLeaf = 1;
pPage->xParseCell = btreeParseCellPtr;
}else{
pPage->intKeyLeaf = 0;
pPage->xCellSize = cellSizePtrNoPayload;
pPage->xParseCell = btreeParseCellPtrNoPayload;
}
pPage->maxLocal = pBt->maxLeaf;
pPage->minLocal = pBt->minLeaf;
}else if( flagByte==PTF_ZERODATA ){
/* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
** interior index b-tree page. */
assert( (PTF_ZERODATA)==2 );
/* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
** leaf index b-tree page. */
assert( (PTF_ZERODATA|PTF_LEAF)==10 );
pPage->intKey = 0;
pPage->intKeyLeaf = 0;
pPage->xParseCell = btreeParseCellPtrIndex;
pPage->maxLocal = pBt->maxLocal;
pPage->minLocal = pBt->minLocal;
}else{
/* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
** an error. */
return SQLITE_CORRUPT_BKPT;
}
pPage->max1bytePayload = pBt->max1bytePayload;
return SQLITE_OK;
}
| 16,165 |
114,539 | 0 | bool WebPluginProxy::FindProxyForUrl(const GURL& url, std::string* proxy_list) {
bool result = false;
Send(new PluginHostMsg_ResolveProxy(route_id_, url, &result, proxy_list));
return result;
}
| 16,166 |
172,681 | 0 | status_t MediaPlayer::setDataSource(const sp<IDataSource> &source)
{
ALOGV("setDataSource(IDataSource)");
status_t err = UNKNOWN_ERROR;
const sp<IMediaPlayerService>& service(getMediaPlayerService());
if (service != 0) {
sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
(NO_ERROR != player->setDataSource(source))) {
player.clear();
}
err = attachNewPlayer(player);
}
return err;
}
| 16,167 |
46,337 | 0 | static int gfs2_open(struct inode *inode, struct file *file)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder i_gh;
int error;
bool need_unlock = false;
if (S_ISREG(ip->i_inode.i_mode)) {
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY,
&i_gh);
if (error)
return error;
need_unlock = true;
}
error = gfs2_open_common(inode, file);
if (need_unlock)
gfs2_glock_dq_uninit(&i_gh);
return error;
}
| 16,168 |
14,775 | 0 | static int _php_pgsql_detect_identifier_escape(const char *identifier, size_t len)
{
size_t i;
/* Handle edge case. Cannot be a escaped string */
if (len <= 2) {
return FAILURE;
}
/* Detect double qoutes */
if (identifier[0] == '"' && identifier[len-1] == '"') {
/* Detect wrong format of " inside of escaped string */
for (i = 1; i < len-1; i++) {
if (identifier[i] == '"' && (identifier[++i] != '"' || i == len-1)) {
return FAILURE;
}
}
} else {
return FAILURE;
}
/* Escaped properly */
return SUCCESS;
}
| 16,169 |
152,386 | 0 | bool IsHttpPost(const blink::WebURLRequest& request) {
return request.HttpMethod().Utf8() == "POST";
}
| 16,170 |
19,984 | 0 | static int nfs4_proc_readdir(struct dentry *dentry, struct rpc_cred *cred,
u64 cookie, struct page **pages, unsigned int count, int plus)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(dentry->d_inode),
_nfs4_proc_readdir(dentry, cred, cookie,
pages, count, plus),
&exception);
} while (exception.retry);
return err;
}
| 16,171 |
89,995 | 0 | size_t ZSTD_CCtx_setParametersUsingCCtxParams(
ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params)
{
DEBUGLOG(4, "ZSTD_CCtx_setParametersUsingCCtxParams");
if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
if (cctx->cdict) return ERROR(stage_wrong);
cctx->requestedParams = *params;
return 0;
}
| 16,172 |
25,265 | 0 | static inline u32 armv7_pmnc_getreset_flags(void)
{
u32 val;
/* Read */
asm volatile("mrc p15, 0, %0, c9, c12, 3" : "=r" (val));
/* Write to clear flags */
val &= ARMV7_FLAG_MASK;
asm volatile("mcr p15, 0, %0, c9, c12, 3" : : "r" (val));
return val;
}
| 16,173 |
135,083 | 0 | void AppCacheHost::SetSpawningHostId(
int spawning_process_id, int spawning_host_id) {
spawning_process_id_ = spawning_process_id;
spawning_host_id_ = spawning_host_id;
}
| 16,174 |
87,698 | 0 | static int ipip6_newlink(struct net *src_net, struct net_device *dev,
struct nlattr *tb[], struct nlattr *data[],
struct netlink_ext_ack *extack)
{
struct net *net = dev_net(dev);
struct ip_tunnel *nt;
struct ip_tunnel_encap ipencap;
#ifdef CONFIG_IPV6_SIT_6RD
struct ip_tunnel_6rd ip6rd;
#endif
int err;
nt = netdev_priv(dev);
if (ipip6_netlink_encap_parms(data, &ipencap)) {
err = ip_tunnel_encap_setup(nt, &ipencap);
if (err < 0)
return err;
}
ipip6_netlink_parms(data, &nt->parms, &nt->fwmark);
if (ipip6_tunnel_locate(net, &nt->parms, 0))
return -EEXIST;
err = ipip6_tunnel_create(dev);
if (err < 0)
return err;
if (tb[IFLA_MTU]) {
u32 mtu = nla_get_u32(tb[IFLA_MTU]);
if (mtu >= IPV6_MIN_MTU &&
mtu <= IP6_MAX_MTU - dev->hard_header_len)
dev->mtu = mtu;
}
#ifdef CONFIG_IPV6_SIT_6RD
if (ipip6_netlink_6rd_parms(data, &ip6rd))
err = ipip6_tunnel_update_6rd(nt, &ip6rd);
#endif
return err;
}
| 16,175 |
84,403 | 0 | get_string (Buffer *buffer, Header *header, guint32 *offset, guint32 end_offset)
{
guint8 len;
char *str;
*offset = align_by_4 (*offset);
if (*offset + 4 >= end_offset)
return FALSE;
len = read_uint32 (header, &buffer->data[*offset]);
*offset += 4;
if ((*offset) + len + 1 > end_offset)
return FALSE;
if (buffer->data[(*offset) + len] != 0)
return FALSE;
str = (char *) &buffer->data[(*offset)];
*offset += len + 1;
return str;
}
| 16,176 |
12,094 | 0 | int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator,
const BIGNUM *order, const BIGNUM *cofactor)
{
return group->order;
}
| 16,177 |
11,702 | 0 | filesystem_set_label_completed_cb (DBusGMethodInvocation *context,
Device *device,
gboolean job_was_cancelled,
int status,
const char *stderr,
const char *stdout,
gpointer user_data)
{
char *new_label = user_data;
/* poke the kernel so we can reread the data */
device_generate_kernel_change_event (device);
if (WEXITSTATUS (status) == 0 && !job_was_cancelled)
{
/* update local copy, don't wait for the kernel */
device_set_id_label (device, new_label);
drain_pending_changes (device, FALSE);
dbus_g_method_return (context);
}
else
{
if (job_was_cancelled)
{
throw_error (context, ERROR_CANCELLED, "Job was cancelled");
}
else
{
throw_error (context,
ERROR_FAILED,
"Error changing fslabel: helper exited with exit code %d: %s",
WEXITSTATUS (status),
stderr);
}
}
}
| 16,178 |
176,475 | 0 | WORD32 ihevcd_ctl(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op)
{
ivd_ctl_set_config_ip_t *ps_ctl_ip;
ivd_ctl_set_config_op_t *ps_ctl_op;
WORD32 ret = 0;
WORD32 subcommand;
codec_t *ps_codec = (codec_t *)ps_codec_obj->pv_codec_handle;
ps_ctl_ip = (ivd_ctl_set_config_ip_t *)pv_api_ip;
ps_ctl_op = (ivd_ctl_set_config_op_t *)pv_api_op;
if(ps_codec->i4_init_done != 1)
{
ps_ctl_op->u4_error_code |= 1 << IVD_FATALERROR;
ps_ctl_op->u4_error_code |= IHEVCD_INIT_NOT_DONE;
return IV_FAIL;
}
subcommand = ps_ctl_ip->e_sub_cmd;
switch(subcommand)
{
case IVD_CMD_CTL_GETPARAMS:
ret = ihevcd_get_status(ps_codec_obj, (void *)pv_api_ip,
(void *)pv_api_op);
break;
case IVD_CMD_CTL_SETPARAMS:
ret = ihevcd_set_params(ps_codec_obj, (void *)pv_api_ip,
(void *)pv_api_op);
break;
case IVD_CMD_CTL_RESET:
ret = ihevcd_reset(ps_codec_obj, (void *)pv_api_ip,
(void *)pv_api_op);
break;
case IVD_CMD_CTL_SETDEFAULT:
{
ivd_ctl_set_config_op_t *s_ctl_dynparams_op =
(ivd_ctl_set_config_op_t *)pv_api_op;
ret = ihevcd_set_default_params(ps_codec);
if(IV_SUCCESS == ret)
s_ctl_dynparams_op->u4_error_code = 0;
break;
}
case IVD_CMD_CTL_FLUSH:
ret = ihevcd_set_flush_mode(ps_codec_obj, (void *)pv_api_ip,
(void *)pv_api_op);
break;
case IVD_CMD_CTL_GETBUFINFO:
ret = ihevcd_get_buf_info(ps_codec_obj, (void *)pv_api_ip,
(void *)pv_api_op);
break;
case IVD_CMD_CTL_GETVERSION:
{
ivd_ctl_getversioninfo_ip_t *ps_ip;
ivd_ctl_getversioninfo_op_t *ps_op;
IV_API_CALL_STATUS_T ret;
ps_ip = (ivd_ctl_getversioninfo_ip_t *)pv_api_ip;
ps_op = (ivd_ctl_getversioninfo_op_t *)pv_api_op;
ps_op->u4_error_code = IV_SUCCESS;
if((WORD32)ps_ip->u4_version_buffer_size <= 0)
{
ps_op->u4_error_code = IHEVCD_CXA_VERS_BUF_INSUFFICIENT;
ret = IV_FAIL;
}
else
{
ret = ihevcd_get_version((CHAR *)ps_ip->pv_version_buffer,
ps_ip->u4_version_buffer_size);
if(ret != IV_SUCCESS)
{
ps_op->u4_error_code = IHEVCD_CXA_VERS_BUF_INSUFFICIENT;
ret = IV_FAIL;
}
}
}
break;
case IHEVCD_CXA_CMD_CTL_DEGRADE:
ret = ihevcd_set_degrade(ps_codec_obj, (void *)pv_api_ip,
(void *)pv_api_op);
break;
case IHEVCD_CXA_CMD_CTL_SET_NUM_CORES:
ret = ihevcd_set_num_cores(ps_codec_obj, (void *)pv_api_ip,
(void *)pv_api_op);
break;
case IHEVCD_CXA_CMD_CTL_GET_BUFFER_DIMENSIONS:
ret = ihevcd_get_frame_dimensions(ps_codec_obj, (void *)pv_api_ip,
(void *)pv_api_op);
break;
case IHEVCD_CXA_CMD_CTL_GET_VUI_PARAMS:
ret = ihevcd_get_vui_params(ps_codec_obj, (void *)pv_api_ip,
(void *)pv_api_op);
break;
case IHEVCD_CXA_CMD_CTL_GET_SEI_MASTERING_PARAMS:
ret = ihevcd_get_sei_mastering_params(ps_codec_obj, (void *)pv_api_ip,
(void *)pv_api_op);
break;
case IHEVCD_CXA_CMD_CTL_SET_PROCESSOR:
ret = ihevcd_set_processor(ps_codec_obj, (void *)pv_api_ip,
(void *)pv_api_op);
break;
default:
DEBUG("\nDo nothing\n");
break;
}
return ret;
}
| 16,179 |
34,786 | 0 | static int apparmor_dentry_open(struct file *file, const struct cred *cred)
{
struct aa_file_cxt *fcxt = file->f_security;
struct aa_profile *profile;
int error = 0;
if (!mediated_filesystem(file->f_path.dentry->d_inode))
return 0;
/* If in exec, permission is handled by bprm hooks.
* Cache permissions granted by the previous exec check, with
* implicit read and executable mmap which are required to
* actually execute the image.
*/
if (current->in_execve) {
fcxt->allow = MAY_EXEC | MAY_READ | AA_EXEC_MMAP;
return 0;
}
profile = aa_cred_profile(cred);
if (!unconfined(profile)) {
struct inode *inode = file->f_path.dentry->d_inode;
struct path_cond cond = { inode->i_uid, inode->i_mode };
error = aa_path_perm(OP_OPEN, profile, &file->f_path, 0,
aa_map_file_to_perms(file), &cond);
/* todo cache full allowed permissions set and state */
fcxt->allow = aa_map_file_to_perms(file);
}
return error;
}
| 16,180 |
35,565 | 0 | static int emulate_popf(struct x86_emulate_ctxt *ctxt,
void *dest, int len)
{
int rc;
unsigned long val, change_mask;
int iopl = (ctxt->eflags & X86_EFLAGS_IOPL) >> IOPL_SHIFT;
int cpl = ctxt->ops->cpl(ctxt);
rc = emulate_pop(ctxt, &val, len);
if (rc != X86EMUL_CONTINUE)
return rc;
change_mask = EFLG_CF | EFLG_PF | EFLG_AF | EFLG_ZF | EFLG_SF | EFLG_OF
| EFLG_TF | EFLG_DF | EFLG_NT | EFLG_AC | EFLG_ID;
switch(ctxt->mode) {
case X86EMUL_MODE_PROT64:
case X86EMUL_MODE_PROT32:
case X86EMUL_MODE_PROT16:
if (cpl == 0)
change_mask |= EFLG_IOPL;
if (cpl <= iopl)
change_mask |= EFLG_IF;
break;
case X86EMUL_MODE_VM86:
if (iopl < 3)
return emulate_gp(ctxt, 0);
change_mask |= EFLG_IF;
break;
default: /* real mode */
change_mask |= (EFLG_IOPL | EFLG_IF);
break;
}
*(unsigned long *)dest =
(ctxt->eflags & ~change_mask) | (val & change_mask);
return rc;
}
| 16,181 |
179,906 | 1 | xfs_attr3_leaf_clearflag(
struct xfs_da_args *args)
{
struct xfs_attr_leafblock *leaf;
struct xfs_attr_leaf_entry *entry;
struct xfs_attr_leaf_name_remote *name_rmt;
struct xfs_buf *bp;
int error;
#ifdef DEBUG
struct xfs_attr3_icleaf_hdr ichdr;
xfs_attr_leaf_name_local_t *name_loc;
int namelen;
char *name;
#endif /* DEBUG */
trace_xfs_attr_leaf_clearflag(args);
/*
* Set up the operation.
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return(error);
leaf = bp->b_addr;
entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
ASSERT(entry->flags & XFS_ATTR_INCOMPLETE);
#ifdef DEBUG
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
ASSERT(args->index < ichdr.count);
ASSERT(args->index >= 0);
if (entry->flags & XFS_ATTR_LOCAL) {
name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
namelen = name_loc->namelen;
name = (char *)name_loc->nameval;
} else {
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
namelen = name_rmt->namelen;
name = (char *)name_rmt->name;
}
ASSERT(be32_to_cpu(entry->hashval) == args->hashval);
ASSERT(namelen == args->namelen);
ASSERT(memcmp(name, args->name, namelen) == 0);
#endif /* DEBUG */
entry->flags &= ~XFS_ATTR_INCOMPLETE;
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
if (args->rmtblkno) {
ASSERT((entry->flags & XFS_ATTR_LOCAL) == 0);
name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
name_rmt->valueblk = cpu_to_be32(args->rmtblkno);
name_rmt->valuelen = cpu_to_be32(args->valuelen);
xfs_trans_log_buf(args->trans, bp,
XFS_DA_LOGRANGE(leaf, name_rmt, sizeof(*name_rmt)));
}
/*
* Commit the flag value change and start the next trans in series.
*/
return xfs_trans_roll(&args->trans, args->dp);
}
| 16,182 |
104,710 | 0 | bool IsWebStoreURL(Profile* profile, const GURL& url) {
ExtensionService* service = profile->GetExtensionService();
const Extension* store = service->GetWebStoreApp();
if (!store) {
NOTREACHED();
return false;
}
return (service->GetExtensionByWebExtent(url) == store);
}
| 16,183 |
109,349 | 0 | void InspectorResourceAgent::clearBrowserCache(ErrorString*)
{
m_client->clearBrowserCache();
}
| 16,184 |
155,141 | 0 | void OmniboxViewViews::OnGestureEvent(ui::GestureEvent* event) {
if (!HasFocus() && event->type() == ui::ET_GESTURE_TAP_DOWN) {
select_all_on_gesture_tap_ = true;
saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
}
views::Textfield::OnGestureEvent(event);
if (select_all_on_gesture_tap_ && event->type() == ui::ET_GESTURE_TAP) {
SelectAllForUserGesture();
if (location_bar_view_)
location_bar_view_->omnibox_page_action_icon_container_view()
->UpdatePageActionIcon(PageActionIconType::kSendTabToSelf);
}
if (event->type() == ui::ET_GESTURE_TAP ||
event->type() == ui::ET_GESTURE_TAP_CANCEL ||
event->type() == ui::ET_GESTURE_TWO_FINGER_TAP ||
event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||
event->type() == ui::ET_GESTURE_PINCH_BEGIN ||
event->type() == ui::ET_GESTURE_LONG_PRESS ||
event->type() == ui::ET_GESTURE_LONG_TAP) {
select_all_on_gesture_tap_ = false;
}
}
| 16,185 |
87,410 | 0 | const RECTANGLE_16* region16_extents(const REGION16* region)
{
if (!region)
return NULL;
return ®ion->extents;
}
| 16,186 |
26,084 | 0 | void perf_event_header__init_id(struct perf_event_header *header,
struct perf_sample_data *data,
struct perf_event *event)
{
if (event->attr.sample_id_all)
__perf_event_header__init_id(header, data, event);
}
| 16,187 |
165,939 | 0 | bool RenderFrameImpl::UpdateNavigationHistory(
const blink::WebHistoryItem& item,
blink::WebHistoryCommitType commit_type) {
NavigationState* navigation_state =
NavigationState::FromDocumentLoader(frame_->GetDocumentLoader());
const RequestNavigationParams& request_params =
navigation_state->request_params();
current_history_item_ = item;
current_history_item_.SetTarget(
blink::WebString::FromUTF8(unique_name_helper_.value()));
bool is_new_navigation = commit_type == blink::kWebStandardCommit;
if (request_params.should_clear_history_list) {
render_view_->history_list_offset_ = 0;
render_view_->history_list_length_ = 1;
} else if (is_new_navigation) {
DCHECK(!navigation_state->common_params().should_replace_current_entry ||
render_view_->history_list_length_ > 0);
if (!navigation_state->common_params().should_replace_current_entry) {
render_view_->history_list_offset_++;
if (render_view_->history_list_offset_ >= kMaxSessionHistoryEntries)
render_view_->history_list_offset_ = kMaxSessionHistoryEntries - 1;
render_view_->history_list_length_ =
render_view_->history_list_offset_ + 1;
}
} else if (request_params.nav_entry_id != 0 &&
!request_params.intended_as_new_entry) {
render_view_->history_list_offset_ =
navigation_state->request_params().pending_history_list_offset;
}
if (commit_type == blink::WebHistoryCommitType::kWebBackForwardCommit)
render_view_->DidCommitProvisionalHistoryLoad();
return is_new_navigation;
}
| 16,188 |
99,651 | 0 | void VaapiVideoDecodeAccelerator::ResetTask() {
DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread());
DVLOG(1) << "ResetTask";
decoder_->Reset();
base::AutoLock auto_lock(lock_);
if (curr_input_buffer_.get())
ReturnCurrInputBuffer_Locked();
message_loop_->PostTask(FROM_HERE, base::Bind(
&VaapiVideoDecodeAccelerator::FinishReset, weak_this_));
}
| 16,189 |
78,035 | 0 | int IsMyBlock(const cmsUInt8Number* Buffer, cmsUInt32Number n)
{
int words = 1, space = 0, quot = 0;
cmsUInt32Number i;
if (n < 10) return 0; // Too small
if (n > 132)
n = 132;
for (i = 1; i < n; i++) {
switch(Buffer[i])
{
case '\n':
case '\r':
return ((quot == 1) || (words > 2)) ? 0 : words;
case '\t':
case ' ':
if(!quot && !space)
space = 1;
break;
case '\"':
quot = !quot;
break;
default:
if (Buffer[i] < 32) return 0;
if (Buffer[i] > 127) return 0;
words += space;
space = 0;
break;
}
}
return 0;
}
| 16,190 |
118,671 | 0 | void InProcessBrowserTest::AddTabAtIndexToBrowser(
Browser* browser,
int index,
const GURL& url,
content::PageTransition transition) {
chrome::NavigateParams params(browser, url, transition);
params.tabstrip_index = index;
params.disposition = NEW_FOREGROUND_TAB;
chrome::Navigate(¶ms);
content::WaitForLoadStop(params.target_contents);
}
| 16,191 |
36,961 | 0 | fep_client_dispatch (FepClient *client)
{
static const struct
{
FepControlCommand command;
void (*handler) (FepClient *client,
FepControlMessage *request,
FepControlMessage *response);
} handlers[] =
{
{ FEP_CONTROL_KEY_EVENT, command_key_event },
{ FEP_CONTROL_RESIZE_EVENT, command_resize_event },
};
FepControlMessage request, response;
int retval;
int i;
retval = _fep_read_control_message (client->control, &request);
if (retval < 0)
return -1;
for (i = 0;
i < SIZEOF (handlers) && handlers[i].command != request.command;
i++)
;
if (i == SIZEOF (handlers))
{
_fep_control_message_free_args (&request);
fep_log (FEP_LOG_LEVEL_WARNING,
"no handler defined for %d", request.command);
return -1;
}
client->filter_running = true;
handlers[i].handler (client, &request, &response);
_fep_control_message_free_args (&request);
_fep_write_control_message (client->control, &response);
_fep_control_message_free_args (&response);
client->filter_running = false;
/* flush queued messages during handler is executed */
while (client->messages)
{
FepList *_head = client->messages;
FepControlMessage *_message = _head->data;
client->messages = _head->next;
_fep_write_control_message (client->control, _message);
_fep_control_message_free (_message);
free (_head);
}
return retval;
}
| 16,192 |
52,238 | 0 | static bool check_underflow(const struct arpt_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(&e->arp))
return false;
t = arpt_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
| 16,193 |
93,560 | 0 | static int ipmr_mfc_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ipmr_mfc_seq_ops,
sizeof(struct ipmr_mfc_iter));
}
| 16,194 |
112,913 | 0 | void GDataCacheMetadata::AssertOnSequencedWorkerPool() {
DCHECK(!pool_ || pool_->IsRunningSequenceOnCurrentThread(sequence_token_));
}
| 16,195 |
158,893 | 0 | void WebContentsImpl::CreateNewWidget(int32_t render_process_id,
int32_t route_id,
bool is_fullscreen,
mojom::WidgetPtr widget,
blink::WebPopupType popup_type) {
RenderProcessHost* process = RenderProcessHost::FromID(render_process_id);
if (!HasMatchingProcess(&frame_tree_, render_process_id)) {
ReceivedBadMessage(process, bad_message::WCI_NEW_WIDGET_PROCESS_MISMATCH);
return;
}
RenderWidgetHostImpl* widget_host = new RenderWidgetHostImpl(
this, process, route_id, std::move(widget), IsHidden());
RenderWidgetHostViewBase* widget_view =
static_cast<RenderWidgetHostViewBase*>(
view_->CreateViewForPopupWidget(widget_host));
if (!widget_view)
return;
if (!is_fullscreen) {
widget_view->SetPopupType(popup_type);
}
pending_widget_views_[GlobalRoutingID(render_process_id, route_id)] =
widget_view;
}
| 16,196 |
142,400 | 0 | void ShelfBackgroundAnimator::OnBackgroundTypeChanged(
ShelfBackgroundType background_type,
AnimationChangeType change_type) {
PaintBackground(background_type, change_type);
}
| 16,197 |
158,567 | 0 | void WebLocalFrameImpl::ReportContentSecurityPolicyViolation(
const blink::WebContentSecurityPolicyViolation& violation) {
AddMessageToConsole(blink::WebConsoleMessage(
WebConsoleMessage::kLevelError, violation.console_message,
violation.source_location.url, violation.source_location.line_number,
violation.source_location.column_number));
std::unique_ptr<SourceLocation> source_location = SourceLocation::Create(
violation.source_location.url, violation.source_location.line_number,
violation.source_location.column_number, nullptr);
DCHECK(GetFrame() && GetFrame()->GetDocument());
Document* document = GetFrame()->GetDocument();
Vector<String> report_endpoints;
for (const WebString& end_point : violation.report_endpoints)
report_endpoints.push_back(end_point);
document->GetContentSecurityPolicy()->ReportViolation(
violation.directive,
ContentSecurityPolicy::GetDirectiveType(violation.effective_directive),
violation.console_message, violation.blocked_url, report_endpoints,
violation.use_reporting_api, violation.header,
static_cast<ContentSecurityPolicyHeaderType>(violation.disposition),
ContentSecurityPolicy::ViolationType::kURLViolation,
std::move(source_location), nullptr /* LocalFrame */,
violation.after_redirect ? RedirectStatus::kFollowedRedirect
: RedirectStatus::kNoRedirect,
nullptr /* Element */);
}
| 16,198 |
131,316 | 0 | static void customGetterLongAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
V8TestObjectPython::customGetterLongAttributeAttributeGetterCustom(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
| 16,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.